doctest
Can be written in docstring. Can be used as a legend.
Import doctest, write the following in docstring, and call doctest.testmod (). When executing, use  python $ {filename} .py -v.
sample.py
# -*- coding: utf-8 -*-
import doctest
def twice(n):
    """A function that doubles the argument and returns
    >>> twice(8)
    16
    >>> twice(1850923)
    3701846
    """
    return n * 2
if __name__ == "__main__":
    doctest.testmod()
Run
python sample.py -v
result
Trying:
    twice(8)
Expecting:
    16
ok
Trying:
    twice(1850923)
Expecting:
    3701846
ok
1 items had no tests:
    __main__
1 items passed all tests:
   2 tests in __main__.twice
2 tests in 2 items.
2 passed and 0 failed.
Test passed.
Read the docstring
python
import sample
help(sample.twice)
twice(n)
A function that doubles the argument and returns
    >>> twice(8)
    16
    >>> twice(1850923)
    3701846
This is ... thank you ...
** When testing the Instance Method **
--Give extraglobs as an argument to testmod. The dictionary key and value sets defined in extraglobs are merged into global variables.
sample.py
# -*- coding: utf-8 -*-
class IntUtil:
    def twice(self, n):
        """A function that doubles the argument and returns
        >>> mine.twice(8)
        16
        >>> mine.twice(1850923)
        3701846
        """
        return n * 2
if __name__ == "__main__":
    import doctest
    doctest.testmod(extraglobs = {'mine': IntUtil()})
unittest
General unit tests and integration tests are done in this module
setUp: run at start tearDown: run on end
functions
| Function name | Description | 
|---|---|
| assertEqual(a, b, msg=None) | a == b | 
| assertNotEqual(a, b, msg=None) | a != b | 
| assertTrue(expr, msg=None) | bool(x) is True | 
| assertFalse(x) | bool(x) is False | 
| assertIs(a, b) | a is b | 
| assertIsNot(a, b) | a is not b | 
| assertIsNone(x) | a is None | 
| assertIsNotNone(x) | a is not None | 
| assertIn(a, b) | a in b | 
| assertNotIn(a, b) | a not in b | 
| assertIsInstance(a, b) | isinstance(a, b) | 
| assertNotIsInstance(a, b) | not isinstance(a, b) | 
sample_test.py
# -*- coding: utf-8 -*-
import unittest
import sample
class SampleTest(unittest.TestCase):
    def setUp(self):
        self.util = sample.IntUtil()
    def test_twice(self):
        #Is it equivalent to the added number?
        import random
        roop = 0
        while roop != 10000:
            n = random.randint(0, 100)
            ans = n + n
            self.assertEqual(self.util.twice(n), ans)
            roop += 1
if __name__ == '__main__':
    unittest.main()
Recommended Posts