{"id":86866,"date":"2023-02-02T09:00:49","date_gmt":"2023-02-02T03:30:49","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=86866"},"modified":"2023-02-02T09:00:49","modified_gmt":"2023-02-02T03:30:49","slug":"unit-testing-in-python","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/unit-testing-in-python\/","title":{"rendered":"Unit Testing in Python"},"content":{"rendered":"<p><span style=\"font-weight: 400\">When testing software, a technique known as unit testing examines the tiniest testable bits of code and checks them for proper operation. We can ensure that every component code, including auxiliary functions that may not be visible to the user<\/span><b>,<\/b><span style=\"font-weight: 400\"> functions correctly and as intended by doing unit tests.<\/span><\/p>\n<p><span style=\"font-weight: 400\">The concept is that we independently test every component of our program to make sure it functions. Regression and integration testing, in contrast, verifies that the program&#8217;s various components function properly and according to plan.<\/span><\/p>\n<p><span style=\"font-weight: 400\">In this post, learn how to use the built-in PyUnit framework and the PyTest framework, two well-known unit testing frameworks, to build unit testing in Python.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Following this training, you will be aware of the following:<\/span><\/p>\n<ul>\n<li>Python unit testing packages like PyUnit and PyTest<\/li>\n<li>Using unit tests to examine expected function behavior<\/li>\n<\/ul>\n<h3><span style=\"font-weight: 400\">What is Unit Testing?<\/span><\/h3>\n<p><span style=\"font-weight: 400\">Do you recall performing various arithmetic operations to complete math problems in school before combining them to produce the correct answer? Then, consider how you would verify that each step&#8217;s calculations were accurate and that nothing was written down incorrectly or carelessly.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Now apply that concept to code! For example, how would you write a test to check that the following line of code returns the area of the rectangle? We wouldn&#8217;t want to constantly review our code to validate that it is accurate statically.<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">def calculate_area_rectangle(width, height):\n    return width * height\n<\/pre>\n<p><span style=\"font-weight: 400\">We might execute the code with a few test instances to see if it produces the desired results.<\/span><\/p>\n<p><span style=\"font-weight: 400\">A unit test should accomplish that! A unit test is a test that verifies the functionality of a single line of code, typically modularised as a function.<\/span><\/p>\n<p><b>Why do we need Unit Testing?<\/b><\/p>\n<p><span style=\"font-weight: 400\">Regression testing relies heavily on unit tests to guarantee that the code is stable and continues to operate as expected after modifications are made. After making changes to our code, we may run the unit tests we previously wrote to make sure that our modifications did not affect the functionality of other areas of the codebase.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Unit tests provide the essential additional advantage of making error isolation simple. Imagine completing the project and getting a long list of errors. What steps would we take to debug our code?<\/span><\/p>\n<p><span style=\"font-weight: 400\">Unit tests can help in this situation. If any part of our code has been producing errors, we may examine the results of our unit tests to determine where to begin the debugging process. That&#8217;s not to suggest that unit testing can&#8217;t sometimes assist us in locating the bug. Still, it provides a much more practical starting point before we examine how components are integrated into integration testing.<\/span><\/p>\n<p><span style=\"font-weight: 400\">By testing the functions in this Rectangle class, we will demonstrate how to perform unit testing for the remainder of the article:<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class Rectangle:\n    def __init__(self, width, height):\n        self.width = width\n        self.height = height\n\n    def get_area(self):\n        return self.width * self.height\n\n    def set_width(self, width):\n        self.width = width\n\n    def set_height(self, height):\n        self.height = height\n<\/pre>\n<p><span style=\"font-weight: 400\">Let&#8217;s investigate how to use motivated unit tests in Python and how to include them in our development workflow now that we have them!<\/span><\/p>\n<h3><span style=\"font-weight: 400\">Designing a Test Strategy<\/span><\/h3>\n<p><span style=\"font-weight: 400\">Now let&#8217;s examine the process of creating a testing strategy.<\/span><\/p>\n<h4>Definition of test scope<\/h4>\n<p><span style=\"font-weight: 400\">A crucial question must be addressed before formulating a test strategy. What components of your computer program do you wish to test?<\/span><\/p>\n<p><span style=\"font-weight: 400\">Due to the impossibility of complete testing, this is a key question. Because of this, you cannot test every input and output; instead, you should prioritize your tests according to the associated risks.<\/span><\/p>\n<p><span style=\"font-weight: 400\">When defining your test scope, many considerations must be made:<\/span><\/p>\n<ul>\n<li style=\"font-weight: 400\"><span style=\"font-weight: 400\">Risk: What would be the business repercussions if a defect were to harm this component?<\/span><\/li>\n<li style=\"font-weight: 400\"><span style=\"font-weight: 400\">How quickly do you want your software to be completed? Have you set a due date?<\/span><\/li>\n<li style=\"font-weight: 400\"><span style=\"font-weight: 400\">Budget: What kind of financial commitment are you willing to make to the testing activity?<\/span><\/li>\n<\/ul>\n<p><span style=\"font-weight: 400\">Once you define the testing scope that determines what you should and shouldn&#8217;t test, you&#8217;re ready to talk about the characteristics a good unit test should have.<\/span><\/p>\n<h3>Qualities of a unit test<\/h3>\n<p><span style=\"font-weight: 400\"><strong>1. Fast<\/strong> &#8211; Unit tests must be quick because they are typically run automatically. Unfortunately, developers are more prone to bypass slow unit tests since they don&#8217;t offer quick feedback.<\/span><\/p>\n<p><span style=\"font-weight: 400\"><strong>2. Isolated<\/strong> &#8211; Unit tests are, by definition, independent. They only test each piece of code and don&#8217;t rely on other resources (like a file or a network resource).<\/span><\/p>\n<p><span style=\"font-weight: 400\"><strong>3. Repeatable<\/strong> &#8211; Unit tests are run often, and the outcome needs to remain constant.<\/span><\/p>\n<p><span style=\"font-weight: 400\"><strong>4. Reliable<\/strong> &#8211; Only if a flaw in the system being tested will unit tests fail. It shouldn&#8217;t matter how the tests are run or in what environment.<\/span><\/p>\n<p><span style=\"font-weight: 400\"><strong>5. Appropriately named<\/strong> &#8211; The exam&#8217;s name should contain pertinent information about the test itself.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Before getting into Python unit testing, one more step needs to be completed. How can we set up our tests, so they are neat and simple to read? We employ a strategy known as Arrange, Act, and Assert (AAA).<\/span><\/p>\n<h3>The AAA pattern<\/h3>\n<p><span style=\"font-weight: 400\">The Arrange, Act, and Assert a paradigm is a typical approach used to write and organize unit tests. The way it operates is as follows:<\/span><\/p>\n<ul>\n<li style=\"font-weight: 400\"><span style=\"font-weight: 400\">All the elements and variables required for the test are set during the Arrange step.<\/span><\/li>\n<li style=\"font-weight: 400\"><span style=\"font-weight: 400\">During the Act phase, the function\/method\/class under test is called.<\/span><\/li>\n<li style=\"font-weight: 400\"><span style=\"font-weight: 400\">We finally validate the test result during the Assert phase.<\/span><\/li>\n<\/ul>\n<p><span style=\"font-weight: 400\">By separating the setup, execution, and verification phases of a test, this technique offers a tidy way to arrange unit tests. Additionally, unit tests are simpler to read because they all use the same format.<\/span><\/p>\n<h3><span style=\"font-weight: 400\">Automated and Manual Testing<\/span><\/h3>\n<p><span style=\"font-weight: 400\">Manual testing takes another form which is known as exploratory testing. It is testing that is done without any plan. For manual testing, we need to prepare a list of the application; we enter various inputs and wait for the expected output.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Every time we make inputs or change code, we have to go through each list function and check it.<\/span><\/p>\n<p><span style=\"font-weight: 400\">It is the most common way of testing and it is also a time-consuming process.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Automated testing, on the other hand, executes the code according to our code plan, which means it runs the part of the code we want to test in the order we want to test them with a script instead of a human.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Python provides a set of tools and libraries that help us create automated tests for an application.<\/span><\/p>\n<h3><span style=\"font-weight: 400\">Description of Tests and Basic Concepts used<\/span><\/h3>\n<h4><span style=\"font-weight: 400\">Basic concepts used in the code:<\/span><\/h4>\n<ul>\n<li><strong>assertEqual() \u2013<\/strong> This statement is used to check if the obtained result is equal to the expected result.<\/li>\n<li><strong>assertTrue()\/assertFalse()<\/strong> \u2013 This statement is used to verify whether a given statement is true or false.<\/li>\n<li><strong>assertRaises()<\/strong> \u2013 This command is used to raise a specific exception.<\/li>\n<\/ul>\n<h3><span style=\"font-weight: 400\">Test description:<\/span><\/h3>\n<p><strong>1. test_strings_a:<\/strong><\/p>\n<p><span style=\"font-weight: 400\">This test is used to test the property of a string in which a character says &#8220;a&#8221; multiplied by a number say &#8220;x&#8221; and gives the output as x times &#8220;a&#8221;. If the result matches the given output, then claimEqual() returns true in this case.<\/span><\/p>\n<p><strong>2. test_upper:<\/strong><\/p>\n<p><span style=\"font-weight: 400\">This test is used to check whether a given string is converted to uppercase or not. assetEqual() returns true if the returned string is in uppercase.<\/span><\/p>\n<p><strong>3. test_isupper:<\/strong><\/p>\n<p><span style=\"font-weight: 400\">This test is used to test a string property that returns TRUE if the string is uppercase, otherwise, it returns False. AssTrue() \/assertFalse() command is used for this verification.<\/span><\/p>\n<p><strong>4. test_strip:<\/strong><\/p>\n<p><span style=\"font-weight: 400\">This test is used to check that all characters passed in the function have been removed from the string. claimEqual() returns true if the string is removed and matches the given output.<\/span><\/p>\n<p><strong>5. test_split:<\/strong><\/p>\n<p><span style=\"font-weight: 400\">This test is used to check the string split function, which splits the string using the argument passed in the function and returns the result as a list. If the result matches the given output, then claimEqual() returns true in this case.<\/span><\/p>\n<p><strong>6. unittest.main()<\/strong><\/p>\n<p><span style=\"font-weight: 400\">It provides a command line interface to the test script.<\/span><\/p>\n<h3><span style=\"font-weight: 400\">Using the PyUnit Framework included in Python<\/span><\/h3>\n<p><span style=\"font-weight: 400\">You might be asking why we need unit testing frameworks in Python and other languages that have the assert keyword. With the aid of unit testing frameworks, we can automate the testing process, run numerous tests with various parameters on the same function, look for expected exceptions, and do many other tasks.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Python&#8217;s built-in unit testing framework is called PyUnit, and it is the language&#8217;s equivalent of the Java-based JUnit testing framework. To get started writing a test file, we need to import the unittest library to use PyUnit: import unittest<\/span><\/p>\n<p><span style=\"font-weight: 400\">The first unit test can then begin to be written. PyUnit&#8217;s unit tests are organized as subclasses of the unittest class. By overriding the runTest() method in the TestCase class, we can create our unit tests that use various assert functions from unittest to verify conditions. TestCase:<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class TestGetAreaRectangle(unittest.TestCase):\n    def runTest(self):\n        rectangle = Rectangle(2, 3)\n        self.assertEqual(rectangle.get_area(), 6, \"incorrect area\")\n<\/pre>\n<p>Our initial unit test is that. It looks to see if the rectangle. The right area is returned by the get area() method for a rectangle with dimensions of 2 and 3. We apply self. Instead of just using assert, the unittest library now supports assertEqual, allowing the runner to gather all test cases and generate a report.<\/p>\n<p><span style=\"font-weight: 400\">Use several assert methods from the unittest.<\/span><\/p>\n<p><span style=\"font-weight: 400\">TestCase also allows us to test diverse behaviors such as self.<\/span><\/p>\n<p><span style=\"font-weight: 400\"><strong>assertRaises(exception)<\/strong> &#8211; This allows us to check if a given code block causes an anticipated exception.<\/span><\/p>\n<p><span style=\"font-weight: 400\">In our program, we call unittest.main() to execute the unit test. unittest.main()<\/span><\/p>\n<p><span style=\"font-weight: 400\">The output indicates that the tests passed properly because the code returned the expected result in this instance:<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">Ran 1 test in 0.003s\nOK\n<\/pre>\n<p><span style=\"font-weight: 400\">Here is the full code:<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import unittest\n\n# Our code to be tested\nclass Rectangle:\n    def __init__(self, width, height):\n        self.width = width\n        self.height = height\n\n    def get_area(self):\n        return self.width * self.height\n\n    def set_width(self, width):\n        self.width = width\n\n    def set_height(self, height):\n        self.height = height\n\n# The test based on unittest module\nclass TestGetAreaRectangle(unittest.TestCase):\n    def runTest(self):\n        rectangle = Rectangle(2, 3)\n        self.assertEqual(rectangle.get_area(), 6, \"incorrect area\")\n\n# run the test\nunittest.main()\n<\/pre>\n<p><span style=\"font-weight: 400\">We can also nest many unit tests together in one subclass of unittest. Using the &#8220;test&#8221; prefix to name methods in the new subclass, for instance<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class TestGetAreaRectangle(unittest.TestCase):\n    def test_normal_case(self):\n        rectangle = Rectangle(2, 3)\n        self.assertEqual(rectangle.get_area(), 6, \"incorrect area\")\n\n    def test_negative_case(self): \n        \"\"\"expect -1 as output to denote error when looking at negative area\"\"\"\n        rectangle = Rectangle(-1, 2)\n        self.assertEqual(rectangle.get_area(), -1, \"incorrect negative output\")\n<\/pre>\n<p><span style=\"font-weight: 400\">We are now focusing on expanding our tests. What if we had some setup code that we were required to perform before each test? In unittest, we can override the setUp method. TestCase.<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class TestGetAreaRectangleWithSetUp(unittest.TestCase):\n  def setUp(self):\n    self.rectangle = Rectangle(0, 0)\n\n  def test_normal_case(self):\n    self.rectangle.set_width(2)\n    self.rectangle.set_height(3)\n    self.assertEqual(self.rectangle.get_area(), 6, \"incorrect area\")\n\n  def test_negative_case(self): \n    \"\"\"expect -1 as output to denote error when looking at negative area\"\"\"\n    self.rectangle.set_width(-1)\n    self.rectangle.set_height(2)\n\n    self.assertEqual(self.rectangle.get_area(), -1, \"incorrect negative output\")\n<\/pre>\n<p><span style=\"font-weight: 400\">We have modified the setUp() method from unittest in the code example above. Using our own setUp() method, we create a Rectangle object in the TestCase. When several tests rely on the same code to set up the test, the setUp() method, executed before each unit test, helps prevent code duplication. This is analogous to the @Before decorator in JUnit. In the same way, we can override the tearDown() method to have code run after each test.<\/span><\/p>\n<p><span style=\"font-weight: 400\">The possibilities for PyUnit are merely the tip of the iceberg. In addition, we could write tests that look for exception messages that match a regex expression or only call setUp\/tearDown methods once or for exception messages that match setUp\/tearDown methods.<\/span><\/p>\n<h3><span style=\"font-weight: 400\">Unit Testing in Action<\/span><\/h3>\n<p><span style=\"font-weight: 400\">We&#8217;ll examine unit testing in practice next. In our example, we&#8217;ll be using PyUnit to test a method that uses pandas datareader to collect stock data from Yahoo Finance:<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import pandas_datareader.data as web\n\ndef get_stock_data(ticker):\n    \"\"\"pull data from stooq\"\"\"\n    df = web.DataReader(ticker, \"yahoo\")\n    return df\n<\/pre>\n<p><span style=\"font-weight: 400\">This function crawls the Yahoo Finance website for stock data on a certain stock ticker and returns a pandas DataFrame. This has many potential failure modes. For instance, if Yahoo Finance is down, the data reader might not return anything or provide a DataFrame with blank columns or blank data in the columns (if the source restructured its website). Therefore, we should offer a variety of test functions to check for a variety of failure modes:<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import datetime\nimport unittest\n\nimport pandas as pd\nimport pandas_datareader.data as web\n\ndef get_stock_data(ticker):\n    \"\"\"pull data from stooq\"\"\"\n    df = web.DataReader(ticker, 'yahoo')\n    return df\n\nclass TestGetStockData(unittest.TestCase):\n    @classmethod\n    def setUpClass(self):\n        \"\"\"We only want to pull this data once for each TestCase since it is an expensive operation\"\"\"\n        self.df = get_stock_data('^DJI')\n\n    def test_columns_present(self):\n        \"\"\"ensures that the expected columns are all present\"\"\"\n        self.assertIn(\"Open\", self.df.columns)\n        self.assertIn(\"High\", self.df.columns)\n        self.assertIn(\"Low\", self.df.columns)\n        self.assertIn(\"Close\", self.df.columns)\n        self.assertIn(\"Volume\", self.df.columns)\n\n    def test_non_empty(self):\n        \"\"\"ensures that there is more than one row of data\"\"\"\n        self.assertNotEqual(len(self.df.index), 0)\n\n    def test_high_low(self):\n        \"\"\"ensure high and low are the highest and lowest in the same row\"\"\"\n        ohlc = self.df[[\"Open\",\"High\",\"Low\",\"Close\"]]\n        highest = ohlc.max(axis=1)\n        lowest = ohlc.min(axis=1)\n        self.assertTrue(ohlc.le(highest, axis=0).all(axis=None))\n        self.assertTrue(ohlc.ge(lowest, axis=0).all(axis=None))\n\n    def test_most_recent_within_week(self):\n        \"\"\"most recent data was collected within the last week\"\"\"\n        most_recent_date = pd.to_datetime(self.df.index[-1])\n        self.assertLessEqual((datetime.datetime.today() - most_recent_date).days, 7)\n\nunittest.main()\n<\/pre>\n<p><span style=\"font-weight: 400\">The unit above tests examine the presence of specific columns (test columns present), the data frame&#8217;s non-emptiness (test non-empty), whether the &#8220;high&#8221; and &#8220;low&#8221; columns truly represent the high and low of the same row (test high low), and whether the most recent data in the DataFrame was entered within the previous week (test most recent within the week).<\/span><\/p>\n<p><span style=\"font-weight: 400\">Consider working on a machine learning project using stock market data. A unit test framework will help you detect if your data preprocessing is performing as planned.<\/span><\/p>\n<p><span style=\"font-weight: 400\">We can determine whether there was a material change in the output of our function using these unit tests, which may be done as part of a Continuous Integration (CI) procedure. Then, depending on the functionality we rely on from that function, we can apply additional unit tests as necessary.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Here is PyTest&#8217;s equivalent version for completeness:<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import pytest\n\n# scope=\"class\" tears down the fixture only at the end of the last test in the class, so we avoid rerunning this step.\n@pytest.fixture(scope=\"class\")\ndef stock_df():\n  # We only want to pull this data once for each TestCase since it is an expensive operation\n  df = get_stock_data('^DJI')\n  return df\n\nclass TestGetStockData:\n\n  def test_columns_present(self, stock_df):\n    # ensures that the expected columns are all present\n    assert \"Open\" in stock_df.columns\n    assert \"High\" in stock_df.columns\n    assert \"Low\" in stock_df.columns\n    assert \"Close\" in stock_df.columns\n    assert \"Volume\" in stock_df.columns\n\n  def test_non_empty(self, stock_df):\n    # ensures that there is more than one row of data\n    assert len(stock_df.index) != 0\n\n  def test_most_recent_within_week(self, stock_df):\n    # most recent data was collected within the last week\n    most_recent_date = pd.to_datetime(stock_df.index[0])\n    assert (datetime.datetime.today() - most_recent_date).days &lt;= 7\n<\/pre>\n<p><span style=\"font-weight: 400\">Building unit tests might seem laborious and time-consuming. Still, they can be an essential component of any CI pipeline and are great tools for finding errors early on before they go further down the pipeline and become more challenging to fix.<\/span><\/p>\n<h3><span style=\"font-weight: 400\">Conclusion:<\/span><\/h3>\n<p><span style=\"font-weight: 400\">To sum up, we discussed the fundamentals of unit testing in this essay. We learned the importance of unit testing and the need for everyone to test their programs. Finally, we discussed unit testing and how to create and use basic Python unit tests.<\/span><\/p>\n","protected":false},"excerpt":{"rendered":"<p>When testing software, a technique known as unit testing examines the tiniest testable bits of code and checks them for proper operation. We can ensure that every component code, including auxiliary functions that may&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":86978,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1053],"tags":[4817],"class_list":["post-86866","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-unit-testing-in-python"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Unit Testing in Python - TechVidvan<\/title>\n<meta name=\"description\" content=\"Learn about Unit Testing in Python with example. See its importance, need, how to create it and basic python unit tests.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/unit-testing-in-python\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Unit Testing in Python - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Learn about Unit Testing in Python with example. See its importance, need, how to create it and basic python unit tests.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/unit-testing-in-python\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-02-02T03:30:49+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/01\/unit-testing-with-python.webp\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/webp\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"12 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Unit Testing in Python - TechVidvan","description":"Learn about Unit Testing in Python with example. See its importance, need, how to create it and basic python unit tests.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/unit-testing-in-python\/","og_locale":"en_US","og_type":"article","og_title":"Unit Testing in Python - TechVidvan","og_description":"Learn about Unit Testing in Python with example. See its importance, need, how to create it and basic python unit tests.","og_url":"https:\/\/techvidvan.com\/tutorials\/unit-testing-in-python\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2023-02-02T03:30:49+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/01\/unit-testing-with-python.webp","type":"image\/webp"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"12 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/unit-testing-in-python\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/unit-testing-in-python\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Unit Testing in Python","datePublished":"2023-02-02T03:30:49+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/unit-testing-in-python\/"},"wordCount":2098,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/unit-testing-in-python\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/01\/unit-testing-with-python.webp","keywords":["Unit Testing in Python"],"articleSection":["Python Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/unit-testing-in-python\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/unit-testing-in-python\/","url":"https:\/\/techvidvan.com\/tutorials\/unit-testing-in-python\/","name":"Unit Testing in Python - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/unit-testing-in-python\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/unit-testing-in-python\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/01\/unit-testing-with-python.webp","datePublished":"2023-02-02T03:30:49+00:00","description":"Learn about Unit Testing in Python with example. See its importance, need, how to create it and basic python unit tests.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/unit-testing-in-python\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/unit-testing-in-python\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/unit-testing-in-python\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/01\/unit-testing-with-python.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/01\/unit-testing-with-python.webp","width":1200,"height":628,"caption":"unit testing with python"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/unit-testing-in-python\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Unit Testing in Python"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/86866","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=86866"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/86866\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/86978"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=86866"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=86866"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=86866"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}