<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tony Redondo on Medium]]></title>
        <description><![CDATA[Stories by Tony Redondo on Medium]]></description>
        <link>https://medium.com/@tonyredondodev?source=rss-4dfbfc0659f5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Gc8h1NCyXlJakuRIhBJ1KQ@2x.jpeg</url>
            <title>Stories by Tony Redondo on Medium</title>
            <link>https://medium.com/@tonyredondodev?source=rss-4dfbfc0659f5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 20:11:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tonyredondodev/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Context-based Code Coverage (now with more .NET!)]]></title>
            <link>https://medium.com/scopedev/context-based-code-coverage-now-with-more-net-d99cb48971bb?source=rss-4dfbfc0659f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/d99cb48971bb</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[code-coverage]]></category>
            <dc:creator><![CDATA[Tony Redondo]]></dc:creator>
            <pubDate>Wed, 18 Dec 2019 17:46:03 GMT</pubDate>
            <atom:updated>2019-12-18T17:46:03.063Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Context-based Code Coverage (now with more .NET!)</strong></h3><p>Nowadays when we hear the term <em>code coverage</em> we immediately think about a process, or an option/flag, in a test runner to generate a report of the code that has been executed. This report often includes a percentage of the code covered relative to the entirety of the executable code in your codebase.</p><p>To do this in .NET Core there is <strong>dotnet test — collect:”Code Coverage” </strong>command; however, it currently only works on Windows machines. If you want to do coverage in a non-Windows OS, such as those offered by most CI (Continuous Integration) providers, you have no choice but to run the test suite with a third party collector (eg. <a href="https://github.com/tonerdo/coverlet">coverlet</a>) and to add it as a dependency in your test projects.</p><p>Something else to keep in mind is that there are different reporting formats for code coverage. If you were to use the coverlet collector, for example, the default report format is <a href="https://cobertura.github.io/cobertura/">Cobertura</a>. Once you have the report, you need to use a supported viewer, or transform it to html, to see and analyze the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gThhAMlB0gmQkqZk" /><figcaption><em>Coverage report using </em><a href="https://github.com/danielpalme/ReportGenerator"><em>https://github.com/danielpalme/ReportGenerator</em></a></figcaption></figure><p>And if you’re interested in seeing the coverage of a specific file, most coverage reports and viewers allow the user to click on the filename to see the coverage within.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E1DH0WX2aGhCgaGW" /><figcaption><em>Coverage within a file</em></figcaption></figure><p><strong>The problem is hidden in plain sight</strong></p><p>By limiting their output to the lines of code and percentage of coverage, code coverage reports today provide limited value to development teams. And thus, without any analysis of the actual coverage, many questions remain unanswered: should all the code be treated the same way? Is it really essential to have 100% code coverage? Is it even feasible? If I have thousands of tests, are there any tests that overlap and/or are redundant? Is a given test testing what we are expecting it to test? In a cloud-native microservices world, what about the coverage from my integration tests or other peer services’ integration tests against mine? are these accounted for? If you’re only interested in an absolute number representing the percentage of code coverage (hint: you shouldn’t be) then the current reports may serve you well. But otherwise, these types of questions will remain unanswered.</p><blockquote>“Test coverage is a useful tool for finding untested parts of a codebase. Test coverage is of little use as a numeric statement of how good your tests are.”</blockquote><blockquote><strong>Martin Fowler<br></strong><a href="https://martinfowler.com/bliki/TestCoverage.html"><strong>https://martinfowler.com/bliki/TestCoverage.html</strong></a></blockquote><p>Unfortunately, the percentage of code coverage is often perceived as a key quality metric to focus on, and so increasing the value of said percentage has become a goal for managers and team leaders alike. This is a mistake. Not only is it relatively unimportant, there will come a time in every organization when the percentage of code coverage gets stuck or decreases. This will have a negative effect on the morale of the team, the percentage will be eventually ignored and code coverage, as a tool, will be written off as useless.</p><blockquote>“Too often, I’ve seen inflated hopes get attached to coverage: at last, here is a quantitative way to get a handle on the mess that is testing! But a year passes and the coverage tool does not bring Utopia. Therefore, it must be useless. And the testing organization lurches wildly in yet another direction.”</blockquote><blockquote><strong>Brian Marick — How to Misuse Code Coverage</strong></blockquote><p>So, what can we do to help answer some of the questions listed above and leverage code coverage as a key tool in the development process?</p><p><strong>Make it much more than just a percentage</strong></p><p>In <a href="https://scope.dev/">Scope</a> we have a feature called Code Path that shows the code that has been executed by a single test (as opposed to the whole test suite). This distinction, which may appear trivial, is actually quite transformational in understanding what each and every test is actually doing. Taking this one step further, Scope has the ability to expand code coverage from unit tests to integration tests with remote services. This would allow service owners to see code coverage contributed by <em>other service’s</em> integration tests (i.e. my service has 84% code coverage from unit tests, plus an additional 3% net new code coverage due to other services testing against mine).</p><p>To do this, Scope uses <a href="https://opentracing.io/">OpenTracing</a> (although we’re already adding support for <a href="https://opentelemetry.io/">OpenTelemetry</a>) as a distributed context mechanism. We do this by analyzing incoming requests. If the Scope agent detects that an incoming request is originating from an instrumented test, then coverage is enabled at runtime for that single request. The coverage results are then shown in the context of the test that originated the request. In other words, service-a defines a test-1 that sends a request to service-b. In the test report for test-1, you’ll see the code coverage for test-1 across service-a <strong>and </strong>service-b as the request is handled.</p><p>Why do this? This provides the <strong>full picture</strong> of what is being tested. And it is only with this level of granularity that it is possible to check if any given test is testing and behaving as expected. Can you imagine a test that hits tens or hundreds of services? Having per test coverage also gives Scope the ability to determine which tests overlap and which tests could be removed with minimal impact from your test suite. But this is just the tip of the iceberg, and we’re actively working on a number of other features that leverage granular code coverage in meaningful ways.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SywzTaKGgguZSvU3" /><figcaption><em>Code Path for the Fibonacci Algorithm in Scope</em></figcaption></figure><p><strong>Going contextual (.NET)</strong></p><p>So how do we do this? One way to achieve this is by storing the coverage information in different data collections. Those collections need to be stored in different contexts, and those contexts can be created and destroyed at runtime.</p><p>For testing, this behavior can be translated as:</p><ol><li>A test method is called.</li><li>Create a coverage session with a context to store the coverage information.</li><li>Run the test.</li><li>End the coverage session and extract the coverage information of the execution.</li><li>The test method returns.</li></ol><p>This behavior can be expanded in an ASP.NET Middleware to support coverage on-demand for integration tests as:</p><ol><li>A request is received.</li><li>Check the request header for a key to create the coverage session (coverage on-demand).</li><li>Create a coverage session with a context to store the coverage information for the request.</li><li>Invoke other middlewares in the pipeline.</li><li>End the coverage session and extract the coverage information of the execution.</li><li>The response is sent to the user and the request is ended.</li></ol><p>When a session is not started, the code should run near maximum speed (the actual numbers are in the Performance section at the end of this post).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ikq0KtkoaVs0_DIG" /><figcaption><em>Context-based coverage in a test runner execution</em></figcaption></figure><p>The biggest challenge? how to keep the context between synchronous code, asynchronous code, and thread executions. We can’t use a normal global variable because all the coverage data from multiple threads would be mixed together, and <strong>ThreadStatic</strong> or <strong>ThreadLocal</strong> are not enough for async/await methods because the continuations could also run in different threads.</p><p>Luckily for us, the Task Parallel Library (TPL) in .NET contains the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.asynclocal-1?view=netcore-3.0"><strong>AsyncLocal</strong></a> class, this type works similar to ThreadLocal, but it allows you to persist the data across the whole asynchronous flow. Unlike other languages, like golang, we can apply AsyncLocal to store the context between method calls without modifying the existing source code.</p><p>Once we had all of the pieces of the puzzle, we implemented a coverage collector by modifying the methods IL of the assemblies like this:</p><ol><li>We duplicate the method to be covered and apply a coverage reporter call over each instruction containing line number and column in the symbols.</li><li>We modify the original method by adding 5 instructions at the beginning. The first 2 checks if the coverage is enabled for the current context. If a coverage session has been created, the method calls the covered version of itself and returns the result (3 instructions). In the case where coverage is not enabled, the execution of the method continues as the original version.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iC-BwY6Kzh3cea15" /><figcaption><em>Method body in IL with the 5 instructions added</em></figcaption></figure><p>By doing this, we are able to enable or disable the coverage in runtime, and with the AsyncLocal, this switch affects only the current context of execution.</p><p><strong>Cool stuff, show me some code</strong></p><p>Ok, let’s dive into an actual implementation example, for this, you need to have the <a href="https://dotnet.microsoft.com/download">.NET Core 3.1</a> SDK installed. Let’s clone the git repo: <a href="https://github.com/tonyredondo/ContextualCoverage.git">https://github.com/tonyredondo/ContextualCoverage.git</a> and run the tests with the Scope collector:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rnK06ltC-NwSL6kQ" /><figcaption>Test suite executed using the Coverage collector</figcaption></figure><p>After running the tests, 4 new files are created with the coverage of each executed test:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/0*Sxl37tI5SnHuECGk" /><figcaption>ContextualCoverage.Tests folder with the 4 coverage json files</figcaption></figure><p>Open the <strong>coverage_WeatherTest.json</strong> file, and you will have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i4YetK11Pz6Gmqpk" /><figcaption><em>Content of coverage_WeatherTest.json</em></figcaption></figure><p>With the coverage of the test, let’s see the test source code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KB38g5lNVoyk2-4c" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c2zUJPTByhK-L5GT" /><figcaption><em>The lines covered according to the .json file are highlighted</em></figcaption></figure><p>As you can see, the coverage is working great across the async calls and multiple tests. But what about doing coverage in ASP.NET? For that, the example has a middleware to show how it can be done. If we detect a query in the request that contains the “cover” variable, we initialize a coverage session, call the next middleware, and end the session.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X01DG6-0D54ayr4Y" /><figcaption><em>ASP.NET example of coverage middleware</em></figcaption></figure><p>Because a collector can only be attached when we are running tests, we have to build and then patch the binaries to have the coverage reporting in a standalone application. To do that, the example has a basic ContextualCoverage.Processor and a run.sh file, then we run the .sh file (there is a .cmd file for Windows too).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZYfoJrBjB1Da7yCG" /><figcaption>Patching the Api binaries with the ContextualCoverage.Processor</figcaption></figure><p>With the binaries already patched, we run the ContextualCoverage.Api without rebuilding it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1tyTh9OHfEV0ttKz" /></figure><p>If we visit <a href="https://localhost:5001/weatherforecast?cover=true">https://localhost:5001/weatherforecast?cover=true</a> in a browser, we will see the current forecast for London and a coverage.json file in the root folder of the API with all the coverage data for that single request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/0*_CwF_L6huYpXaBTA" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/0*JJdI772AyqDl6iGl" /><figcaption>File created by the CoverageMiddleware</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZzU477qFw8sswTH0" /><figcaption>Content of the coverage.json file</figcaption></figure><p>Leveraging the distributed context in OpenTracing allows Scope to dynamically enable and disable coverage per request at runtime. This is great if you’re interested in collecting code coverage information from integration tests done in performance sensitive systems, like production.</p><p><strong>Performance</strong></p><p>Using the ASP.NET example, we can measure the impact of the contextual coverage algorithm. The possible scenarios to measure are:</p><ol><li><strong>No coverage at all</strong>: The ContextualCoverage.Api is compiled in release mode without patching the binaries, we comment the CoverageMiddleware in the Startup.cs so we are testing without any additional code. This is the baseline.</li><li><strong>Coverage disabled</strong>: The ContextualCoverage.Api is compiled in release mode and patched with the ContextualCoverage.Processor, we enable the CoverageMiddleware but test with an endpoint without the “cover” query in the url, so no coverage session is created.</li><li><strong>Coverage enabled</strong>: Similar to coverage disabled, but testing against an endpoint with the “cover” query in the url, so a coverage session is created and the lines being executed are reported to the coverage context.</li></ol><p>By running: <em>wrk -c 8 -d 10 -t 4 https://localhost:5001/weatherforecast</em></p><p>and: <em>wrk -c 8 -d 10 -t 4 </em><a href="https://localhost:5001/weatherforecast?cover"><em>https://localhost:5001/weatherforecast?cover</em></a></p><p>We get the following results:</p><p><strong>The results in a 13 inch MacBook Pro of late 2014 are:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b49a8e1e99126ac8a5cacb1867e68ba2/href">https://medium.com/media/b49a8e1e99126ac8a5cacb1867e68ba2/href</a></iframe><p><strong>The results in a 15 inch MacBook Pro of 2018 are:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17c3f708cfc340b66769d94889d03f53/href">https://medium.com/media/17c3f708cfc340b66769d94889d03f53/href</a></iframe><p>Using the same machine but, running:</p><p><em>wrk -c 12 -d 10 -t 6 </em><a href="https://localhost:5001/weatherforecast"><em>https://localhost:5001/weatherforecast</em></a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07aefd27e426fa2715adafc19bd0590d/href">https://medium.com/media/07aefd27e426fa2715adafc19bd0590d/href</a></iframe><p><strong>The results in a Ryzen Threadripper 2950X 16-Core Processor (Windows 10 + WSL 1), running:</strong></p><p><em>wrk -c 32 -d 10 -t 16 </em><a href="https://localhost:5001/weatherforecast"><em>https://localhost:5001/weatherforecast</em></a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f4c917885b7f612ee32a149071f1985/href">https://medium.com/media/2f4c917885b7f612ee32a149071f1985/href</a></iframe><p>It’s important to notice the similarities of both No Coverage and With Coverage Disabled results. This minor performance impact allows us to have the contextual coverage ready in production code while leaving the more significant performance impact on request only to occur when coverage is enabled. Do keep in mind that this is an initial implementation, and there’s likely room for improvement to reduce performance impact when the coverage is enabled.</p><p><strong>Final thoughts, What’s next?</strong></p><p>Scope turns tests into the insights you need to ship higher quality software more frequently. Features such as this bring development teams an unprecedented level of detail into their software tests. In our mission to build tools to solve challenges in software engineering so development teams can do more, faster, we see untapped potential in contextual code coverage.</p><p>If you’d like to see this in action, you can sign up now at <a href="http://scope.dev/">http://scope.dev</a></p><p><strong>References</strong>:</p><ul><li>TestCoverage by Martin Fowler <a href="https://martinfowler.com/bliki/TestCoverage.html">https://martinfowler.com/bliki/TestCoverage.html</a></li><li>How to Misuse Code Coverage by Brian Marick <a href="http://www.exampler.com/testing-com/writings/coverage.pdf">http://www.exampler.com/testing-com/writings/coverage.pdf</a></li><li>Code coverage should not be a management concern by Erik Dietrich <a href="https://blog.ndepend.com/code-coverage-not-management-concern/">https://blog.ndepend.com/code-coverage-not-management-concern/</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/157/0*HA9tVVqSvtWQh7c0.png" /></figure><p><em>Testing is a core competency to build great software. But testing has failed to keep up with the fundamental shift in how we build applications. Scope gives engineering teams production-level visibility on </em><strong><em>every test</em></strong><em> for </em><strong><em>every app</em></strong><em> — spanning mobile, monoliths, and microservices.</em></p><p><strong><em>Your journey to better applications through better testing </em></strong><a href="https://scope.dev/?utm_source=medium"><strong><em>starts with Scope</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d99cb48971bb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/scopedev/context-based-code-coverage-now-with-more-net-d99cb48971bb">Context-based Code Coverage (now with more .NET!)</a> was originally published in <a href="https://medium.com/scopedev">Scope</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>