{"id":3393,"date":"2020-02-17T09:23:54","date_gmt":"2020-02-17T09:23:54","guid":{"rendered":"https:\/\/www.askpython.com\/?p=3393"},"modified":"2023-02-16T19:57:15","modified_gmt":"2023-02-16T19:57:15","slug":"python-unittest-module","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python-modules\/python-unittest-module","title":{"rendered":"Python unittest Module"},"content":{"rendered":"\n<p>In this article, we&#8217;ll cover the Python unittest module and some of its common use cases.<\/p>\n\n\n\n<p>But before that, let&#8217;s understand why we need this module in the first place.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\" \/>\n\n\n\n<h2 class=\"wp-block-heading\">Why should you use the unittest Module?<\/h2>\n\n\n\n<p>When you&#8217;re working with large code-bases, Application development is often categorized into two phases.<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>Development Phase<\/li><li>Testing Phase<\/li><\/ol>\n\n\n\n<p>Phase 1 is your <em>development phase<\/em>, where you build your core idea into a bare-bones application.<\/p>\n\n\n\n<p>But, this is not sufficient if you actually want to use it regularly. There may have been situations that you may have missed, which can actually cause your program to work unexpectedly.<\/p>\n\n\n\n<p>To minimize such errors, there is another phase called <strong>Testing Phase<\/strong>, which is aimed at testing different possible scenarios for your application, and check if it&#8217;s working correctly.<\/p>\n\n\n\n<p>Often, if you don&#8217;t have an established framework for this phase, you may need to verify all scenarios manually, which is tedious.<\/p>\n\n\n\n<p>To reduce the developer&#8217;s hassle, we can use the Python <code>unittest<\/code> module and solve exactly this problem by using automated testing.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Types of testing<\/h3>\n\n\n\n<p>For an application, there are two types of tests:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Integrated Tests<\/li><li>Unit Tests<\/li><\/ul>\n\n\n\n<p><strong>Integrated Tests<\/strong> are those tests that check if modules of an application work properly alongside each other.<\/p>\n\n\n\n<p><strong>Unit Tests<\/strong> are those which check small components in the application.<\/p>\n\n\n\n<p>While we can write both Integration Tests and Unit Tests, integration tests depend hugely on your application and can combine multiple unit tests.<\/p>\n\n\n\n<p>With all that covered, let&#8217;s now look at how we can use this module!<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\" \/>\n\n\n\n<h2 class=\"wp-block-heading\">Python unittest Module<\/h2>\n\n\n\n<p>This module comes built-in with your <strong>Python 3+<\/strong> installation, so there&#8217;s no need to install it using <strong>pip<\/strong>.<\/p>\n\n\n\n<p>You can import the module by typing:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport unittest\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">Python unittest Methods<\/h2>\n\n\n\n<p>This module has several methods by which you can perform unittests.<\/p>\n\n\n\n<p>The most common ones are listed in the table below.<\/p>\n\n\n\n<figure class=\"wp-block-table aligncenter\"><table class=\"\"><tbody><tr><td>Method<\/td><td>Assertion Check<\/td><\/tr><tr><td><strong>assertEqual(a,b)<\/strong><\/td><td>a == b<\/td><\/tr><tr><td><strong>assertNotEqual(a,b)<\/strong><\/td><td>a != b<\/td><\/tr><tr><td><strong>assertTrue(x)<\/strong><\/td><td>bool(x) is True<\/td><\/tr><tr><td><strong>assertFalse(x)<\/strong><\/td><td>bool(x) is False<\/td><\/tr><tr><td><strong>assertIs(a,b)<\/strong><\/td><td>a is b<\/td><\/tr><tr><td><strong>assertIsNot(a, b)<\/strong><\/td><td>a is not b<\/td><\/tr><tr><td><strong>assertIsNone(x)<\/strong><\/td><td>x is None<\/td><\/tr><tr><td><strong>assertIsNotNone(x)<\/strong><\/td><td>x is not None<\/td><\/tr><tr><td><strong>assertIn(a, b)<\/strong><\/td><td>a in b<\/td><\/tr><tr><td><strong>assertNotIn(a, b)<\/strong><\/td><td>a not in b<\/td><\/tr><tr><td><strong>assertIsInstance(a, b)<\/strong><\/td><td>isinstance(a, b)<\/td><\/tr><tr><td><strong>assertNotIsInstance(a, b)<\/strong><\/td><td>not isinstance(a, b)<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\" \/>\n\n\n\n<h2 class=\"wp-block-heading\">Writing a Unit Test<\/h2>\n\n\n\n<p>We need an program to apply tests on. So let&#8217;s write one!<\/p>\n\n\n\n<p>I will write a program that simply tries to verify the sum of elements in a list. We will write a <strong>unittest<\/strong> program for that.<\/p>\n\n\n\n<p>Now, to write an individual test case, we need to inherit the <code>unittest.TestCase<\/code> class, and then override it using some specific methods.<\/p>\n\n\n\n<p>I will call my class <code>MyTestClass<\/code>.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport unittest\n\ndef list_sum(my_list):\n    # Sums the elements of the list\n    return sum(my_list)\n\nclass MyTestClass(unittest.TestCase):\n    def test_list(self):\n        # Checks if the sum of the below list is as expected\n        my_list = &#x5B;1, 2, 3, 4, 5]\n        self.assertEqual(list_sum(my_list), 15, &quot;Should be 15&quot;)\n\n    def test_string(self):\n        # Checks if the string is &#039;Hello from AskPython&#039;\n        my_str = &#039;Hi&#039;\n        self.assertEqual(my_str, &#039;Hello from AskPython&#039;, &quot;Should be &#039;Hello from AskPython&#039;&quot;)\n\n\nif __name__ == &#039;__main__&#039;:\n    # Main module\n    unittest.main()\n\n<\/pre><\/div>\n\n\n<p class=\"has-text-color has-background has-text-align-left has-very-light-gray-color has-vivid-cyan-blue-background-color\"><strong>NOTE<\/strong>: To write a test method we <strong>must<\/strong> prefix a method name with <code>test_<\/code>. So, any test method must be of the form <code>test_xyz()<\/code><\/p>\n\n\n\n<p>I&#8217;m writing a method <code>test_list()<\/code> that checks if the sum of elements in the list equals 15, and similarly another method to check for the given string.<\/p>\n\n\n\n<p>I&#8217;m using <strong>unittest<\/strong>&#8216;s <code>assertEqual()<\/code> method, which will run the unittest and check if this assertion holds.<\/p>\n\n\n\n<p>Let&#8217;s now execute this file using Python.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nuser@AskPython $ python my_test.py \n.F\n======================================================================\nFAIL: test_string (__main__.MyTestClass)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n  File &quot;my_test.py&quot;, line 16, in test_string\n    self.assertEqual(my_str, &#039;Hello from AskPython&#039;, &quot;Should be &#039;Hello from AskPython&#039;&quot;)\nAssertionError: &#039;Hi&#039; != &#039;Hello from AskPython&#039;\n- Hi\n+ Hello from AskPython\n : Should be &#039;Hello from AskPython&#039;\n\n----------------------------------------------------------------------\nRan 2 tests in 0.000s\n\nFAILED (failures=1)\n<\/pre><\/div>\n\n\n<p>As you can see, the first test passed, while the second one failed, since the strings do not match.<\/p>\n\n\n\n<p>You&#8217;ve now written your first unittest method!<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\" \/>\n\n\n\n<h2 class=\"wp-block-heading\">Run Unit Tests on an Application<\/h2>\n\n\n\n<p>Let&#8217;s now run unittests on <em>another<\/em> program, since you won&#8217;t be writing your entire application inside a unittest file!<\/p>\n\n\n\n<p>Let&#8217;s write a simple application program and perform unit tests on it.<\/p>\n\n\n\n<p>I&#8217;ll be writing a program that acts as a very simple database to store the names and marks of students. <\/p>\n\n\n\n<p>Save the below file as <code>test_example.py<\/code> as we&#8217;ll be referencing it in our next piece of code.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nclass MyClass:\n    # Database of {&#039;Name&#039;: &#039;Marks&#039;} dict pairs\n    db = dict()\n    num_students = 0\n\n    def add_db(self, name, marks):\n        self.db&#x5B;name] = marks\n        self.num_students += 1\n\n    def rm_db(self, name):\n        # Removes key value pair corresponding\n        # to student name\n        if name in self.db:\n            del self.db&#x5B;name]\n        else:\n            return f&#039;Student with Name:{name} not in Database&#039;\n\n    def get_marks(self, name):\n        if name in self.db:\n            return self.db&#x5B;name]\n        else:\n            return f&#039;Student with Name:{name} not in Database&#039;\n\n\nif __name__ == &#039;__main__&#039;:\n    my_class = MyClass()\n    my_class.add_db(&#039;John&#039;, 47)\n    my_class.add_db(&#039;Mary&#039;, 34)\n    print(my_class.get_marks(&#039;John&#039;))\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">The recommended method to run Unit Tests<\/h3>\n\n\n\n<p>It is a common practice to keep the testing modules separated from the core application.<\/p>\n\n\n\n<p>So we will import the <code>unittest<\/code> module <em>only during the test phase<\/em>.<\/p>\n\n\n\n<p>Python allows us to do, that, by specifying the <code>-m MODULE_NAME<\/code> option. So, our command will be:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\npython -m unittest -v my_test.py\n<\/pre><\/div>\n\n\n<p>We&#8217;ll use the <code>-v<\/code> verbose option to display all helpful messages.<\/p>\n\n\n\n<p>Now, you don&#8217;t need to write <code>import unittest<\/code> on your application!<\/p>\n\n\n\n<p>To run unit tests, we must write a test file for our program, similar to the one we did before. We&#8217;ll also import the <code>MyClass<\/code> that we created earlier by referencing the file <code>test_example.py<\/code> that we saved earlier.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport unittest\n\nfrom test_example import MyClass\n\nimport random\n\nclass MyTest(unittest.TestCase):\n    # Init the MyClass class\n    my_class = MyClass()\n\n    # Database to verify test cases\n    database = dict()\n\n    def test_case_1(self):\n        print(&quot;\\n\\nRunning Test 1....\\n\\n&quot;)\n\n        name = &#039;John Doe&#039;\n        marks = 50\n        self.database&#x5B;name] = marks\n        self.my_class.add_db(name, marks)\n        self.assertEqual(self.database, self.my_class.db)\n        print(self.database)\n        print(&quot;\\n\\nFinished Test 1\\n\\n&quot;)\n\n    def test_case_2(self):\n        print(&quot;\\n\\nRunning Test 2....\\n\\n&quot;)\n        for i in range(5):\n            name = &#039;&#039;\n            for j in range(6):\n                name += chr(random.randint(97, 97+25))\n            marks = random.randint(0, 100)\n            self.database&#x5B;name] = marks\n\n            # Insert to MyClass Database\n            self.my_class.add_db(name, marks)\n        # Now check if both databases have the same key:value pairs\n        self.assertEqual(self.database, self.my_class.db)\n        print(self.database)\n        print(&quot;\\n\\nFinished Test 2\\n\\n&quot;)\n\n\nif __name__ == &#039;__main__&#039;:\n    # Run the main unittest code\n    unittest.main()\n\n<\/pre><\/div>\n\n\n<p>Now that we&#8217;ve written the tests separately, let&#8217;s verify if it works.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\npython -m unittest run_tests.py\n<\/pre><\/div>\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"874\" height=\"588\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/02\/unittest_example.png\" alt=\"Unittest Example\" class=\"wp-image-3414\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/02\/unittest_example.png 874w, https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/02\/unittest_example-300x202.png 300w, https:\/\/www.askpython.com\/wp-content\/uploads\/2020\/02\/unittest_example-768x517.png 768w\" sizes=\"auto, (max-width: 874px) 100vw, 874px\" \/><figcaption>Unittest Example<\/figcaption><\/figure><\/div>\n\n\n\n<p>This does work, since both our tests passed!<\/p>\n\n\n\n<p>Note that our final test database contains records from both Test1 and Test2, so it&#8217;s possible to manipulate the test mechanism based on your program!<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\" \/>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>Hopefully, you now understand how you can use Python&#8217;s <code>unittest<\/code> module to perform sanity checks during the testing phase. If you have any queries, do mention them in the comment section below!<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\" \/>\n\n\n\n<h2 class=\"wp-block-heading\">References<\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li>JournalDev article on Python unittest Module<\/li><li><a href=\"https:\/\/realpython.com\/python-testing\/\" class=\"rank-math-link\" target=\"_blank\" rel=\"noopener\">RealPython article<\/a> on Python unittest<\/li><\/ul>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\" \/>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we&#8217;ll cover the Python unittest module and some of its common use cases. But before that, let&#8217;s understand why we need this module in the first place. Why should you use the unittest Module? When you&#8217;re working with large code-bases, Application development is often categorized into two phases. Development Phase Testing Phase [&hellip;]<\/p>\n","protected":false},"author":7,"featured_media":3430,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-3393","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python-modules"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/3393","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/7"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=3393"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/3393\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/3430"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=3393"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=3393"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=3393"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}