Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

Visual Studio - Fine Code Coverage에서 동작하지 않는 Fake/Shim 테스트

이런 코드 커버리지 도구가 있군요.

Fine Code Coverage
; https://marketplace.visualstudio.com/items?itemName=FortuneNgwenya.FineCodeCoverage

음... 별로 매력적인 부분을 찾을 수 없는데, 왜 Visual Studio의 기본 Code Coverage를 놔두고 이걸 사용하는 걸까요? 혹시 장점을 아시는 분은 덧글 부탁드립니다. ^^

일단, 설치는 Visual Studio 2022에서도 할 수 있습니다. 그런데, 이게 한 가지 문제가 있는데요, 바로 Fake/Shim을 지원하지 못한다는 점입니다.

실제로 해당 코드가 들어간 단위 테스트를 작성하면, FCC 창에서 다음과 같은 오류를 확인할 수 있습니다.

  Failed TestTest [19 ms]
  Error Message:
   Test method ClassLibrary1.Tests.Class1Tests.TestTest threw exception: 
Microsoft.QualityTools.Testing.Fakes.UnitTestIsolation.UnitTestIsolationException: Failed to resolve profiler path from COR_PROFILER_PATH and COR_PROFILER environment variables.
  Stack Trace:
      at Microsoft.QualityTools.Testing.Fakes.UnitTestIsolation.IntelliTraceInstrumentationProvider.ResolveProfilerPath()
   at Microsoft.QualityTools.Testing.Fakes.UnitTestIsolation.IntelliTraceInstrumentationProvider.Initialize()
   at Microsoft.QualityTools.Testing.Fakes.UnitTestIsolation.UnitTestIsolationRuntime.InitializeUnitTestIsolationInstrumentationProvider()
   at Microsoft.QualityTools.Testing.Fakes.Shims.ShimRuntime.CreateContext()
   at Microsoft.QualityTools.Testing.Fakes.ShimsContext.Create()
   at ClassLibrary1.Tests.Class1Tests.TestTest() in C:\Users\SeongTae Jeong\Dropbox\articles\fin_code_coverage\net6_fakes_sample\ClassLibrary1Tests\Class1Tests.cs:line 19
Failed!  - Failed:     1, Passed:     1, Skipped:     0, Total:     2, Duration: 42 ms - ClassLibrary1Tests.dll (net6.0)

왜냐하면 Fake/Shim은 .NET Profiler의 IL Rewriter 기능을 이용해 작성되기 때문인데, 저렇게 Profiler 로딩을 못하므로 실패한 것입니다. 아마도 "{324F817A-7420-4E6D-B3C1-143FBED6D855}" GUID에 해당하는 Profiler로 여겨지는데, Visual Studio에서 제공하는 Code Coverage에서는 저 프로파일러가 잘 로딩이 되지만 Fine Code Coverage에서는 로딩에 실패하고 있는 것입니다. (이유는 잘 모르겠습니다.)

암튼, 저렇게 되면 ShimsContext.Create 호출부터 오류가 발생할 것이기 때문에 Code Coverage가 제대로 될 수 없습니다.




약간의 원인 분석을 해보자면.

Visual Studio가 실행하는 vstest.console.exe는 하위 프로세스로 testhost.exe를 통해 단위 테스트를 수행합니다. 이때 해당 프로세스에는 PROFILER 관련 환경 변수 설정들이 동적으로 추가되는데요,

SET CORECLR_PROFILER={324F817A-7420-4E6D-B3C1-143FBED6D855}
SET CORECLR_PROFILER_PATH_64=C:\Program Files\Microsoft Visual Studio\2022\Enterprise\Common7\IDE\CommonExtensions\Platform\InstrumentationEngine\x64\MicrosoftInstrumentationEngine_x64.dll
SET CORECLR_ENABLE_PROFILING=1

SET COR_PROFILER={324F817A-7420-4E6D-B3C1-143FBED6D855}
SET COR_PROFILER_PATH_64=C:\Program Files\Microsoft Visual Studio\2022\Enterprise\Common7\IDE\CommonExtensions\Platform\InstrumentationEngine\x64\MicrosoftInstrumentationEngine_x64.dll
SET COR_ENABLE_PROFILING=1

SET MicrosoftInstrumentationEngine_ConfigPath64_FakesInstrumentation=C:\Program Files\Microsoft Visual Studio\2022\Enterprise\Common7\IDE\Extensions\TestPlatform\Extensions\Fakes\x64\FakesInstrumentationProfiler_x64.config

