Summary

  • The unittest module is a framework for developing reliable automated tests.
  • You define test cases by subclassing from unittest.TestCase.
  • The unittest.main() function is useful for running all of the
    tests in a module.
  • The setUp() and tearDown() fixtures are used to run code before and after each test method.
  • Test methods are defined by creating method names that start with test_ on test case objects.
  • The various TestCase.assert... methods can be used to make a test method fail when the right conditions aren't met.
  • Use TestCase.assertRaises() in a with-statement to check that the right exceptions are thrown in a test.
  1. Test-driven development, or simply TDD, is a form of software development where tests are written first, That is, before you write the actual functionality to be tested. This may seem backwards at first, but it can be a surprisingly powerful technique. You can learn more about TDD here.

  2. Note that we don't actually try to test any functionality yet. This is just the initial skeleton of our test suite that lets us verify that the test method executes.

  3. A tenet of TDD is that your tests should fail before they pass, and you should only ever write enough implementation code to make you tests pass. In this way, your tests stand as a complete description how your code should behave.

  4. You may have noticed that the setUp() and tearDown() method names aren't in line with what PEP 8 prescribes. This is because the unittest module predates those parts of PEP 8 which specify the convention of function names being in lower case with underscores. There are several such cases in the Python standard library but most new Python code follows the PEP 8 style.

  5. If we were strictly interpreting TDD here, this amount of implementation would have been too much. To make our existing test pass, we didn't need to actually implement line counting; we just needed to return the value 4. Subsequent tests would have then forced us to continually "update" our implementation as they described a more complete version of the analysis algorithm. We think you'll agree that such a dogmatic approach would be inappropriate here and, frankly, in real development as well.

 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset