<?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 Navaratnarajah Suman on Medium]]></title>
        <description><![CDATA[Stories by Navaratnarajah Suman on Medium]]></description>
        <link>https://medium.com/@sumanrbt1997?source=rss-e3c821d67e7f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*8BJI0K_pV6tfc9je.jpg</url>
            <title>Stories by Navaratnarajah Suman on Medium</title>
            <link>https://medium.com/@sumanrbt1997?source=rss-e3c821d67e7f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 23:48:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sumanrbt1997/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[Python Test Driven Development]]></title>
            <link>https://medium.com/@sumanrbt1997/python-test-driven-development-a4cb860cd8bd?source=rss-e3c821d67e7f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4cb860cd8bd</guid>
            <dc:creator><![CDATA[Navaratnarajah Suman]]></dc:creator>
            <pubDate>Tue, 25 Oct 2022 02:01:11 GMT</pubDate>
            <atom:updated>2022-10-25T02:01:11.396Z</atom:updated>
            <content:encoded><![CDATA[<p>Test driven development is a software development practice known to be rediscovered by an American software engineer named Kent Beck. Its a software development practice where much importance is given to testing during the development phase.</p><p>If you are not familiar with the concepts of unit testing and coverage, it is a good idea to revisit my previous articles on those topics before further reading..</p><p><a href="https://medium.com/@sumanrbt1997/unit-testing-with-pytest-7b217e77c3ab">Unit testing</a></p><p><a href="https://medium.com/@sumanrbt1997/code-coverage-with-pytest-1f72653b0bf2">Coverage</a></p><p>Before we dive in to the details of TDD, lets look at some facts that will motivate us to take TDD seriously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/120/1*Sn76gkSQF79BUfRc_6xeXA.png" /></figure><p>‘We do TDD’ is a community for TDD practitioners and companies that promote TDD to their teams and employees. You can get reliable data about which companies are promoting TDD, the facts on this platform are a result of direct interviews with people in leading positions in those companies, thanks to the efforts of the founders in bringing up the entire TDD community and resources to one place. In addition to that, the historic first International Conference on TDD was held around mid 2021. In spite of usual controversies that rise up for new ideologies, TDD is slowly getting the attention of many developers and companies, so its worth investing some of your time to get started with TDD.</p><p>Its now time for us to look into what TDD really is. TDD basically has just one main rule which says “ Not a single piece of code must be written to solve a problem before the test case is written and in place”. Below is a clear demonstration of the steps involved in TDD.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Zj0iY7lR6NI_-rfsnddLFw.png" /><figcaption>Image Credit: <a href="https://rubentejera.com/algoritmo-tdd/">https://rubentejera.com/algoritmo-tdd/</a></figcaption></figure><p>The very first step of TDD is to write a test case, so remember that you are not allowed to write a single piece of code unless you have a test case in place. Once you have written the test case, obviously your test would fail since you do not have the solution yet. Now is the time to write your solution, make the test case pass and the do some refactoring. One cycle of TDD is completed. You can go for more iterations if you need to update your test cases.</p><p>Lets look at a simple problem to understand the process of TDD clearly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*ahqicFlmAIwvkrRcScQA9Q.png" /><figcaption>A simple task</figcaption></figure><p>Suppose you are required to write a function that takes in two numbers and returns the sum depending on their signs.</p><p>So once you are assigned with the task you should analyze the problem and follow the steps below to solve it in a TDD based approach.</p><h4>STEP 1: ______ Write a failing test case______</h4><p>The third test case is intentionally made wrong for demonstration purposes, the expected value is supposed to be ‘1’ not ‘-1’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*ilCwwMjpKiN7dYBYk1kmwA.png" /></figure><p>If you not familiar with writing unit tests using pytest, I would recommend to revisit my previous article <a href="https://medium.com/@sumanrbt1997/unit-testing-with-pytest-7b217e77c3ab">Unit testing with pytest</a>.</p><h4>STEP 2: ______ Write a Solution ______</h4><p>Once you have the test case in place, you can go ahead and code the solution, you can write the code confidently and faster because you already have a test case in place which will give you the opportunity to get immediate feedback.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*z9OA8WUWi2LmYoZZQazpSA.png" /></figure><p>Writing the function is upto you, the goal is to make the test case pass.</p><h4>STEP 3: ______ Refactor and continue ______</h4><p>After the test passes you may refactor and continue iterations until you are satisfied, you may update the test cases and make the test stronger and stronger at each iteration, similarly at each iteration the solution can be made more and more robust.</p><p>For the above solution the test summary would be as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*H54xB_vQ9SD6kSelV0_Frw.png" /></figure><p>As expected the third test case fails, so in the next iteration you can update the test and run the test again and make sure all test cases pass.</p><p>Also remember while iterating you can take into consideration the coverage as well, just making the tests pass is not sufficient, you must make sure that the code and tests are both optimized and no unwanted tests and no unwanted pieces of code exists, these things can be handled in the refactoring stage.</p><p>This concludes the introduction to test driven development in python. Please comment if you have any questions/discussions..</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4cb860cd8bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Code coverage with pytest]]></title>
            <link>https://medium.com/@sumanrbt1997/code-coverage-with-pytest-1f72653b0bf2?source=rss-e3c821d67e7f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f72653b0bf2</guid>
            <category><![CDATA[line-coverage]]></category>
            <category><![CDATA[unit-testing-framework]]></category>
            <category><![CDATA[coverage]]></category>
            <category><![CDATA[pytest-cov]]></category>
            <category><![CDATA[coverage-report]]></category>
            <dc:creator><![CDATA[Navaratnarajah Suman]]></dc:creator>
            <pubDate>Sat, 16 Jul 2022 04:29:07 GMT</pubDate>
            <atom:updated>2022-10-23T04:26:06.060Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*CpbCF8a4OQKLf5eFvJt85A.jpeg" /><figcaption>Code coverage with pytest-cov plugin</figcaption></figure><p>Great software products emerge with a great code base and great code base comes as a result of great testing efforts. It is always a best practice to write tests for the code that you write(even before starting the code implementation whenever possible).</p><p>Coming to the topic, suppose we write a test script for a programme, we always want to know how effective the test we wrote is and <strong>code coverage</strong> can be used for this purpose.</p><p>Code coverage measures how effectively we have written our tests scripts. In this article we will be using <strong>pytest-cov </strong>to measure the code coverage for the examples that follow. Before starting, the install requirement is given below.</p><pre>pip install pytest==7.1.2<br>pip install pytest-cov==3.0.0</pre><p>Lets consider the following simple function. Create a python file called add.py and write the below function inside it.</p><pre>def find_sign(a: int, b: int) -&gt; str:<br>    summation = a + b<br>    if summation &gt; 0:<br>        ans = &quot;positive&quot;<br>    else:<br>        ans = &quot;negative&quot;<br>    return ans</pre><p>The above simple function takes in two integers and returns the string “positive” and “negative” depending on the sign.</p><p>Now lets write a test function for this. Import the add script with the defined function into this test script. I would strongly suggest to have a look at pytest parametrization for a clearer understanding(Simply put its a way to give multiple (input, output) cases to a test without having to write multiple test functions)</p><pre>import add<br>import pytest<br><br><br>@pytest.mark.parametrize(&quot;inp1, inp2, exp&quot;, [[2, 3, &quot;positive&quot;]])<br>def test_return_value(inp1, inp2, exp):<br>    assert add.find_sign(inp1, inp2) == exp</pre><p>Now lets generate the coverage report for this test script and do some initial analysis.</p><p>In the terminal with the test script and add.py in the current working directory, lets type the following command. The first command runs pytest using coverage run and the second command generates the coverage report.</p><pre>coverage run -m pytest<br>coverage report -m</pre><p>The following report is generated.</p><p>add.py is the script we are interested in while test_coverage.py is the script where we wrote the tests.</p><pre>Name               Stmts   Miss  Cover   Missing<br>------------------------------------------------<br>add.py                 6      1    83%   6<br>test_coverage.py       5      0   100%<br>------------------------------------------------<br>TOTAL                 11      1    91%</pre><p>You can observe that out of 7 lines in add.py only 6 lines have been <strong>covered</strong> by our test script, the number under the <strong>Missing </strong>column gives the line that has not been tested.</p><p>Thats the power and benefit of using coverage when you write test scripts. You are pointed to the line for which you have to add a test case.</p><p>If you observe the find_sign function again you notice that that you tested the function for positive output, but not for negative outputs, therefore you can go ahead and update the test script to include that case.</p><pre>import add<br>import pytest<br><br><br>@pytest.mark.parametrize(&quot;inp1, inp2, exp&quot;, [[2, 3, &quot;positive&quot;],<br>                                             [-3, -4, &quot;negative&quot;]])<br>def test_return_value(inp1, inp2, exp):<br>    assert add.find_sign(inp1, inp2) == exp</pre><p>After adding the inputs that generate a negative output, you can generate the coverage report again.</p><pre>Name               Stmts   Miss  Cover   Missing<br>------------------------------------------------<br>add.py                 6      0   100%<br>test_coverage.py       5      0   100%<br>------------------------------------------------<br>TOTAL                 11      0   100%</pre><p>Now you can observe that our test script covers the entire add.py script.</p><p>The coverage that we discussed so far is known as line coverage or statement coverage(how many lines of the code base have been executed while performing the tests), its one of the basic measures of the effectiveness of your test scripts, there are far more superior measures that you can adapt to. Since the intention of this article is to give you a practical introduction to code coverage, I will cover the other aspects of code coverage in another article.</p><p>In the mean time a great youtube video to understand some advanced coverage measures in addition to the line coverage that I have covered in this article. I must acknowledge the following youtube video for a great discussion about code coverage in general</p><p><a href="https://www.youtube.com/watch?v=n313mojz9hI&amp;t=1485s">https://www.youtube.com/watch?v=n313mojz9hI&amp;t=1485s</a></p><p>This concludes the introduction to understanding code coverage in testing python scripts. Please comment any questions you might have..</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f72653b0bf2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit testing with pytest]]></title>
            <link>https://medium.com/@sumanrbt1997/unit-testing-with-pytest-7b217e77c3ab?source=rss-e3c821d67e7f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b217e77c3ab</guid>
            <category><![CDATA[testing-file-writing]]></category>
            <category><![CDATA[pytest-medium]]></category>
            <category><![CDATA[python-testing]]></category>
            <category><![CDATA[unittest]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Navaratnarajah Suman]]></dc:creator>
            <pubDate>Sat, 09 Jul 2022 05:02:53 GMT</pubDate>
            <atom:updated>2022-10-25T01:31:56.481Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*CpbCF8a4OQKLf5eFvJt85A.jpeg" /><figcaption>Unit testing with pytest</figcaption></figure><p>There are various levels of testing involved in a software development process including integration testing, system testing and acceptance testing to name a few. Unlike other tests, Unit test is the basic form of tests that are written for the smallest piece of code that can be logically isolated, for example unit tests can be written for functions or methods.</p><p>Writing unit tests is the responsibility of the developers themselves, having unit tests is place is highly beneficial because they help in avoiding unwanted bugs and also are highly useful when it comes to refactoring, once you refactor your codes, you can easily check is still all the unit tests are passing, if you have introduced a bug while refactoring these unit tests will immediately point them out. And finally its a form of documentation that the next developer who takes over the code can have, at times it may be a good informal documentation for your future self as well. That said we can now go into the technical details of writing basic unit tests in Python using the pytest framework.</p><p>Lets look at writing unit tests for the following cases:</p><h4><strong>1. Functions that return a value</strong></h4><p>For functions that return a value, you can verify the <strong>type</strong> and <strong>value</strong> of the returned value using an assert statement.</p><h4>2. Functions that write to a file</h4><p>For functions that write contents to a file, you can verify that the expected contents have been written to the files</p><h4>3. Certain inputs to a function will raise intended exceptions</h4><p>When writing a function, you will know that certain exceptions should be raised for certain inputs. You can verify that the expected exceptions are raised.</p><p>The following simple function that divides two numbers pretty much covers all the aspects of testing described above.</p><pre>def divide_func(num1: float, num2: float, filename: str = None):<br>    <em>&quot;&quot;&quot;<br>    </em><strong><em>:param</em></strong><em> num1: (int)<br>    </em><strong><em>:param</em></strong><em> num2: (int)<br>    </em><strong><em>:param</em></strong><em> filename: (str)<br>    </em><strong><em>:return</em></strong><em>: (float) returns float and writes the output to the file<br><br>    &quot;&quot;&quot;<br><br>    </em>if num2 == 0:<br>        raise ZeroDivisionError(&quot;Number not divisible by zero!!&quot;)<br><br>    elif isinstance(num1, str) or isinstance(num2, str):<br>        raise TypeError(&quot;The numbers entered must be integers&quot;)<br><br>    else:<br>        if filename is not None:<br>            with open(filename, &quot;w&quot;) as fo:<br>                fo.write(str(num1 / num2))<br>        return num1/num2<br><br><br>divide_func(2, 4.2, &quot;ans.txt&quot;)</pre><p>This fucntion takes in two numbers and an optional filename, if num2 is zero and ZeroDivisionError is raised and if either of the numbers is a string, then a TypeError is raised, else the answer is returned and optionally can be written to the given text file.</p><h4><strong>Testing the return value</strong></h4><p>Write the test inputs and then we use assert to make sure both the returned value and the expected values are the same</p><pre>def test_divide_fun_return_value():<br>    num1 = 2<br>    num2 = 4<br>    exp_ans1 = 0.5<br><br>    assert divide_function.divide_func(num1, num2) == exp_ans1</pre><h4>Testing the return type</h4><p>Although this part can be included in the previous test, it is upto the developer whether to create a seperate test for this.</p><pre>def test_divide_fun_return_type():<br>    num1 = 2<br>    num2 = 4<br><br>    assert isinstance(divide_function.divide_func(num1, num2, None),<br>                      float)</pre><h4>Testing whether expected exceptions are raised</h4><p>We can write seperate tests for the different types of exceptions that are raised, again is the choice of the developer to make them seperate or not.</p><pre>def test_divide_fun_exception():<br>    with pytest.raises(ZeroDivisionError):<br>        divide_function.divide_func(1, 0)<br><br><br>def test_divide_fun_exception2():<br>    with pytest.raises(TypeError):<br>        divide_function.divide_func(1, &quot;2&quot;)</pre><p>These tests pass only if the intended exceptions are raised, otherwise the tests fail.</p><h4>Testing if the writing to file is succesful</h4><p>When checking whether the file writing has been successful its a good practice to write the files to a temporary file provided by pytest so that testing files dont pile up in the working directory. pytest tmppath is used to create temporary files and then delete them once the testing is done.</p><pre>def test_divide_fun_file_write(tmp_path):<br>    num1 = 2<br>    num2 = 4<br>    exp_ans1 = 0.5<br><br>    # call the function that writes output to file<br>    divide_function.divide_func(num1,<br>                                num2,<br>                                str(tmp_path)+&quot;/test.txt&quot;)<br>    <br>    with open(str(tmp_path)+&quot;/test.txt&quot;, &quot;r&quot;) as fo:<br>        assert fo.read() == str(exp_ans1)</pre><p>We read the file that is created and make sure that the contents are equal to our expected outputs.</p><p>This concludes the short introduction to testing different components of a function. Please comment if you have any questions..</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b217e77c3ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>