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

OpenCover 오픈 소스를 이용한 .NET 코드 커버리지(Code coverage)

지난 글에 이어,

C# Code Coverage 도구 - Semantic Designs 소개
; https://www.sysnet.pe.kr/2/0/2880

또 다른 code coverage 도구로 OpenCover를 소개해 보겠습니다.

Getting code coverage from your .NET testing using OpenCover.
; http://www.codeproject.com/Articles/677691/Getting-code-coverage-from-your-NET-testing-using

위의 글에 워낙 자세하게 설명이 되어 있어서 ^^; 사실 쓰기가 민망할 정도군요.




"Getting code coverage from your .NET testing using OpenCover." 글에 나온 것처럼, github 커밋을 보면 4일 전의 기록이 있는 것으로 보아 살아 있는 프로젝트가 맞는 것 같습니다.

그럼, 한번 따라해 볼까요? ^^

우선, bitbucket에서 컴파일 된 바이너리를 zip 파일로 받습니다.

opencover.4.5.3207.zip
; https://bitbucket.org/shaunwilde/opencover/downloads/opencover.4.5.3207.zip

이전에 소개해 드린 Semantic Designs 제품은 소스 코드를 직접 변경하는 반면, OpenCover는 .NET Profiler 기법을 사용해 EXE 프로세스가 실행되면서 JIT 컴파일 시에 code-coverage 용 IL 코드를 추가해 변경시켜 실행하는 제품입니다.

예제로 테스트를 직접 해보면 더 이해가 빠르겠지요? ^^ 간단하게 if 문과 메서드를 추가한 콘솔 예제를 마련하고,

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length == 2)
            {
                Console.WriteLine("Args == 2");
            }
            else
            {
                Console.WriteLine("Args != 2");
            }

            TestIt();
            Console.WriteLine("Main");
        }

        private static void TestIt()
        {
            Console.WriteLine("TestIt");
            TestIt2();
        }

        private static void TestIt2()
        {
            Console.WriteLine("TestIt2");
        }
    }
}

빌드한 후, 이 프로그램을 OpenCover.Console.exe의 인자로 전달해 실행해 줍니다.

c:\temp\ConsoleApplication1\bin\Debug>c:\temp\OpenCover.Console.exe -target:c:\temp\ConsoleApplication1\bin\Debug\ConsoleApplication1.exe -register:user -filter:+[*]*
Executing: c:\temp\ConsoleApplication1\bin\Debug\ConsoleApplication1.exe
Args != 2
TestIt
TestIt2
Main
Committing...
Visited Classes 1 of 1 (100)
Visited Methods 3 of 3 (100)
Visited Points 15 of 18 (83.33)
Visited Branches 4 of 5 (80)

==== Alternative Results (includes all methods including those without corresponding source) ====
Alternative Visited Classes 1 of 1 (100)
Alternative Visited Methods 3 of 4 (75)

ConsoleApplication1.exe 프로세스가 실행이 완료되면 results.xml 파일이 나오는데요. 이 파일은 ConsoleApplication1.exe가 구동되면서 실행된 메서드들의 코드 커버리지 결과를 XML 형식으로 담고 있습니다. 이것을 ReportGenerator 도구를 이용해 html로 변환해 볼 수 있습니다. 따라서 다음의 도구를 다운로드 받고,

danielpalme/ReportGenerator 
; https://github.com/danielpalme/ReportGenerator/releases

이렇게 실행해 주면,

c:\temp\ConsoleApplication1\bin\Debug>c:\temp\ReportGenerator.exe -reports:c:\temp\ConsoleApplication1\bin\Debug\results.xml -targetdir:coverage
Loading report 'c:\temp\ConsoleApplication1\bin\Debug\results.xml'
 Preprocessing report
 Initiating parser for OpenCover
  Current Assembly: ConsoleApplication1
