首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

模糊測試實戰:為 Visual Studio Team System 打造自訂測試介面提供者 (TIP)

     編輯:關於.NET

什麼是模糊測試?

向程式輸入大量隨機/半隨機/惡意構造資料,觀察是否崩潰。三大結果:

  1. 多數輸入被拒 (格式錯誤)
  2. 少數正常通過
  3. 極少數觸發未預期 bug (緩衝區溢位、整數溢位等) — 安全測試核心目標

策略:已知合法輸入 (繞過驗證層) + 故意錯誤輸入 (針對可疑邊界) + 隨機輸入 (探索未知) — 迭代微調,人機結合。

VSTS 測試擴展架構

  • TIP (Test Interface Provider):測試類型插件,負責載入/建立/執行/結果解讀
  • TMI (Test Management Interface):託管 TIP 的宿主
  • SDK 內建 MyTest 範例為起點

打造 FuzzTestAdapter 核心步驟

1. 修改專案結構

  • 重命名 MyTestAdapter → FuzzTestAdapter
  • 補齊缺失資源:mytest.ico、mytestui.rc
  • 修正 mytestui 專案後建置事件路徑 (ctc.exe 絕對路徑)

2. 核心 Run 方法實現

public void Run(ITestElement testElement, ITestContext testContext) {
    var test = (MyTest)testElement;
    var result = new MyTestResult(...);
    var timer = Stopwatch.StartNew();
    bool errorFound = false;
    
    for (int i = 0; i < char.MaxValue; i++) {
        char ch = Convert.ToChar(i);
        string cmdLine = test.CommandLine.Replace("", "\"" + ch + "\"");
        
        var p = new Process {
            StartInfo = {
                FileName = cmdLine.Substring(0, exeEnd),
                Arguments = cmdLine.Substring(exeEnd + 1),
                UseShellExecute = false, CreateNoWindow = true,
                RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true
            }
        };
        p.Start();
        p.StandardInput.WriteLine();
        string err = p.StandardError.ReadToEnd();
        p.WaitForExit();
        
        if (!string.IsNullOrEmpty(err)) {
            errorFound = true;
            result.Outcome = TestOutcome.Failed;
            result.ErrorMessage = $"Input: {cmdLine}, Error: {err}";
            break;
        }
    }
    
    if (!errorFound) result.Outcome = TestOutcome.Passed;
    timer.Stop(); result.Duration = timer.Elapsed;
    testContext.ResultSink.AddResult(result);
}

關鍵點:

  • 命令列佔位符 <FuzzTestString> 支援參數化
  • 遍歷所有 Unicode 字元測試邊界條件
  • 捕獲 StdError 判定失敗
  • SuppressMessage 屬性允許捕獲所有異常

3. 被測試範例 ConsoleApp

Int32 arraySize = Math.Max(Math.Max('Z', 'A'), Math.Max('z', 'a')) + 1;
int[] charCountArray = new int[arraySize];
char c = inputString[0];
charCountArray[c] += 1; // 非字母字元導致 IndexOutOfRange

模糊測試快速觸發陣列越界異常。

部署與調試流程

  1. 關閉 VS,建置方案
  2. Visual Studio 命令提示字元執行 deploy.bat (複製組件、regpkg.exe 註冊)
  3. 執行 devenv /setup 合併封裝中繼資料
  4. 重開方案,設 TestProject 為啟動專案
  5. 新增測試 → 選擇 "My Test" → 填入命令列含佔位符
  6. F5 調試:可在 Run 斷點觀察每次迴圈啟動過程

VSTE 測試結果

代碼修改後的熱重載步驟

  1. 修改代碼、建置
  2. 關閉 VS
  3. 複製 Microsoft.VisualStudio.QualityTools.Samples.MyTestTIP.dll 至 PrivateAssemblies
  4. 重開方案、新增測試項目

總結

自適應模糊測試 + VSTS 自動化框架 = **人類直覺 + 機器耐力** = 完美測試覆蓋。專案源碼:下載連結。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved