public inbox for devel@edk2.groups.io
 help / color / mirror / Atom feed
* [PATCH v3 0/2] UnitTestFrameworkPkg: Add code coverage support for GCC
@ 2022-09-22  7:09 Guo, Gua
  2022-09-22  7:09 ` [PATCH v3 1/2] " Guo, Gua
  2022-09-22  7:09 ` [PATCH v3 2/2] BaseTools/Plugin: Add coverage support for Unit Test Guo, Gua
  0 siblings, 2 replies; 3+ messages in thread
From: Guo, Gua @ 2022-09-22  7:09 UTC (permalink / raw)
  To: devel; +Cc: Gua Guo

From: Gua Guo <gua.guo@intel.com>

V1: Add coverage option for GCC
V2: Add ReadMe.md for how to generate coverage report
V3: Add VS2019 and GCC code coverage support

Gua Guo (2):
  UnitTestFrameworkPkg: Add code coverage support for GCC
  BaseTools/Plugin: Add coverage support for Unit Test

 .../HostBasedUnitTestRunner.py                | 124 ++++++++++++++++++
 UnitTestFrameworkPkg/ReadMe.md                |  42 +++++-
 .../UnitTestFrameworkPkg.ci.yaml              |   2 +
 .../UnitTestFrameworkPkgHost.dsc.inc          |   3 +-
 4 files changed, 167 insertions(+), 4 deletions(-)

-- 
2.31.1.windows.1


^ permalink raw reply	[flat|nested] 3+ messages in thread

* [PATCH v3 1/2] UnitTestFrameworkPkg: Add code coverage support for GCC
  2022-09-22  7:09 [PATCH v3 0/2] UnitTestFrameworkPkg: Add code coverage support for GCC Guo, Gua
@ 2022-09-22  7:09 ` Guo, Gua
  2022-09-22  7:09 ` [PATCH v3 2/2] BaseTools/Plugin: Add coverage support for Unit Test Guo, Gua
  1 sibling, 0 replies; 3+ messages in thread
From: Guo, Gua @ 2022-09-22  7:09 UTC (permalink / raw)
  To: devel
  Cc: Gua Guo, Michael D Kinney, Sean Brogan, Bret Barkelew,
	Michael Kubacki

From: Gua Guo <gua.guo@intel.com>

In order to collect code coverage after running executable
file, generate *.gcda and *.gcno file that require by lcov tool
to generate code coverage report.

Cc: Michael D Kinney <michael.d.kinney@intel.com>
Cc: Sean Brogan <sean.brogan@microsoft.com>
Cc: Bret Barkelew <Bret.Barkelew@microsoft.com>
Cc: Michael Kubacki <mikuback@linux.microsoft.com>
Signed-off-by: Gua Guo <gua.guo@intel.com>
---
 UnitTestFrameworkPkg/ReadMe.md                | 42 +++++++++++++++++--
 .../UnitTestFrameworkPkg.ci.yaml              |  2 +
 .../UnitTestFrameworkPkgHost.dsc.inc          |  3 +-
 3 files changed, 43 insertions(+), 4 deletions(-)

diff --git a/UnitTestFrameworkPkg/ReadMe.md b/UnitTestFrameworkPkg/ReadMe.md
index e696412cb3..3c69cfdd97 100644
--- a/UnitTestFrameworkPkg/ReadMe.md
+++ b/UnitTestFrameworkPkg/ReadMe.md
@@ -60,7 +60,7 @@ you should be good to go.
 
 See this example in 'SampleUnitTestUefiShell.inf'...
 
-```
+```inf
 [Packages]
   MdePkg/MdePkg.dec
 
@@ -75,7 +75,7 @@ See this example in 'SampleUnitTestUefiShell.inf'...
 Also, if you want you test to automatically be picked up by the Test Runner plugin, you will need
 to make sure that the module `BASE_NAME` contains the word `Test`...
 
-```
+```inf
 [Defines]
   BASE_NAME      = SampleUnitTestUefiShell
 ```
@@ -361,7 +361,7 @@ RUNNING TEST SUITE: Int Safe Conversions Test Suite
 ```
 
 You can also, if you are so inclined, read the output from the exact instance of the test that was run during
-`stuart_ci_build`. The ouput file can be found on a path that looks like:
+`stuart_ci_build`. The output file can be found on a path that looks like:
 
 `Build/<Package>/HostTest/<Arch>/<TestName>.<TestSuiteName>.<Arch>.result.xml`
 
@@ -399,6 +399,42 @@ CMOCKA_XML_FILE=<absolute or relative path to output file>
 
 This mode is used by the test running plugin to aggregate the results for CI test status reporting in the web view.
 
+### Code Coverage
+
+Host based Unit Tests will automatically i enable coverage data.
+This is primarily leveraged for pipeline builds, but this can be leveraged locally using the
+lcov linux tool, and parsed using the lcov_cobertura python tool. pycobertura is used to
+covert this coverage data to a human readable HTML file. These tools must be installed
+to parse code coverage.
+
+- Windows Prerequisite
+  ```bash
+  Download and install https://github.com/OpenCppCoverage/OpenCppCoverage/tags
+  pip install pycobertura
+  ```
+
+- Linux Prerequisite
+  ```bash
+  sudo apt-get install -y lcov
+  pip install lcov_cobertura
+  pip install pycobertura
+  ```
+
+During CI builds, use the  ```CODE_COVERAGE=TRUE``` flag to generate the code coverage XML files,
+and additionally use the ```CC_HTML=TRUE``` flag to generate the HTML file. This will be generated
+in Build/coverage.html.
+
+There is currently no official guidance or support for code coverage when compiling
+in Visual Studio at this time.
+During CI builds, use the  ```CODE_COVERAGE=TRUE``` flag to generate the code coverage XML files,
+and additionally use the ```CC_HTML=TRUE``` flag to generate the HTML file. This will be generated
+in Build/coverage.html.
+
+Example
+```bash
+  stuart_ci_build -c .pytool/CISettings.py  -t NOOPT TOOL_CHAIN_TAG=VS2019 -p MdeModulePkg CC_HTML=TRUE CODE_COVERAGE=TRUE
+ ```
+
 ### Important Note
 
 This works on both Windows and Linux, but is currently limited to x64 architectures. Working on getting others, but we
diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml
index 77d51e1348..f68882e1cf 100644
--- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml
+++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml
@@ -90,6 +90,8 @@
             "pytools",
             "NOFAILURE",
             "cmockery",
+            "cobertura",
+            "pycobertura",
             "DHAVE", # build flag for cmocka in the INF
             "corthon",      # Contact GitHub account in Readme
             "mdkinney",     # Contact GitHub account in Readme
diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc b/UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc
index 4dd8d4ac67..ca46b8513a 100644
--- a/UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc
+++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc
@@ -25,7 +25,8 @@
   GCC:*_*_*_CC_FLAGS   = -D UNIT_TESTING_DEBUG=1
   XCODE:*_*_*_CC_FLAGS = -D UNIT_TESTING_DEBUG=1
 !endif
-
+  GCC:*_GCC5_*_CC_FLAGS = --coverage
+  GCC:*_GCC5_*_DLINK_FLAGS = --coverage
 [BuildOptions.common.EDKII.HOST_APPLICATION]
   #
   # MSFT
-- 
2.31.1.windows.1


^ permalink raw reply related	[flat|nested] 3+ messages in thread

* [PATCH v3 2/2] BaseTools/Plugin: Add coverage support for Unit Test
  2022-09-22  7:09 [PATCH v3 0/2] UnitTestFrameworkPkg: Add code coverage support for GCC Guo, Gua
  2022-09-22  7:09 ` [PATCH v3 1/2] " Guo, Gua
@ 2022-09-22  7:09 ` Guo, Gua
  1 sibling, 0 replies; 3+ messages in thread
From: Guo, Gua @ 2022-09-22  7:09 UTC (permalink / raw)
  To: devel
  Cc: Gua Guo, Bob Feng, Liming Gao, Bret Barkelew, Michael D Kinney,
	Sean Brogan

From: Gua Guo <gua.guo@intel.com>

For GCC, use lcov to generate Unit Test code coverage
report

For VS2019, use OpenCppCoverage to generate code
coverage report

