<?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 Shradhasharma on Medium]]></title>
        <description><![CDATA[Stories by Shradhasharma on Medium]]></description>
        <link>https://medium.com/@shradhasharma131?source=rss-86ac6b12edbe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*1mp5twffEi6kwfUl</url>
            <title>Stories by Shradhasharma on Medium</title>
            <link>https://medium.com/@shradhasharma131?source=rss-86ac6b12edbe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 12:15:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shradhasharma131/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[Unit test cases]]></title>
            <link>https://medium.com/@shradhasharma131/unit-test-cases-2e842d32aee2?source=rss-86ac6b12edbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e842d32aee2</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python-testing]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[unittest]]></category>
            <category><![CDATA[python-flask]]></category>
            <dc:creator><![CDATA[Shradhasharma]]></dc:creator>
            <pubDate>Thu, 01 Jun 2023 11:08:21 GMT</pubDate>
            <atom:updated>2023-06-01T11:08:21.743Z</atom:updated>
            <content:encoded><![CDATA[<ul><li>What Is a Unit?</li><li>Structure of unit test cases</li><li>Running test cases</li><li>How to Write Assertions</li><li>Testing different components of code</li><li>Testing Pure Functions</li><li>Testing Private Methods</li><li>Testing Expected Failures</li><li>Testing Side Effects</li><li>What are Side Effects</li><li>Outcomes Possible</li><li>References</li></ul><h4><strong>What Is a Unit?</strong></h4><p>A unit could be bucketed into various categories:</p><ul><li>An entire module,</li><li>An individual function,</li><li>A complete interface like a class or a method.</li></ul><h4>Structure of unit test cases</h4><p>The structure of a test method is pretty standard:</p><ul><li>Prepare the environment (override setup()).</li><li>Prepare the expected result.</li><li>Mock out all dependencies</li><li>Call the code under test.</li><li>Assert that the actual result matches the expected result.</li><li>Perform cleanup of the environment (override teardown())</li></ul><h4>Running test cases</h4><p>To discover and run your unit test-based tests, simply type on the command line:</p><p><em>1</em>python -m unittest discover</p><p>unit test will scan all the files and sub-directories, run any tests it finds, and provide a nice report as well as runtime. If you want to see what tests it is running, you can add the -v flag:</p><p><em>1</em>python -m unittest discover -v</p><h4>How to Write Assertions</h4><p>The last step of writing a test is to validate the output against a known response. This is known as an assertion. There are some general best practices around how to write assertions:</p><ul><li>Make sure tests are repeatable and run your test multiple times to make sure it gives the same result every time</li><li>Try and assert results that relate to your input data, such as checking that the result is the actual sum of values in the sum() example</li></ul><p>.assertIs(), .assertIsNone(), .assertIn(), and .assertIsInstance() all have opposite methods, named .assertIsNot(), and so forth.</p><p>assertRaises()<strong>: </strong>This statement is used to raise a specific exception.</p><p><strong>Example code: Testing that a function raised a ValueError exception</strong></p><pre>import unittest<br>def parse_int(s):<br>  return int(s)<br><br>class TestConversion(unittest.TestCase):<br>  def test_bad_int(self):<br>    self.assertRaises(ValueError, parse_int, &#39;N/A&#39;)</pre><h3>Testing different components of code</h3><h4>Testing Pure Functions</h4><p>The easiest code to test is pure functions. Pure functions are functions that access only the values of their parameters, have no side effects, and return the same result whenever called with the same arguments. They don’t change your program’s state, and don’t access the file system or the network. Their benefits are too many to count here.</p><p>Let&#39;s say, we have a function to calculate the volume of the cuboid:</p><pre>def cuboid_volume(l):<br>  return (l*l*l)</pre><p>We can test this function as:</p><pre>def test_cuboid_volume(self):<br>   side = 5<br>   expected_volume = 125<br>   self.assertEqual(expected_volume, cuboid_volume(side))<br>   </pre><h4>Testing Private Methods</h4><p>Should you test every function and method? In particular, should you test private methods called only by your code? The typically unsatisfying answer is: “It depends”.</p><p>Unit testing a private method is considered bad. Why?</p><p>A couple of reasons:</p><ol><li><strong>Typically when you’re tempted to test a class’s private method, it’s a design smell</strong> (iceberg class, not enough reusable public components, etc). There’s almost always some “larger” issue at play.</li><li><strong>You can test them through the public interface (which is how you want to test them because that’s how the client will call/use them).</strong> You can get a false sense of security by seeing the green light on all the passing tests for your private methods. It is much better/safer to test edge cases on your private functions through your public interface.</li><li><strong>You risk severe test duplication (tests that look/feel very similar) by testing private methods.</strong> This has major consequences when requirements change, as many more tests than necessary will break. It can also put you in a position where it is hard to refactor because of your test suite…which is the ultimate irony because the test suite is there to help you safely redesign and refactor!</li></ol><p><strong>When to test private methods: </strong>If you think you should test your private methods and have a legitimate reason (like you’re writing characterization tests for a legacy application), then test your private methods. Specific circumstances always trump any general rule or best practice. Just be aware of some of the things that can go wrong (see above).</p><p><strong>How to test private methods:</strong><br>Example: let&#39;s say we have the following class</p><pre>class Foo:<br>  def __bar(self, arg):<br>    return arg<br>  def baz(self, arg):<br>    self.__bar(arg)<br>    </pre><p>Now to test the above class, we can have the following function:</p><pre>f = Foo()<br>def test_private_method(self):<br>  arg = &#39;a&#39;<br>  expected_result = &#39;a&#39;<br>  self.assertEqual(f._Foo__bar(arg), expected_result)</pre><p>so it’s quite clear with the example, python adds class_name as a suffix in private_methods.</p><h4>Testing Expected Failures</h4><p>Error handling is another thing that’s critical to test. It is also part of the design. Who is responsible for the correctness of input? Every function and method should be clear about it. If it’s the function’s responsibility, it should verify its input, but if it’s the caller’s responsibility then the function can just go about its business and assume the input is correct. The overall correctness of the system will be ensured by having tests for the caller to verify that it only passes correct input to your function.</p><p>Let&#39;s say in addition to the example given above in this doc. Class SelfDrivingCar has a functioning drive():</p><pre>def drive(self, destination):<br>  self.destination = destination<br>  while not self._has_arrived():<br>    self._advance_to_destination()<br>  self.stop()</pre><p>lets start testing this function:</p><pre>def test_drive(self):<br>  # Valid destination<br>  self.car.drive((55.0, 66.0))<br>  # Invalid destination wrong range<br>  self.assertRaises(Exception, self.car.drive, (-55.0, 200.0))</pre><p><em>1</em><strong>def</strong> test_drive(self): <em>2</em> <em># Valid destination</em> <em>3</em> self.car.drive((55.0, 66.0)) <em>4</em> <em># Invalid destination wrong range</em> <em>5</em> self.assertRaises(Exception, self.car.drive, (-55.0, 200.0))</p><p>The test fails because the drive() method doesn’t check its arguments for validity and doesn’t raise an exception.</p><pre>python -m unittest discover -v test_drive<br>(untitled.test_self_driving_car.SelfDrivingCarTest) ... FAIL<br>FAIL: test_drive (untitled.test_self_driving_car.SelfDrivingCarTest)<br>Traceback (most recent call last): 10 File<br>&quot;/Users/Shradha/PycharmProjects/untitled/test_self_driving_car.py&quot;,<br> line 29, in test_drive self.assertRaises(Exception, self.car.drive, (-55.0, 200.0))<br> AssertionError: Exception not raised<br>Ran 2 tests in 0.000s</pre><p>Let&#39;s fix this, ideally drive() should check the range of its arguments.</p><pre>def drive(self, destination):<br>  lat, lon = destination<br>  if not (0.0 &lt;= lat &lt;= 90.0):<br>    raise Exception(&#39;Latitude out of range&#39;)<br>  if not (-180.0 &lt;= lon &lt;= 180.0):<br>    raise Exception(&#39;Latitude out of range&#39;)<br>  self.destination = destination<br>  while not self._has_arrived():<br>    self._advance_to_destination()<br>  self.stop()</pre><p>Now it will get passed</p><pre>python -m unittest discover -v test_drive<br>(untitled.test_self_driving_car.SelfDrivingCarTest) ... ok<br>(untitled.test_self_driving_car.SelfDrivingCarTest) ... ok<br>Ran 2 tests in 0.000s OK</pre><h3>Testing Side Effects</h3><h4>What are Side Effects?</h4><p>Testing is not always simple as the result doesn’t have to be the output of a method. It can be a state change of a class, inserting a new row in a database, writing a file, or sending an email. These are known as side effects. Below is a simple example of the same</p><p>Let’s say, we have a partial implementation SelfDrivingCar of driving logic. It has properties like destination and speed, and functions like accelerate, decelerate and stop</p><pre>class SelfDrivingCar(object):<br>  def __init__(self):<br>    self.speed = 0<br>    self.destination = None<br><br>  def _accelerate(self):<br>    self.speed += 1<br><br>  def _decelerate(self):<br>    if self.speed &gt; 0:<br>      self.speed -= 1<br><br>  def stop(self):<br>    self.speed = 0</pre><p>Testing stop() of this class:</p><pre>def test_stop_speed_is_zero_after_stopping(self):<br>    self.car.speed = 5<br>    self.car.stop()<br>    # Verify the speed is 0 after stopping 5<br>    self.assertEqual(0, self.car.speed)<br><br>def test_multiple_stops_if_car_already_stopped(self):<br>    self.car.speed = 5<br>    self.car.stop()<br>    # Verify it is Ok to stop again if the car is already stopped<br>    self.car.stop()<br>    self.assertEqual(0, self.car.speed)</pre><p>Be sure if the side effect is being tested before including it in your list of assertions. Side effects make unit testing harder since, each time a test is run, it might give a different result, or even worse, one test could impact the state of the application and cause another test to fail!</p><p>There are some simple techniques you can use to test parts of your application that have many side effects:</p><ul><li>Refactoring code to follow the Single Responsibility Principle</li><li>Mocking out any method or function calls to remove side effects</li><li>Using integration testing instead of unit testing for this piece of the application</li></ul><h3>Outcomes Possible</h3><p>There are three types of possible test outcomes :</p><ul><li><strong>OK</strong> — This means that all the tests are passed.</li><li><strong>FAIL</strong> — This means that the test did not pass and an AssertionError exception is raised.</li><li><strong>ERROR</strong> — This means that the test raises an exception other than AssertionError.</li></ul><h3>References</h3><p><a href="https://code.tutsplus.com/tutorials/write-professional-unit-tests-in-python--cms-25835">https://code.tutsplus.com/tutorials/write-professional-unit-tests-in-python--cms-25835</a></p><p><a href="https://realpython.com/python-testing/">https://realpython.com/python-testing/</a></p><p><a href="https://www.geeksforgeeks.org/python-exceptional-conditions-testing-in-unit-tests/?ref=rp">https://www.geeksforgeeks.org/python-exceptional-conditions-testing-in-unit-tests/?ref=rp</a></p><p><a href="https://stackoverflow.com/questions/105007/should-i-test-private-methods-or-only-public-ones/47401015#47401015">https://stackoverflow.com/questions/105007/should-i-test-private-methods-or-only-public-ones/47401015#47401015</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e842d32aee2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mocking with Python]]></title>
            <link>https://medium.com/@shradhasharma131/mocking-with-python-e9ab0367d927?source=rss-86ac6b12edbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9ab0367d927</guid>
            <category><![CDATA[mock]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[mocking]]></category>
            <dc:creator><![CDATA[Shradhasharma]]></dc:creator>
            <pubDate>Mon, 06 Feb 2023 13:24:02 GMT</pubDate>
            <atom:updated>2023-02-06T13:24:02.240Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Whats is Mocking?</strong></h3><p>Mocking is simply replacing actual part of code with dummy data for testing purpose. Instead of calling actual code, we would call the mock implementation</p><h3>Benefits of Mocking</h3><ul><li><strong>Increased speed</strong> — Tests that run quickly are extremely beneficial. E.g. if you have a very resource intensive function, a mock of that function would cut down on unnecessary resource usage during testing, therefore reducing test run time.</li><li><strong>Avoiding undesired side effects during testing</strong> — If you are testing a function which makes calls to an external API, you may not want to make an actual API call every time you run your tests. You’d have to change your code every time that API changes, or there may be some rate limits, but mocking helps you avoid that.</li></ul><h3>Basic Example</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3afa3b06558bbdbfc8d1f02a91075de6/href">https://medium.com/media/3afa3b06558bbdbfc8d1f02a91075de6/href</a></iframe><p>A simple test case for above code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f309743bbb5f6a55237078a425c8a3b0/href">https://medium.com/media/f309743bbb5f6a55237078a425c8a3b0/href</a></iframe><p>Now lets run the code</p><pre>python -m unittest<br>.<br>_____________________________________________________________</pre><pre>Ran 1 test in 0.003s</pre><pre>OK</pre><p>Now lets say, our code looks something like below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18dfa32f49e3d1c72c1dbc0617e46399/href">https://medium.com/media/18dfa32f49e3d1c72c1dbc0617e46399/href</a></iframe><p>After running calculator test file, we’ll get below output</p><pre>python -m unittest<br>.<br>_____________________________________________________________</pre><pre>Ran 1 test in 10.003s</pre><pre>OK</pre><p>Lets see the power of mocking</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/257d60076c89d25f2f6bc9cb4ab649bb/href">https://medium.com/media/257d60076c89d25f2f6bc9cb4ab649bb/href</a></iframe><pre>python -m unittest<br>.<br>_____________________________________________________________</pre><pre>Ran 1 test in 0.001s</pre><pre>OK</pre><p>Now it gets executed in just 1ms.</p><h3>Assertions We Can Make on Mocks</h3><p>You can assert that your program used an object as you expected</p><p><em>.assert_called()</em> ensures you called the mocked method while<em> .assert_called_once() </em>checks that you called the method exactly one time.</p><p>Both assertion functions have variants that let you inspect the arguments passed to the mocked method:</p><pre>.assert_called_with(*args, **kwargs)</pre><pre>.assert_called_once_with(*args, **kwargs)</pre><p>To pass these assertions, you must call the mocked method with the same arguments that you pass to the actual method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc430d04e3c4453f0ff83cdebce01b37/href">https://medium.com/media/bc430d04e3c4453f0ff83cdebce01b37/href</a></iframe><pre>Traceback (most recent call last):<br>  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;<br>  File &quot;/usr/local/shradha/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/mock.py&quot;, line 814, in assert_called_with<br>    raise AssertionError(_error_message()) from cause<br>AssertionError: Expected call: loads(&#39;{&quot;key&quot;: &quot;value&quot;}&#39;)<br>Actual call: loads(s=&#39;{&quot;key&quot;: &quot;value&quot;}&#39;)</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63d143101eaa9d9538c0e54305e18dbd/href">https://medium.com/media/63d143101eaa9d9538c0e54305e18dbd/href</a></iframe><p><em>json.loads.assert_called_with(‘{“key”: “value”}’)</em> raised an AssertionError because it expected you to call <em>loads()</em> with a positional argument, but you actually called it with a keyword argument. <em>json.loads.assert_called_with(s=’{“key”: “value”}’)</em> gets this assertion correct.</p><h3>Return Value</h3><p>To override <strong>calls</strong> to the mock you’ll need to configure its return_value property, The Mock will <strong>always return the same value on all calls</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac0aa61f14f9c1b419bd9422e239952a/href">https://medium.com/media/ac0aa61f14f9c1b419bd9422e239952a/href</a></iframe><h3>patch Decorator</h3><h3>Where to Patch ???</h3><p>Knowing where to tell patch() to look for the object you want mocked is important because if you choose the wrong target location, the result of patch() could be something you didn’t expect.</p><p>Let’s say you are mocking is_weekday() in my_calendar.py using patch()</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/614b1d02566b35752d027664d4126146/href">https://medium.com/media/614b1d02566b35752d027664d4126146/href</a></iframe><pre>&lt;MagicMock name=&#39;is_weekday()&#39; id=&#39;4336501256&#39;&gt;</pre><p>First, you import my_calendar.py. Then you patch is_weekday(), replacing it with a Mock. Great! This is working as expected.</p><p>Now, let’s change this example slightly and import the function directly:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/133932853b56f5f7a3207127dbef1bd0/href">https://medium.com/media/133932853b56f5f7a3207127dbef1bd0/href</a></iframe><pre>False</pre><p>Notice that even though the target location you passed to patch() did not change, the result of calling is_weekday() is different. The difference is due to the change in how you imported the function.</p><p>from my_calendar import is_weekday binds the real function to the local scope. So, even though you patch() the function later, you ignore the mock because you already have a local reference to the un-mocked function.</p><p>A <a href="https://docs.python.org/3/library/unittest.mock.html#where-to-patch">good rule of thumb</a> is to patch() the object where it is looked up.</p><p>In the first example, mocking ‘my_calendar.is_weekday()’ works because you look up the function in the my_calendar module. In the second example, you have a local reference to is_weekday(). Since you use the function found in the local scope, you should mock the local function:</p><pre>&gt;&gt;&gt; from unittest.mock import patch<br>&gt;&gt;&gt; from my_calendar import is_weekday</pre><pre>&gt;&gt;&gt; with patch(&#39;__main__.is_weekday&#39;):<br>...     is_weekday()<br>...<br>&lt;MagicMock name=&#39;is_weekday()&#39; id=&#39;4502362992&#39;&gt;</pre><h3>Applying the same patch to every test method</h3><pre><a href="http://twitter.com/patch">@patch</a>(&#39;mymodule.SomeClass&#39;)<br>... class MyTest(unittest.TestCase):<br>...<br>...     def test_one(self, MockSomeClass):<br>...         self.assertIs(mymodule.SomeClass, MockSomeClass)<br>...<br>...     def test_two(self, MockSomeClass):<br>...         self.assertIs(mymodule.SomeClass, MockSomeClass)<br>...<br>...     def not_a_test(self):<br>...         return &#39;something&#39;</pre><h3>Side Effects</h3><p>When you want something to happen when you called your mock function, that something is side effects. For example you want to call another function, raise an exception or return an iterable, you can make use of side effects.</p><h3>Calling another function using side effects</h3><p>Lets’ say in our previous example, we want to call another function for mocked sum function. lets check how can we do it?</p><pre>from unittest import TestCase<br>from unittest.mock import</pre><pre>def mock_sum(a, b):<br>    # mock sum function without the long running time.sleep<br>    return a + b</pre><pre>class TestCalculator(TestCase):<br>    <a href="http://twitter.com/patch">@patch</a>(&#39;main.Calculator.sum&#39;, side_effect=mock_sum)<br>    def test_sum(self, sum):<br>        self.assertEqual(sum(2,3), 5)</pre><p>running this</p><pre>.<br>_____________________________________________________________</pre><pre>Ran 1 test in 0.001s</pre><pre>OK</pre><h3>Return different values with side effects</h3><pre>from unittest import mock</pre><pre>m = mock.Mock()</pre><pre>m.side_effect = [&#39;foo&#39;, &#39;bar&#39;, &#39;baz&#39;]<br>assert m() == &#39;foo&#39;<br>assert m() == &#39;bar&#39;<br>assert m() == &#39;baz&#39;</pre><h3>Raise exception with side effects</h3><pre>m.side_effect = RuntimeError(&#39;Boom&#39;)<br>try:<br>    m()<br>except RuntimeError:<br>    assert True<br>else:<br>    assert False</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9ab0367d927" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>