/* FakesInstrumentationProfiler_x64.config
<?xml version="1.0" encoding="utf-8"?>
<InstrumentationEngineConfiguration>
  <InstrumentationMethod>
    <Name>Fakes Instrumentation Method</Name>
    <Description>Instrumentation method to support Microsoft Fakes</Description>
    <Module>Microsoft.QualityTools.Testing.Fakes.Instrumentation.dll</Module>
    <ClassGuid>{F02C3E96-F6FD-4552-9544-9F06BE6E5A0B}</ClassGuid>
    <Priority>11</Priority>
  </InstrumentationMethod>
</InstrumentationEngineConfiguration>
*/

반면 FineCodeCoverage는 coverlet.exe를 통해 몇 층의 dotnet.exe를 거쳐 testhost.exe를 실행하게 되는데 이 계층 구조에서는 당연히 PROFILER 관련 환경 변수 설정이 없습니다. 그래서, 혹시나 싶어 명령행을 실행해 위의 COR_..., CORECLR_... 환경 변수 설정을 한 후 이를 상속받을 수 있도록 devenv.exe를 실행시켜 Code Coverage를 수행해 봤습니다.

그래서 분명히 환경 변수가 적용까지는 되지만 아쉽게도, 여전히 이런 오류가 발생합니다.

  Failed TestTest [26 s]
  Error Message:
   Test method ClassLibrary1.Tests.Class1Tests.TestTest threw exception: 
Microsoft.QualityTools.Testing.Fakes.UnitTestIsolation.UnitTestIsolationException: Unexpected error returned by SetDetourProvider in profiler library 'C:\Program Files\Microsoft Visual Studio\2022\Enterprise\Common7\IDE\Extensions\TestPlatform\Extensions\Fakes\x64\Microsoft.QualityTools.Testing.Fakes.Instrumentation.dll'.
  Stack Trace:
      at Microsoft.QualityTools.Testing.Fakes.UnitTestIsolation.IntelliTraceInstrumentationProvider.Initialize()
   at Microsoft.QualityTools.Testing.Fakes.UnitTestIsolation.UnitTestIsolationRuntime.InitializeUnitTestIsolationInstrumentationProvider()
   at Microsoft.QualityTools.Testing.Fakes.Shims.ShimRuntime.CreateContext()
   at Microsoft.QualityTools.Testing.Fakes.ShimsContext.Create()
   at ClassLibrary1.Tests.Class1Tests.TestTest() in C:\temp2\ClassLibrary1Tests\Class1Tests.cs:line 27
Failed!  - Failed:     1, Passed:     1, Skipped:     0, Total:     2, Duration: 26 s - ClassLibrary1Tests.dll (net6.0)

이때 뜬 FineCodeCoverage의 testhost.exe에는 MicrosoftInstrumentationEngine_x64.dll과, "C:\Program Files\Microsoft Visual Studio\2022\Enterprise\Common7\IDE\Extensions\TestPlatform\Extensions\Fakes\x64\Microsoft.QualityTools.Testing.Fakes.Instrumentation.dll" 파일이 로딩된 것을 확인할 수 있습니다.

그런데 웬일인지 SetDetourProvider를 실행하지 못하고 있는 것입니다. 위의 코드가 실행되는 ".\bin\Debug\net6.0\Microsoft.QualityTools.Testing.Fakes.dll" 파일을 Reflector로 열어 보면 다음의 코드에서 오류가 발생하고 있는데요,

// Microsoft.QualityTools.Testing.Fakes.UnitTestIsolation.IntelliTraceInstrumentationProvider
// Token: 0x060000FE RID: 254 RVA: 0x0000382C File Offset: 0x00001A2C
public void Initialize()
{
    string text = this.ResolveProfilerPath();
    this.profilerModule = IntelliTraceInstrumentationProvider.LoadProfilerModule(text);
    this.setDetourProvider = LibraryMethods.GetFunction<NativeSetDetourProvider>(this.profilerModule, "SetDetourProvider");
    this.canDetour = LibraryMethods.GetFunction<NativeCanDetour>(this.profilerModule, "CanDetour");
    if (this.setDetourProvider(IntelliTraceInstrumentationProvider.detourProviderAddress) != 0)
    {
        throw new UnitTestIsolationException(string.Format(CultureInfo.CurrentCulture, FakesFrameworkResources.FailedToSetDetourProvider, text));
    }
    this.enabled = true;
}

public static T GetFunction<T>(IntPtr hModule, string functionName) where T : class
{
    return (T)((object)Marshal.GetDelegateForFunctionPointer(LibraryMethods.GetProcAddress(hModule, functionName), typeof(T)));
}

ResolveProfilerPath의 코드를 통해,

