<?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[Scope - Medium]]></title>
        <description><![CDATA[Better Applications Through Better Testing - Medium]]></description>
        <link>https://medium.com/scopedev?source=rss----352ac4e6ed28---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Scope - Medium</title>
            <link>https://medium.com/scopedev?source=rss----352ac4e6ed28---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 19:53:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/scopedev" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Undefined Labs is now a part of Datadog!]]></title>
            <link>https://medium.com/scopedev/undefined-labs-is-now-a-part-of-datadog-b614f246b973?source=rss----352ac4e6ed28---4</link>
            <guid isPermaLink="false">https://medium.com/p/b614f246b973</guid>
            <category><![CDATA[datadog]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Borja Burgos]]></dc:creator>
            <pubDate>Thu, 06 Aug 2020 20:38:15 GMT</pubDate>
            <atom:updated>2020-08-06T20:38:15.152Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*02tuz2WnDrkI9DNc3GtWxw.jpeg" /></figure><p>We’re excited to announce that Undefined Labs has been acquired by Datadog!</p><p>Two years ago, we started Undefined Labs to completely rethink testing in a world rapidly shifting to the cloud.</p><p>Having experienced firsthand the transition from simple and monolithic web applications to the complex and distributed cloud-native applications of modern days, we’ve encountered organizations of all sizes dealing with the same painful issues around testing and deployment.</p><p>There’s been a lack of tooling to debug tests in microservice environments, an absence of historical understanding when it comes to testing, gross inefficiencies that lead to both bottlenecks as well as exorbitant CI costs, and no centralized and automated way to deal with test flakiness.<br>With our latest release of Scope, we’re proud to have been able to address all of these problems in a meaningful way.</p><p>After founding Undefined Labs, Datadog was one of the first services we added to our tech stack. We’ve always greatly admired the power of the Datadog platform to provide us with best-in-class production observability, as well as their ability to remain agile and innovative and to continually redefine the monitoring space.</p><p>We’re excited by the opportunity to extend Datadog’s industry-leading visibility into the software development and pre-production workflows.<br>We believe joining Datadog will accelerate our vision of helping thousands of engineering organizations operate with a better understanding of the entire software development lifecycle, from git push to production.</p><p>We’d like to extend a special thanks to all of our users and customers who have supported us and pushed us, and have provided incredible feedback in shaping our products.</p><p>In light of the acquisition, we’ll be hard at work creating an even better product and experience within the Datadog platform, with the added benefit of carrying forward all of the lessons learned while building Scope. We know many of our users are already Datadog customers, so we’ll be seeing you again very soon!</p><p>We’re not only excited about the future of what we’ll build as a part of Datadog, but also the chance to make a positive impact in Madrid, Spain. We will maintain our engineering office in Madrid, and we look forward to growing the team over time as part of Datadog.</p><p>Last but not least, we’d like to thank our investors, advisors, and friends for all of your support, advice, and mentorship over the past couple of years.<br>The entire team at Undefined Labs will be joining Datadog and we look forward to continuing the journey to build tools that solve challenges in software engineering so development teams can do more, faster.</p><p>For a peek into what this means for Datadog, you can see their announcement <a href="https://investors.datadoghq.com/news-releases/news-release-details/datadog-acquires-undefined-labs-provide-visibility-cicd">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b614f246b973" width="1" height="1" alt=""><hr><p><a href="https://medium.com/scopedev/undefined-labs-is-now-a-part-of-datadog-b614f246b973">Undefined Labs is now a part of Datadog!</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>
        <item>
            <title><![CDATA[Master is the new Prod, Devs are the new Ops]]></title>
            <link>https://medium.com/scopedev/master-is-the-new-prod-devs-are-the-new-ops-270e954388ce?source=rss----352ac4e6ed28---4</link>
            <guid isPermaLink="false">https://medium.com/p/270e954388ce</guid>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[cloud-native]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Borja Burgos]]></dc:creator>
            <pubDate>Thu, 02 Apr 2020 18:57:31 GMT</pubDate>
            <atom:updated>2020-04-02T19:17:19.009Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RGbVXn8Ugr7OlnpQ7rnKGw.png" /></figure><p>Operational concerns of shipping software and keeping production up and running have been largely automated. Ultimately, even when things go wrong, modern-day monitoring and observability tools allow engineers to triage and fix nasty bugs faster than ever before. In part due to this, engineering teams and their budgets are shifting left. With the fear of downtime in the rearview mirror and operational challenges largely at bay, businesses are investing heavily in development to increase the quality and speed at which business value is delivered. The biggest bottleneck? Your failing master branch.</p><h3>The Ops Wayback Machine</h3><p><em>The year is 2004. It’s time for deployment. You’re confident about the software you’ve written. You clear your mind, get one last sip of coffee, and get ready to deploy. Before you proceed, you open up terminals, many terminals, and tail every log file on every server that could possibly be affected. You have business metrics up and running on your second monitor. Next to it, there are infrastructure and application-level metrics. You hit the return key and proceed to deploy the latest release to a single server. Now you watch.</em></p><p><em>You scan rapidly across every terminal in your 19&#39;’ CRT monitors to identify patterns and look for discrepancies: are there any errors in the logs? Has the conversion rate changed? What’s the load on the server? Was there a change in disk or network i/o? You wait a few minutes, if everything looks good, you proceed with a second server, else you roll back to the previous release as fast as humanly possible, hoping that’ll fix whatever it is that broke.</em></p><p>While the excerpt above may sound ridiculous in this day and age, that’s how many deployments were done in the good old days of the internet after the <a href="https://en.wikipedia.org/wiki/Dot-com_bubble">Dot-com bubble</a>. Then came automation, hand-in-hand with the proliferation of “DevOps” and “microservices”. These practices were born from the ever-increasing speed and complexity of the applications being developed, a consequence of businesses’ competitive desires to deliver more value to customers, faster. Businesses could no longer afford to ship new features every 6 months; a slow release cycle represented an existential threat.</p><p>But businesses weren’t always concerned with shipping new features at all costs. If anything, that wasn’t even a priority back in the early 2000s. The biggest fear of any company running software on the internet has always been downtime (ok, maybe the second biggest fear, with a security breach being at the top). And for this reason, among others, ops teams have always had sizable budgets for tech companies to sell into. After all, anything that minimizes downtime is likely cheaper than downtime itself.</p><p>Fast-forward to today and you’ll see a <a href="https://www.youtube.com/watch?v=hZ1Rb9hC4JY">whole new world</a>. A world in which high-performing engineering organizations run as close to a fully-automated operation as possible. While every team does things a little bit differently, the sequence mimics the following: the moment a developer’s code is merged into master, a continuous integration (CI) job is triggered to build and test the application; upon success, a continuous delivery process is triggered to deploy the application in production; oftentimes this automated deployment is done in a minimal fashion, just a few nodes at a time or what’s known as a <a href="https://martinfowler.com/bliki/CanaryRelease.html">canary deployment or release</a>; in the meantime, the system, equipped with the knowledge of thousands of previous deployments, automatically performs multi-dimensional pattern matching to ensure no regressions have been introduced; at a certain degree of confidence, the system proceeds to automatically update the remaining nodes; and if there are any issues during deployment, rollbacks are automated, of course.</p><p>Automation doesn’t necessarily stop with the deployment and release of an application. More and more operational tasks are being automated. It’s now possible, and not uncommon, to automate redundant tasks, like rotating security keys or fixing vulnerabilities the moment a patch is made available. And it’s been many years since the introduction of automatic scaling to handle spikes in CPU or memory utilization, to improve response time and user-experience, or even to take advantage of discounted preemptible/spot instances from IaaS providers.</p><p>But, as anyone who has ever had to manage systems will be quick to tell you: <a href="https://medium.com/scopedev/testing-in-the-cloud-native-era-41f63a0e101b">no amount of testing</a> or automation will ever guarantee the desired availability, reliability, and durability of web applications. Fortunately enough, for those times when shit ultimately hits the fan (and it undoubtedly will), there is monitoring to help us find the root cause and quickly fix it. Modern-day monitoring tooling — nowadays being marketed as “observability” — offers fast multi-dimensional (metrics, logs, traces) analysis with which to quickly debug those pesky unknown-unknowns that affect production systems. Thanks to <em>observability</em>, in just a handful of minutes, high-performing engineering organizations can turn “degraded performance”, and other problematic production regressions, to business as usual.</p><p>The amount and complexity of the data that an engineer can rapidly process using a modern observability tool is truly astounding. In just a few keystrokes you can identify the specific combination of device id and version number that results in that troublesome backend exception, or which API endpoint is slowest for requests originating from Kentucky and why, or identify the root cause behind that seemingly random spike in memory consumption that occurs on the third Sunday of every month.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TvnYwCNVWqiXd1WkVWkNOQ.gif" /><figcaption>Using an observability service (Datadog shown) to narrow down on problematic transactions.</figcaption></figure><p>While this level of automation and visibility isn’t achieved overnight, we’re unequivocally headed this way. And it is the right path forward, as demonstrated by the adoption of these tools and processes by the world’s most innovative tech companies. And so, with operational concerns at ease, what’s next? Business value! And what’s the biggest bottleneck we’re currently facing? Failing to keep master branch green (i.e. healthy/passing CI). Let me explain.</p><h3>Keeping master green</h3><p>In terms of development, testing, and continuous integrations, the closest software engineering concept to “keeping production up” is to “keep master green”, which essentially means it’s deployable.</p><p>This is something that’s likely to strike a chord with most software developers out there. It makes sense after all; if teams are going to cut releases from master, then master must be ready to run in production. Unlike years ago, when releases were cut far and few between, the adoption of automation (CI) and DevOps practices has resulted in development teams shipping new software at a much faster rate. So fast, that high performing engineering organizations are able to take this practice to its extreme, by automatically releasing any and every commit that gets merged to master — resulting in hundreds, sometimes even thousands, of production deployments on a daily basis. It’s quite impressive.</p><p>But you might be left wondering, if you’re not continuously deploying master, and instead, you’re doing so once a week, or maybe once a month, why bother keeping master green? The short answer is: to increase developer productivity, to drive business value, and to decrease infrastructure costs. Even if you’re not shipping every commit to master, tracking down and rolling back a faulty change is a tedious and error-prone task, and more often than not requires human intervention. But it doesn’t stop there, a red (broken) master branch introduces the following problems:</p><ul><li>A red master leads to delayed feature rollouts, which themselves lead to a delay or decrease in business value and potential monetary loss. Under the assumption that CI is functioning as expected, breaking master means that a faulty or buggy code commit needs to be detected, rolled back, and debugged. And for many companies, the cost of delaying the release of a new feature, or [security] patch, has a direct correlation to a decrease in revenue.</li><li>A broken (red) master branch has a cascading negative effect that also hurts developer productivity. In most engineering organizations, new features or bug fixes are likely to start as a branch of master. With developers branching off a broken master branch, they might experience local build and test failures or end up working on code that is later removed or modified when a commit is rolled back.</li><li>A broken/failing build is also money wasted. Yes, automated builds and tests are performed precisely to catch errors, many of which are impractical to catch any other way. But keep in mind that for every failed build, there’s at least another build (often more) that needs to run to ensure the rollback works. With engineering teams merging thousands of commits every day, build infrastructure costs can no longer be disregarded — at some organizations, CI infrastructure costs already exceed those of production infrastructure.</li></ul><p>Convinced of the perils of a red master branch, you may ask yourself, what can I do to keep things green? There are many different strategies to reduce the number of times that master is broken, and when it breaks, how often it stays broken. From <a href="https://cacm.acm.org/magazines/2016/7/204032-why-google-stores-billions-of-lines-of-code-in-a-single-repository/fulltext">Google’s presubmit infrastructure</a> and <a href="http://dev.chromium.org/developers/tree-sheriffs/sheriff-details-chromium-os">Chromium’s Sheriff</a>, to <a href="https://www.dropbox.com/s/w88eccvm2gthyfk/eurosys19uber.pdf?dl=0">Uber’s “evergreen” SubmitQueue</a>, there’s no doubt that the world’s highest performing software organizations understand the benefits of keeping master green.</p><p>For those that aren’t dealing with the scale of Google, Facebook, and others their size, the most widely established, and easily automated approach is to simply build and test branches before merging to master; easy, huh? Not really. While this often works for relatively simple, and monolithic codebases, this approach falls short when it comes to testing the microservice applications of today. Given the inherent distributed complexity of microservice applications, and the rate at which developers are changing the codebase, it is often impractical (i.e. too many builds that would take too long) to run every build, not to mention running the full integration and end-to-end test suites on every commit for every branch for every service in the system. Due to this limitation, branch builds are often limited in the scope of their testing. Unfortunately, after the changes are merged and the complete test suite is executed, it is common for this approach to result in test failures. And back to square one, master is red. So what can you do?</p><h3>There’s been an outage in master</h3><p>At Undefined Labs, we spend a lot of our time meeting and interviewing software engineering teams of all sizes and maturity levels. These teams are developing systems and applications with varying degrees of complexity, from the simplest mobile applications to some of the largest distributed systems servicing millions of customers worldwide. We’ve seen an interesting new pattern emerge across several software engineering organizations. This pattern can be summarized as:</p><p><em>“Treat a failure (i.e. automated CI build failure) in your master branch as you would treat a production outage.”</em></p><p>This is not only exciting but indicative of how engineering organizations continue shifting left, further and earlier into the development lifecycle.</p><p>Most software teams already aim to “keep master green”, so what’s the difference? Traditionally, keeping master green has been on a best-effort basis, with master often failing over multiple builds across different commits, and days going by before returning to green.</p><p>As engineering teams mature, it becomes even more urgent to fix master in a timely manner. Now, if master is red, it’s a development outage, and it needs to be addressed with the utmost urgency. It is this sense of urgency and responsibility that development teams have set upon themselves to get things back to normal as quickly as possible that is truly transformative. Given the business repercussions, associated costs, and productivity losses of a failing master branch, we expect broad adoption of this pattern across engineering teams of all sizes in the near future.</p><p>Let’s take a look at some practical things you can do to keep master green:</p><h4>If you can’t measure it, you can’t improve it</h4><p>This is true for many things, and it’s particularly true here. Before setting out on a journey to improve anything, one needs to be able to answer these questions:</p><ul><li>How long does it take us to fix master when it breaks?</li><li>How often do we break master?</li></ul><p>These questions may sound familiar. Change master to “production” and these questions have well-known acronyms in the operational world. For anyone that has hung around an SRE (site reliability engineer) long enough, the terms MTTR and MTBF come to mind.</p><p>MTTR or mean time to repair/resolution is a measure of maintainability. In the context of this article, MTTR answers the question, how long does it take to fix master? MTTR starts a running clock the moment a build fails and only stops when it’s fixed. As failures continue to occur, the MTTR is averaged over a period of time.</p><p>MTBF, or mean time between failure, is a measure of reliability. In the context of this article, MTBF answers the question, how often do we break master? MTBF starts a running clock the moment a build goes from failing to passing and stops the next time a build fails. For example, for a team that breaks master once every week, the project’s MTBF will be approximately 7 days. As the project continues to experience failures, the MTBF is averaged over a period of time.</p><p>Unfortunately, until now, there’s no easy nor automated way to monitor these metrics. Few CI providers/tools provide insights into related information, and even fewer provide an API with which to more accurately calculate these metrics over time.</p><p>In Scope, we’re adding both MTTR and MTBF to our user’s service dashboards. That is, for every service for which Scope is configured, teams automatically see these values and trends tracked over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s1G3qmpuPdPnBW039sKNhA.png" /><figcaption>Scope Service Dashboard showing MTTR &amp; MTBF for Development.</figcaption></figure><p>Now that you know what “normal” is, it’s time to figure out ways to improve MTTR and MTBF, in the never-ending quest to keep master evergreen.</p><h4>MTTR — if you can’t debug it, you can’t fix it</h4><p>MTTR is a measure of maintainability: how quickly a failure can be fixed. To fix a software problem, software engineers need to understand what the system was doing at the time of the error. To do this in production, SREs and developers rely on monitoring and observability tools to provide them with the information they need in the form of metrics, logs, traces, and more to understand the problem at hand. Once the problem is well understood, implementing a fix is usually the easy part.</p><p>However, the contrast between production and development is quite stark. In CI, developers lack the detailed and information-rich dashboards of production. In CI, developers get a “build failed” notification, followed by a dump of the logs of the build. Here is an example output from a top CI provider:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aIMcqzY3Mqx8Fhi3Uz_FmA.gif" /><figcaption>Example failure output from a CI provider.</figcaption></figure><p>The problem is evident. Whereas operationally we have an endless amount of data, visibility, and infinite cardinality to probe the system and quickly understand complex production issues, when it comes to CI, developers are left in the dark, with nothing more than a log dump.</p><p>To deal with this problem, before moving to Scope, the organizations we’ve encountered had either built a custom solution, frustrated by the lack of options in the market, or were trying to jerry-rig their production monitoring tools to work for CI without much success. There are key differences between production, a long-lived system handling transactions, and CI, short-lived and fast-changing environments running unit and integration tests, that make using production tooling impractical in CI.</p><p>Teams interested in reducing the mean time to resolution in development to increase productivity, reduce CI costs, and increase business value, ought to look no further. Scope provides low-level insights into builds, with visibility into each and every test, across commits and PRs. With distributed traces, logs, exceptions, performance tracking and much, much more, teams using Scope are able to cut down their MTTR by more than 90%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CO-6xjKJeHGtPxuEN3qKhg.gif" /><figcaption>Debugging a flaky integration test using Scope.</figcaption></figure><h4>MTBF — a reliably flaky build</h4><p>MTBF is a measure of reliability: how often master breaks. After meeting with countless teams, and reviewing their CI builds, the verdict was clear: the leading cause for build failures in today’s software development teams is flakiness. If something is flaky, by definition, it cannot be reliable. As such, to increase a project’s MTBF the best thing any engineering organization can do today is to improve how flakiness is managed in a test suite and its codebase.</p><p>Lots have been written about flakiness. Most recently, Bryan Lee, from Undefined Labs, has written a <a href="https://medium.com/scopedev/how-can-we-peacefully-co-exist-with-flaky-tests-3c8f94fba166">great primer on flakiness</a>; you should read it. In this post, Bryan lists a clear set of patterns to successfully handle flakiness:</p><ul><li>Identification of flaky tests</li><li>Critical workflow ignores flaky tests</li><li>Timely flaky test alerts routed to the right team or individual</li><li>Flaky tests are fixed fast</li><li>A public report of the flaky tests</li><li>Dashboard to track progress</li><li>Advanced: stability/reliability engine</li><li>Advanced: quarantine workflow</li></ul><p>Due in part to the limited visibility into CI that most development teams have today, the way developers deal with flakiness is quite rudimentary. When a build fails, and if the developer suspects a flaky test is the reason behind it, they simply hit that retry button. Again and again, until the build passes, at which point they can proceed with their job. Not only is this wasteful, and costly, from an infrastructure perspective, it’s also highly inefficient and unproductive, as developers may be blocked while a build is taking place.</p><p>Other solutions, less rudimentary, but still largely ineffective, require manual intervention from developers to investigate builds in order to identify flakes; however, these flakes are not properly tracked, and rarely dealt with, given the overhead experienced by teams without testing visibility. Without the means to quarantine or exclude known flaky tests from builds in master, teams with flaky tests are quick to give up on any ambition to keep master green. This, of course, carries grave business consequences as the team’s ability to innovate and ship new features is hindered by their broken builds.</p><p>While this may be the case for most, there are those high-performing engineering organizations that have built internal tooling to address these challenges. Google, Microsoft, Netflix, Dropbox, among others, have built custom solutions to deal with flakiness and minimize the frequency at which master is red. The problem? These solutions are custom-built and not readily available for the rest of us.</p><p>To address this glaring problem, we’re adding flaky test management features right into Scope. Starting with flaky test detection, automatic test retries, and a dashboard to track all flaky tests. In this dashboard, teams can track every flaky test, their flaky rate, the date and commit in which the test first exhibited flakiness, as well as the most recent flaky execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x9NO29gqCp3Ztjv2l7wBcA.png" /><figcaption>Flaky Test Management in Scope.</figcaption></figure><p>Another one of the biggest struggles developers face when attempting to improve very flaky codebases and test suites are: where do I even begin? While all flaky tests may seem as good candidates for fixing, prioritization is key when dealing with flaky test suites. If you’re actively experiencing flakiness across hundreds of tests, it’ll be a futile attempt to try and fix them all. Instead, development teams should prioritize those tests that experience the highest rate of flakiness and are also the slowest to execute. Everything else being equal, these are the tests that have the most negative impact on your application and development processes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fermnUHfe1e-x9j4SlTKcA.png" /><figcaption>Scatterplot of flaky tests — top-right quadrant contains the most negatively impactful flaky tests.</figcaption></figure><h3>Our journey to the left</h3><p>At Undefined Labs we’re big believers in shifting left, and are always looking for innovative and transformative ways to improve application development. Treating master as production may still raise a few eye-brows in this day and age, but as shown in this article, there is clear business value in doing so: faster feature rollouts, increased developer productivity, and reduced costs. Similarly, once-reserved-for-production indicators like MTTR and MTBF, feel right at home as part of the development process, and provide development teams with the responsibility and accountability they need to more efficiently run their operations.</p><p>When building Scope, we often ask ourselves: what happens when you apply the modern and sophisticated tooling that we have in production to problems in development? what happens when you close the feedback loop, and use everything we know about our applications running in production to make more informed decisions during the development process? The possibilities are endless, and quite exciting! If this sounds interesting, make sure to follow and stay tuned for more coming from us very soon!</p><p>In the meantime, happy testing!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/157/1*DC09ClmlhKC-Q5aHUNyaiQ.png" /></figure><p>The way we build applications has drastically changed with the rise of DevOps, Microservices, and Cloud Native — but the pinnacle of developer testing has remained static: run every test for every commit in CI and get no visibility whatsoever when things go wrong.</p><p>We’re building <a href="https://scope.dev/?utm_source=medium">Scope</a> to give teams a modern testing platform that provides a solution to the biggest pains in testing:</p><ul><li>Debugging unit and integration tests</li><li>Identifying and managing flaky tests</li><li>Reducing time spent testing by 50–90% (leading to a dramatic decrease in CI costs)</li><li>Detecting regressions before they reach production</li><li>Keeping master green</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=270e954388ce" width="1" height="1" alt=""><hr><p><a href="https://medium.com/scopedev/master-is-the-new-prod-devs-are-the-new-ops-270e954388ce">Master is the new Prod, Devs are the new Ops</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>
        <item>
            <title><![CDATA[Working at Undefined Labs]]></title>
            <link>https://medium.com/scopedev/working-at-undefined-labs-c690acfbaec8?source=rss----352ac4e6ed28---4</link>
            <guid isPermaLink="false">https://medium.com/p/c690acfbaec8</guid>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[madrid]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[workplace]]></category>
            <category><![CDATA[startup]]></category>
            <dc:creator><![CDATA[Bryan Lee]]></dc:creator>
            <pubDate>Wed, 26 Feb 2020 19:53:42 GMT</pubDate>
            <atom:updated>2020-02-26T19:53:42.651Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*CrDjd5Twu73fozSvN5Yocw.png" /></figure><p><strong><em>Originally written by </em></strong><a href="https://twitter.com/JaVidalPe"><strong><em>Javier Vidal</em></strong></a></p><p>If you are planning to invest or work with Undefined Labs, this blog post is for you. After almost a year working as a Frontend Engineer at Undefined Labs, I’m excited to summarize how it’s been one of my best experiences working for startups.</p><p>This is my personal view of a promising startup inside the rich Spanish culture.</p><h3>The Team</h3><p>The team is led by <a href="https://twitter.com/borja_burgos">@borjaburgos</a> and <a href="https://twitter.com/fernandomayo">@fernandomayo</a>, very smart technologists with a clear vision about the future. <a href="https://www.docker.com/blog/docker-acquires-tutum/">They already sold their previous startup to Docker</a>, Tutum, and since then, they have been working on the same market, so few people in the world know the Docker environment better than these two. They are always looking at the industry, obsessed about converting ideas into business. And now they are trying to repeat the success of Tutum. Believe me, they know what they are doing.</p><p>We are only eight engineers, all talented senior developers. Not having any junior or mid-level developers is a questionable decision, but what I can say is that this is working for us. We try to build as fast as possible. Fewer people means less time communicating and organizing, so we can move and pivot quickly.</p><p>Our strength is our differences. Except for the frontend team, who are three javascript developers, the rest of our engineers code in different languages: .NET, Python, Java, Go, and Swift. This diversity in programming languages is required by the products we are building, but also a decision we made to support the multilingual systems of most engineering organizations. Since the majority of our developers work alone on their stack, it requires a high degree of responsibility and ownership. And we don’t fall into the trap of having what-is-the-best language or IDE arguments. Brie Wolfson described it as Tupertine.</p><h3>Brie Wolfson on Twitter</h3><p>1/Turpentine: Picasso said, &quot;when art critics get together they talk about Form and Structure and Meaning. When artists get together they talk about where you can buy cheap turpentine.&quot; Stripe is obsessed with turpentine.</p><p>Sometimes, having only one person resolving technical problems in each language can be painful, but it gives us a considerable perspective when dealing with a strategic decision about products.</p><p>And all of this was possible because of the hiring process. Fernando, the CTO, has tried very hard to find the best talent in Spain. He has a clear vision of the kinds of players that would aspire to form a perfect team. It should fit perfectly for the way we do technology.</p><h3>Software development</h3><p>Choosing technology is a vital decision, so we do it strategically. As we are building things from scratch, we have the freedom to choose whatever we want, with no dependencies or debt. But we also know that there are <a href="https://en.wikipedia.org/wiki/There_are_known_knowns">unknown unknowns</a> that could slow us down, so we always try to use already proven technology. Or frontend is written in React, while our backend is in Python. We use Apollo for communications, so GraphQL is our daily language.</p><p>While it’s easy to get overeager in our choices around technology, the team always grounds these decisions by holding the end-user experience as the leading priority. We always make decisions with the user in mind, careful not to add complexity that isn’t justified by the value delivered to the user. Keep it simple is our mantra. Unjustified complexity is forbidden.</p><p>The benefit of building developer tools is that we are always our first users. Dogfooding is a widespread practice in the industry, and we embrace it. It increases the sense of ownership, as you feel the wins and pains of the product directly. It’s a common occurrence to see a colleague sharing a new dogfooding case in Slack, followed by questions and suggestions on how we could improve the experience.</p><p>Another exciting prospect of building developer tools is the opportunity to impact how you and others in your profession will work. Few professions are responsible for building many of the tools they will use on a day to day basis. It can be invigorating having such a tight feedback loop, where every iteration of the product immediately enhances the way my coworkers and I work.</p><p>Dream big, everything is possible. Fernando has taught — by doing — that no matter how far you are from the Bay Area, you can still out-compete technology incumbents. An inspirational ideal that gives us the confidence to compete in a demanding market.</p><h3>The market</h3><p>We are developing tools for developers. The space for tooling is vast, so we are focusing on the CI/CD phases. Some of the hot topics at the office are observability, testing, and building.</p><p>If you want to know more about the products we have already released, check out <a href="https://undefinedlabs.com/">https://undefinedlabs.com</a>.</p><p>In the beginning, when I entered Undefined Labs, I was skeptical about the market. I thought it was all about IDEs and Plugins, which I find very boring. But the founders’ motivation surprised me. And after a couple of months, I could understand why this market has so much potential.</p><p>We are in a new promising market. As digital products evolve, so does the software behind it. The systems that power these products are getting more complex every day, so companies are spending more and more money developing, shipping, and maintaining these complex systems. On the other hand, the DevOps culture is growing fast and more and more developers are getting into the operations space. By addressing the needs of developers, your technology can reach millions of end-users.</p><p>Many of the existing solutions at our disposal are brilliant, built by the best minds in the industry. You can learn a lot by just looking inside these new products and features. To have the opportunity to compete with these minds — and do it successfully — is a very humbling and fulfilling experience.</p><p>Because the market is getting bigger, a lot of companies from small startups to big fortune 500s are entering, and it can be exciting being a part of this chaotic, fast-paced ecosystem. We usually watch the more significant industry conferences together like <a href="https://www.youtube.com/watch?v=9EoNqyxtSRM">GitHub Universe</a> and <a href="https://www.youtube.com/watch?v=7-31KgImGgU">AWS re:Invent</a>, and pay close attention to how the announcements may affect us, either immediately or down the road. It seems commonplace during these conferences that a big company announces an acquisition or the release of a new feature that makes the latest trendy tool in the market useless. The frenetic pace can seem crazy, but it gives you a sense of urgency. This adrenaline keeps us focused.</p><p>Finally, our customers are smart people. Often, they are the innovators within their larger company. They know exactly what they need, so the feedback they give is invaluable. Also, we speak the same language as our customers, so <a href="https://www.youtube.com/watch?v=mAiNdU1go1A&amp;t=2791s">the GAP between what we are building and why we are doing it</a> is drastically reduced.</p><h3>The environment</h3><p>At the time I’m writing this, there are ten of us in the company. Two of us are in the USA, handling meetings and looking for customers and partners. The developer team is in Madrid, the capital of Spain.</p><p>VC investors from Silicon Valley back the company. The difference in the average salary between Silicon Valley and Madrid is significant, which allows us to be very money-efficient while still offering the best compensation in Spain. This allows us to enjoy and live in one of the best countries in the world.</p><p>We also enjoy one of the best locations in Madrid. The office is located in the city center, near good restaurants and public transportation.</p><p>Madrid is a vibrant city. Like other capitals, it is full of young people from all around Spain striving to leave their mark. Also, it receives influences from people coming from Latin America. This makes Madrid a beautiful place to sample Spanish culture.</p><p>We have the best weather in Europe, with clear skies and a temperate climate. The summer is hot, and the winter is cold, but it never snows. If you want to go to the beach, you can take a 3h train to Valencia or Barcelona. If you prefer the mountains, you have ski resorts less than 2h by car.</p><p>We enjoy the city together. Some of the team members have lunch in the office, and others go out to have lunch daily. But altogether we go out on Friday for our team lunch.</p><p>I’m looking forward to seeing what new products or ideas we bring to life. If you are also interested, follow us on <a href="https://twitter.com/undefinedlabs">Twitter</a>, and keep an eye out for an opportunity of joining us at <a href="https://undefinedlabs.com/about-us/">https://undefinedlabs.com/about-us/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/157/0*KCWB-TJGKvqLu_Od.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=c690acfbaec8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/scopedev/working-at-undefined-labs-c690acfbaec8">Working at Undefined Labs</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>
        <item>
            <title><![CDATA[Testing strategies for modern web applications]]></title>
            <link>https://medium.com/scopedev/testing-strategies-for-modern-web-applications-71836e480cc6?source=rss----352ac4e6ed28---4</link>
            <guid isPermaLink="false">https://medium.com/p/71836e480cc6</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[static-code-analysis]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Ramón Guijarro]]></dc:creator>
            <pubDate>Fri, 21 Feb 2020 14:42:20 GMT</pubDate>
            <atom:updated>2020-02-21T14:44:21.277Z</atom:updated>
            <content:encoded><![CDATA[<h3>Testing Strategies for Modern Web Applications</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*EFwDH-ld8g1iwNkAKcQKtw.png" /></figure><h3>Why frontend testing matters</h3><p>It’s no secret that websites are nowadays more complex than ever. The last decade has seen a big shift on the web: as user expectations have changed with the rise of the smartphone, we’ve effectively transitioned from web pages mostly based on HTML and CSS to web applications driven by tons of JavaScript code. Unlike traditional document-based websites, current webapps have rich interfaces that support heavy user interaction, <a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Fetching_data">async data fetching for partial content updates</a>, <a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Client-side_storage">data caching</a> and even <a href="https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps/Offline_Service_workers">offline usage</a>.</p><p>If only because of this complexity, we should be testing our web applications to make sure that they behave as expected. As developers, we want to <a href="https://medium.com/scopedev/testing-in-the-cloud-native-era-41f63a0e101b">increase our confidence in the software we write</a>, and that’s what tests provide. But making sure our webapps work is even more important if we think about the fact that they’re the entry point to our products. It can even be argued that your webapp <strong>is</strong> your product since it’s the thing your users are actually using. When users think about your product, they think about your UI, and all they care about is accomplishing tasks through it. So how do we go about testing it?</p><h3>Interpreting the test pyramid</h3><p>From a conceptual standpoint, besides picking specific testing tools and technologies, one of the first questions that arise is at which level we need to be testing and how many tests of each kind we should be writing. The classic <a href="https://martinfowler.com/bliki/TestPyramid.html">test pyramid</a> quickly comes to mind as an answer, but let’s see how it applies to modern component-based web applications — the kind built with libraries like <a href="https://reactjs.org/">React</a> or <a href="https://vuejs.org/">Vue</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/0*43POxwpBWejylBAb.png" /><figcaption>Traditional testing pyramid, not practical for today’s applications (source: <a href="https://martinfowler.com/articles/practical-test-pyramid.html">https://martinfowler.com/articles/practical-test-pyramid.html</a>)</figcaption></figure><h4>The thin line between unit and integration</h4><p>Following the test pyramid will get us writing lots of unit tests, as those constitute its base. In our webapp context, they’re usually interpreted as testing a single component completely isolated from the rest of the tree, mocking out all of its dependencies and subcomponents. However, this kind of test doesn’t very accurately reflect how people will actually use our app.</p><p>That last statement is especially true for those who believe that a test that writes to the DOM or receives user input cannot be considered a unit test but an integration test, because there is <a href="https://en.wikipedia.org/wiki/Input/output">I/O</a> involved or <a href="https://en.wikipedia.org/wiki/Side_effect_%28computer_science%29">side effects</a> in general. But while you can call it an integration test all you want, it’s probably not the kind of integration test the pyramid is referring to, as it is not noticeably more expensive to run. And hence the advice of not writing as many of them arguably doesn’t apply.</p><p>The technologies used for unit and integration tests of components are in fact usually the same — typically, a test runner like <a href="https://jestjs.io/">Jest</a> that uses an emulated <a href="https://github.com/jsdom/jsdom">browser-like environment</a> under the hood — so sometimes the distinction between them only comes down to who you’re asking.</p><h4>End to end tests are fundamentally different</h4><p>On the other hand, end to end tests at the top of the pyramid much better reflect how users interact with the app. For web applications, these rely on tools that run your tests in an actual web browser, instead of an emulated DOM like the ones we just mentioned. This fact makes them conceptually different and forces you to test from the end user’s point of view. You can think of them as manual tests that are automated.</p><p>Historically, end to end tests have been slow, prone to flakiness, and hard to debug. However recent testing tools and frameworks, like <a href="https://www.cypress.io/">Cypress</a> or <a href="https://pptr.dev/">Puppeteer</a>, are improving all of these aspects to the point where some people are even advocating to invert the test pyramid altogether — something generally considered an antipattern — on the basis that we ought to be testing <strong>exactly</strong> what the user is experiencing.</p><p>I personally wouldn’t go as far as inverting the test pyramid, but what is definitely becoming clearer nowadays is that our webapps could benefit from raising the level at which you’d typically write tests; moving it above single isolated components. Let’s see why.</p><h3>The case for higher-level tests</h3><h4>Why classic unit testing doesn’t cut it</h4><p>Testing our components in isolation and mocking everything around them is not only a poor reflection of their real-world usage — hence not providing that much value in terms of confidence — but it almost inevitably leads to coupling our tests with their implementation details. This can get particularly bad with libraries such as<a href="https://airbnb.io/enzyme/"> Enzyme</a>, which lets developers select nodes based on component names, arbitrarily modify their internal state, and skip rendering of all children altogether with <a href="https://airbnb.io/enzyme/docs/api/shallow.html">shallow rendering</a>.</p><p>Under this approach, it’s common that making almost any change to a component will break its tests, even if its API stays the same. If end users or consumers of the component would not notice changes, why should tests fail? Also, fixing the tests will sometimes force you to basically rewrite them from scratch. This means that those tests will actually hinder your ability to refactor and will never be able to catch regressions. So what’s their value then?</p><h4>Integration tests to the rescue</h4><p>A lot of components in our applications are meant to be working in conjunction with others to form a larger component, a certain screen, or a feature. Features are what users care about and how we should measure confidence in our app. So instead of testing the individual components at the leaves of the tree — what would be usually referred to as unit testing them — look for the higher-level components that constitute true units in terms of features and test these without mocking its children. You will cover the real use case, the tests will take less effort to write and maintain, and you will be able to refactor all the subcomponents without breaking multiple tests.</p><p>To ensure that you’re testing the same way your users would use the app, it’s a good idea to rely on tools like <a href="https://testing-library.com/">Testing Library</a>, since it gives you utilities to query for nodes similarly to how users would find them. And because its queries are based on<a href="https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques"> ARIA roles</a>, testing with it will force you to improve the accessibility of your app as a bonus.</p><p>This approach allows us to write tests that closely imitate real user interactions and are resilient to changes, just as end to end tests would do, which is exactly what we want. But they have the benefit of running much faster, since they’re not using a real browser.</p><h4>The role of end to end tests</h4><p>So if we can get a similar level of confidence with integration tests, what are end to end tests good for then? An excellent use for them in our context is <a href="https://en.wikipedia.org/wiki/Smoke_testing_%28software%29">smoke testing</a>. Build processes of modern webapps have many moving pieces and involve sophisticated tools like <a href="https://babeljs.io/">transpilers</a>, <a href="https://webpack.js.org/">bundlers</a> or <a href="https://developer.mozilla.org/en-US/docs/Glossary/Polyfill">polyfills</a>, with non-trivial configurations that are often different for development and production. That means that your production build could fail whilst the development one is working fine. So a simple test that opens your webapp in a browser and checks that it loads actually gives you quite some value for little investment.</p><p>Another use case for end to end tests is to cover the happy path of your most important user flows, exercising real APIs instead of having network requests mocked — either production ones, or in testing or staging environments. These tests might seem redundant, as well as more prone to exhibit flakiness since they hit real backend services, all on top of being slower. That’s why it’s advisable not to have a ton of them and maybe only run them before a deployment or as a nightly process. But they’re still relevant since they emulate the usage of your app in the most realistic way of all automated types of testing.</p><h3>Making responsible use of mocking</h3><p>We’ve discussed an approach to tests based on emulated DOM technology that tries to get as close as possible to the benefits of end to end browser-based tests, and we’ve seen how too much mocking goes against our goals in this area. But you will still need and want to mock some things in your non-browser tests. So let’s briefly discuss what to mock and how.</p><h4>Global mechanisms</h4><p>You usually won’t want to render your whole app, but at the same time, you’ll want whatever global mechanisms you have in place to be available in your tests. This way, you can confidently rely on those in your code knowing that your tests won’t fail. For example, if you’re using React you will probably have some top-level <a href="https://reactjs.org/docs/context.html#contextprovider">context providers</a>; it can be a good idea to write mocked versions of them and mount them in all your tests.</p><p>In a similar vein, you will want some functions used across your app to always be mocked. A typical example is date formatters: if you ever change the way you format dates in your app, you don’t want to have to modify assertions in every test under the sun. You can write unit tests for those functions to check that the formatting works as expected, and then have global mocks return a constant to ignore these in the rest of your tests. Testing frameworks like Jest allow you to <a href="https://jestjs.io/docs/en/manual-mocks">define global mocks once</a> for your own modules or third party dependencies. And you can always restore the original implementation for a particular test if you need to.</p><h4>Network requests</h4><p>You will also want to mock network requests in your integration tests to ensure that they run fast and are not flaky. You can do that in exactly the same way, as long as all your requests eventually go through the same module. The key is to always encapsulate core functionality like this in reusable modules and consistently rely on them. This will not only make testing easier but improve the architecture of your application, avoiding duplication and reducing the risk of diverging implementations and duplicated errors.</p><h4>Specific components</h4><p>Finally, there are legitimate reasons to mock components in a particular test, besides top-level or global ones. For example, you might want to have actual unit tests for some core components. That’s fine, but instead of using techniques like <a href="https://airbnb.io/enzyme/docs/api/shallow.html">shallow rendering</a> to completely prevent rendering all child components — which might unknowingly hide errors from you — explicitly mock only what you need. Again, Jest makes it easy with <a href="https://jestjs.io/docs/en/mock-functions#using-a-mock-function">mock functions</a>.</p><h3>Going beyond tests with static analysis</h3><p>The easiest tests to maintain are the ones that you don’t need to write. Static analysis tools can automatically catch a lot of bugs for us, effectively saving us from writing certain kinds of tests. These tests tend to be repetitive and cumbersome, so help is even more welcomed.</p><h4>Prevent common bugs</h4><p>A common source of bugs in modern web applications is the incorrect use of components by other consumers, like forgetting to set some mandatory property, or using a mismatching value for it — e.g., a string when a number is expected. This can be addressed with mechanisms like <a href="https://reactjs.org/docs/typechecking-with-proptypes.html">PropTypes in React</a>, but these only warn you in runtime during development, if the particular component happens to be mounted, and via the browser console — so you can miss the warning anyway. A better alternative is to declare types for properties and state of components with tools like <a href="http://typescriptlang.org/">TypeScript</a> or <a href="https://flow.org/">Flow</a>, that perform static checking of the types to ensure that these issues are all caught at build time. They will also support you while making changes in your components and allow you to refactor with greater confidence.</p><p>Another relevant source of bugs in JavaScript applications is null pointer errors, such as <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cant_access_property">cannot read property <em>x</em> of undefined</a> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Not_a_function"><em>x</em> is not a function</a>. Type checkers can also help prevent these errors, as they will for example statically check if a particular key that your code is trying to access actually exists in an object. They do this based on the <a href="https://www.typescriptlang.org/docs/handbook/interfaces.html">object shapes you declare</a>, and their value is multiplied thanks to <a href="https://www.typescriptlang.org/docs/handbook/type-inference.html">type inference</a> — so you don’t need to explicitly declare types all the time. Support for <a href="https://www.typescriptlang.org/docs/handbook/advanced-types.html#nullable-types">nullable types</a> completes the deal.</p><h4>Define safe data models</h4><p>We can leverage this ability to declare our own types to make our applications safer in some other ways. For example, we can write factory functions that receive data fetched from our backend APIs and process and sanitize it, returning objects safe to use in our components — what we’d call <a href="https://en.wikipedia.org/wiki/Data_model">models</a>. And we can define custom types for the shape of these models and export them to use as prop types of our components. This can help us gracefully handle mistakes in backend responses so that our UI doesn’t break, while still being able to log custom errors to a monitoring service like <a href="http://sentry.io/">Sentry</a> to be aware of the issues.</p><p>We can go even further down this road by using tools that automatically generate type definitions for our API responses. This allows us to use the generated types directly in our components without any extra work, providing a solid safety layer. Since <a href="https://graphql.org/">GraphQL</a> has a type system at its core, APIs based on it are particularly well-suited for this. Tools like <a href="https://graphql-code-generator.com/">GraphQL Code Generator</a> can generate TypeScript and Flow types from a GraphQL schema, and next-generation systems like <a href="https://www.prisma.io/with-graphql">Prisma</a> go one step further and generate them from the database itself.</p><h3>In conclusion</h3><p>Writing tests for our web frontend code is important because it’s the part of our product that our users will be directly interacting with. We want to simulate that interaction as faithfully as possible, so browser-based tests would be the way to go, but they’re too slow to use at scale. However, we can get pretty close with non-browser based tests if we write them at a high enough level, use selectors based on accessibility roles, and make sensible use of mocking. Adding a static type checker to the mix will further increase our confidence and prevent some common bugs.</p><p>So go ahead and write some tests for your webapp. Your users will unknowingly thank you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/174/0*suyXMYjgxQ315pyQ.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=71836e480cc6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/scopedev/testing-strategies-for-modern-web-applications-71836e480cc6">Testing strategies for modern web applications</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>
        <item>
            <title><![CDATA[Introduction to Profiling and Optimizing SQL Queries for Software Engineers]]></title>
            <link>https://medium.com/scopedev/introduction-to-profiling-and-optimizing-sql-queries-for-software-engineers-3cf376ecc712?source=rss----352ac4e6ed28---4</link>
            <guid isPermaLink="false">https://medium.com/p/3cf376ecc712</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[AdrianLC]]></dc:creator>
            <pubDate>Mon, 03 Feb 2020 20:02:15 GMT</pubDate>
            <atom:updated>2020-02-04T02:46:18.867Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8jwkhnvlkvOIVoDZU21VNg.png" /></figure><p>Nowadays it is quite uncommon to have dedicated <a href="https://en.wikipedia.org/wiki/Database_administrator"><em>Database Admins</em> (DBAs)</a> on application development teams. Whether it’s the adoption of microservices architectures, cloud, or DevOps processes that is to blame, more and more development teams are now responsible for their databases. Now more than ever, solid database skills are indispensable on your path to becoming a proficient programmer.</p><p>Response-time is a key indicator of the performance of any application, and Database optimization can be one of the fastest ways to give a speed boost to your application, website or API. Learning the basics of profiling and optimizing SQL queries is actually not as hard as it might seem, and you should not feel intimidated by it. In this post, I will explain the general steps I followed with a real-world scenario I ran into recently while working on <a href="http://scope.dev/">Scope</a>. Armed with the skills described in this post, you’ll be optimizing your own database queries in no time!</p><p><em>Note: our main database is PostgreSQL and most of our backend stack is written in Python. While the concepts I cover should also be applicable to MySQL or other SQL databases, please bear in mind that all practical examples in this article will be for PostgreSQL. There will also be some recommendations or examples specific to Python.</em></p><h3>Finding slow queries to profile</h3><p>First things first, before jumping to profile any random query, we need to find a good candidate database query to profile. Slow queries are usually the best ones to start with, but profiling can be used for much more than speeding up slow queries. If there are queries that appear to be behaving erratically, or otherwise returning unexpected data, profiling will help you determine the reason for these abnormal behaviors.</p><p>There are many ways to find slow queries. From client-side instrumentation to server-side configuration, through automatic application-level monitoring or through server logs. Each has its pros and cons. Let’s take a look at some of our options:</p><h3>Database Slow Query Log</h3><p>Most SQL databases provide a <a href="https://wiki.postgresql.org/wiki/Logging_Difficult_Queries">Slow Query Log</a>, a log where the database server registers all queries that exceed a given threshold of execution time. With it enabled and configured, the database will automatically output warning messages and query information for all slow queries.</p><p>There is no prescriptive way to access these logs, and most of the usual suspects will work here. You could use <em>grep</em>, for example. But you can also get more sophisticated, and have a simple script that parses the contents of the file and notifies you via Slack.</p><p>The Slow Query Log method, while somewhat rudimentary, does have an advantage. With this method you’re getting the information directly from the source of truth, thus eliminating the need for any third-party system or component. The downside? You may experience a <a href="http://blog.symedia.pl/2016/10/performance-impact-general-slow-query-log.html">small performance hit</a>, originating from the database server having to time every query. Furthermore, keep in mind that enabling this feature does require admin privileges in the database.</p><h3>Middleware and Application Logs</h3><p>Other alternatives are application-side middlewares and application-level logging. There are many ready-made solutions for this approach. For example, a popular choice for Python and Django is the <a href="https://github.com/jazzband/django-debug-toolbar"><em>django-debug-toolbar</em></a><em>. </em>Alternatively, there also exists the option to enable <a href="https://docs.djangoproject.com/en/3.0/topics/logging/#django-db-backends">logging directly from the ORM</a>. But even simpler than this is to just add logging to the code interacting directly with the database to print or log the latency of each query. You can even mimic the behavior of the Slow Query Log, and only log the queries exceeding a given threshold of execution time.</p><p>Since these are client-side solutions, latencies include networking times. This can be advantageous. Oftentimes a slow query isn’t due to the database taking too long to resolve the given query, but instead, the slowness is due to the size of the payload. With large payloads, the bottleneck may actually be on the data transfer between the database and the application server. This is more likely to occur while using an ORM, as it may default to fetching all the columns from the database table, even when they’re all not required.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*2x79sH2fxOAh72YV" /><figcaption>Screenshot from <em>django-debug-toolbar, </em>which adds a debugging panel to your website displaying all the SQL queries with latency information. Really useful when you need to profile queries on a specific page from your website!</figcaption></figure><h3>APM and Distributed Tracing</h3><p>Last on this list is APM (Application Performance Management) and Distributed Tracing. While they aren’t one and the same, for the purpose of this article, and the value they provide in profiling database queries, I’ve decided to put them in the same category.</p><p>The way most APMs work is through a library or agent that is installed alongside your application and automatically instruments its client libraries, like http, grpc, sql, etc. to monitor and log transactions and queries.</p><p>If you are up to speed with the latest advancements in <a href="https://opentelemetry.io/">observability and distributed tracing</a>, and already have instrumentation for your application’s database queries, there are open-source distributed trace visualization tools, like <a href="https://www.jaegertracing.io/">Jaeger</a>, that can help you easily identify slow queries.</p><p>Let’s see an example of a request containing one such slow database query:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ig60ywTcW8bs1oU1" /><figcaption>Searching recent traces by duration and noticing the latency breakdown by service. In this screenshot from Datadog, the green area is time running our backend code whilst purple is time spent on resolving PostgreSQL queries.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8fJf2Ao8u9B6PU6-" /><figcaption>Detail screen of a trace for a slow request with an SQL query spanning over 10 seconds. The flame graph shows that &gt;90% of the request time was spent on a single query.</figcaption></figure><p>As you can see, with APM or tracing data, and a good service or tool for visualization, finding slow database queries to profile is actually quite easy.</p><p>In any case, no matter which method you choose, as long as you have a way to time your queries, you’re likely to find a slow query that is worth optimizing!</p><h3>Profiling a SQL Query</h3><p>Now that we’ve identified our slow query, the next step is profiling. Profiling, in the context of a SQL database generally means, <a href="https://www.postgresql.org/docs/current/sql-explain.html"><em>explaining</em></a> our query. The <em>EXPLAIN</em> command outputs details from the <a href="https://www.postgresql.org/docs/current/planner-optimizer.html"><em>query planner</em></a>, and gives us additional information and visibility to better understand what the database is actually doing to resolve the query.</p><p>You can execute this command directly from a command line shell in your database, but if you would rather avoid terminals, most database clients with a GUI also include <em>EXPLAIN</em> capabilities. Following along with the earlier example of our slow query, let’s now profile it. To do this, we simply need to pre-append the original slow query with <em>EXPLAIN ANALYZE</em>.</p><p>Attention! It’s important to understand the difference between <em>EXPLAIN</em> and <em>EXPLAIN</em> <em>ANALYZE</em>. While <em>EXPLAIN</em> will only give details about the plan, without executing the query, <em>EXPLAIN</em> <em>ANALYZE</em> actually executes the query, providing you with exact timing information under the current server load. But you need to be very careful with this, particularly on production databases. Not only could it impact performance, you could potentially modify or delete data if you are profiling an <em>UPDATE</em> or <em>DELETE</em> operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ghHXc44RHPN2_ticWCZmFg.png" /><figcaption>Public gist <a href="https://gist.github.com/AdrianLC/eaac58f4429d41deaa16a5529539bd34#file-sql-explain-sql">here</a></figcaption></figure><p>After running the EXPLAIN ANALYZE query on a PostgreSQL shell, you’ll get an output similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nhpoTo7lBBhoAFDPAFGkjQ.png" /><figcaption>Public gist <a href="https://gist.github.com/AdrianLC/eaac58f4429d41deaa16a5529539bd34#file-sql-explain-txt">here</a></figcaption></figure><p>As you can see, the output for this is quite cryptic! What does all of this mean? PostgreSQL’s <em>EXPLAIN </em>is very thorough, it really shows us everything the database knows and plans to do with our queries. As such, it is to be expected that we will not understand most things. While explaining all of the output is beyond the scope of this article, we can still learn quite a few things from it.</p><p>The first tip is that, if we want to think about the steps the database would follow with our query <em>sequentially,</em> it helps to read from the bottom upwards. This is because the output is like a break-down of operations, so the last ones are actually the first step for each parallelized block of the execution.</p><p>Also, if you are obtaining your <em>EXPLAIN</em> output from the shell, I highly recommend using an <em>EXPLAIN</em> visualization tool, I personally like <a href="https://explain.depesz.com/">this one</a>. It provides syntax highlighting and table formatting to help with legibility. You can also easily share the report with other teammates! <a href="https://explain.depesz.com/s/uaan">Here’s a link to an example query</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I_VqbN9x3_nAiyiA" /><figcaption>PostgreSQL EXPLAIN visualization <a href="https://explain.depesz.com/s/uaan">website</a>.</figcaption></figure><p><a href="https://use-the-index-luke.com/sql/explain-plan/postgresql/operations">This site</a> is also a great source to learn about what most of the operations on SQL plans are. But for this practical example, we’ll just be taking a look at two operations, <em>Seq Scan</em> and <em>Index Scan</em>:</p><ul><li><em>Seq Scan </em>is a full search on the table with the given conditions. These are usually bad because they will become slower as the data in your tables grow.</li><li><em>Index Scan </em>is using one of the indexes that exist on your table. These are usually better since the database has a shortcut to the rows that match the conditions.</li></ul><p>Most often optimizing your queries will be a matter of replacing a <em>Seq Scan </em>that is too big with an <em>Index Scan</em> by creating an index on the columns that are involved in the conditions. Thought you should know that adding indexes to your tables is not always appropriate. When adding a new index we are trading off writing performance for query speed, due to the database having to update the index when writing to the table. So you should try to have the lowest number of indexes that you can afford and only create the ones that you find unavoidable.</p><p>As we continue to debug our slow query, we can see in the visualization above that a single step in the plan is the culprit for most of the time spent resolving the query. So we should focus on these lines:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*__brbXGG2K9yjUx5krZU2Q.png" /><figcaption>Public gist <a href="https://gist.github.com/AdrianLC/eaac58f4429d41deaa16a5529539bd34#file-sql-explain-snippet-txt">here</a></figcaption></figure><p>This step in the plan is finding rows in the table <em>scope_testexecution </em>with a column <em>agent_id </em>that matches the primary key on the table scope_agent<em> </em>through<em> </em>the index called <em>scope_teste_agent_i_f352da_idx</em>. It is resolving a foreign key from one table to another. Unfortunately, it is already using an index, so that is not the issue for this specific query.</p><p>You can check what kind of index is being used on PostgreSQL. To do that we use the command <em>\d+ scope_testexecution</em>, resulting in:</p><pre>Indexes:</pre><pre>…</pre><pre>“scope_teste_agent_i_f352da_idx” btree (agent_id, fqn)</pre><p>This is not how we usually index foreign keys. The database is using a compound index on 2 columns, <em>agent_id</em> and <em>fqn</em> and we do not have a single column index on <em>agent_id</em>!</p><p>Furthermore, the <em>fqn</em> column is a varchar(1000)<em> </em>with very high cardinality (a lot of different values per agent) and the <em>EXPLAIN </em>is actually telling us that this step involves 83967 <em>heap fetches. </em>On the <a href="https://www.postgresql.org/docs/current/indexes-index-only-scans.html"><em>Index Only Scan</em></a> operation, PostgreSQL scans through the index but it stills needs access to the table storage. This area in storage where the table is stored is called the <em>heap</em>, so the number of <em>heap fetches</em> is the number of read operations from the table. In summary, the query is requiring a lot of I/O access to fetch these values from the table, and that is probably the cause for low performance.</p><p>We could decrease the size of the data that PostgreSQL needs to resolve this condition if we had a single column index on agent_id. Having a dedicated index for each foreign key is the standard set up, usually autogenerated by ORMs or framework tooling, but in this case, it’s missing.</p><h3>Testing an optimization</h3><p>Now that we have an idea of what to change, we can experiment and see if the query performs better. It is better to do this on a testing or staging database when possible since it will involve altering our indexes and there’s always the chance we’re wrong, potentially affecting our production database.</p><p>It’s likely that you have a mechanism in place to change your database schema; these are usually called <a href="https://en.wikipedia.org/wiki/Schema_migration">database or schema migrations</a>. Schema changes should involve code reviews, as well as be part of a continuous integration process to be tested and validated.</p><p>While this isn’t the best way to debug, unfortunately, we cannot test this kind of change on a development machine, since we need data resembling the actual size of the production database. With this in mind, a trick I’ve used to get past this limitation is to make our changes within a transaction itself. PostgreSQL allows transactional changes to indexes and table structures, which comes in handy for our use case:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fsUR7FQKwbp4koO6J8GDdw.png" /><figcaption>Public gist <a href="https://gist.github.com/AdrianLC/eaac58f4429d41deaa16a5529539bd34#file-optimization-create-index-sql">here</a></figcaption></figure><p>With this change, we can actually test a different plan for our query without affecting how it currently works for other transactions, and if we were to be wrong, nothing is affected; we can simply undo the index through a quick <em>ROLLBACK</em>!</p><p>Let’s try this out. The next step is to profile the query again, and to use our visualizer to see the report and compare to the previous results we obtained:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dkJLzAD6wbzEu05y" /><figcaption>Visualization of the <em>explain</em> after our new index optimization. Public link <a href="https://explain.depesz.com/s/Qxq6">here</a>.</figcaption></figure><p>As you can see in the screenshot above, the same query now takes just over a second. Remember it initially took over 10 seconds! Our optimization, creating a separate index for <em>agent_id</em>, has been successful!</p><p>You may be curious as to why we did not have the standard index for the foreign key on the <em>agent_id</em> column. It turns out that in previous iterations of our product, the table <em>scope_testexecution</em> was being used on several queries that aggregated results. Because of this, we had more queries with <em>GROUP BY</em> on <em>agent_id, fqn</em> than we did directly accessing it. That index was necessary at the time. Fortunately, things have changed since then and we can now revert back to using the standard index.</p><h3>Conclusion</h3><p>Optimization of SQL queries may be daunting at first, but it is fascinating and within every developer’s reach. Hopefully, this post has helped demonstrate that there are easy optimizations you can do today, such as proposing the addition of a missing index.</p><p>But even if you’re just getting started with databases, you can already help your team by identifying slow queries and providing the output of <em>EXPLAIN</em> to help debug issues — they will surely appreciate it!</p><p><em>Scope can help you identify slow SQL queries in testing before they ever make it to production!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/193/0*U0pSX6D8v1FM2pgq.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=3cf376ecc712" width="1" height="1" alt=""><hr><p><a href="https://medium.com/scopedev/introduction-to-profiling-and-optimizing-sql-queries-for-software-engineers-3cf376ecc712">Introduction to Profiling and Optimizing SQL Queries for Software Engineers</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>
        <item>
            <title><![CDATA[Limitations of xUnit in Cloud Native Testing]]></title>
            <link>https://medium.com/scopedev/why-nobody-cares-about-xunit-bba97f4be044?source=rss----352ac4e6ed28---4</link>
            <guid isPermaLink="false">https://medium.com/p/bba97f4be044</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[cloud-native]]></category>
            <dc:creator><![CDATA[Daniel Rodríguez]]></dc:creator>
            <pubDate>Mon, 13 Jan 2020 16:29:14 GMT</pubDate>
            <atom:updated>2020-01-13T16:34:31.257Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M_6VvAuVl1c8l_4jc8cFIQ.png" /></figure><p>xUnit is the name used for the collection of test frameworks loosely based on the original Smalltalk Test Framework, proposed by Kent Beck in 1998, and later popularized by <a href="https://junit.org/junit5/">JUnit</a>. While it has become common nowadays, the idea of systematically checking an application’s correctness in code (e.g. a test) was quite novel at the time.</p><p>Another revolutionary idea in those days was the concept of Continuous Integration: every developer merging code on a recurring basis to ensure everything was working as expected. And to help them check for correctness and identify potential regressions, teams leveraged these testing frameworks to test their applications during the continuous integration flow.</p><p><em>But if you stop to think about it, we are talking about practices that were introduced somewhere between 20 and 25 years ago!</em></p><p>With regard to CI, there is no shortage of options nowadays, from free and open-source solutions to commercial SaaS and on-premise products. And with the adoption and proliferation of Docker and containers, it is really easy for developers to run their custom tech stacks on any CI provider. But at the end of the day, CI services are still predominantly dumb runtimes, where a developer can define what to run, but the CI doesn’t actually understand what is being executed. And it is only due to “<em>standardization”</em> around the xUnit XML format that some CI tools are able to parse and report on test data.</p><h4>xUnit has failed to evolve for the cloud native world</h4><p>But in the era of cloud native applications, innovation in testing has been stuck in a seemingly alternate universe where XML is the pinnacle of testing innovation. There are sophisticated engineering organizations running thousands of tests at planet scale, and they’re still generating XML reports and uploading them to their CI or reviewing them with a text editor.</p><p>Furthermore, there is no XML schema standard to represent this report – every vendor has freedom in how they define their schema, which may have varying levels of compatibility with the most popular CI’s. All of this only to see a summary of your passing and failed tests. It makes no sense.</p><p>While this way of testing was sufficient when we only had unit tests, it falls predictably short with current software engineering needs that emphasize integration with other services. Suites of integration tests are now a must-have to reduce the risk of deploying bugs into production. As a matter of fact, <a href="https://blog.usejournal.com/lean-testing-or-why-unit-tests-are-worse-than-you-think-b6500139a009">Lean Testing</a>, a modern testing philosophy, questions the validity of the traditional <a href="https://martinfowler.com/bliki/TestPyramid.html">testing pyramid</a> and instead advocates for more integration tests, and fewer unit tests — resulting in the “Testing Trophy”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*PW0wMKOY4DamEsK6mRYxew.png" /><figcaption>Testing trophy by Kent C. Dodds</figcaption></figure><h4>xUnit only provides superficial insights</h4><p>XML test reports are insufficient to understand what is happening under the hood. Yes, the reports show when a test has failed, but developers won’t know the type of test (unit? integration? benchmark? end-to-end? other?) and if it is an integration test, to which services it is integrating to, or which versions are running, or in which environment. Is a test failing due to a code change or a config change? Or is it failing because of a dependency? With today’s XML reports, we simply cannot figure out the answer to these and many other questions. And consequently, developers end up spending more time trying to understand the problem than fixing it.</p><h4>Observability in testing: a must-have in a cloud native world</h4><p><a href="https://medium.com/scopedev/what-happened-to-tests-9af43b1bc2be">Leveraging observability patterns in our integration tests</a>, we cannot only start providing reliable information about what services are touched by our tests, but we could also <a href="https://medium.com/scopedev/testing-in-the-cloud-native-era-41f63a0e101b">start executing controlled tests in production</a>. Modern production observability tools give developers the visibility they need to understand complex systems, but why wait until production to actually understand how our applications are behaving? Given a choice, every developer would much rather catch a bug before it ships to production, <a href="https://medium.com/scopedev/testing-in-the-cloud-native-era-41f63a0e101b">where the cost is always much greater.</a> Yet, developers lack the tools to efficiently do this with today’s modern applications.</p><p>It’s now clear that with the proliferation of containers, serverless, Kubernetes, and cloud native, both the way we develop and the applications we develop have changed. But developers are struggling to properly test and debug these new applications with the current tools at their disposal. Testing and testing frameworks need to evolve to understand better what is happening in our tests. As is, current methods for debugging integration tests are unreliable, time-consuming, requires a high level of expertise, and don’t always lead to resolution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/193/1*xYv0oMQNQikyluNvN4EBig.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=bba97f4be044" width="1" height="1" alt=""><hr><p><a href="https://medium.com/scopedev/why-nobody-cares-about-xunit-bba97f4be044">Limitations of xUnit in Cloud Native Testing</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>
        <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----352ac4e6ed28---4</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>
        <item>
            <title><![CDATA[Announcing ctr.run]]></title>
            <link>https://medium.com/scopedev/announcing-ctr-run-710d4c881ccf?source=rss----352ac4e6ed28---4</link>
            <guid isPermaLink="false">https://medium.com/p/710d4c881ccf</guid>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[buildkit]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Fernando Mayo]]></dc:creator>
            <pubDate>Wed, 04 Dec 2019 20:40:32 GMT</pubDate>
            <atom:updated>2019-12-09T18:59:52.895Z</atom:updated>
            <content:encoded><![CDATA[<h3>Announcing ctr.run: on-demand Docker builds</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bWrEFjNOMDnNetOsKnF84Q.png" /></figure><p>At <a href="https://undefinedlabs.com/">Undefined Labs</a>, we’re building tools to solve challenges in software engineering so development teams can do more, faster. Being developers ourselves, we often find inspiration for new products in the problems that we face while building other solutions. This is how <a href="http://ctr.run/">ctr.run</a> (aka container-run) was born.</p><h4>Why ctr.run?</h4><p>We built <a href="http://ctr.run/">ctr.run</a> to stop wasting time and money building, pushing, and storing container images that <strong>never</strong> get used – think about all those images being built as part of CI on every commit “just in case”. To speed up <strong>all</strong> container builds with automatically configured caching and parallelism that works everywhere: locally, across CI providers, and container runtimes. And to eliminate the guesswork of what tag to pull to see the latest changes in master or a feature-branch.</p><p>Using <a href="http://ctr.run/">ctr.run</a> is easy, simply docker pullor docker run the git commit you need when you need it. You can try it out now with any public git repository, for example:</p><pre>$ docker run ctr.run/github.com/undefinedlabs/hello-world:master</pre><p>and just like that, this is what you get out of the box:</p><ul><li>Automatic build caching</li><li>Parallel build step execution</li><li>CDN-based edge caching</li><li>Git-inherited authorization</li><li>On-demand builds</li><li>Works with Kubernetes and other container runtimes</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v5P3m-Yn7HKjKRPdw8NLfQ.png" /></figure><p><a href="http://ctr.run/">ctr.run</a> works as a “virtual” docker image registry, where container image repositories map to git repositories. Container image repository names are built by prepending ctr.run/ to the git repository URL, and by using a git reference (a branch, a tag, or a commit hash) as the image tag:</p><pre>ctr.run/&lt;git repository URL&gt;[/path]:(branch|tag|commit hash)</pre><p>In the example above, running:</p><pre>$ docker run ctr.run/github.com/undefinedlabs/hello-world:master</pre><p>will build the latest commit of the <em>master</em> branch of the <a href="https://github.com/undefinedlabs/hello-world">https://github.com/undefinedlabs/hello-world</a> repository at the time of the command execution, and then serve the resulting image.</p><p>The tag latest always points to the tip of the master branch. <a href="http://ctr.run/">ctr.run</a> will always check for updates in the git repository, but don’t worry, because it will also use the cache automatically, avoiding rebuilds if nothing changed.</p><p>If you want to build a subdirectory of your git repository, just append it to the end of the image name:</p><pre>$ docker run ctr.run/github.com/docker-library/redis/5.0:master</pre><p>This will build <a href="https://github.com/docker-library/redis/tree/master/5.0">https://github.com/docker-library/redis/tree/master/5.0</a>. Pretty straightforward, right?</p><p>Because <a href="http://ctr.run/">ctr.run</a> acts as a regular docker image registry, you can use it on any platform that runs container images, for example, in Kubernetes. Just use the ctr.run/... image name in your pod spec and that’s it!</p><p>If your git repositories are private, just log into <a href="http://ctr.run/">ctr.run</a> with your GitHub, Bitbucket or GitLab credentials, and use the provided username and password to authenticate your docker client. This way, when you pull an image using those credentials, your git credentials will be used to access the source code to be built. <strong>No need for separate authorization mechanisms.</strong></p><p>Under the hood, <a href="http://ctr.run/">ctr.run</a> uses <a href="https://github.com/moby/buildkit">BuildKit</a>, an amazing open source project that enables efficient container image builds by providing concurrent dependency resolution and automatic instruction caching. You should <a href="http://github.com/moby/buildkit">check it out</a>!</p><h4>Try it out RIGHT now!</h4><p><a href="http://ctr.run/">ctr.run</a> is currently available as a public and free alpha release. It works with any public GitHub, Bitbucket or GitLab repository without authentication, and if you sign up, you can also use it for private repositories. Try it out today, and never <em>build</em> another docker image locally ever again!</p><pre>$ docker run -it ctr.run/github.com/docker/doodle/cheers2019:master</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*46IX_pCh83Wuy4NY6gOEig.gif" /></figure><p>We hope <a href="http://ctr.run/">ctr.run</a> helps you and your team ship faster by removing unnecessary steps on your CI/CD pipeline. Let us know what you think!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=710d4c881ccf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/scopedev/announcing-ctr-run-710d4c881ccf">Announcing ctr.run</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>
        <item>
            <title><![CDATA[A Modern Approach to Manual Testing]]></title>
            <link>https://medium.com/scopedev/a-modern-approach-to-manual-testing-82d4005c620?source=rss----352ac4e6ed28---4</link>
            <guid isPermaLink="false">https://medium.com/p/82d4005c620</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Juan Fernández]]></dc:creator>
            <pubDate>Wed, 04 Dec 2019 16:01:02 GMT</pubDate>
            <atom:updated>2019-12-11T19:51:32.957Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1fYbPC5ENyGl8ata91fBqg.png" /><figcaption>Bridging the gap between Dev and QA.</figcaption></figure><h3>Setting the stage</h3><p>We’ve all seen it, the bigger an organization gets, the more difficult it becomes to have meaningful and efficient communication between teams. This is particularly apparent when incentives are misaligned. Often, development teams are incentivized to build as much as possible in the shortest time possible. On the other hand, QA teams are incentivized to reduce the inherent risk in a codebase/application to an acceptable degree. The problem is obvious: whereas development teams optimize for speed, QA teams optimize for correctness. This misalignment of incentives results in frustration and burnout between and within these teams.</p><p>This inherent friction between development and QA teams is most acute when finding a bug. At that time, QA professionals prioritize having said bug fixed. In contrast, developers get conflicted between shipping a new feature in a timely manner, or delaying it in exchange for a bugfix, which could take five minutes or five weeks to implement, and has no clear ROI.</p><p>While an argument could be made that the right culture could [potentially] prevent this, our experience having talked to hundreds of organizations is that, more often than not, teams with competing incentives behave this way.</p><h3>The state of affairs</h3><p>Let’s take a look at what happens today, at any given organization, when QA finds a bug in an application. For the sake of this post, let’s pretend this is an e-commerce application.</p><ol><li>QA contacts the developer or development team <em>supposedly</em> responsible for the fix. They do this on a communications tool like Slack, or by creating an issue on a tracker like Jira.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F1_UBK6DnbDyKXgX" /></figure><p>2. The QA professional then proceeds to talk with the “Checkout Dev Team.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_dAtWesgd9GRasEs" /></figure><p>3. QA is left confounded and unsure of how to proceed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*A5442di6_E4SY6Sv" /></figure><p>What would follow is a back and forth between the QA and development teams struggling to reproduce the issue across different development environments, while sharing screenshots and recordings, and trying to fish for the appropriate logs of the apparent issue at hand. All of this while banging their heads against the wall, because the problems only show up under seemingly random circumstances that cannot be determined. On top of it all, it’s likely that after days with this issue lingering and bouncing around JIRA, not one development team confidently claimed ownership of the fault, let alone is working on a fix.</p><p>This sequence of events happens even in the most dedicated and collaborative organizations with robust processes in place. The problem is the depth and complexity of the software applications that we’re developing these days. Correctly identifying what team, microservice, configuration, or transaction is at fault for any given issue, and quickly debugging it to find a proper solution is one of the most difficult challenges in modern-day software engineering.</p><h3>Can we do better?</h3><p>Of course, we can! But before I show you how, let me introduce myself: I’m Juan, and I work as a Software Engineer at Undefined Labs. We work on developer tools, and we believe it’s time to fundamentally change the way testing and development teams collaborate, and significantly improve how organizations test their applications. In this post, I’d like to show you the power of <a href="http://scope.dev/">Scope</a> for manual web-based testing.</p><p>To explain our approach better, let’s revisit our previous scenario, this time with Scope:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6PhD_-dpP1-uMl4e" /><figcaption>QA can provide a deep link to the test report for Developers to analyze.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1ll9QywOvi1CR8BF" /><figcaption><em>All reports in Scope include a trace showing the transaction recorded during the execution of the test.</em></figcaption></figure><p><em>The verdict:</em> screenshots and logs, while handy, are hardly sufficient to deal with most of the issues a development team will face any given day in today’s modern applications. With Scope, we’re making it trivially easy for QA teams to provide their development teams with the rich and in-depth visibility they need to fix any manual test and any bug. Let’s see how.</p><h3>Introducing Scope for Chrome</h3><p>When we set out to build Scope, we mainly set out to solve problems for developers. And while developers are ultimately responsible for fixing a bug, we saw in Scope the potential to build a bridge between QA and development teams. Scope for Chrome is our first step towards building this bridge.</p><p>Whereas many of the frameworks, SDKs, and agents for testing we’ve built to date cater to developers, it was clear early on that the needs and tools of a QA are quite different. With Scope for Chrome, we wanted to build the easiest way for anyone to create meaningful manual browser tests. As such, the only requirement to use Scope for Chrome is to (1) install our browser extension, and (2) know how to use a web browser.</p><p>It really is that easy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JBuK49QxjvfyNiUe77F2nQ.gif" /><figcaption>Performing a manual test using Scope for Chrome</figcaption></figure><p>After anyone records a manual test using Scope for Chrome, a report is generated automatically. This test report includes:</p><ul><li>User actions like clicks or keyboard strokes.</li><li>HTTP requests with their headers and payloads.</li><li>Responses by the backend and even database queries being fired as a result of the request.</li><li>Console logs.</li><li>Exceptions.</li></ul><p>Finally, every manual test comes with a detailed report, including everything a developer would want to see when trying to debug any given regression. And best of all, it eliminates the need to try to reproduce the issue at hand. There is also no “what browser were you using?” or “what user were you logged in as?” Everything you need to understand the problem is in a single pane of glass. And it is easier than ever to know what team is best suited for the fix, or what service is at fault.</p><h3>How it works</h3><p>Simply put: when a user clicks on the “Start Recording” button, <a href="https://home.undefinedlabs.com/goto/scope-for-chrome">Scope For Chrome</a> starts listening and recording everything happening within your current tab.</p><p>In more detail, to accomplish this, our effort is threefold:</p><ul><li>Listen to and record user events such as mouse clicks, keyboard strokes, and exceptions happening within the tab.</li><li>Monkey patch <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest">XHR</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch">fetch</a> by injecting code to the tab under test. Each request creates a new span (“individual unit of work” as per <a href="https://opentracing.io/docs/overview/spans/">OpenTracing terminology</a>) that then propagates to the backend.</li><li>Listen to <em>main_frame</em> requests (a document that is loaded for a top-level frame). This is the first request that your browser does when going to a new page. For this, we use the <a href="https://developer.chrome.com/extensions/webRequest">webRequest extension API</a>.</li></ul><p>Of course, this is just a glimpse at what Scope for Chrome does. None of it would have been possible without the work behind our <a href="https://docs.scope.dev/docs/javascript-installation">javascript agent</a>, our other agents (<a href="https://docs.scope.dev/docs/python-installation">Python</a>, <a href="https://docs.scope.dev/docs/ios-installation">iOS</a>, <a href="https://docs.scope.dev/docs/dotnet-installation">.NET</a>, <a href="https://docs.scope.dev/docs/java-installation">Java</a>, <a href="https://docs.scope.dev/docs/go-installation">Golang</a>), our backend capable of ingesting and processing test data and distributed traces, and our purpose-built web UI to display tests in an interactive and structured way.</p><p><em>P.S. Check out the Technical Addendum below for more information.</em></p><h3>What’s next?</h3><p>With the ever-increasing complexity of modern software comes bigger, more sophisticated software teams. In the same way teams work to improve the interfaces between distributed services, we should improve how we collaborate and communicate between teams. We believe <a href="https://home.undefinedlabs.com/goto/scope-for-chrome">Scope for Chrome</a> can help alleviate the most frustrating problems associated with the lack of visibility in manual testing, and help bridge the gap between QA and Dev.</p><p>You can learn more about <a href="https://home.undefinedlabs.com/goto/scope-for-chrome">Scope for Chrome here</a>.</p><h3>Technical Addendum: technical challenges faced while building Scope for Chrome.</h3><h4>1. Monkey patching is hard</h4><p>For those that haven’t dwell into the world of monkey patching, it is <a href="https://www.audero.it/blog/2016/12/05/monkey-patching-javascript/">a technique to add, modify, or suppress the default behavior of a piece of code at runtime without changing its original source code</a>.</p><p>For example, consider a class with a method <strong>get_value</strong>. Suppose this method does a database query when being called. Imagine you are now unit testing your class: you may not want to do an actual database query, so you dynamically replace <strong>get_value</strong> by a stub that returns some mock data.</p><p>This can be extended to other uses. For example, in a web application, you might want to substitute <strong>console.log</strong> by a function that not only logs a message but also adds the date at which the function was called.</p><p>Here’s an example:</p><pre>const log = console.log</pre><pre>console.log = function() {</pre><pre>  log.apply(console, [new Date().toISOString(), ...arguments])</pre><pre>}</pre><p>Basic monkey patching of <strong>window.fetch</strong> is simple (note that this is just an example and is not prepared to be production code):</p><pre>const oldFetch = window.fetch</pre><pre>window.fetch = (...args) =&gt; {</pre><pre>   // do something here<br>   return oldFetch(...args)</pre><pre>}</pre><p>Things get more interesting when you want to do async stuff in there, like communicating with a <a href="https://developer.chrome.com/extensions/background_pages">background script</a>:</p><pre>const oldFetch = window.fetch</pre><pre> window.fetch = (...args) =&gt;</pre><pre>  new Promise(resolve =&gt; {</pre><pre>   asyncCommWithBackground().then(newRequestInfo =&gt; {</pre><pre>    const newFetchArgs = [...args, ...newRequestInfo]</pre><pre>    resolve(oldFetch(...newFetchArgs))</pre><pre>   })</pre><pre>  })</pre><p>This pattern is quite powerful. But with great power comes great responsibility. By monkey patching, we are slowing every request in the active tab down by however long <em>asyncCommunicationWithBackground </em>takes to resolve.</p><p>And here’s an example of doing <em>something</em> with the result of the fetch:</p><pre>window.fetch = (...args) =&gt;</pre><pre> new Promise(resolve =&gt; {</pre><pre>  asyncCommWithBackground().then(newRequestInfo =&gt; {</pre><pre>   const newFetchArgs = [...args, ...newRequestInfo]</pre><pre>   resolve(oldFetch(...newFetchArgs)).then(fetchResult =&gt; {</pre><pre>    // do something with fetchResult</pre><pre>    return fetchResult </pre><pre>   })</pre><pre>  })</pre><pre> })</pre><pre>}</pre><p>You can simplify the code a bit with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function">async/await</a>, but you have to be careful. You probably want to know if your fetch has failed, for which you would use try/catch. But if you do that, you would stop exceptions from propagating to the consumer, which is a scenario you’d want to avoid. The most important thing to remember here is: monkey patching done right should be transparent.</p><p>To do something with the response data, like adding it to the span as tag or metadata, you need to be careful with <a href="https://developer.mozilla.org/en-US/docs/Web/API/Response/clone">cloning</a> your response before, as it is a stream and can only be consumed once.</p><p>If you want to dig a bit deeper into this pattern, we have set up a repository with a <a href="https://github.com/juan-fernandez/monkeypatch-example-scope">small project of a functioning chrome extension</a> that delays all your <em>fetch</em> requests. The pattern is highlighted <a href="https://github.com/juan-fernandez/monkeypatch-example-scope/blob/master/background.js#L16-L26">here</a>.</p><p>An alternative to this solution is to use the <a href="https://developer.chrome.com/extensions/webRequest">webRequest API</a> with hooks like <em>onBeforeSendHeaders</em>, but as of now, this API does not allow the capture of response payloads, which was a requirement for Scope.</p><h4>2. Monkey patching in a browser is even harder</h4><p>As it turns out, if you want to affect the <em>window</em> variable of the tab, which we need for monkey patching, a <a href="https://developer.chrome.com/extensions/content_scripts">content script</a> is not enough. You need to execute code like the one shown in <a href="https://github.com/juan-fernandez/monkeypatch-example-scope/blob/master/background.js#L3-L9">here</a>. This means handling your code as string. There are some alternatives like using <em>function.toString()</em> and <a href="https://github.com/kentcdodds/babel-plugin-macros">babel macros</a> to evaluate variables in build time, but the extra complexity defeats the purpose, as your monkey patched functions should not be big anyway.</p><p>Utility functions that your monkey patched functions need, like random number generation or parsing of data need to be available in the tab, which means again handling your code as strings to inject it. The tab shares no execution environment with your background, and while it would be possible to asynchronously request and wait for results, this would mean slowing down all your requests.</p><h4>3. Sending responses asynchronously</h4><p>Your content scripts and injected code will communicate with your background through <a href="https://developer.chrome.com/extensions/messaging">message passing</a>. At some point, the responses might require some async operation. To leave the communication channel open you need to return <em>true</em> before calling <em>sendResponse</em>. More of this pattern <a href="https://riptutorial.com/google-chrome-extension/example/7152/send-a-response-asynchronously">here</a>.</p><h4>4. Bundling your extension</h4><p>The window that appears when you click on your browser’s extension icon, also known as a popup, will grow sooner than you expect and a state management library will come in really handy.</p><p>To avoid the hassle of managing a webpack configuration with all the perks (like hot reloading), there are some excellent starter projects and tools for this specific purpose.</p><ul><li><a href="https://github.com/samuelsimoes/chrome-extension-webpack-boilerplate">samuelsimoes/chrome-extension-webpack-boilerplate</a></li><li><a href="https://github.com/xpl/crx-hotreload/">xpl/crx-hotreload</a></li></ul><p>We’ve used React but these should work for any other state management library.</p><h4>5. Browser compatibility</h4><p>The problem with browser compatibility is not well solved with extensions. Though we have not dug into it yet, there seems to be a lot of potential in <a href="https://hacks.mozilla.org/2019/10/developing-cross-browser-extensions-with-web-ext-3-2-0/">web-ext</a>.</p><h4>6. Host commands</h4><p>Our javascript agent gets some of its metadata with <strong>host </strong>commands. But you’re running in a browser extension, so that is not an option.</p><p>Some questions then arise:</p><ol><li>Where to get credentials from? Traces sent to the backend need an API endpoint and an API key.</li><li>How would I calculate the <a href="http://www.ntp.org/">NTP</a> offset in my machine needed for precise timestamp measurements in the trace view? When talking about distributed traces, resolution and precision in the order of microseconds and even nanoseconds is important, as the traces are often generated in different machines. Any small offset can ruin your data.</li><li>In the future: how do I get the code of this specific file and line number that threw an exception?</li></ol><p>There are different ways to answer these questions. For example, we can solve number 1 by logging our extension in using the browser’s cookies. This would allow the extension to send authenticated requests to our backend. This is risky though, as it requires a <a href="https://www.chromestatus.com/feature/5088147346030592">SameSite=None cookie</a>. Number 2 is tricky as there are no “external world” solutions — we need host rights. Number 3 could be solved the same way as number 1, but again, that is risky.</p><p>An option that answers all 3 questions is using our Scope Native App via the <a href="https://developer.chrome.com/extensions/nativeMessaging">native messaging API</a>. The native app is already configured with the API endpoint of your choice and it has access to the API key, which solves question number 1. It can also run host commands, so that solves number 2 and number 3. The disadvantage is that we couple our extension with a different product, but with our current and future requirements in mind, this seems like the best possible alternative.</p><p>Building browser extensions is very rewarding. The technical challenges we faced on this one were really thought provoking and and we’re sure we will continue to face many more. You can also rest assured we’ll continue to invest and innovate in this space, as we’re confident of our ability to help bridge the gap between Dev &amp; QA with tools like Scope for Chrome.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/174/0*PyDT_bdqYdcNP7p1.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 engineering 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=82d4005c620" width="1" height="1" alt=""><hr><p><a href="https://medium.com/scopedev/a-modern-approach-to-manual-testing-82d4005c620">A Modern Approach to Manual Testing</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>
        <item>
            <title><![CDATA[Thanksgiving OpenTelemetry for Swift]]></title>
            <link>https://medium.com/scopedev/thanksgiving-opentelemetry-for-swift-2b6abcc97ac3?source=rss----352ac4e6ed28---4</link>
            <guid isPermaLink="false">https://medium.com/p/2b6abcc97ac3</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[opentelemetry]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Borja Burgos]]></dc:creator>
            <pubDate>Thu, 28 Nov 2019 16:01:01 GMT</pubDate>
            <atom:updated>2019-12-11T19:50:54.455Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*-Jo_V3wSuklPa7IuPowtqA.png" /></figure><p>If you’ve been following <a href="https://undefinedlabs.com/">Undefined Labs</a> and our work with <a href="https://scope.dev/">Scope</a>, you’ll have noticed we’re big proponents of modern observability practices, distributed tracing, and application-level telemetry. In the past, the team has had lots of success implementing solutions leveraging OpenTracing and OpenCensus. And when OpenTelemetry was announced, we did not hesitate to jump on board.</p><p>As <a href="http://scope.dev/">Scope</a> continues to grow to support numerous frameworks, architectures, and testing paradigms, developers are quickly realizing the true value of client-based (e.g. mobile, browser, etc.) testing in distributed cloud-native applications. Before Scope, running end-to-end tests from a browser or mobile device often turned into a futile attempt at managing an ever-increasing collection of flaky and impossible-to-debug tests.</p><p>With Scope, development teams can confidently run end-to-end tests originating in their mobile applications, knowing that when something fails, they’re seconds away from understanding why. We’ve written about this more extensively in a previous <a href="https://medium.com/scopedev/introduction-to-observability-for-an-ios-developer-b9bb94c654a2">blog post</a>.</p><p>Today, on Thanksgiving Day, in our mission to help development teams do more, faster, and to give back to the projects Scope is built on, we’re happy to announce we are open-sourcing an OpenTelemetry client for Swift. The project is currently available here: <a href="https://github.com/undefinedlabs/opentelemetry-swift">https://github.com/undefinedlabs/opentelemetry-swift</a>. And <a href="https://github.com/open-telemetry/community/issues/261">discussion has already began to donate it to OpenTelemetry</a>.</p><p>The Swift client for OpenTelemetry is not limited to iOS, and can also be used with macOS applications. It doesn’t support Swift for Linux, yet. If you’re interested in learning more or contributing to this project, please reach out! We’re excited to bring the exciting world of OpenTelemetry to the Swift community at large!</p><p>Happy Thanksgiving!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/174/1*Ry6cBUDFDRFV5Ng02dGXWA.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 engineering 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=2b6abcc97ac3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/scopedev/thanksgiving-opentelemetry-for-swift-2b6abcc97ac3">Thanksgiving OpenTelemetry for Swift</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>