SoFunction
Updated on 2025-03-02

Detailed explanation of python unit test framework unittest

1: Unittest is a unit test framework built into Python. It is similar to java's junit, and its basic structure is similar.

The basic usage is as follows:

1. Use import unittest to import unittest module

2. Define a test case class inherited from, such as

class abcd():

3. Define setUp and tearDown. These two methods are the same as junit. That is, if defined, the setUp method will be executed before each test case is executed, and the tearDown method will be executed after the execution is completed.

4. Define the test case, the name starts with test, and unittest will automatically put the method starting with test into the test case set.

5. A test case should only test one aspect, and the purpose and content of the test should be clear. It mainly calls assertEqual, assertRaises and other assert methods to determine whether the program execution result and the expected value are consistent.

6. Call () to start the test

7. If the test fails, e will be displayed and a specific error will be given (here is caused by a program problem). If the test fails, it will be displayed as f, and if the test passes, it will be displayed in sequence.

A simple example of a single testcase:

# -*- coding:UTF-8 -*-
'''
 Created on March 24, 2015

 @author: Administrator
 '''
import unittest
from selenium import webdriver
import time


class TestCase1():


  def setUp(self):
    =()
    self.base_url=""


  def tearDown(self):
    ()


  def testCase1(self):
    driver=
    (self.base_url)
    print "Maximize window"
    driver.maximize_window()
    (10)


if __name__ == "__main__":
  ()

An example of multiple testcases:

# -*- coding:UTF-8 -*-
'''
Created on 
@author: Administrator
'''
from selenium import webdriver
from  import By
from  import Keys
from .action_chains import ActionChains
from  import WebDriverWait
from  import Select
from  import NoSuchElementException,\
  NoAlertPresentException
import HTMLTestRunner
#form  import NoAlertPresentException
import unittest, time, re

class Baidu():
  def setUp(self):
     = ()
    .implicitly_wait(30)
    self.base_url = "/?tn=98012088_4_dg&ch=3"
     = []
    self.accept_next_alert = True
    (self.base_url)

  def test_baidu_search(self):
    '''Baidu search'''
    driver = 
#    (self.base_url + "/")
    try:
      driver.find_element_by_id("kw").send_keys("selenium webdriver")
      driver.find_element_by_id("su").click()
    except:
      driver.get_screenshot_as_file('D:\\workspace\\python_prictise\\src\\')
    (2)
    ()

  def test_baidu_set(self):
    '''Baidu News'''
    driver = 
    driver.find_element_by_name("tj_trnews").click()
    (,u'Baidu News Search - the world's largest Chinese news platform',"switch to baidu news faile!")
#    (2)

  def is_element_present(self, how, what):
    try: .find_element(by=how, value=what)
    except NoSuchElementException: return False
    return True

  def is_alert_present(self):
    try: .switch_to_alert()
    except NoAlertPresentException: return False
    return True

  def close_alert_and_get_its_text(self):
    try:
      alert = .switch_to_alert()
      alert_text = 
      if self.accept_next_alert:
        ()
      else:
        ()
      return alert_text
    finally: self.accept_next_alert = True

  def tearDown(self):
    ()
    ([], )

if __name__ == "__main__":  
  ()

Two: Methods to skip single testcase and testclass

In unittest, it also supports methods similar to junit to skip a single test case or test class, as follows:

@(reason)

Unconditionally skip the modified testcase or testclass, reason describes why the test is skipped as a string;

@(condition,reason)

If the condition condition is true, the testcase or testclass is skipped;

@(condition,reason)

Skip the modified testcase or testclass unless the condition is true;

@

Tagged tests as a test that is expected to fail, but are not counted as a failed test in the results;

Three: Assertion

Use assertions to determine whether it is pass or fail in unittest. The common assertion methods are as follows:

assertEqual(a, b) a == b
assertNotEqual(a, b) a != b
assertTrue(x) 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) x is None
assertIsNotNone(x) x 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)
assertAlmostEqual(a, b) round(a-b, 7) == 0
assertNotAlmostEqual(a, b) round(a-b, 7) != 0
assertGreater(a, b) a > b 2.7
assertGreaterEqual(a, b) a >= b 2.7
assertLess(a, b) a < b 2.7
assertLessEqual(a, b) a <= b 2.7
assertRegexpMatches(s, re) (s) 2.7
assertNotRegexpMatches(s, re) not (s) 2.7
assertItemsEqual(a, b) sorted(a) == sorted(b) and works with unhashable objs 2.7
assertDictContainsSubset(a, b) all the key/value pairs in a exist in b 2.7
assertMultiLineEqual(a, b) strings 2.7
assertSequenceEqual(a, b) sequences 2.7
assertListEqual(a, b) lists 2.7
assertTupleEqual(a, b) tuples 2.7
assertSetEqual(a, b) sets or frozensets 2.7
assertDictEqual(a, b) dicts 2.7
assertMultiLineEqual(a, b) strings 2.7
assertSequenceEqual(a, b) sequences 2.7
assertListEqual(a, b) lists 2.7
assertTupleEqual(a, b) tuples 2.7
assertSetEqual(a, b) sets or frozensets 2.7
assertDictEqual(a, b) dicts 2.7

Please refer to the official documentation for other assertion methods

Four: Make up the test suite

1. Add a smaller number of test cases, you can use the following method:

suite=()
(testclass(testcase))

Here testclass is the name of the test class, and testcase is the name of the test case under the test class, which is a string.

2. For situations where there are multiple test classes, the following method can be used:

def createsuite():
  testunit=()
  discover=(testdir,pattern='test_*.py', top_level_dir=None)
  print discover
  for test_suite in discover:
    for testsuit in test_suite:
      (testsuit)
  return testunit
alltestnames = createsuite()

This allows you to import testcases from multiple test files in one directory.