Initializing report builders for report types: Html
Analyzing 1 classes
 Creating report 1/1 (Assembly: ConsoleApplication1, Class: ConsoleApplication1.Program)
 Creating summary
Report generation took 0.9 seconds

coverage 폴더 하위에 html 파일들이 생성됩니다. 그중에서, index.htm을 실행하면 다음 화면과 같이 ConsoleApplication1.exe 실행 중 코드 커버리지 된 내용을 쉽게 파악할 수 있습니다.

open_cover_1.png

멋지군요. ^^

참고로, "Semantic Designs"의 방식과 비교하면? "Semantic Designs" 제품은 소스 코드를 변경해서 빌드하기 때문에 실행시 부담이 거의 없습니다. 하지만, OpenCover는 실행 시 메서드의 IL 코드를 분석해 변경하는 .NET Profiler 기술을 사용하고 있기 때문에 동작이 좀 느립니다. 하지만, 적용 방식은 "Semantic Designs" 제품이 소스 코드의 변경이 필요하다는 점에서 "제품의 빌드 프로세스"에 참여할 필요가 있지만, OpenCover는 최종 빌드된 제품을 대상으로 하기 때문에 코드 커버리지를 원할 때만 OpenCover.Console.exe에 실어서 실행하기 때문에 더 편리합니다.




OpenCover.Console.exe는 인자로 받은 실행 파일을 구동하면서 다음과 같은 환경 변수를 전달합니다.

Cor_Enable_Profiling=1
Cor_Profiler={1542C21D-80C3-45E6-A56C-A9C1E4BEB7B8}
CoreClr_Profiler={1542C21D-80C3-45E6-A56C-A9C1E4BEB7B8}
OpenCover_Profiler_Key=DC566F4C
OpenCover_Profiler_Namespace=Local
OpenCover_Profiler_Threshold=0

이 중에서 OpenCover_Profiler_Key는 프로세스 실행시마다 달라집니다. 즉, 이 값을 기반으로 .NET Profiler(OpenCover.Profiler.dll)와 OpenCover.Console.exe 간의 통신 용 커널 핸들을 생성합니다.




마지막으로, 실행 시 다음과 같은 오류가 발생할 수 있습니다.

c:\temp\ConsoleApplication1\bin\Debug>c:\temp\OpenCover.Console.exe -target:c:\temp\ConsoleApplication1\bin\Debug\ConsoleApplication1.exe -register:user -filter:+[*]*
Executing: c:\temp\ConsoleApplication1\bin\Debug\ConsoleApplication1.exe
Args != 2
TestIt
TestIt2
Main
Committing...
No results, this could be for a number of reasons. The most common reasons are:
    1) missing PDBs for the assemblies that match the filter please review the output file and refer to the Usage guide (Usage.rtf) about filters.
    2) the profiler may not be registered correctly, please refer to the Usage guide and the -register switch.

왜냐하면, OpenCover는 소스 코드의 위치를 PDB파일과 연계해 알아내기 때문에 반드시 exe 파일과 함께 빌드 당시의 pdb 파일이 함께 위치하고 있어야 합니다. (또는 -register와 같은 옵션을 생략해도 같은 오류 메시지가 뜹니다.)




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/10/2021]

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

비밀번호

댓글 작성자
 