private string ResolveProfilerPath()
{
    string environmentVariable = Environment.GetEnvironmentVariable((IntPtr.Size == 8) ? "MicrosoftInstrumentationEngine_ConfigPath64_FakesInstrumentation" : "MicrosoftInstrumentationEngine_ConfigPath32_FakesInstrumentation", EnvironmentVariableTarget.Process);
    if (File.Exists(environmentVariable))
    {
        XmlReaderSettings settings = new XmlReaderSettings
        {
            DtdProcessing = DtdProcessing.Prohibit,
            XmlResolver = null
        };
        XmlReader xmlReader = XmlReader.Create(environmentVariable, settings);
        if (xmlReader.ReadToDescendant("Module"))
        {
            string path = xmlReader.ReadInnerXml();
            return Path.Combine(Path.GetDirectoryName(environmentVariable), path);
        }
    }
    ...[생략]...
    throw new UnitTestIsolationException(FakesFrameworkResources.FailedToResolveProfilerPath);
}

FakesInstrumentationProfiler_x64.config에 있는 Module 노드의 값, 즉 "Microsoft.QualityTools.Testing.Fakes.Instrumentation"을 가져오게 되고, 결국 다음의 DLL에서,

C:\Program Files\Microsoft Visual Studio\2022\Enterprise\Common7\IDE\Extensions\TestPlatform\Extensions\Fakes\x64\Microsoft.QualityTools.Testing.Fakes.Instrumentation.dll      

SetDetourProvider를 구하게 됩니다. 물론, 이 파일에는,

C:\temp> dumpbin /EXPORTS "C:\Program Files\Microsoft Visual Studio\2022\Enterprise\Common7\IDE\Extensions\TestPlatform\Extensions\Fakes\x64\Microsoft.QualityTools.Testing.Fakes.Instrumentation.dll"
...[생략]...
    ordinal hint RVA      name

          1    0 000088A0 CanDetour
          2    1 00001920 DllCanUnloadNow
          3    2 00001930 DllGetClassObject
          4    3 00001920 DllRegisterServer
          5    4 00001920 DllUnregisterServer
          6    5 00008800 SetDetourProvider
...[생략]...

해당 API 함수를 정상적으로 export 하고 있습니다. 따라서 거기까지는 완료를 했는데, 아쉽게도 this.setDetourProvider 호출에서 오류가 발생한 것입니다.

// Microsoft.QualityTools.Testing.Fakes.UnitTestIsolation.IntelliTraceInstrumentationProvider
// Token: 0x060000FE RID: 254 RVA: 0x0000382C File Offset: 0x00001A2C
public void Initialize()
{
    string text = this.ResolveProfilerPath();
    this.profilerModule = IntelliTraceInstrumentationProvider.LoadProfilerModule(text);
    this.setDetourProvider = LibraryMethods.GetFunction<NativeSetDetourProvider>(this.profilerModule, "SetDetourProvider");
    this.canDetour = LibraryMethods.GetFunction<NativeCanDetour>(this.profilerModule, "CanDetour");
    if (this.setDetourProvider(IntelliTraceInstrumentationProvider.detourProviderAddress) != 0)
    {
        throw new UnitTestIsolationException(string.Format(CultureInfo.CurrentCulture, FakesFrameworkResources.FailedToSetDetourProvider, text));
    }
    this.enabled = true;
}

여기서 IntelliTraceInstrumentationProvider.detourProviderAddress가 가리키는 주소는,

private static readonly IntPtr detourProviderAddress = typeof(IntelliTraceInstrumentationProvider).GetMethod("DetourProvider", BindingFlags.Static | BindingFlags.NonPublic).MethodHandle.GetFunctionPointer();

internal static void DetourProvider(object receiver, RuntimeMethodHandle methodHandle, RuntimeTypeHandle declaringTypeHandle, RuntimeTypeHandle[] genericMethodTypeArgumentHandles, out object detourDelegate, out IntPtr detourPointer)
{
    detourDelegate = null;
    detourPointer = IntPtr.Zero;
    if (IntelliTraceInstrumentationProvider.ProtectingContext.IsThreadProtected)
    {
        return;
    }
    using (new IntelliTraceInstrumentationProvider.ProtectingContext())
    {
        MethodBase methodBase = MethodBase.GetMethodFromHandle(methodHandle, declaringTypeHandle);
        if (methodBase.IsGenericMethodDefinition)
        {
            Type[] array = new Type[genericMethodTypeArgumentHandles.Length];
            for (int i = 0; i < genericMethodTypeArgumentHandles.Length; i++)
            {
                array[i] = Type.GetTypeFromHandle(genericMethodTypeArgumentHandles[i]);
            }
            methodBase = ((MethodInfo)methodBase).MakeGenericMethod(array);
        }
        detourDelegate = UnitTestIsolationRuntime.GetDetour(receiver, methodBase);
        if (detourDelegate != null)
        {
            detourPointer = detourDelegate.GetType().GetMethod("Invoke").MethodHandle.GetFunctionPointer();
        }
    }
}

위와 같은데, 따라서 SetDetourProvider에 저 메서드(DetourProvider)를 전달한 다음 내부에서 뭔가 동작이 있었는데 거기서 알 수 없는 오류가 발생하고 있는 것입니다. 일단, 더 이상 추적할 수 없으니, 안 되는 걸로 ^^ 종료합니다. 뭔가 잡힐 듯하다가 놓치고 마니 아쉽군요.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 4/20/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 46  47  48  49  50  51  52  53  54  55  [56]  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12235정성태6/19/202010054오류 유형: 620. Windows 10 - Inaccessible boot device 블루 스크린
12234정성태6/19/20209783개발 환경 구성: 494. NuGet - nuspec의 패키지 스키마 버전(네임스페이스) 업데이트 방법
12233정성태6/19/20209500오류 유형: 619. SQL 서버 - The transaction log for database '...' is full due to 'LOG_BACKUP'. - 두 번째 이야기
12232정성태6/19/20208425오류 유형: 618. SharePoint - StoreBusyRetryLater 오류
12231정성태6/15/202010928.NET Framework: 911. Console/Service Application을 위한 SynchronizationContext - AsyncContext
12230정성태6/15/202010269오류 유형: 617. IMetaDataImport::GetMethodProps가 반환하는 IL 코드 주소(RVA) 문제
12229정성태6/13/202012119.NET Framework: 910. USB/IP PROJECT를 이용해 C#으로 USB Keyboard + Mouse 가상 장치 만들기 [1]
12228정성태6/12/202012211.NET Framework: 909. C# - Source Generator를 적용한 XmlCodeGenerator파일 다운로드1
12227정성태6/12/202016200오류 유형: 616. Visual Studio의 느린 업데이트 속도에 대한 원인 분석 [5]
12226정성태6/11/202013471개발 환경 구성: 493. OpenVPN의 네트워크 구성 [4]파일 다운로드1
12225정성태6/11/202012474개발 환경 구성: 492. 윈도우에 OpenVPN 설치 - 클라이언트 측 구성
12224정성태6/11/202020411개발 환경 구성: 491. 윈도우에 OpenVPN 설치 - 서버 측 구성 [1]
12223정성태6/9/202014349.NET Framework: 908. C# - Source Generator 소개 [10]파일 다운로드2
12222정성태6/3/202010226VS.NET IDE: 146. error information: "CryptQueryObject" (-2147024893/0x80070003)
12221정성태6/3/20209938Windows: 170. 비어 있지 않은 디렉터리로 symbolic link(junction) 연결하는 방법
12220정성태6/3/202012400.NET Framework: 907. C# DLL로부터 TLB 및 C/C++ 헤더 파일(TLH)을 생성하는 방법
12219정성태6/1/202011507.NET Framework: 906. C# - lock (this), lock (typeof(...))를 사용하면 안 되는 이유파일 다운로드1
12218정성태5/27/202011417.NET Framework: 905. C# - DirectX 게임 클라이언트 실행 중 키보드 입력을 감지하는 방법 [3]
12217정성태5/24/20209872오류 유형: 615. Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 0, current count = 1.
12216정성태5/15/202013062.NET Framework: 904. USB/IP PROJECT를 이용해 C#으로 USB Keyboard 가상 장치 만들기 [14]파일 다운로드1
12215정성태5/12/202018116개발 환경 구성: 490. C# - (Wireshark의) USBPcap을 이용한 USB 패킷 모니터링 [10]파일 다운로드1
12214정성태5/5/202010433개발 환경 구성: 489. 정식 인증서가 있는 경우 Device Driver 서명하는 방법 (2) - UEFI/SecureBoot [1]
12213정성태5/3/202012077개발 환경 구성: 488. (User-mode 코드로 가상 USB 장치를 만들 수 있는) USB/IP PROJECT 소개
12212정성태5/1/20209765개발 환경 구성: 487. UEFI / Secure Boot 상태인지 확인하는 방법
12211정성태4/27/202012097개발 환경 구성: 486. WSL에서 Makefile로 공개된 리눅스 환경의 C/C++ 소스 코드 빌드
12210정성태4/20/202012529.NET Framework: 903. .NET Framework의 Strong-named 어셈블리 바인딩 (1) - app.config을 이용한 바인딩 리디렉션 [1]파일 다운로드1
... 46  47  48  49  50  51  52  53  54  55  [56]  57  58  59  60  ...