Cc: Bob Feng <bob.c.feng@intel.com>
Cc: Liming Gao <liming.gao@intel.com>
Cc: Bret Barkelew <Bret.Barkelew@microsoft.com>
Cc: Michael D Kinney <michael.d.kinney@intel.com>
Cc: Sean Brogan <sean.brogan@microsoft.com>
Signed-off-by: Gua Guo <gua.guo@intel.com>
---
 .../HostBasedUnitTestRunner.py                | 124 ++++++++++++++++++
 1 file changed, 124 insertions(+)

diff --git a/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py b/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py
index c1eeaf2625..0b77576f3c 100644
--- a/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py
+++ b/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py
@@ -112,4 +112,128 @@ class HostBasedUnitTestRunner(IUefiBuildPlugin):
                                             "  %s - %s" % (case.attrib['name'], result.text))
                                         failure_count += 1
 
+            if thebuilder.env.GetValue("CODE_COVERAGE") == "TRUE":
+                if thebuilder.env.GetValue("TOOL_CHAIN_TAG") == "GCC5":
+                    self.gen_code_coverage_gcc(thebuilder)
+                elif thebuilder.env.GetValue("TOOL_CHAIN_TAG") == "VS2019":
+                    self.gen_code_coverage_msvc(thebuilder)
+                else:
+                    logging.info("Skipping code coverage. Only supported on GCC.")
+
         return failure_count
+
+    def gen_code_coverage_gcc(self, thebuilder):
+        logging.info("Generating UnitTest code coverage")
+
+        buildOutputBase = thebuilder.env.GetValue("BUILD_OUTPUT_BASE")
+        workspace = thebuilder.env.GetValue("WORKSPACE")
+
+        # Generate base code coverage for all source files
+        ret = RunCmd("lcov", f"--no-external --capture --initial --directory {buildOutputBase} --output-file {buildOutputBase}/cov-base.info --rc lcov_branch_coverage=1")
+        if(ret != 0):
+            logging.error("UnitTest Coverage: Failed to build initial coverage data.")
+            return 1
+
+        # Coverage data for tested files only
+        ret = RunCmd("lcov", f"--capture --directory {buildOutputBase}/ --output-file {buildOutputBase}/coverage-test.info --rc lcov_branch_coverage=1")
+        if(ret != 0):
+            logging.error("UnitTest Coverage: Failed to build coverage data for tested files.")
+            return 1
+
+        # Aggregate all coverage data
+        ret = RunCmd("lcov", f"--add-tracefile {buildOutputBase}/cov-base.info --add-tracefile {buildOutputBase}/coverage-test.info --output-file {buildOutputBase}/total-coverage.info --rc lcov_branch_coverage=1")
+        if(ret != 0):
+            logging.error("UnitTest Coverage: Failed to aggregate coverage data.")
+            return 1
+
+        # Generate coverage XML
+        ret = RunCmd("lcov_cobertura",f"{buildOutputBase}/total-coverage.info -o {buildOutputBase}/compare.xml")
+        if(ret != 0):
+            logging.error("UnitTest Coverage: Failed to generate coverage XML.")
+            return 1
+
+        # Filter out auto-generated and test code
+        ret = RunCmd("lcov_cobertura",f"{buildOutputBase}/total-coverage.info --excludes ^.*UnitTest\|^.*MU\|^.*Mock\|^.*DEBUG -o {buildOutputBase}/coverage.xml")
+        if(ret != 0):
+            logging.error("UnitTest Coverage: Failed generate filtered coverage XML.")
+            return 1
+
+        # Generate all coverage file
+        testCoverageList = glob.glob (f"{workspace}/Build/**/total-coverage.info", recursive=True)
+
+        coverageFile = ""
+        for testCoverage in testCoverageList:
+            coverageFile += " --add-tracefile " + testCoverage
+        ret = RunCmd("lcov", f"{coverageFile} --output-file {workspace}/Build/all-coverage.info --rc lcov_branch_coverage=1")
+        if(ret != 0):
+            logging.error("UnitTest Coverage: Failed generate all coverage file.")
+            return 1
+
+        # Generate and HTML file if requested.by each package
+        if thebuilder.env.GetValue("CC_HTML") == "TRUE":
+            ret = RunCmd("pycobertura", f"show --format html --output {buildOutputBase}/coverage.html {buildOutputBase}/coverage.xml --source {workspace}")
+            if(ret != 0):
+                logging.error("UnitTest Coverage: Failed to generate HTML in single package..")
+
+        # Generate and HTML file if requested.for all package
+        if os.path.isfile(f"{workspace}/Build/coverage.xml"):
+            os.remove(f"{workspace}/Build/coverage.xml")
+        ret = RunCmd("lcov_cobertura",f"{workspace}/Build/all-coverage.info --excludes ^.*UnitTest\|^.*MU\|^.*Mock\|^.*DEBUG -o {workspace}/Build/coverage.xml")
+
+        if thebuilder.env.GetValue("CC_HTML") == "TRUE":
+            if os.path.isfile(f"{workspace}/Build/coverage.html"):
+                os.remove(f"{workspace}/Build/coverage.html")
+            ret = RunCmd("pycobertura", f"show --format html --output {workspace}/Build/coverage.html {workspace}/Build/coverage.xml --source {workspace}")
+            if(ret != 0):
+                logging.error("UnitTest Coverage: Failed to generate HTML.")
+
+        return 0
+
+
+    def gen_code_coverage_msvc(self, thebuilder):
+        logging.info("Generating UnitTest code coverage")
+
+
+        buildOutputBase = thebuilder.env.GetValue("BUILD_OUTPUT_BASE")
+        testList = glob.glob(os.path.join(buildOutputBase, "**","*Test*.exe"), recursive=True)
+        workspace = thebuilder.env.GetValue("WORKSPACE")
+
+        # Generate coverage file
+        coverageFile = ""
+        for testFile in testList:
+            ret = RunCmd("OpenCppCoverage", f"--source {workspace} --export_type binary:{testFile}.cov -- {testFile}")
+            coverageFile += " --input_coverage=" + testFile + ".cov"
+            if(ret != 0):
+                logging.error("UnitTest Coverage: Failed to collect coverage data.")
+                return 1
+
+        # Generate and HTML file if requested.by each package
+        if thebuilder.env.GetValue("CC_HTML") == "TRUE":
+            ret = RunCmd("OpenCppCoverage", f"--export_type cobertura:{buildOutputBase}/coverage.xml --working_dir={workspace}/Build {coverageFile}")
+            if(ret != 0):
+                logging.error("UnitTest Coverage: Failed to generate cobertura format xml in single package.")
+                return 1
+
+            ret = RunCmd("pycobertura", f"show --format html --output {buildOutputBase}/cverage.html {buildOutputBase}/coverage.xml --source {workspace}")
+            if(ret != 0):
+                logging.error("UnitTest Coverage: Failed to generate HTML in single package.")
+                return 1
+
+        # Generate total report HTML file for all package
+        testCoverageList = glob.glob(os.path.join(workspace, "Build", "**","*Test*.exe.cov"), recursive=True)
+        coverageFile = ""
+        for testCoverage in testCoverageList:
+            coverageFile += " --input_coverage=" + testCoverage
+
+        if thebuilder.env.GetValue("CC_HTML") == "TRUE":
+            ret = RunCmd("OpenCppCoverage", f"--export_type cobertura:{workspace}/Build/coverage.xml --working_dir={workspace}/Build {coverageFile}")
+            if(ret != 0):
+                logging.error("UnitTest Coverage: Failed to generate cobertura format xml.")
+                return 1
+
+            ret = RunCmd("pycobertura", f"show --format html --output {workspace}/Build/coverage.html {workspace}/Build/coverage.xml --source {workspace}")
+            if(ret != 0):
+                logging.error("UnitTest Coverage: Failed to generate HTML.")
+                return 1
+
+        return 0
-- 
2.31.1.windows.1


^ permalink raw reply related	[flat|nested] 3+ messages in thread

end of thread, other threads:[~2022-09-22  7:09 UTC | newest]

Thread overview: 3+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2022-09-22  7:09 [PATCH v3 0/2] UnitTestFrameworkPkg: Add code coverage support for GCC Guo, Gua
2022-09-22  7:09 ` [PATCH v3 1/2] " Guo, Gua
2022-09-22  7:09 ` [PATCH v3 2/2] BaseTools/Plugin: Add coverage support for Unit Test Guo, Gua

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox