Make sure you get it

Take a look at the following doctest. Can you work out how the equivalent unittest would look like?

>>> try:
...     int('123')
... except ValueError:
...     pass
... else:
...     print('Expected exception was not raised')

That doctest code tries to convert a string into an integer; if this conversion does not raise a ValueError, it reports an error. In unittest, that looks like this:

class test_exceptions(TestCase):
    def test_ValueError(self):
        self.assertRaises(ValueError, int, '123')

How do you check whether two floating point numbers are equal in unittest? You should use the assertAlmostEqual method, so as not to get tripped by the floating point imprecision.

When would you choose to use assertTrue? How about fail? You would use assertTrue if none of the more specialized assertions suit your needs. You would use fail if you need maximum control when a test succeeds or fails.

Look back at some of the tests we wrote in the previous chapters, and translate them from doctest into unittest. Given what you already know of unittest, you should be able to translate any of the tests.

While you're doing this, think about the relative merits of unittest and doctest for each of the tests that you translate. The two systems have different strengths, so it makes sense that each will be the more appropriate choice for different situations. When is doctest the better choice, and when is unittest?

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

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