Unittest usage instance in Python

  • 2020-04-02 14:07:16
  • OfStack

This article illustrates the use of unittest in Python as an example and shares it with you for your reference. Specific usage analysis is as follows:

1. Unittest module contains the function of writing and running unittest. All customized test classes should be integrated with unitest.testcase class.
Setup (): run before each test function runs
Teardown (): execute after each test function is run
SetUpClass (): must use the @classmethod decorator and run all tests once before running them
TearDownClass (): you must use the @classmethod decorator and run all tests once they are run

2. Sample code:


# The file name runtest.py
import random
import unittest

class TestSequenceFunctions(unittest.TestCase):

  def setUp(self):
    self.seq = list(range(10))

  def test_shuffle(self):
    # make sure the shuffled sequence does not lose any elements
    random.shuffle(self.seq)
    self.seq.sort()
    self.assertEqual(self.seq, list(range(10)))

    # should raise an exception for an immutable sequence
    self.assertRaises(TypeError, random.shuffle, (1,2,3))

  def test_choice(self):
    element = random.choice(self.seq)
    self.assertTrue(element in self.seq)

  def test_sample(self):
    with self.assertRaises(ValueError):
      random.sample(self.seq, 20)
    for element in random.sample(self.seq, 5):
      self.assertTrue(element in self.seq)

if __name__ == '__main__':
  unittest.main()

3. How to run: run runtest.py directly from the command line

You can skip test method or test class using the unitest. Skip decorator family, which includes:
Unittest.skip (reason): skip the test unconditionally
Skipif (conditition,reason): pass the test when condititon is true
@unittest.skipunless(condition,reason): skip the test if condition is not true

You can customize the skip decorator


# This is a custom one skip decorrator
def skipUnlessHasattr(obj, attr):
  if hasattr(obj, attr):
    return lambda func: func
  return unittest.skip("{!r} doesn't have {!r}".format(obj, attr))

Skip decorator sample code:


class MyTestCase(unittest.TestCase):

  @unittest.skip("demonstrating skipping")
  def test_nothing(self):
    self.fail("shouldn't happen")

  @unittest.skipIf(mylib.__version__ < (1, 3),
           "not supported in this library version")
  def test_format(self):
    # Tests that work for only a certain version of the library.
    pass

  @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
  def test_windows_support(self):
    # windows specific testing code
    pass

@unittest.skip("showing class skipping")
class MySkippedTestCase(unittest.TestCase):
  def test_not_run(self):
    pass

4. Expected failure: use the @unittest. ExpectedFailure decorator, which does not count the number of cases that fail if the test fails

I hope that this article has helped you to learn Python programming.


Related articles: