{"id":11448,"date":"2020-02-06T07:19:55","date_gmt":"2020-02-06T12:19:55","guid":{"rendered":"https:\/\/qxf2.com\/blog\/?p=11448"},"modified":"2021-04-21T08:55:39","modified_gmt":"2021-04-21T12:55:39","slug":"unit-testing-using-mock-python","status":"publish","type":"post","link":"https:\/\/qxf2.com\/blog\/unit-testing-using-mock-python\/","title":{"rendered":"Getting started with Unit Testing using mock in Python"},"content":{"rendered":"<p>Unit testing is considered as a vital phase in software testing. Anyone who has been involved in the software development life cycle will have encountered some form of testing. Although the aim of testing is to find bugs, it cannot guarantee the absence of other faults, no matter how creative the test cases are designed. Unit testing enables a more thorough level of acceptance mechanism.<\/p>\n<p>This post will give you a brief introduction on how to start with unit testing using the mock module in python.<\/p>\n<h3>What is Unit testing and why do we need it?<\/h3>\n<p>Unit testing\u00a0is a type of software testing where individual units or components of a software are tested. The purpose is to validate whether each unit of the software code performs as expected.\u00a0 Unit tests isolate a section of code and verify its correctness.<br \/>\n<span>Mock is a library for testing in Python. It helps you to replace real objects in your code with mock instances and make assertions about how they have been used.<\/span><\/p>\n<h3>Getting started:<\/h3>\n<p><strong>Step 1. Install mock<\/strong><br \/>\nGet started by installing the mock module. To do this simply open command prompt and type:<\/p>\n<pre lang=\"\">pip install -U mock<\/pre>\n<p><strong>Step 2. Select the application you want to test.<\/strong><\/p>\n<p>Pick the application that you would like to test. In my case, I will be using Qxf2&#8217;s interview scheduler application. You can find it here:\u00a0<a href=\"https:\/\/github.com\/qxf2\/interview-scheduler\">Interview Scheduler<\/a><\/p>\n<p><strong>Step 3. Choose a method which you want to write the unit test for:<\/strong><\/p>\n<p>Now, decide on the method for which you want to write the unit test. Go through the method and find out what it does.<br \/>\nThen choose a method call that you want to mock.<br \/>\nIn my case, I&#8217;m choosing the <code>is_past_date()<\/code> method from the <code>qxf2_scheduler.py<\/code> file. It&#8217;s a simple method that tells us if the selected date is a past date or not.<\/p>\n<pre lang=\"python\">\r\ndef is_past_date(date):\r\n    \"Is this date in the past?\"\r\n\r\n    result_flag = True\r\n    date = gcal.process_date_string(date)\r\n    today = gcal.get_today()\r\n    \r\n    if date > = today:\r\n        result_flag = False\r\n    \r\n    return result_flag\r\n<\/pre>\n<h3>Writing the Unit test<\/h3>\n<p><strong>Step 1. Create a new python file to write the unit test<\/strong><\/p>\n<p>Ideally, you name your unit test as &#8216;<strong><em>test_<\/em><\/strong>&#8216;\u00a0 followed by whatever name you want. I am going to name it &#8220;<em><strong>test_check_past_date&#8221;<\/strong><\/em><\/p>\n<p><strong>Step 2. Import the required modules<\/strong><\/p>\n<p>The first step in writing our unit test is to import the unit test and mock modules.<\/p>\n<p><code>import unittest, mock<\/code><\/p>\n<p>Then import the function that you would like to test. In my case, it is &#8211;<\/p>\n<p><code>from qxf2_scheduler.qxf2_scheduler import is_past_date<\/code><\/p>\n<p>I will also be importing the date parser for converting the date from string format to DateTime format before passing it to the method.<\/p>\n<p><strong>Step 3. Create a Class to hold the various unit test methods<\/strong><\/p>\n<p>Once you have imported the required modules, go ahead and create a class to hold the various unit test methods. Make sure to include the subclass &#8220;unittest.TestCase&#8221; while creating the test case. Your class declaration should look similar as below:<\/p>\n<p><code>class Check_is_past_date(unittest.TestCase):<\/code><\/p>\n<p><strong>Step 4. Patch the\u00a0function that you want to mock using &#8216;mock.patch() decorator&#8217;<\/strong><\/p>\n<p>The <em>mock.patch()<\/em> decorator helps us mock any function we need. In other sense, we can replicate the action performed by that function and have the function return any value of our choice. In this case, I am going to mock gcal.get_today() method and make it return a value of my choice.<\/p>\n<p>I will be using the following command to mock the method:<\/p>\n<p><code>@mock.patch('qxf2_scheduler.qxf2_scheduler.gcal.get_today',return_value=parse(\"2020-01-22\"))<\/code><\/p>\n<p>As you can see above, I have passed the path of the function to be mocked as the first argument and the return value I want as the second argument.<\/p>\n<p><strong>Step 5. Define a method for writing the test<\/strong><\/p>\n<p>The next step is creating a method where you&#8217;ll be writing your test conditions. The method name must start with &#8220;<em><strong>test_<\/strong><\/em>&#8221; followed by any name you want. I will name my method &#8220;<em><strong>test_check_if_past_date<\/strong><\/em>&#8220;. Pass the mock variable as an argument to the method.<\/p>\n<p>Your method definition should look similar as below:<\/p>\n<p><code>def test_check_if_past_date(self, mock_today):<\/code><\/p>\n<p><strong>Step 6. Add your required test conditions inside the method:<\/strong><\/p>\n<p>Add your required test scenarios inside the method. You can refer to <a href=\"https:\/\/python.readthedocs.io\/en\/stable\/library\/unittest.html\"><strong><em>this<\/em><\/strong><\/a> documentation to know more about the unit test commands.<br \/>\n<span>Here, I will use the mock function to return a past date and verify if the method returns a false value.<\/span><\/p>\n<p><code>assert is_past_date(self.date)==False<\/code><\/p>\n<p><strong>Step 7. Call the unittest in the main method<\/strong><\/p>\n<p>The final step is to add the main function and call the unittest from it.<br \/>\n<code><br \/>\nif __name__==\"__main__\":<br \/>\nunittest.main()<br \/>\n<\/code><\/p>\n<p>Here is the final code:<\/p>\n<pre lang=\"python\">import unittest, mock\r\nimport os,sys\r\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\r\nfrom qxf2_scheduler.qxf2_scheduler import is_past_date\r\nfrom dateutil.parser import parse\r\n\r\nclass Check_is_past_date(unittest.TestCase):\r\n\"\"\"\r\nThis class contains unit test for is_past_date method in qxf2_scheduler module\r\n\"\"\"\r\n    #hardcoding the date\r\n    date='03\/04\/2020'\r\n\r\n    #mocking gcal.get_today() method\r\n    @mock.patch('qxf2_scheduler.qxf2_scheduler.gcal.get_today',return_value=parse(\"2020-01-22\"))\r\n    def test_check_if_past_date(self, mock_today):\r\n    \"\"\"\r\n    This method tests whether the function returns false if the given date is not a past date\r\n    \"\"\"\r\n        assert is_past_date(self.date)==False\r\n\r\nif __name__==\"__main__\":\r\n    unittest.main()\r\n<\/pre>\n<figure id=\"attachment_12306\" aria-describedby=\"caption-attachment-12306\" style=\"width: 850px\" class=\"wp-caption alignnone\"><a href=\"https:\/\/qxf2.com\/blog\/wp-content\/uploads\/2020\/02\/unit_test.jpg\" data-rel=\"lightbox-image-0\" data-rl_title=\"\" data-rl_caption=\"\" title=\"\"><img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-12306\" src=\"https:\/\/qxf2.com\/blog\/wp-content\/uploads\/2020\/02\/unit_test.jpg\" alt=\"\" width=\"850\" height=\"140\" srcset=\"https:\/\/qxf2.com\/blog\/wp-content\/uploads\/2020\/02\/unit_test.jpg 850w, https:\/\/qxf2.com\/blog\/wp-content\/uploads\/2020\/02\/unit_test-300x49.jpg 300w, https:\/\/qxf2.com\/blog\/wp-content\/uploads\/2020\/02\/unit_test-768x126.jpg 768w\" sizes=\"auto, (max-width: 850px) 100vw, 850px\" \/><\/a><figcaption id=\"caption-attachment-12306\" class=\"wp-caption-text\">Result of the unit test<\/figcaption><\/figure>\n<p>And voila! You just ran a unit check on your application!!<\/p>\n<p>I hope you found this blog helpful. Here are some other posts which I found helpful in making of this blog,<br \/>\n<a href=\"https:\/\/www.guru99.com\/unit-testing-guide.html\">Guide to unit testing<\/a><br \/>\n<a href=\"https:\/\/qxf2.com\/blog\/python-unit-checks\/\">Python unit tests using mock<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Unit testing is considered as a vital phase in software testing. Anyone who has been involved in the software development life cycle will have encountered some form of testing. Although the aim of testing is to find bugs, it cannot guarantee the absence of other faults, no matter how creative the test cases are designed. Unit testing enables a more [&hellip;]<\/p>\n","protected":false},"author":29,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[38,64,18,61,66],"tags":[],"class_list":["post-11448","post","type-post","status-publish","format-standard","hentry","category-automation","category-mock","category-python","category-testing","category-unit-testing"],"_links":{"self":[{"href":"https:\/\/qxf2.com\/blog\/wp-json\/wp\/v2\/posts\/11448","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/qxf2.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/qxf2.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/qxf2.com\/blog\/wp-json\/wp\/v2\/users\/29"}],"replies":[{"embeddable":true,"href":"https:\/\/qxf2.com\/blog\/wp-json\/wp\/v2\/comments?post=11448"}],"version-history":[{"count":22,"href":"https:\/\/qxf2.com\/blog\/wp-json\/wp\/v2\/posts\/11448\/revisions"}],"predecessor-version":[{"id":15232,"href":"https:\/\/qxf2.com\/blog\/wp-json\/wp\/v2\/posts\/11448\/revisions\/15232"}],"wp:attachment":[{"href":"https:\/\/qxf2.com\/blog\/wp-json\/wp\/v2\/media?parent=11448"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/qxf2.com\/blog\/wp-json\/wp\/v2\/categories?post=11448"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/qxf2.com\/blog\/wp-json\/wp\/v2\/tags?post=11448"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}