<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by iamdefinitelyahuman on Medium]]></title>
        <description><![CDATA[Stories by iamdefinitelyahuman on Medium]]></description>
        <link>https://medium.com/@iamdefinitelyahuman?source=rss-1f38e34e130f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bz2guF49nX31gFuO_gWS_w.jpeg</url>
            <title>Stories by iamdefinitelyahuman on Medium</title>
            <link>https://medium.com/@iamdefinitelyahuman?source=rss-1f38e34e130f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 21:35:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@iamdefinitelyahuman/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[An In-Depth Guide to Testing Ethereum Smart Contracts]]></title>
            <link>https://iamdefinitelyahuman.medium.com/an-in-depth-guide-to-testing-ethereum-smart-contracts-ff061e79bb86?source=rss-1f38e34e130f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff061e79bb86</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[pytest]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[iamdefinitelyahuman]]></dc:creator>
            <pubDate>Thu, 23 Jul 2020 11:30:22 GMT</pubDate>
            <atom:updated>2020-07-23T11:30:22.768Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part Seven: Stateful Testing</h4><p><em>This article is part of a series. If you haven’t yet, check out the previous articles:</em></p><p><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-2e41b2770297">Part One: Why we Test</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-d403574a8c42">Part Two: Core Concepts of Testing</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-3e07b8c38755">Part Three: Writing Basic Tests</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-fd699e3087e6">Part Four: Running Your Tests</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-31534a48e177">Part Five: Tools and Techniques for Effective Testing</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-2236902bf826">Part Six: Parametrization and Property-Based Testing</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-ff061e79bb86">Part Seven: Stateful Testing</a></p><p>Stateful testing is a more advanced method of <a href="https://eth-brownie.readthedocs.io/en/stable/tests-hypothesis-property.html#hypothesis">property-based testing</a> used to test complex systems. In a stateful test you define a number of actions that can be combined together in different ways, and Hypothesis attempts to find a sequence of those actions that results in a failure. This is useful for testing complex contracts or contract-to-contract interactions where there are many possible states.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*kTAH2Sl-QKn8LsFv" /></figure><h3>State Machines</h3><p>At the core of each stateful test is a class referred to as a <em>state machine</em>. This class defines the initial test state, a number of actions outlining the structure that the test will execute in, and invariants that should not be violated during execution.</p><p>State machines are composed of the following components:</p><h4>Rules</h4><p>At the core of every state machine are one or more <em>rules</em>. Rules are class methods that are very similar to <a href="https://eth-brownie.readthedocs.io/en/stable/tests-hypothesis-property.html#brownie.test.given">@given</a> based tests; they receive values drawn from strategies and pass them to a user defined test function. The key difference is that where <a href="https://eth-brownie.readthedocs.io/en/stable/tests-hypothesis-property.html#brownie.test.given">@given</a> based tests run independently, rules can be chained together - a single stateful test run may involve multiple rule invocations, which may interact in various ways.</p><p>Any state machine method named rule or beginning with rule_ is treated as a rule:</p><pre>class StateMachine:<br><br>    def <strong>rule_one</strong>(self):<br>        <em># performs a test action</em><br><br>    def <strong>rule_two</strong>(self):<br>        <em># performs another, different test action</em></pre><h4>Initializers</h4><p>There is also a special type of rule known as an initializer. These are rules that are guaranteed to be executed at most one time at the beginning of a run (i.e. before any normal rule is called). They may be called in any order, or not at all, and the order will vary from run to run.</p><p>Any state machine method named initialize or beginning with initialize_ is treated as an initializer.</p><pre>class StateMachine:<br><br>    def <strong>initialize</strong>(self):<br>        <em># this method may or may not be called prior to rule_one</em><br><br>    def rule_one(self):<br>        <em># once this method is called, initialize will not be<br>        # called during the test run</em></pre><h4>Strategies</h4><p>A state machine should contain one or more <a href="https://eth-brownie.readthedocs.io/en/stable/tests-hypothesis-property.html#hypothesis-strategies">strategies</a>, in order to provide data to it’s rules.</p><p>Strategies must be defined at the class level, typically before the first function. They can be given any name.</p><p>Similar to how fixtures work within pytest tests, state machine rules receive strategies by referencing them within their arguments. This is shown in the following example:</p><pre>class StateMachine:<br><br>    <strong>st_uint = strategy(&#39;uint256&#39;)</strong><br>    <strong>st_bytes32 = strategy(&#39;bytes32&#39;)</strong><br><br>    def initialize(self, <strong>st_uint</strong>):<br>        <em># this method draws from the uint256 strategy</em><br><br>    def rule(self, <strong>st_uint</strong>, <strong>st_bytes32</strong>):<br>        <em># this method draws from both strategies</em><br><br>    def rule_two(self, value=&quot;<strong>st_uint</strong>&quot;, othervalue=&quot;<strong>st_uint</strong>&quot;):<br>        <em># this method draws from the same strategy twice</em></pre><h4>Invariants</h4><p>Along with rules, a state machine often defines invariants. These are properties that should remain unchanged, regardless of any actions performed by the rules. After each rule is executed, every invariant method is always called to ensure that the test has not failed.</p><p>Any state machine method named invariant or beginning with invariant_ is treated as an invariant. Invariants are meant for verifying correctness of state; they cannot receive strategies.</p><pre>class StateMachine:<br><br>    def rule_one(self):<br>        pass<br><br>    def rule_two(self):<br>        pass<br><br>    def <strong>invariant</strong>(self):<br>        <em># assertions in this method should always pass regardless</em><br>        <em># of actions in both rule_one and rule_two</em></pre><h4>Setup and Teardown Methods</h4><p>A state machine may optionally include setup and teardown procedures. Similar to pytest fixtures, setup and teardown methods are available to execute logic on a per-test and per-run basis.</p><ul><li><a href="https://eth-brownie.readthedocs.io/en/stable/tests-hypothesis-stateful.html#StateMachine.__init__"><strong>__init__</strong></a>: This method is called once, prior to the chain snapshot taken before the first test run. It is run as a class method — changes made to the state machine will persist through every run of the test.</li><li><a href="https://eth-brownie.readthedocs.io/en/stable/tests-hypothesis-stateful.html#StateMachine.setup"><strong>setup</strong></a>: This method is called at the beginning of each test run, immediately after chain is reverted to the snapshot. Changes applied during setup will only have an effect for the upcoming run.</li><li><a href="https://eth-brownie.readthedocs.io/en/stable/tests-hypothesis-stateful.html#StateMachine.teardown"><strong>teardown</strong></a>: This method is called at the end of each successful test run, prior to the chain revert. teardown is not called if the run fails.</li><li><a href="https://eth-brownie.readthedocs.io/en/stable/tests-hypothesis-stateful.html#StateMachine.teardown_final"><strong>teardown_final</strong></a>: This method is called after the final test run has completed and the chain has been reverted. teardown_final is called regardless of whether the test passed or failed.</li></ul><h3>Test Execution Sequence</h3><p>A stateful test executes in the following sequence:</p><ol><li>The setup phase of all pytest fixtures are executed in their regular order.</li><li>If present, the <a href="https://eth-brownie.readthedocs.io/en/stable/tests-hypothesis-stateful.html#StateMachine.__init__">StateMachine.__init__</a> method is called.</li><li>A snapshot of the current chain state is taken.</li><li>If present, the <a href="https://eth-brownie.readthedocs.io/en/stable/tests-hypothesis-stateful.html#StateMachine.setup">StateMachine.setup</a> method is called.</li><li>Zero or more StateMachine initialize methods are called, in no particular order.</li><li>One or more StateMachine rule methods are called, in no particular order.</li><li>After each initialize and rule, every StateMachine invariant method is called.</li><li>If present, the <a href="https://eth-brownie.readthedocs.io/en/stable/tests-hypothesis-stateful.html#StateMachine.teardown">StateMachine.teardown</a> method is called.</li><li>The chain is reverted to the snapshot taken in step 3.</li><li>Steps 4–9 are repeated 50 times, or until the test fails.</li><li>If present, the <a href="https://eth-brownie.readthedocs.io/en/stable/tests-hypothesis-stateful.html#StateMachine.teardown_final">StateMachine.teardown_final</a> method is called.</li><li>The teardown phase of all pytest fixtures are executed in their normal order.</li></ol><h3>Writing Stateful Tests</h3><p>There are three steps to writing a stateful test:</p><ol><li>Create a state machine class. It should include at least one rule and invariant.</li><li>Create a regular pytest-style test that includes the <a href="https://eth-brownie.readthedocs.io/en/stable/api-test.html#fixtures.state_machine">state_machine</a> fixture</li><li>Within the test, call <a href="https://eth-brownie.readthedocs.io/en/stable/api-test.html#stateful.state_machine">state_machine</a> with the state machine as the first argument</li></ol><p>As an example, let’s build a state machine to test the following Vyper Depositer contract:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4cf9fd1b05517e532fc17b5ed33b9eca/href">https://medium.com/media/4cf9fd1b05517e532fc17b5ed33b9eca/href</a></iframe><p>This is very simple contract with two functions and a public mapping. Anyone can deposit ether for another account using the deposit_for method, or withdraw deposited ether using withdraw_from.</p><p>If you look closely you may noticed an issue in the contract code. If not, don’t worry! We’re going to find it using our test.</p><p>Here is the state machine and test function we will use to test our contract:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0b68523645bf25144229e0702e1d528/href">https://medium.com/media/c0b68523645bf25144229e0702e1d528/href</a></iframe><p>When this test is executed, it will call rule_deposit and rule_withdraw using random data from the given strategies until it encounters a state which violates one of the assertions. If this happens, it repeats the test in an attempt to find the shortest path and smallest data set possible that reproduces the error. Finally it saves the failing conditions to be used in future tests, and then delivers the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Hk7isnWg5y7KJSkJAQ4Kw.png" /></figure><p>From this output we can see where in the test an invariant failed: self.contract.deposited(address) is zero, when we expected it to be one. We also know the sequence of calls leading to the error. From this information we can infer that the contract is incorrectly adjusting balances within the withdraw_from function. Let’s take a look at that function again:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5cbf54b0874315aa0a97855961d8e7b3/href">https://medium.com/media/5cbf54b0874315aa0a97855961d8e7b3/href</a></iframe><p>On line 4, rather than subtracting _value, the balance is being <em>set</em> to _value. We found the bug!</p><h3>Running Stateful Tests</h3><p>By default, stateful tests are included when you run your test suite. There is no special action required to invoke them. You can choose to exclude stateful tests, or to <em>only</em> run stateful tests, with the --stateful flag.</p><p>To only run stateful tests:</p><pre>brownie test --stateful true</pre><p>To skip stateful tests:</p><pre>brownie test --stateful false</pre><p>While a stateful test is active, the console shows a spinner that rotates each time a run of the test has finished. If the color changes from yellow to red, it means the test has failed and hypothesis is now searching for the shortest path to the failure.</p><h3>Real-world Examples</h3><p>To learn more about stateful testing, it might help to explore a few repositories making use of this technique:</p><ul><li><a href="https://github.com/iamdefinitelyahuman/nftoken/tree/master/tests/stateful"><strong>iamdefinitelyahuman/NFToken</strong></a>: A non-fungible implementation of the ERC20 standard</li><li><a href="https://github.com/apguerrera/DreamFrames/tree/master/tests/stateful"><strong>apguerrera/DreamFrame</strong></a><strong>s</strong>: Buy and sell frames in movies</li><li><a href="https://github.com/curvefi/curve-dao-contracts/tree/master/tests/integration"><strong>curvefi/curve-dao-contracts</strong></a>: Vyper contracts used by Curve DAO</li></ul><h3>…and that’s it!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*8I2CuF8CFGM0el-h" /></figure><p>If you’ve read this entire series start to finish — thanks for staying with me! I hope that you learned something new along the way, and that you’re feeling inspired to go and write some tests.</p><p>If you’re looking for more, check out “<a href="https://medium.com/@iamdefinitelyahuman/ethereum-mainnet-testing-with-python-and-brownie-82a61dee0222"><strong>Ethereum Mainnet Testing with Python and Brownie</strong></a>” — it <em>almost</em> fits into this series, I nearly made it part eight, but the writing style is a bit too different so ultimately I decided to just mention it here as a bonus.</p><p>If you enjoyed this, please follow the <a href="https://twitter.com/BrownieEth">Brownie Twitter</a> and like and share our content! Help get the word out about and show others what’s possible when testing their contracts.</p><p>You can also <a href="https://medium.com/@iamdefinitelyahuman">follow me on Medium</a> and check out other articles I’ve written, and join the <a href="https://gitter.im/eth-brownie/community">Brownie Gitter</a> to chat with and learn from other like-minded developers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/0*W6XjPtvSssibmLDc.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff061e79bb86" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An In-Depth Guide to Testing Ethereum Smart Contracts]]></title>
            <link>https://iamdefinitelyahuman.medium.com/an-in-depth-guide-to-testing-ethereum-smart-contracts-2236902bf826?source=rss-1f38e34e130f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2236902bf826</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[pytest]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[iamdefinitelyahuman]]></dc:creator>
            <pubDate>Thu, 23 Jul 2020 11:29:42 GMT</pubDate>
            <atom:updated>2020-07-23T11:29:42.837Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part Six: Parametrization and Property-Based Testing</h4><p><em>This article is part of a series. If you haven’t yet, check out the previous articles:</em></p><p><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-2e41b2770297">Part One: Why we Test</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-d403574a8c42">Part Two: Core Concepts of Testing</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-3e07b8c38755">Part Three: Writing Basic Tests</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-fd699e3087e6">Part Four: Running Your Tests</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-31534a48e177">Part Five: Tools and Techniques for Effective Testing</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-2236902bf826">Part Six: Parametrization and Property-Based Testing</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-ff061e79bb86">Part Seven: Stateful Testing</a></p><p>Let’s revisit one of our earlier ERC20 test cases:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/afe88d2fcb1d5e399e5be6bb463d5170/href">https://medium.com/media/afe88d2fcb1d5e399e5be6bb463d5170/href</a></iframe><p>Here we verify that the transfer function adjusts the sender’s balance as intended. Simple enough, right? Ship it and on to test the next behavior!</p><p>On it’s own, however, this test isn’t as strong as it could be. Imagine if the contract being tested always modified the balance by exactly 1⁰¹⁸, regardless of the amount that was supposed to be transferred. Our initial test would not catch this behavior. For this reason <strong>it is a good practice to test each behavior against a range of data, rather than only a single value</strong>. This can be accomplished with liberal use of copy and paste, but the smarter approach is to use a technique known as <em>parametrization</em>.</p><h3>Test Parametrization</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*xHXUYNT4IAznx2db" /></figure><p><a href="https://eth-brownie.readthedocs.io/en/stable/tests-pytest-intro.html#parametrizing-tests">Parameterization</a> is an essential tool for any test suite. It allows you to replace a single test value with a range of data, effectively creating multiple tests without having to duplicate code.</p><p>In Brownie we achieve this using the <a href="https://docs.pytest.org/en/latest/parametrize.html">@pytest.mark.parametrize</a> decorator. Here is the same test as above, rewritten to use parametrization:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b718e9836a0dc6cd3433e0e09e3a3ba/href">https://medium.com/media/4b718e9836a0dc6cd3433e0e09e3a3ba/href</a></iframe><p>This test verifies the same behavior as our first example, but it executes three times with different amounts transferred each time. This is useful for two reasons:</p><ol><li>We have significantly strengthened our testing of this behavior. If there is a flaw in how the balances are adjusted, our test suite is more likely to discover it.</li><li>In the future, if we want to expand or change how this behavior is tested, we only have to modify one test case instead of four.</li></ol><p>Pretty good, right? With just one more line of code, we’ve taken our original test and made it significantly more effective.</p><h3>…but can we do better?</h3><p>There are many testing situations where parametrization the correct tool for the job. But there’s still a problem that is doesn’t adequately address: <strong>ultimately, we are only testing our own expectations of how a contract <em>should</em> function</strong>. Even with parametrized tests we are producing the data sets that our tests execute against. And where do edge cases happen? Exactly where we aren’t looking!</p><p>So how do we get past this paradox? How can we write tests for the things we don’t expect? The answer: <em>property-based testing</em>.</p><h3>Property-based Testing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*CnuRDDcDl7AT7UCz" /></figure><p>Property-based testing is a powerful tool for locating edge cases and discovering faulty assumptions within your code.</p><p>The key idea behind property-based testing is that <strong>rather than writing a test for a single scenario, you write tests that describe a range of scenarios</strong>. Then you let your computer explore the possibilities for you, rather than having to hand-write each case yourself.</p><p>This is effective because it automates one of the most time consuming parts of writing tests — coming up with the examples. And it means your contract is more likely to be hit with cases you <em>didn’t</em> consider, which is exactly where the bugs like to hide.</p><p>Brownie achieves this by integrating the <a href="https://hypothesis.works/">hypothesis</a> library. Here is our same test, written to take advantage of property-based testing:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13d79371334af18cfbea01c11a5d946f/href">https://medium.com/media/13d79371334af18cfbea01c11a5d946f/href</a></iframe><p>When this test executes, the logic is run fifty times. During each run, amount is a different value somewhere between 0 and 10¹⁸. The chosen values are stored in a database, and in subsequent test runs different values are be used. <strong>If a value is found that causes the test to fail, this value will <em>always</em> be included in subsequent tests</strong>.</p><p>That last line is important! While you wouldn’t be wrong to describe this process as randomized testing, it is also <em>repeatable</em> randomized testing. While a bug may take some time to be found, it will never simply go away once it has been discovered.</p><h3>Writing Property-Based Tests</h3><p>Writing property-based tests is a fairly straightforward process. The magic is coming from two methods:</p><ul><li><a href="https://eth-brownie.readthedocs.io/en/stable/tests-hypothesis-property.html#brownie.test.given"><strong>@given</strong></a> is a decorator that converts a test function into a randomized test. It specifies which arguments in the function are to be parametrized, and how that process should be handled.</li><li><a href="https://eth-brownie.readthedocs.io/en/stable/tests-hypothesis-property.html#brownie.test.strategy"><strong>strategy</strong></a> is a method for creating test strategies based on smart contract ABI types. A test strategy is a recipe for describing the sort of data you want to generate. It typically defines the data type, lower and upper bounds, and values that should be excluded.</li></ul><p>By combining these two methods, we can easily generate property-based tests that will test a behavior of your contract’s specification much more thoroughly than with regular parametrized tests.</p><p>Here is another example where we add a second strategy receiver, to parametrize the receiver of the tokens. This new strategy uses the exclude keyword argument to avoid generating a test where the sender and receiver are the same account.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/60934714bc61c35a12c879bdde09b0b7/href">https://medium.com/media/60934714bc61c35a12c879bdde09b0b7/href</a></iframe><p>Note that when using exclude, you should also include a separate test for the excluded value(s).</p><h3>Where to Use Property-Based Tests</h3><p>If you’re unsure where to begin adding property-based tests within your test suite, here are some ideas:</p><ol><li>Look for simple tests that verify “when X, then Y”, where there is a direct relationship between X and Y. Balances, approval amounts, user permissions — smart contracts are full of situations where this sort of testing can come in handy.</li><li>Look for code duplication in your test suite. Are there cases where you have multiple tests verifying the same behavior? Can you refactor these tests into a single, property-based case?</li></ol><h3>Learning More</h3><p>To learn more about property-based testing for smart contracts, check out the <a href="https://eth-brownie.readthedocs.io/en/stable/tests-hypothesis-property.html">Brownie Property-Based Testing</a> documentation. It explores of the above functionality in greater depth, and shows how to integrate <a href="https://hypothesis.works/">Hypothesis</a> into your tests to utilize this powerful testing technique.</p><h3>What’s Next</h3><p>We’re almost done! In “<a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-ff061e79bb86"><strong>Part Seven: Stateful Testing</strong></a>”, we delve into stateful testing, an advanced form of property-based testing that can be used to write effective integration tests for complex systems.</p><p><em>You can also follow the Brownie </em><a href="https://twitter.com/BrownieEth"><em>Twitter account</em></a><em>, read my other </em><a href="https://medium.com/@iamdefinitelyahuman"><em>Medium articles</em></a><em>, and join us on </em><a href="https://gitter.im/eth-brownie/community"><em>Gitter</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/0*T-VDtDtzueoU_RSJ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2236902bf826" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An In-Depth Guide to Testing Ethereum Smart Contracts]]></title>
            <link>https://iamdefinitelyahuman.medium.com/an-in-depth-guide-to-testing-ethereum-smart-contracts-31534a48e177?source=rss-1f38e34e130f------2</link>
            <guid isPermaLink="false">https://medium.com/p/31534a48e177</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[pytest]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[iamdefinitelyahuman]]></dc:creator>
            <pubDate>Thu, 23 Jul 2020 11:29:00 GMT</pubDate>
            <atom:updated>2020-07-23T11:29:00.461Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part Five: Tools for Effective Testing</h4><p><em>This article is part of a series. If you haven’t yet, check out the previous articles:</em></p><p><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-2e41b2770297">Part One: Why we Test</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-d403574a8c42">Part Two: Core Concepts of Testing</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-3e07b8c38755">Part Three: Writing Basic Tests</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-fd699e3087e6">Part Four: Running Your Tests</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-31534a48e177">Part Five: Tools and Techniques for Effective Testing</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-2236902bf826">Part Six: Parametrization and Property-Based Testing</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-ff061e79bb86">Part Seven: Stateful Testing</a></p><h3>Dealing with Tests that cannot Pass</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/0*eNMfBxHRGBka9-0n" /></figure><p>At some point you may find yourself dealing with a test that cannot pass. Maybe you are unsure of the reason why but need to focus on something else for now, maybe you’re in the middle of a large-scale refactor and so the failure is expected. Either way it can be annoying to see the test fail repeatedly.</p><p>In these cases, pytest provides markers to help you deal with the situation:</p><h4>pytest.mark.skip</h4><pre><strong>@pytest.mark.skip</strong>(reason=&quot;no way of currently testing this&quot;)<br><strong>def</strong> test_the_unknown():<br>    ...</pre><p>The skip marker tells pytest not to run the test. You can optionally provide a reason why you are skipping it, to help remember why when you come back to it later.</p><h4>pytest.mark.xfail</h4><pre><strong>@pytest.mark.xfail</strong><br><strong>def</strong> test_function():<br>    ...</pre><p>The xfail marker indicates that the test should still run, but the outcome is inverted. No traceback is given for the failing test, and the console output is x for “expected to fail”. If the test <em>passes</em> it is interpreted as a failure, or “unexpected pass”.</p><h3>Time Travel</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*bJyhFKP9wHbcYsIS" /></figure><p>The <a href="https://eth-brownie.readthedocs.io/en/stable/core-chain.html#manipulating-the-development-chain">chain</a> object provides methods for fast forwarding the clock and mining new blocks. These are invaluable when testing time dependent behaviors.</p><h4>chain.sleep</h4><p>chain.sleep fast forwards the clock in the local environment. It accepts one argument — the number of seconds to advance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6d7048083b816af8653c88de707cfc3/href">https://medium.com/media/d6d7048083b816af8653c88de707cfc3/href</a></iframe><h4>chain.mine</h4><p>chain.mine mines 1 or more new, empty blocks.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/750e763626698a81b2a1271844e83ee7/href">https://medium.com/media/750e763626698a81b2a1271844e83ee7/href</a></iframe><h3>Revert Comments</h3><p><em>To explore developer revert comments in greater detail, check out </em><a href="https://medium.com/coinmonks/effective-smart-contract-testing-developer-revert-comments-c7a6f250df0f"><em>this article</em></a><em>.</em></p><p>When testing we want to ensure that every branch is correctly hit — and the best way to do this with reverting transactions is to expect a specific error string.</p><p>Unfortunately, each revert string adds a minimum 20,000 gas to your contract deployment cost, and increases the cost for a function to execute. Including an error message for every require and revert statement is often impractical and sometimes simply not possible due to the block gas limit.</p><p>Brownie solves this issue by letting you include revert strings as source code comments. The comments are not included in the bytecode, but are still accessible via <a href="https://eth-brownie.readthedocs.io/en/stable/api-network.html#TransactionReceipt.revert_msg">TransactionReceipt.revert_msg</a> or the brownie.reverts context manager.</p><p>Using developer revert comments is simple. At the end of a line of code that includes a potential revert, add a comment starting with// dev: in Solidity or # dev: in Vyper. Brownie detects these comments and adds them automatically during testing.</p><p>Here is an example admin function where revert comments are used in place of actual error strings:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae091137846db8ce5c5f7f7dd53d5ecc/href">https://medium.com/media/ae091137846db8ce5c5f7f7dd53d5ecc/href</a></iframe><p>And here is a test that targets a specific revert comment:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6607c29fca769f1bf096938f69e3f3c7/href">https://medium.com/media/6607c29fca769f1bf096938f69e3f3c7/href</a></iframe><h3>What’s Next</h3><p>In “<a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-2236902bf826"><strong>Part Six: Parametrization and Property-Based Testing</strong></a>”, we explore how parametrization can strengthen our test cases and help us find unexpected edge cases.</p><p><em>You can also follow the Brownie </em><a href="https://twitter.com/BrownieEth"><em>Twitter account</em></a><em>, read my other </em><a href="https://medium.com/@iamdefinitelyahuman"><em>Medium articles</em></a><em>, and join us on </em><a href="https://gitter.im/eth-brownie/community"><em>Gitter</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/0*wYgS8S846txnhELs.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31534a48e177" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An In-Depth Guide to Testing Ethereum Smart Contracts]]></title>
            <link>https://iamdefinitelyahuman.medium.com/an-in-depth-guide-to-testing-ethereum-smart-contracts-fd699e3087e6?source=rss-1f38e34e130f------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd699e3087e6</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[pytest]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[iamdefinitelyahuman]]></dc:creator>
            <pubDate>Thu, 23 Jul 2020 11:26:30 GMT</pubDate>
            <atom:updated>2020-07-23T11:26:30.277Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part Four: Running Your Tests</h4><p><em>This article is part of a series. If you haven’t yet, check out the previous articles:</em></p><p><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-2e41b2770297">Part One: Why we Test</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-d403574a8c42">Part Two: Core Concepts of Testing</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-3e07b8c38755">Part Three: Writing Basic Tests</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-fd699e3087e6">Part Four: Running Your Tests</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-31534a48e177">Part Five: Tools and Techniques for Effective Testing</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-2236902bf826">Part Six: Parametrization and Property-Based Testing</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-ff061e79bb86">Part Seven: Stateful Testing</a></p><p>Now that we’ve covered the basics of writing tests, let’s look at how to run them and how to understand the output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/0*2yqZb8sZOb3bES1a" /></figure><h3>Running Tests</h3><p>To execute the entire test suite, run the following command in the root folder of your project:</p><pre>brownie test</pre><p>You will receive output similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KkEmNefThf1nUBrGbEACsg.png" /></figure><p>The output shows a list of filenames, with a series of dots or F’s to show that tests are passing or failing. Everything is color coded to make life easier — as long as you’re seeing green, things are good!</p><h3>Only Running Updated Tests</h3><p>As your test suite grows you will find your tests taking longer and longer to run. Waiting on feedback from your tests can eat into your development time, so it’s sometimes useful to only run tests where the outcome might have changed. For this, we have the --update flag (or just -U):</p><pre>brownie test --update</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0geasAx7VLJ59KBjkL4uuQ.png" /></figure><p>In this mode, Brownie only runs tests where either the test itself or the contracts it touches have been modified. The . and F become s, still color coded to show the outcome when it did run.</p><p>— update works on a per-file basis, so if you modify a single test you will have to re-run the entire test module. For this reason, it’s usually preferable to have many short test modules as opposed to a few long ones.</p><h3>Running Tests in Parallel</h3><p>Another way to speed up execution is by running your tests in parallel on multiple processors. This is possible thanks to a wonderful plugin known as <a href="https://github.com/pytest-dev/pytest-xdist">pytest-xdist</a>, which is included when installing Brownie.</p><p>To run tests in parallel we use the -n flag:</p><pre>brownie test -n auto</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ERT-hg1ORYPSKKdtLvp8GA.png" /></figure><p>In the above command, auto indicates how many processes to use. You can manually set it, or let xdist choose the ideal value based on the number of CPUs your computer has.</p><p>You’ll notice that there’s a longer delay in the setup phase. This is because Brownie must launch a separate instance of Ganache for each processor. For this reason, the benefit to this mode is much more apparent when running large test suites.</p><p>A couple of important things to know about this mode:</p><ul><li>It only works if all of your tests are properly isolated with an isolation fixture. If even a single test isn’t isolated, it will raise an exception.</li><li>Tests are distributed to workers on a per-file basis. For the best performance with this mode, organize your test suite into many small modules rather than just a few large ones.</li></ul><h3>When Tests Fail</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/0*dr2HYdRXtDSoEAAc" /></figure><p>Next, let’s take a look at some failing tests. If you’re following along, copy the following code and save it under tests/test_failure.py:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8ec80c3a6d5a339362fd4f09be499ec/href">https://medium.com/media/f8ec80c3a6d5a339362fd4f09be499ec/href</a></iframe><p>Let’s run it and see what happens:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F4e0hddp4RHkAusaSRsf3w.png" /></figure><p>As expected, both tests have failed. Below the test results, pytest gives us some information on why:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JoiqXpXgJmSVqZGGTxM1rQ.png" /></figure><p>Pytest provides the following information to help determine what happened:</p><ul><li>a list of fixtures used in this test, and their values</li><li>the test source code, with the failing line highlighted</li><li>a translated version of the source code where variable names are shown as actual values</li><li>the filename and line number where the test failed</li></ul><p>And so we can see that the test has failed because the balance of accounts[0] was 10²¹, not 31337.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SZJuWpzLU4ncOJp4TmUozA.png" /></figure><p>Whereas our first example failed from an assertion, the second failed because of a reverting transaction. In this case we see:</p><ul><li>the error string of the revert</li><li>the contract name and line number where the revert occurred</li><li>a source highlight showing the failing contract code</li></ul><p>The test has failed because accounts[1] had an insufficient balance to complete the transfer.</p><h3>Interactive Debugging</h3><p>Sometimes the cause of a failing test is not immediately obvious, and you might want to have a look around. To do so, you can use the --interactive flag (or just -I):</p><pre>brownie test --interactive</pre><p>In this mode, when a test fails you’re immediately dropped into Brownie’s console mode:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QCkOfr5bio-rkQPUBijcmQ.png" /></figure><p>The console opens at the exact moment that the test fails. All local and global variables within the test are available, as well as the usual console objects.</p><ul><li>For failing transactions, use the <a href="https://eth-brownie.readthedocs.io/en/stable/core-chain.html#local-transaction-history">history</a> object to obtain the recent <a href="https://eth-brownie.readthedocs.io/en/stable/core-transactions.html#inspecting-and-debugging-transactions">TransactionReceipt</a> and then examine it with Brownie’s various <a href="https://eth-brownie.readthedocs.io/en/stable/core-transactions.html#debugging-failed-transactions">debugging methods</a> (another article on this soon!)</li><li>For tests that involve multiple transactions, use <a href="https://eth-brownie.readthedocs.io/en/stable/core-chain.html#undo-redo">chain.undo and </a><a href="https://eth-brownie.readthedocs.io/en/stable/core-chain.html#undo-redo">chain.redo</a> to move back and forward through the test</li></ul><p>When you are finished, type quit() and Brownie will continue with the next test.</p><h3>Evaluating Test Coverage</h3><p><em>To explore coverage evaluation in greater detail, check out </em><a href="https://medium.com/coinmonks/brownie-evaluating-solidity-code-coverage-via-opcode-tracing-a7cf5a92d28c"><em>this article</em></a><em>.</em></p><p>Brownie uses traces to evaluate statement and branch coverage of your tests. To generate a coverage report, use the --coverage flag (or -C):</p><pre>brownie test -C</pre><p>When the tests finish running you will see output similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NFyWZ1AQKHqZQ8ckTiJvmg.png" /></figure><p>A percentage value is shown in the console, and a detailed report is saved at reports/coverage.json. To view this report we use the <a href="https://eth-brownie.readthedocs.io/en/stable/gui.html#the-brownie-gui">Brownie GUI</a>:</p><pre>brownie gui</pre><p>Within the GUI:</p><ul><li>First, select a contract name from the drop-down menu in the upper right hand corner</li><li>Immediately left of the contract name, choose “coverage” from the reports drop-down</li><li>A third drop-down menu will appear. Select “branch” or “statement” to view a coverage report</li></ul><p>The report highlights sections of code that Brownie has identified as statements or branches. For statement coverage everything is highlighted in green or red to show if the statement did or did not execute. For branches, some are additionally highlighted in yellow or orange. These colors indicate that a branch was hit, but only evaluated truthfully or falsely.</p><p>The image below shows a branch report with all four possible colors:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZIpC_gSdjmOogo35.png" /></figure><h3>What’s Next</h3><p>In “<a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-31534a48e177"><strong>Part Five: Tools and Techniques for Effective Testing</strong></a>”, we explore some useful functionality within Brownie and pytest to help take our testing skills to the next level.</p><p><em>You can also follow the Brownie </em><a href="https://twitter.com/BrownieEth"><em>Twitter account</em></a><em>, read my other </em><a href="https://medium.com/@iamdefinitelyahuman"><em>Medium articles</em></a><em>, and join us on </em><a href="https://gitter.im/eth-brownie/community"><em>Gitter</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/0*WYm3SaPWEbzPhknT.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd699e3087e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An In-Depth Guide to Testing Ethereum Smart Contracts]]></title>
            <link>https://iamdefinitelyahuman.medium.com/an-in-depth-guide-to-testing-ethereum-smart-contracts-3e07b8c38755?source=rss-1f38e34e130f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e07b8c38755</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[pytest]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[iamdefinitelyahuman]]></dc:creator>
            <pubDate>Thu, 23 Jul 2020 11:25:45 GMT</pubDate>
            <atom:updated>2020-07-23T11:27:21.519Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part Three: Writing Basic Tests</h4><p><em>This article is part of a series. If you haven’t yet, check out the previous articles:</em></p><p><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-2e41b2770297">Part One: Why we Test</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-d403574a8c42">Part Two: Core Concepts of Testing</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-3e07b8c38755">Part Three: Writing Basic Tests</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-fd699e3087e6">Part Four: Running Your Tests</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-31534a48e177">Part Five: Tools and Techniques for Effective Testing</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-2236902bf826">Part Six: Parametrization and Property-Based Testing</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-ff061e79bb86">Part Seven: Stateful Testing</a></p><p>It’s time to write our first tests! We will be testing functionality in a simple ERC20 contract. If you want to follow along using Solidity you can create a local copy of the contract with the following command:</p><pre>brownie bake token</pre><p>or if you prefer Vyper:</p><pre>brownie bake vyper-token</pre><p>Note that each of these projects come with a complete test suite. Feel free to look around at the files in the <a href="https://github.com/brownie-mix/vyper-token-mix/tree/master/tests">tests/</a> directory for some more examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*cXZB2AQwL5a7DrTU" /></figure><h3>Writing our First Tests</h3><p>Let’s start with a simple test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21329f7fa8eed0c7c9315386ee9e5f45/href">https://medium.com/media/21329f7fa8eed0c7c9315386ee9e5f45/href</a></iframe><ul><li>In line 1 we are importing the Brownie objects that we require for the test. <a href="https://eth-brownie.readthedocs.io/en/stable/core-accounts.html#working-with-accounts">accounts</a> give us access to funded and unlocked accounts, and <a href="https://eth-brownie.readthedocs.io/en/stable/core-contracts.html">Token</a> is used to deploy our ERC20 contract.</li><li>Line 3 is the start of our test. When using pytest, all functions that begin with test_ are considered a test.</li><li>In lines 4 and 5 we perform our test setup. First we deploy a Token contract, and then we keep a record of the balance of accounts[0] which we will use later in our assertion.</li><li>In line 7 we perform the action we are testing, transferring 10¹⁸ tokens from accounts[0] to accounts[1].</li><li>In line 9 we make our assertion: the token balance of accounts[0] should have decreased by exactly 10¹⁸.</li></ul><p>There is a fair amount happening here, but once you get the hang of it the syntax is quite simple.</p><p>Now, time for a second test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a5d64aeb157550cbe7273acc511d7f2/href">https://medium.com/media/2a5d64aeb157550cbe7273acc511d7f2/href</a></iframe><p>The key difference between this test and the first is that in the first one we took a “happy path” — one where the code executed successfully; but in this test we are expecting a transaction to revert.</p><p>The important section here is lines 7 and 8, where we use the <a href="https://eth-brownie.readthedocs.io/en/stable/tests-pytest-intro.html#handling-reverted-transactions">brownie.reverts</a> context manager. In order for the test to pass, the transaction within the context manager must revert with the given error message. Note that specifying an error message is optional — we could simply say brownie.reverts() as a broad catch-all for any reverting transaction.</p><h3>Fixtures</h3><p>We have only scratched the surface of testable behaviors around the transfer function. Our test verified a change in the sender’s balance; an obvious next step is to verify that the receiver’s balance also changes.</p><p>Our new test will be nearly identical to the first one, so you might be tempted to copy-paste and make a few modification:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d6f076127d617e3bb6bf53f5579eff8/href">https://medium.com/media/9d6f076127d617e3bb6bf53f5579eff8/href</a></iframe><p>This works, but we’re repeating some code here. We’ll now have three tests that start by deploying a Token contract. Later on if we modify the constructor arguments for our contract, we will have to change this line in every one of our tests. In a large test suite that could be a lot of work!</p><p>Fortunately pytest offers a solution to this problem, known as a fixture. <a href="http://docs.pytest.org/en/latest/fixture.html">Fixtures</a> are functions that are applied to one or more tests, and which are called prior to the execution of each test. They are used to setup initial conditions that are required for a test.</p><p>To create a fixture, we apply the @pytest.fixture decorator to a function. Let’s create a fixture to handle deploying our contract:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0944251a4ffb62db37c84b37cf5ad1a9/href">https://medium.com/media/0944251a4ffb62db37c84b37cf5ad1a9/href</a></iframe><p>We then pass the result of the fixture into our tests by adding the fixture name as a test input argument:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/929d965f8f7b101e034dfc69f3a2010e/href">https://medium.com/media/929d965f8f7b101e034dfc69f3a2010e/href</a></iframe><p>The duplicated code is no more, and make our tests are now easier to maintain!</p><h3>Sharing Fixtures across Test Modules</h3><p>When you require the same fixture in multiple test files, you can move it into a file named <a href="https://docs.pytest.org/en/latest/fixture.html#conftest-py-sharing-fixture-functions">conftest.py</a> within the same folder or a common parent folder. Pytest automatically discovers these fixtures and makes them available — you don’t have to import anything manually.</p><h3>Chaining Fixtures</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*0Vn8Rtt9E9VKtEy6" /></figure><p>Along with passing fixtures into test functions, <strong>you can also pass fixtures into other fixtures</strong>. In this way you can build complex test setup processes with minimal repeated code.</p><p>As an example, let’s create a fixture to distribute tokens, that requires our original token fixture:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b11a93579b452b8160ef3544a5920d0a/href">https://medium.com/media/b11a93579b452b8160ef3544a5920d0a/href</a></iframe><p>We can then add distribute_tokens to any test where we require an initial token balance in many accounts.</p><h3>Builtin Fixtures</h3><p>Brownie provides us with a set of builtin fixtures to access various functionality. As an example, let’s further refactor our current tests to use the builtin accounts and Token fixtures:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7554b11a00d2e4d9fbfd60dfc4f6ede7/href">https://medium.com/media/7554b11a00d2e4d9fbfd60dfc4f6ede7/href</a></iframe><p>We’ve managed to remove the import statement by instead accessing the same functionality via builtin fixtures.</p><p>Most core Brownie components and project objects are available via fixtures — the <a href="https://eth-brownie.readthedocs.io/en/stable/tests-pytest-fixtures.html">Brownie documentation</a> contains a complete list.</p><h3>Fixture Scope</h3><p>The default behavior for a fixture is to execute each time it is required for a test. By adding the scope parameter to the decorator, we can alter how frequently the fixture executes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a11ca3f6015097989bd56853ac80cb00/href">https://medium.com/media/a11ca3f6015097989bd56853ac80cb00/href</a></iframe><p>By setting our fixture to module scope, it now only deploys a single Token contract, passing the same value into both tests. With complex test suites this can save you a significant amount of time.</p><p>Fixture of higher scopes (such as session or module) are always instantiated before lower-scoped fixtures (such as function). The execution order of fixtures of the same scope is determined by the order they are declared as fixture and test input arguments. The only exception to this rule is isolation fixtures, which we’ll explore next.</p><h3>Test Isolation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*cILEArH1Oxaj3hgy" /></figure><p>As we discussed previously, isolation is a key component of a well written test suite. In almost all cases you should isolate your tests from one another so the actions performed in one test cannot affect the outcome of the tests that come after it.</p><p>Brownie provides two fixtures that are used to handle isolation:</p><ul><li><a href="https://eth-brownie.readthedocs.io/en/stable/tests-pytest-fixtures.html#module_isolation"><strong>module_isolation</strong></a> is a module scoped fixture. It resets the local chain before and after completion of the test module, ensuring a clean environment for the module and that the results of it will not affect subsequent modules.</li><li><a href="https://eth-brownie.readthedocs.io/en/stable/tests-pytest-fixtures.html#fn_isolation"><strong>fn_isolation</strong></a> is function scoped. It additionally takes a snapshot of the chain before running each test, and reverts to it when the test completes. This fixture allows you to define a common chain state for each test, reducing repetitive transactions and thus making your tests complete quicker.</li></ul><p>Isolation fixtures are <strong>always the first fixture within their scope to execute</strong>. You can be certain that all module-scoped fixtures will be executed <em>before</em> the isolation snapshot, and all function-scoped fixtures will run <em>after</em> the snapshot.</p><p>To apply an isolation fixture to all tests in a module, require it in another fixture and include the autouse keyword argument:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a47cdfdded601bbfb10f4ef7f4b274e8/href">https://medium.com/media/a47cdfdded601bbfb10f4ef7f4b274e8/href</a></iframe><h3>Bringing it all Together</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*c_3aW0eaJI6HQ2ef" /></figure><p>Let’s do one last refactor of our tests, bringing together everything that we’ve discussed so far:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a9e343df93acdf60941d823abeea553/href">https://medium.com/media/8a9e343df93acdf60941d823abeea553/href</a></iframe><ul><li>Lines 5–7 we declare a fixture that deploys the <a href="https://eth-brownie.readthedocs.io/en/stable/core-contracts.html">Token</a> contract. We set it as module-scoped so that it only deploys one contract for all of the tests.</li><li>Lines 10–12 we add the <a href="https://eth-brownie.readthedocs.io/en/stable/tests-pytest-intro.html#isolation-fixtures">fn_isolation</a> fixture to ensure that our tests are properly isolated. A snapshot of the local blockchain will be taken immediately after the token fixture executes, and each test will start from this snapshot.</li><li>Lines 15–19 are our first test. We are using the builtin <a href="https://eth-brownie.readthedocs.io/en/stable/core-accounts.html#working-with-accounts">accounts</a> fixture as well as the token fixture we declared earlier. In this test we transfer some tokens, and make an assertion about the balance of the sender.</li><li>Lines 22–26 are our second test. Very similar to the previous test, except this time we make an assertion about the receiver’s balance.</li><li>Lines 29–31 are our third and final test. In this test we use the <a href="https://eth-brownie.readthedocs.io/en/stable/tests-pytest-intro.html#handling-reverted-transactions">brownie.reverts</a> context manager to confirm that a transaction reverts when we attempt to transfer too many tokens.</li></ul><p>Save the tests as tests/test_first.py inside the token project. Then, run them with the following command:</p><pre>brownie test tests/test_first.py</pre><p>You should receive an output similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*92EE8iG_RjCD5d6U5rzAdQ.png" /></figure><p>Each green dot represents one of our tests. Everything passed! 🎉</p><h3>What’s Next</h3><p>In “<a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-fd699e3087e6"><strong>Part Four: Running Your Tests</strong></a>”, we learn the ins-and-outs of running our test suite, understanding the output, and debugging failed tests.</p><p><em>You can also follow the Brownie </em><a href="https://twitter.com/BrownieEth"><em>Twitter account</em></a><em>, read my other </em><a href="https://medium.com/@iamdefinitelyahuman"><em>Medium articles</em></a><em>, and join us on </em><a href="https://gitter.im/eth-brownie/community"><em>Gitter</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/0*El9AhUFmsAesjG5_.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e07b8c38755" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An In-Depth Guide to Testing Ethereum Smart Contracts]]></title>
            <link>https://iamdefinitelyahuman.medium.com/an-in-depth-guide-to-testing-ethereum-smart-contracts-d403574a8c42?source=rss-1f38e34e130f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d403574a8c42</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[pytest]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[iamdefinitelyahuman]]></dc:creator>
            <pubDate>Thu, 23 Jul 2020 11:25:05 GMT</pubDate>
            <atom:updated>2021-03-08T13:38:50.660Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part Two: Core Concepts of Testing</h4><p><em>This article is part of a series. If you haven’t yet, check out the previous articles:</em></p><p><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-2e41b2770297">Part One: Why we Test</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-d403574a8c42">Part Two: Core Concepts of Testing</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-3e07b8c38755">Part Three: Writing Basic Tests</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-fd699e3087e6">Part Four: Running Your Tests</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-31534a48e177">Part Five: Tools and Techniques for Effective Testing</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-2236902bf826">Part Six: Parametrization and Property-Based Testing</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-ff061e79bb86">Part Seven: Stateful Testing</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/0*uFIwNjBN-dT_7Lqc.gif" /></figure><p>Before we get into actually writing tests, it’s good to review some core testing concepts. We’re going to focus on unit testing initially — integration testing follows many of the same principles, but it is a more complex and nuanced subject that is better approached once we have a handle on unit tests.</p><p>We begin with a definition. What <em>is</em> a unit test?</p><blockquote>“A <strong>unit test</strong> is a test that verifies a single behavior or component within your code.”</blockquote><h3>Properties of Unit Tests</h3><p>There are many properties that set a good unit test apart from a bad one. Try to keep all of these in mind as you write your own tests.</p><ul><li><strong>Simple</strong>: Each unit test should be evaluating a single behavior. When a test fails it should be immediately obvious why. It is better to write many short tests with a single assertion, than one long test with many assertions.</li><li><strong>Repeatable</strong>: A unit test should always produce the same result, as long as the code being tested has not changed. Tests should never be influenced by some uncontrollable parameter. This is important so that when a test fails, you can repeat it and observe the result to help you find the issue.</li><li><strong>Isolated</strong>: Tests should not depend upon or affect other tests You should be able to run your tests in any order, together or independently, and always receive the same outcome.</li><li><strong>Readable</strong>: Use long, descriptive variable names and don’t be afraid of adding comments to your tests. Once you have finished writing a test, it’s likely you’ll never look at that code again - until it fails. When that does happen, you should not have to spend time trying to understand what the test is doing.</li><li><strong>Fast</strong>: Unit tests should be written with speed in mind. Each time you add or change your code you should run your tests to confirm that everything is still working. Having a quick test suite ensure you get this feedback sooner.</li></ul><p>We’ll explore each of these ideas in greater depth throughout this tutorial.</p><h3>Design Principles</h3><p>When writing tests, there is a commonly referenced design principle known as Arrange-Act-Assert (AAA):</p><ul><li>First, you <strong>arrange</strong> the initial conditions required</li><li>Next, you <strong>act</strong> by calling the function to be tested</li><li>Finally, you <strong>assert</strong> the result of the action</li></ul><p>Following this pattern ensures that your tests are readable and not overly complex. <strong>If you find yourself performing many actions and assertions in a single test, or making an assertion mid-test and then following it with more actions — consider refactoring into multiple tests</strong>. Remember, we want our tests to be simple and easy to understand when they fail!</p><h3>What to Test</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*KEDLOE6hxk1FFh4x.gif" /></figure><p>Well… everything! Take the following example, a simple ERC20 transfer function written in Vyper:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be857a5c3e23e50672971064a1e3b5f0/href">https://medium.com/media/be857a5c3e23e50672971064a1e3b5f0/href</a></iframe><p>Generally, we want to start by considering the possible paths through the function. In this case there are two outcomes:</p><ul><li>The token transfer is successful. In this case, testable behaviors include the sender and receiver balances being correctly adjusted, the Transfer event firing and the function returning True.</li><li>The transfer is not successful. In this case, we expect that the transaction reverts with an error message of &quot;Insufficient Funds&quot; when the sender does not have a sufficient balance.</li></ul><p>Going further we might also want to test edge cases, such as:</p><ul><li>A transfer of 0 tokens</li><li>A transfer where the sender and receiver are the same address</li></ul><p>In some cases we might also write tests to perform assertions about behaviors that should <em>not</em> occur, such as a change in the total supply.</p><p>So you can see, from this single function we can produce many unit tests!</p><h3>What’s Next</h3><p>In “<a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-3e07b8c38755"><strong>Part Three: Writing Basic Tests</strong></a>”, we explore the basics of pytest and write our first tests!</p><p><em>You can also follow the Brownie </em><a href="https://twitter.com/BrownieEth"><em>Twitter account</em></a><em>, read my other </em><a href="https://medium.com/@iamdefinitelyahuman"><em>Medium articles</em></a><em>, and join us on </em><a href="https://gitter.im/eth-brownie/community"><em>Gitter</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/0*icrS69OCMsjCraZs.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d403574a8c42" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An In-Depth Guide to Testing Ethereum Smart Contracts]]></title>
            <link>https://iamdefinitelyahuman.medium.com/an-in-depth-guide-to-testing-ethereum-smart-contracts-2e41b2770297?source=rss-1f38e34e130f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e41b2770297</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[pytest]]></category>
            <dc:creator><![CDATA[iamdefinitelyahuman]]></dc:creator>
            <pubDate>Thu, 23 Jul 2020 11:24:28 GMT</pubDate>
            <atom:updated>2021-03-08T13:36:54.313Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part One: Why we Test</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*JqSPrPfQ72m3wLNu.gif" /></figure><p>A major component in developing smart contracts is <em>testing</em> smart contracts. And yet, for the amount of content written on “how to code in Solidity” there is an unfortunate lack of content about how to write tests for that code.</p><p>I think there are several reasons for this:</p><ol><li>This is still a very new ecosystem. Solidity is only 5 years old, Vyper less than 3. While the tooling available today is much greater than what it was just a year ago, it is still far from the state of most mainstream languages.</li><li>Many developers with experience in other languages come from a culture where testing isn’t the norm — as such they may be competent programmers, but lack the knowledge of how to effectively test.</li><li>Smart contracts are deceptively simple. They are limited in syntax and complexity such that it can be easy to be lulled into a false sense of confidence about your code.</li></ol><p>So — developers who don’t know what they don’t know are using immature tools to test code that appears <em>so simple</em>, but where a single mistake can mean financial ruin.</p><p>In this series of articles we’re going to explore testing Ethereum smart contracts in depth, starting from the absolute basics and working our way into more complex ideas. By the end you should have a moderate understanding of the tools that are available, and an appreciation for what separates a good test suite from a great test suite.</p><h3>Why Test?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*IfjpcHYqj99WGzyB.gif" /></figure><p>I asked this a lot when I first started coding. Testing brings many benefits to the development process:</p><ol><li>Tests validate behaviors within your smart contract. They give you confidence that your code performs in the ways that you intend, and does not perform in the ways that it should not.</li><li>When developing, tests provide assurance that newly added code does not have unintended side effects. As you add new logic, a passing test suite helps you to confirm that you have not broken any previous functionality.</li><li>A good test suite simplifies refactoring. As you make changes and your tests begin to fail, they provide a clear indicator of which areas still must be addressed.</li><li>Tests save time in debugging. When an unexpected error appears, your test suite allows you to immediately rule out many potential causes. You can often adapt a test to help you reproduce the bug, aiding you in fixing the issue so you can resume development more quickly.</li></ol><p>A less tangible benefit, but most important in my mind — <strong>learning to write effective tests changes your approach to coding</strong>. The process of testing is somewhat akin to attacking your code, and as you hunt for vulnerabilities and edge cases you are developing a more security-focused mindset,which in turn improves the quality of the code that you write.</p><p>Similarly, <strong>well structured code is much easier to test than spaghetti</strong>. Being confronted with the challenge of “how do I test this?” helps you to recognize bad design patterns and learn to write code that is both more organized and more readable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/0*lY5qQ0PgiIyZo0o4.gif" /></figure><h3>Types of Tests</h3><p>Much has been written on different types of tests, how to define them and when to use them. For the purposes of this article we will keep things relatively simple by using two broad categories:</p><ul><li><strong>Unit tests</strong> are simple tests that verify a single behavior or component within your code. A well written unit test is quick to execute, and provides a clear picture of what went wrong when it fails.</li><li><strong>Integration tests</strong> are more complex tests that validate interactions between multiple components. For smart contract testing this can mean interactions between different components of a single contract, or across multiple contracts.</li></ul><p>We’re going to focus on unit testing — integration testing follows many of the same principles, but it is a more complex and nuanced subject that is better approached once we have a handle on the basics of unit testing.</p><h3>Tools for Testing</h3><p>You can only test as effectively as the tool set that you are using allows you to. For the purposes of this tutorial I am using the following development tools:</p><ol><li><a href="https://github.com/eth-brownie/brownie"><strong>Brownie</strong></a>, a python framework for developing smart contracts. Python is an excellent choice for testing because of it’s simple, readable syntax. It also has two incredibly powerful testing frameworks — <a href="https://docs.pytest.org/en/latest/"><strong>pytest</strong></a> and <a href="https://hypothesis.works/"><strong>hypothesis</strong></a>. Brownie extends upon each of these to provide unparalleled capabilities for testing your contracts.</li><li><a href="https://www.trufflesuite.com/docs/ganache/overview"><strong>Ganache</strong></a>, a temporary local blockchain used for testing and development. Ganache provides unlocked, funded accounts and mines new transactions instantly. It also allows actions such as reverting transactions and jumping forward in time, which are essential when testing.</li></ol><p>If you wish to follow along with the examples in this article, you should make sure each of these programs is installed and that the version is up-to-date. For help with installation you can check out my other article, “<a href="https://medium.com/@iamdefinitelyahuman/getting-started-with-brownie-part-1-9b2181f4cb99"><strong>Getting Started With Brownie</strong></a>”.</p><p>This tutorial is split into the following articles. When you’re ready, continue on with <a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-d403574a8c42"><strong>Part Two: Core Concepts of Testing</strong></a>. See you there!</p><p><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-2e41b2770297">Part One: Why we Test</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-d403574a8c42">Part Two: Core Concepts of Testing</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-3e07b8c38755">Part Three: Writing Basic Tests</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-fd699e3087e6">Part Four: Running Your Tests</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-31534a48e177">Part Five: Tools and Techniques for Effective Testing</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-2236902bf826">Part Six: Parametrization and Property-Based Testing</a><br><a href="https://medium.com/@iamdefinitelyahuman/an-in-depth-guide-to-testing-ethereum-smart-contracts-ff061e79bb86">Part Seven: Stateful Testing</a></p><p><em>You can also follow the Brownie </em><a href="https://twitter.com/BrownieEth"><em>Twitter account</em></a><em>, read my other </em><a href="https://medium.com/@iamdefinitelyahuman"><em>Medium articles</em></a><em>, and join us on </em><a href="https://gitter.im/eth-brownie/community"><em>Gitter</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/0*EX53l9s9iG3nwNR8.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e41b2770297" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ethereum Mainnet Testing with Python and Brownie]]></title>
            <link>https://iamdefinitelyahuman.medium.com/ethereum-mainnet-testing-with-python-and-brownie-82a61dee0222?source=rss-1f38e34e130f------2</link>
            <guid isPermaLink="false">https://medium.com/p/82a61dee0222</guid>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[defi]]></category>
            <dc:creator><![CDATA[iamdefinitelyahuman]]></dc:creator>
            <pubDate>Sat, 02 May 2020 17:50:19 GMT</pubDate>
            <atom:updated>2021-07-31T12:02:12.777Z</atom:updated>
            <content:encoded><![CDATA[<h4>or: how I learned to stop mocking and embrace the --fork</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/0*SuSxDoyS74X06w8D.gif" /></figure><h3>An Indulgent Introduction…</h3><p>Looking at Ethereum smart contract development over the years all I can think is —man, the times, they are a-changin’. When I wrote my first smart contract, my approach to security was to view that contract as an island. I sought to build an impenetrable fortress, capable of protecting the wealth within and preventing unsolicited interactions from what I viewed as an unknown horde of potential attackers.</p><p>As I kept learning and tinkering I grew to understand the unique challenges that immutability presented me. I started using libraries and building interconnected systems. I became comfortable with the idea that my own contracts were but a drop in a vast sea. Looking beyond the borders of my small empire of code, I stopped seeing threats and started seeing a world of opportunity. And the complexity continued to grow.</p><p>I wasn’t the only one having my smart contract coming-of-age. Collectively we have seriously leveled up at this stuff. Look around today and you’ll be hard pressed to find someone building a project that doesn’t interact with at least one existing protocol. DeFi has spurred an explosion of development as we find new and creative ways to put together our money legos. Increasingly complex <em>things</em> are popping up everywhere — it can be hard to keep up.</p><p>I can’t imagine how daunting this must be for a new developer. The attack surface is exponentially more than what it was just two years ago, and people can and do get rekt far too often. The digital wild west can be an unforgiving world.</p><p>But do not lose hope! As the complexity of protocols has grown, so too have the tools available for building and securing them. As the ecosystem matures we’re not only innovating in what we build, we’re also coming up with better ways to make sure it doesn’t break.</p><h3>And so we --fork…</h3><p><a href="https://github.com/trufflesuite/ganache-cli">Ganache</a>’s — fork option (hereafter called “fork mode”) is an absolute game changer. Through a bit of magic it provides a local development chain that’s been forked from the mainnet. Are you tired of struggling with mocks or figuring out how to locally deploy all those complex protocols you need to test against? Fork mode’s got you covered!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*7EI3EKtvvWIl1JNfsq41BQ.gif" /></figure><p>Of course it’s not without drawbacks — it’s a<em> </em>lot slower than working in a purely local environment. And while it works with <a href="https://infura.io/">Infura</a>, it’s a much more responsive experience when using your own node.</p><p>But on the other hand, it <em>does</em> work with Infura. Stop for a moment to appreciate how amazing it is that such a powerful resource is publicly available with such a low barrier to entry.</p><p>Now, let’s dive in.</p><h3>Using Ganache’s Fork Mode with Brownie</h3><h4>Initial Setup</h4><p>To get started using <a href="https://github.com/eth-brownie/brownie">Brownie</a> on a forked mainnet, all you need to do is <a href="https://medium.com/@iamdefinitelyahuman/getting-started-with-brownie-part-1-9b2181f4cb99">install Brownie</a> and set up an <a href="https://eth-brownie.readthedocs.io/en/stable/network-management.html#using-infura">Infura API key</a>. There’s no additional configuration required — it’s that easy!</p><p>Once installed, we can test it by opening the console:</p><pre>brownie console --network mainnet-fork</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SBS4-yhw9_1wanvNzCyq_w.png" /></figure><h4>Interacting with Mainnet Projects</h4><p>Brownie is integrated with the <a href="https://etherscan.io/">Etherscan</a> API to simplify interactions with other projects. All you need is an address in order to interact with any contract that has verified source code.</p><p>As an example, let’s query the current price of Ether from Chainlink’s <a href="https://etherscan.io/address/0xf79d6afbb6da890132f9d7c355e3015f15f3406f">ETH/USD oracle</a>:</p><pre>address = &quot;0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419&quot;<br>oracle = Contract.from_explorer(address)<br>oracle.latestAnswer()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sd6G_doc2Wc_K13N3Yz4tg.png" /></figure><p>In only three lines of code and without providing an ABI or source file, we’ve created an object to interact with a mainnet contract and fetched information from it. <strong><em>Impressive</em></strong><em>!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*rnRQo9zOm0ITYe-p.gif" /></figure><p>We can also access <a href="https://solidity.readthedocs.io/en/latest/natspec-format.html">NatSpec documentation</a> for any contract function that implements it — perfect for exploring an unfamiliar protocol. Chainlink makes good use of NatSpec, so let’s try it in our current session:</p><pre>oracle.updateRequestDetails.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5F_UO2P4oscejVUrZjSJaA.png" /></figure><h4>Unit Testing on Mainnet</h4><p>Now that we’ve confirmed everything works and gotten a taste for Brownie in fork mode, let’s write some tests! If you’re following along in a terminal, now is the time to <a href="https://medium.com/@iamdefinitelyahuman/getting-started-with-brownie-part-2-615a1eec167f">create a new Brownie project</a>.</p><p>To effectively write unit tests for the mainnet we’re going to build some fixtures. If you’re unfamiliar — a <a href="https://eth-brownie.readthedocs.io/en/stable/tests-pytest-intro.html#fixtures">fixture</a> is a test component that handles the setup and teardown phases of one or more unit tests. Fixtures reduce duplicated code and ensure that tests are run against the same initial conditions, producing consistent and repeatable results. They are a core component in any pytest test suite and an extremely powerful tool.</p><p>Let’s start by building a very simple fixture to access the DAI stablecoin:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/391536ef9bf684c4a4cebe3349e4dea8/href">https://medium.com/media/391536ef9bf684c4a4cebe3349e4dea8/href</a></iframe><p>How it works:</p><ol><li>The <strong>@pytest.fixture</strong> decorator on line 4 marks the <strong>dai</strong> function as a fixture. Within the fixture we are querying Etherscan to generate a <a href="https://eth-brownie.readthedocs.io/en/stable/core-contracts.html#contracts-outside-of-your-project"><strong>Contract</strong></a> object for the <a href="https://etherscan.io/address/0x6b175474e89094c44da98b954eedeac495271d0f">DAI smart contract</a>.</li><li>The <strong>test_dai_fixture</strong> function on line 10 is our test case. By including <strong>dai</strong> in the function inputs, we tell pytest that this function requires the <strong>dai</strong> fixture. When the test executes, the logic within <strong>dai</strong> is executed as the setup phase of our test, and the return value is made available to the actual test.</li></ol><p>Save this test as <strong>tests/test_dai_example.py</strong> within your Brownie project, and then run it with the following command:</p><pre>brownie test --network mainnet-fork</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kEQrPdKJ0J1W5gDBIx-F-Q.png" /></figure><p>It worked! So now you might be thinking “Ok great, I can interact with the DAI contract. But how do I actually <em>get</em> some DAI?”</p><p>Let’s build another fixture!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be94d58e1de3827e7b0bc0011ee18602/href">https://medium.com/media/be94d58e1de3827e7b0bc0011ee18602/href</a></iframe><ol><li>First, we add another fixture named <strong>uniswap_dai_exchange</strong>to allow access to the <a href="https://etherscan.io/address/0x2a1530C4C41db0B0b2bB646CB5Eb1A67b7158667">Uniswap DAI exchange.</a></li><li>Next we create a new test named test_buy_dai. It uses both the <strong>dai</strong> and <strong>uniswap_dai_exchange</strong> fixtures, as well as the builtin Brownie <a href="https://eth-brownie.readthedocs.io/en/stable/tests-pytest-fixtures.html#accounts"><strong>accounts</strong></a> fixture. Within this test we’re calling to Uniswap to exchange 10 ether for DAI, and then asserting that the exchange was successful.</li></ol><p>That’s pretty cool… but can we improve on this further? Let’s make some tweaks.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17b9348ff1c1aa9d0a1af338fdbab28d/href">https://medium.com/media/17b9348ff1c1aa9d0a1af338fdbab28d/href</a></iframe><p>In this example:</p><ol><li>First we moved the call to purchase DAI out of the test and into another fixture named <strong>buy_dai</strong>.</li><li>We then add a flag <strong>autouse=True</strong> to the fixture. This tells pytest to automatically run the fixture, even if a test doesn’t specifically require it.</li><li>We also add <strong>scope</strong> arguments to each of our fixtures. <a href="https://eth-brownie.readthedocs.io/en/stable/tests-pytest-intro.html#fixture-scope">Scoping</a> lets us alter how frequently the logic within a fixture executes — in this case, only once for the entire test session.</li></ol><p>The end result? In under 25 lines of code we’ve constructed a base testing environment in which we always have DAI available for use in our actual tests!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*f2ZsZ9fnHzjSoWCrhW-jyQ.gif" /></figure><h3>What’s next…</h3><p>We’ve only scratched the surface of what’s possible with Brownie when combined with Ganache’s fork mode. I hope this leaves you feeling inspired to go out and r̶e̶w̶r̶i̶t̶e̶ ̶y̶o̶u̶r̶ ̶t̶e̶s̶t̶ ̶s̶u̶i̶t̶e buidl something new and incredible with these tools!</p><p>To learn more about <a href="https://github.com/iamdefinitelyahuman/brownie">Brownie</a> and keep up to date with all the new features in development, please follow our <a href="https://twitter.com/BrownieEth">Twitter account</a> and read our other <a href="https://medium.com/@iamdefinitelyahuman">Medium articles</a>. You can also say hi on <a href="https://gitter.im/eth-brownie/community">Gitter</a> if you have any questions about using pytest, working in fork mode, or anything else related to Ethereum or Python development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*0L-gvbm-B8rpzQ65ISmkoQ.png" /><figcaption>I’m open to assistance with graphics and branding :)</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82a61dee0222" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started With Brownie (Part 3)]]></title>
            <link>https://medium.com/better-programming/getting-started-with-brownie-part-3-ef6bfa9867d7?source=rss-1f38e34e130f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef6bfa9867d7</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[iamdefinitelyahuman]]></dc:creator>
            <pubDate>Sun, 19 Apr 2020 21:19:10 GMT</pubDate>
            <atom:updated>2020-05-04T15:51:10.785Z</atom:updated>
            <content:encoded><![CDATA[<h4>Basic Brownie functionality</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yx7msuiRyIOM1rGFdkogPw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@silverhousehd?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">André François McKenzie</a> on <a href="https://unsplash.com/s/photos/ethereum?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Now that we’ve <a href="https://medium.com/@iamdefinitelyahuman/getting-started-with-brownie-part-1-9b2181f4cb99">installed Brownie</a> and <a href="https://medium.com/@iamdefinitelyahuman/getting-started-with-brownie-part-2-615a1eec167f">created a project</a>, it’s time to get acquainted with some of the core functionality.</p><p>If you haven’t yet, start by opening the console:</p><pre>brownie console</pre><p><a href="https://github.com/iamdefinitelyahuman/brownie">Brownie</a> will launch <a href="https://github.com/trufflesuite/ganache-cli">Ganache</a> and create some objects to help you interact with your project. Once it’s ready, you are given a command prompt:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*ZTkKgk6Lh2PPwaPFnbNQwQ.png" /></figure><p>For the newcomers to Python, it’s time to level up! Let’s take a look at two very useful built-in functions:</p><ul><li><strong>dir</strong> displays a list of objects within the namespace or a list of members of an object. If using Python feels like visiting a foreign country to you, then think of dir as your roadmap.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RXCN-7XVnxdiiVi95sUkIw.png" /></figure><ul><li><strong>help</strong> accepts any object as an argument and displays documentation for the object. Continuing with our previous analogy, if dir is your roadmap, thenhelp is your guidebook.</li></ul><p>With these two functions and a healthy dose of curiosity, you can pretty much figure out how to do anything without reaching for the documentation. (But please do open the <a href="https://eth-brownie.readthedocs.io/en/stable/index.html">Brownie documentation</a>. I put a lot of work into it.)</p><h3>Transferring Ether</h3><p>Let’s start with a simple transaction. Because we’re using Ganache, there are already several unlocked accounts available to us that are funded with 100 ether. Objects to interact with these accounts can be found in a container called accounts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T5r1pEgmHwkK_wS3N7ajcQ.png" /></figure><p>Let’s start with a simple transfer of one ether from accounts[0] to accounts[1]. Enter the following command:</p><pre>accounts[0].transfer(accounts[1], &quot;1 ether&quot;)</pre><p>Instead of &quot;1 ether&quot; you could type 1e18 or even 1000000000000000000, but I find the string easier to read and Brownie will happily convert it.</p><p>Ganache mines the transaction immediately, and the result is outputted to the console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*non2Xk5nymXQ0QOr4SJVDw.png" /></figure><p>See that last line? &lt;Transaction ...&gt;? That’s an object representing the transaction that you just made. Because it wasn’t assigned to a variable, it was printed to the console. But don’t worry, even though you didn’t assign it all is not lost! Transactions are also added to a container called history:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NDoNf-SzYQN0E52bOPsOUA.png" /></figure><p>The TransactionReceipt object contains many attributes and methods for inspecting a transaction. It is one of the most powerful components of Brownie and probably deserves its own article. We’ll come back to it soon.</p><h3>Working With Contracts</h3><p>The token-mix template includes one deployable contract, named Token. Each contract has an object that can be used for deployment, like so:</p><pre>Token.deploy(&quot;TST&quot;, &quot;Test Token&quot;, 18, 1e24, {&#39;from&#39;: accounts[0]})</pre><p>While typing the command, you’ll notice that Brownie offers hints as to the required values. How neat is that?</p><p>The final value is known as a <strong>transaction dictionary</strong>. This is where you specify information such as the sender, gas price, and gas limit. Brownie uses sensible defaults where possible — the only required field is from.</p><p>Broadcast the transaction, and behold: A newly deployed contract is born.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*zU_H_H_oNJva3h_LJBItiw.png" /></figure><p>The call returns a Contract object, which is used to interact with the deployment. What’s that? You didn’t assign it again?! No biggie. The object that you used to deploy is also a container that holds the deployments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*2C2GabYOhwMaeVdYp4KlMQ.png" /></figure><p>Assign the deployed Contract object to a variable, and then let’s have a look at it with our good friend dir:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*OY28Pppag3YFw2ab8eqWTA.png" /></figure><p>All of the standard ERC20 methods are available as callable members within the object. Start by checking the total supply and a balance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*hiIV6dpyZ32AXZRjQDXEuA.png" /></figure><p>As expected, all the tokens were initially assigned to the address we used to deploy the contract. Let’s try sending some of those tokens, and this time be sure to assign the returned TransactionReceipt:</p><pre>tx = contract.transfer(accounts[1], 1e18, {&#39;from&#39;: accounts[0]})</pre><h3>Working With Transactions</h3><p>Now it’s time to take a look at that transaction. We’ll start with a quick call to dir(tx). You can see just how much information is available:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*V4dYnBGoDIBrv1kvskji7Q.png" /></figure><p>It’s a long list, and most of the attributes are fairly self-explanatory. For now, call tx.info() to get an expanded human-readable description of the transaction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*NZxdYzjbFXE80PjKIxxAWw.png" /></figure><p>Where the TransactionReceipt object really shines is when things don’t go according to plan. Type the following command:</p><pre>tx = contract.transfer(accounts[3], 1e18, {&#39;from&#39;: accounts[2]})</pre><p>Oh no, our transaction failed!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FwmHryF3Oa14xwSM5A3ULg.png" /></figure><p>You might already know what went wrong, but we’ll investigate anyway. Start with the following command:</p><pre>tx.error()</pre><p>Brownie outputs a chunk of source code where the error occurred:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*Pq7jmnHdgXm_8xKpeSx2dA.png" /></figure><p>Okay, we failed a SafeMath underflow check. Good to know, but we could use some context. Try this command next:</p><pre>tx.traceback()</pre><p>This time we’re shown a Python-style traceback highlighting each frame leading up to the revert:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zcTa5RLqKbx2bOc6PLe0sw.png" /></figure><p>And voila! The underflow was because msg.sender had an insufficient balance. This example is quite simple, but when you find yourself building the next DeFi gem and you’re jumping between a dozen contracts in a single transaction, those tracebacks are gonna leave you feeling pretty zen.</p><h3>Next Up</h3><p>That’s it for now! Soon we’ll release a Part Four where we discuss unit testing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef6bfa9867d7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/getting-started-with-brownie-part-3-ef6bfa9867d7">Getting Started With Brownie (Part 3)</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started With Brownie (Part 2)]]></title>
            <link>https://medium.com/better-programming/getting-started-with-brownie-part-2-615a1eec167f?source=rss-1f38e34e130f------2</link>
            <guid isPermaLink="false">https://medium.com/p/615a1eec167f</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[iamdefinitelyahuman]]></dc:creator>
            <pubDate>Sun, 19 Apr 2020 21:17:54 GMT</pubDate>
            <atom:updated>2020-05-04T15:50:56.290Z</atom:updated>
            <content:encoded><![CDATA[<h4>Working with Brownie projects</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*92DgiNmPPshn_rQDi8QQoA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@thoughtcatalog?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Thought Catalog</a> on <a href="https://unsplash.com/s/photos/ethereum?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><em>Missed part one? </em><a href="https://medium.com/@iamdefinitelyahuman/getting-started-with-brownie-part-1-9b2181f4cb99"><em>Click here</em></a><em>.</em></p><p>We’ve just installed <a href="https://github.com/iamdefinitelyahuman/brownie">Brownie</a> and confirmed that it works. Now what? Let’s start with a quick orientation, and then we’ll dive into some of the more important areas. First things first: We need a project!</p><h3>Create a Brownie Project</h3><p>Most of the time when using Brownie, you’ll be working with a project. A project consists of one or more smart contracts, unit tests, and scripts to handle deployment and common interactions.</p><p>We can start a new project by typing brownie init inside an empty folder, but for this tutorial, we’re instead going work from a pre-made project. Brownie offers several templates (known as <em>mixes</em>), and a tool for initializing them, brownie bake.</p><p>Let&#39;s get started by initializing <a href="https://github.com/brownie-mix/token-mix">token-mix</a>, a simple ERC20 project:</p><pre>brownie bake token<br>cd token</pre><p>Once the initialization finishes, open the newly created token subdirectory and have a look around. If you’ve used other smart contract frameworks, this layout is likely familiar.</p><ul><li><strong>contracts/</strong> holds all of the source files for your project’s smart contracts. Brownie supports contracts written in <a href="https://solidity.readthedocs.io/en/v0.6.6/">Solidity</a> (with a .sol suffix) and <a href="https://vyper.readthedocs.io/en/latest/">Vyper</a> (with a .vy suffix).</li><li><strong>interfaces/</strong> holds smart contract interfaces required by your project. An interface is a file that can be used to interact with a contract but doesn’t contain enough information to deploy it.</li><li><strong>scripts/</strong> holds the Python scripts used for deployment and interaction with your project.</li><li><strong>tests/</strong> holds the unit tests for your project. Brownie uses the <a href="https://docs.pytest.org/en/latest/">pytest</a> framework for testing.</li></ul><h3>Run the Compiler</h3><p>The project was initialized, but it hasn’t been compiled yet. We can manually trigger the compiler with the following command:</p><pre>brownie compile</pre><p>You should see some output like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*zVpV9zDxWGHvWUnHaz1jnQ.png" /></figure><p>Brownie automatically tracks the files in your project’scontracts/ folder and will run the compiler when a file is added or changed. There isn’t often a need to manually compile — but it’s still good to know how.</p><h3>Run the Tests</h3><p>Brownie uses <a href="https://docs.pytest.org/en/latest/">pytest</a> for unit testing. Pytest is a mature and full-featured testing framework — if you haven’t used it before, you’ll quickly come to love it. We’ll get into the how of unit testing in another article. For now, let’s just run the test suite:</p><pre>brownie test</pre><p>You should see output like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*gpbUFHDMcR8anj7_Aqhmvw.png" /></figure><p>Brownie can also evaluate test coverage:</p><pre>brownie test --coverage</pre><p>You should see output like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*FLknFV6_FQFfnVokFE1S5g.png" /></figure><h3>Run the Deployment Script</h3><p>Inside the scripts/ folder, you’ll find a single file, token.py. This is a very basic script that can handle deployment of the Token contract. Let’s try running it:</p><pre>brownie run token</pre><p>You should see output like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*qom3CyEYmp0RMEvYdGWmHw.png" /></figure><p>You may have noticed that Brownie loaded <a href="https://github.com/trufflesuite/ganache-cli">Ganache</a> and the contract was deployed there. This is good since we’re just figuring out how everything works, but when it comes time for an actual deployment we’d use the --network flag to instead deploy to a live network. More on that later.</p><h3>Launch the Console</h3><p>The Brownie console is a valuable tool for quick testing and debugging while you develop. It’s also an excellent starting point to familiarize yourself with Brownie’s functionality.</p><p>To load the console:</p><pre>brownie console</pre><p>You should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*ZTkKgk6Lh2PPwaPFnbNQwQ.png" /></figure><p>As you type, Brownie provides auto-completion and input hints to help you navigate. You’re connected on a development chain provided by Ganache, so feel free to play around. You won’t break anything :)</p><h3>Next Up</h3><p>Don’t close the console just yet! In <a href="https://medium.com/@iamdefinitelyahuman/getting-started-with-brownie-part-3-ef6bfa9867d7">Part Three</a> of this series, we’ll be using it to explore some of Brownie’s functionality.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=615a1eec167f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/getting-started-with-brownie-part-2-615a1eec167f">Getting Started With Brownie (Part 2)</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>