... 61  62  [63]  64  65  66  67  68  69  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12052정성태11/15/201911245오류 유형: 578. Azure - 일정(schedule)에 등록한 runbook이 1년 후 실행이 안 되는 문제(Reason - The key used is expired.)
12051정성태11/14/201913758개발 환경 구성: 462. 시작하자마자 비정상 종료하는 프로세스의 메모리 덤프 - procdump [1]
12050정성태11/14/201911466Windows: 165. AcLayers의 API 후킹과 FaultTolerantHeap
12049정성태11/13/201911519.NET Framework: 868. (닷넷 프로세스를 대상으로) 디버거 방식이 아닌 CLR Profiler를 이용해 procdump.exe 기능 구현
12048정성태11/12/201912358Windows: 164. GUID 이름의 볼륨에 해당하는 파티션을 찾는 방법
12047정성태11/12/201914159Windows: 163. 안전하게 eject시킨 USB 장치를 물리적인 재연결 없이 다시 인식시키는 방법
12046정성태10/29/201910119오류 유형: 577. windbg - The call to LoadLibrary(...\sos.dll) failed, Win32 error 0n193
12045정성태10/27/20199469오류 유형: 576. mstest.exe 실행 시 "Visual Studio Enterprise is required to execute the test." 오류 - 두 번째 이야기
12044정성태10/27/20199725오류 유형: 575. mstest.exe - System.Resources.MissingSatelliteAssemblyException: The satellite assembly named "Microsoft.VisualStudio.ProductKeyDialog.resources.dll, ..."
12043정성태10/27/201910459오류 유형: 574. Windows 10 설치 시 오류 - 0xC1900101 - 0x4001E
12042정성태10/26/201910815오류 유형: 573. OneDrive 하위에 위치한 Documents, Desktop 폴더에 대한 권한 변경 시 "Unable to display current owner"
12041정성태10/23/201910852오류 유형: 572. mstest.exe - The load test results database could not be opened.
12040정성태10/23/201911140오류 유형: 571. Unhandled Exception: System.Net.Mail.SmtpException: Transaction failed. The server response was: 5.2.0 STOREDRV.Submission.Exception:SendAsDeniedException.MapiExceptionSendAsDenied
12039정성태10/22/20199564스크립트: 16. cmd.exe의 for 문에서는 ERRORLEVEL이 설정되지 않는 문제
12038정성태10/17/20199152오류 유형: 570. SQL Server 2019 RC1 - SQL Client Connectivity SDK 설치 오류
12037정성태10/15/201914771.NET Framework: 867. C# - Encoding.Default 값을 바꿀 수 있을까요?파일 다운로드1
12036정성태10/14/201916100.NET Framework: 866. C# - 고성능이 필요한 환경에서 GC가 발생하지 않는 네이티브 힙 사용파일 다운로드1
12035정성태10/13/201912238개발 환경 구성: 461. C# 8.0의 #nulable 관련 특성을 .NET Framework 프로젝트에서 사용하는 방법 [2]파일 다운로드1
12034정성태10/12/201911622개발 환경 구성: 460. .NET Core 환경에서 (프로젝트가 아닌) C# 코드 파일을 입력으로 컴파일하는 방법 [1]
12033정성태10/11/201915261개발 환경 구성: 459. .NET Framework 프로젝트에서 C# 8.0/9.0 컴파일러를 사용하는 방법
12032정성태10/8/201911742.NET Framework: 865. .NET Core 2.2/3.0 웹 프로젝트를 IIS에서 호스팅(Inproc, out-of-proc)하는 방법 - AspNetCoreModuleV2 소개
12031정성태10/7/20199225오류 유형: 569. Azure Site Extension 업그레이드 시 "System.IO.IOException: There is not enough space on the disk" 예외 발생
12030정성태10/5/201915417.NET Framework: 864. .NET Conf 2019 Korea - "닷넷 17년의 변화 정리 및 닷넷 코어 3.0" 발표 자료 [1]파일 다운로드1
12029정성태9/27/201915489제니퍼 .NET: 29. Jennifersoft provides a trial promotion on its APM solution such as JENNIFER, PHP, and .NET in 2019 and shares the examples of their application.
12028정성태9/26/201911373.NET Framework: 863. C# - Thread.Suspend 호출 시 응용 프로그램 hang 현상을 해결하기 위한 시도파일 다운로드1
12027정성태9/26/20198656오류 유형: 568. Consider app.config remapping of assembly "..." from Version "..." [...] to Version "..." [...] to solve conflict and get rid of warning.
... 61  62  [63]  64  65  66  67  68  69  70  71  72  73  74  75  ...