17.4. unittest — 自动化测试框架 | 开发者工具 |《python 3 标准库实例教程》| python 技术论坛-金年会app官方网

未匹配的标注

目的:自动测试框架

python 的 unittest 模块基于 kent beck 和 erich gamma 的 xunit 框架设计。这一模式被许多语言采用,包括 c,perl,java 和 smalltalk。由 uniitest 实现的框架支持 fixtures,test suites, 和 test runner,以实现自动化测试。

测试的基本结构

unittest 中的测试包括两部分:管理测试依赖项( fixtures )的代码,和测试本身的代码。每个单独的测试通过子类化 testcase 和重写或添加适当的方法来创建。下面的示例中,simplistictest 有一个 test() 方法,该方法会失败,因为 ab 永远不会相等。

unittest_simple.py

import unittest
class simplistictest(unittest.testcase):
    def test(self):
        a = 'a'
        b = 'a'
        self.assertequal(a, b)

运行测试

运行测试最简单的方法是使用命令行接口提供的自动发现功能。

$ python3 -m unittest unittest_simple.py
.
----------------------------------------------------------------
ran 1 test in 0.000s
ok

这个简短的输出包括测试所用的时间,以及每个测试的状态指示符(输出的第一行中的 . 表示测试已通过)。需要更详细的测试结果,使用 -v 选项。

$ python3 -m unittest -v unittest_simple.py
test (unittest_simple.simplistictest) ... ok
----------------------------------------------------------------
ran 1 test in 0.000s
ok

测试结果

测试有3种可能的结果,详见下表。

测试用例结果

结果 描述
ok 测试通过。
fail 测试未通过,并引发 assertionerror 异常。
error 测试引发了不是 assertionerror 的异常。

没有明确的方法使测试「通过」,因此测试的状态取决于异常的存在(或不存在)。

unittest_outcomes.py

import unittest
class outcomestest(unittest.testcase):
    def testpass(self):
        return
    def testfail(self):
        self.assertfalse(true)
    def testerror(self):
        raise runtimeerror('test error!')

当测试失败或发生错误时,堆栈跟踪(traceback)将包含在输出中。

$ python3 -m unittest unittest_outcomes.py
ef.
================================================================
error: testerror (unittest_outcomes.outcomestest)
----------------------------------------------------------------
traceback (most recent call last):
  file ".../unittest_outcomes.py", line 18, in testerror
    raise runtimeerror('test error!')
runtimeerror: test error!
================================================================
fail: testfail (unittest_outcomes.outcomestest)
----------------------------------------------------------------
traceback (most recent call last):
  file ".../unittest_outcomes.py", line 15, in testfail
    self.assertfalse(true)
assertionerror: true is not false
----------------------------------------------------------------
ran 3 tests in 0.001s
failed (failures=1, errors=1)

在前面的例子中,testfail() 失败,堆栈跟踪(traceback)显示了失败代码所在的行。不过,还需要人来查看代码,找出测试失败的原因。

unittest_failwithmessage.py

import unittest
class failuremessagetest(unittest.testcase):
    def testfail(self):
        self.assertfalse(true, 'failure message goes here')

为了更容易地理解测试失败的原因,fail*()assert*() 方法都接受一个参数 msg,用于报告更详细的错误消息。

$ python3 -m unittest -v unittest_failwithmessage.py
testfail (unittest_failwithmessage.failuremessagetest) ... fail
================================================================
fail: testfail (unittest_failwithmessage.failuremessagetest)
----------------------------------------------------------------
traceback (most recent call last):
  file ".../unittest_failwithmessage.py", line 12, in testfail
    self.assertfalse(true, 'failure message goes here')
assertionerror: true is not false : failure message goes here
----------------------------------------------------------------
ran 1 test in 0.000s
failed (failures=1)

测试真假

大多数测试判断条件的真假。编写真假测试有两种方法,取决于测试者的意图和被测代码的预期结果。

unittest_truth.py

import unittest
class truthtest(unittest.testcase):
    def testasserttrue(self):
        self.asserttrue(true)
    def testassertfalse(self):
        self.assertfalse(false)

如果代码结果是 true,则应该使用方法 asserttrue()。如果代码结果是 false,则应该使用方法 assertfalse()

$ python3 -m unittest -v unittest_truth.py
testassertfalse (unittest_truth.truthtest) ... ok
testasserttrue (unittest_truth.truthtest) ... ok
----------------------------------------------------------------
ran 2 tests in 0.000s
ok

测试相等

作为特例,unittest 有几个方法用于测试两个值是否相等。

unittest_equality.py

import unittest
class equalitytest(unittest.testcase):
    def testexpectequal(self):
        self.assertequal(1, 3 - 2)
    def testexpectequalfails(self):
        self.assertequal(2, 3 - 2)
    def testexpectnotequal(self):
        self.assertnotequal(2, 3 - 2)
    def testexpectnotequalfails(self):
        self.assertnotequal(1, 3 - 2)

当测试失败,测试方法会报告错误信息,信息中包括进行比较的两个值。

$ python3 -m unittest -v unittest_equality.py
testexpectequal (unittest_equality.equalitytest) ... ok
testexpectequalfails (unittest_equality.equalitytest) ... fail
testexpectnotequal (unittest_equality.equalitytest) ... ok
testexpectnotequalfails (unittest_equality.equalitytest) ...
fail
================================================================
fail: testexpectequalfails (unittest_equality.equalitytest)
----------------------------------------------------------------
traceback (most recent call last):
  file ".../unittest_equality.py", line 15, in
testexpectequalfails
    self.assertequal(2, 3 - 2)
assertionerror: 2 != 1
================================================================
fail: testexpectnotequalfails (unittest_equality.equalitytest)
----------------------------------------------------------------
traceback (most recent call last):
  file ".../unittest_equality.py", line 21, in
testexpectnotequalfails
    self.assertnotequal(1, 3 - 2)
assertionerror: 1 == 1
----------------------------------------------------------------
ran 4 tests in 0.001s
failed (failures=2)

近似相等?

除了严格相等,还可以使用 assertalmostequal() 和 assertnotalmostequal() 测试浮点数的近似相等。

unittest_almostequal.py

import unittest
class almostequaltest(unittest.testcase):
    def testequal(self):
        self.assertequal(1.1, 3.3 - 2.2)
    def testalmostequal(self):
        self.assertalmostequal(1.1, 3.3 - 2.2, places=1)
    def testnotalmostequal(self):
        self.assertnotalmostequal(1.1, 3.3 - 2.0, places=1)

参数是要比较的值,以及用于比较的小数位数(译者注:四舍五入到指定位数)。

$ python3 -m unittest unittest_almostequal.py
.f.
================================================================
fail: testequal (unittest_almostequal.almostequaltest)
----------------------------------------------------------------
traceback (most recent call last):
  file ".../unittest_almostequal.py", line 12, in testequal
    self.assertequal(1.1, 3.3 - 2.2)
assertionerror: 1.1 != 1.0999999999999996
----------------------------------------------------------------
ran 3 tests in 0.001s
failed (failures=1)

容器

除了通用的 assertequal()assertnotequal() 之外,还有一些比较容器的特殊方法,用于比较 listdictset 等对象。

unittest_equality_container.py

import textwrap
import unittest
class containerequalitytest(unittest.testcase):
    def testcount(self):
        self.assertcountequal(
            [1, 2, 3, 2],
            [1, 3, 2, 3],
        )
    def testdict(self):
        self.assertdictequal(
            {'a': 1, 'b': 2},
            {'a': 1, 'b': 3},
        )
    def testlist(self):
        self.assertlistequal(
            [1, 2, 3],
            [1, 3, 2],
        )
    def testmultilinestring(self):
        self.assertmultilineequal(
            textwrap.dedent("""
            this string
            has more than one
            line.
            """),
            textwrap.dedent("""
            this string has
            more than two
            lines.
            """),
        )
    def testsequence(self):
        self.assertsequenceequal(
            [1, 2, 3],
            [1, 3, 2],
        )
    def testset(self):
        self.assertsetequal(
            set([1, 2, 3]),
            set([1, 3, 2, 4]),
        )
    def testtuple(self):
        self.asserttupleequal(
            (1, 'a'),
            (1, 'b'),
        )

每个方法都使用针对输入类型有意义的格式输出信息,从而使失败的测试结果更容易理解和纠正。

$ python3 -m unittest unittest_equality_container.py
fffffff
================================================================
fail: testcount
(unittest_equality_container.containerequalitytest)
----------------------------------------------------------------
traceback (most recent call last):
  file ".../unittest_equality_container.py", line 15, in
testcount
    [1, 3, 2, 3],
assertionerror: element counts were not equal:
first has 2, second has 1:  2
first has 1, second has 2:  3
================================================================
fail: testdict
(unittest_equality_container.containerequalitytest)
----------------------------------------------------------------
traceback (most recent call last):
  file ".../unittest_equality_container.py", line 21, in
testdict
    {'a': 1, 'b': 3},
assertionerror: {'a': 1, 'b': 2} != {'a': 1, 'b': 3}
- {'a': 1, 'b': 2}
?               ^
  {'a': 1, 'b': 3}
?               ^
================================================================
fail: testlist
(unittest_equality_container.containerequalitytest)
----------------------------------------------------------------
traceback (most recent call last):
  file ".../unittest_equality_container.py", line 27, in
testlist
    [1, 3, 2],
assertionerror: lists differ: [1, 2, 3] != [1, 3, 2]
first differing element 1:
2
3
- [1, 2, 3]
  [1, 3, 2]
================================================================
fail: testmultilinestring
(unittest_equality_container.containerequalitytest)
----------------------------------------------------------------
traceback (most recent call last):
  file ".../unittest_equality_container.py", line 41, in
testmultilinestring
    """),
assertionerror: '\nthis string\nhas more than one\nline.\n' !=
'\nthis string has\nmore than two\nlines.\n'
- this string
  this string has
?                
- has more than one
? ----           --
  more than two
?             
- line.
  lines.
?      
================================================================
fail: testsequence
(unittest_equality_container.containerequalitytest)
----------------------------------------------------------------
traceback (most recent call last):
  file ".../unittest_equality_container.py", line 47, in
testsequence
    [1, 3, 2],
assertionerror: sequences differ: [1, 2, 3] != [1, 3, 2]
first differing element 1:
2
3
- [1, 2, 3]
  [1, 3, 2]
================================================================
fail: testset
(unittest_equality_container.containerequalitytest)
----------------------------------------------------------------
traceback (most recent call last):
  file ".../unittest_equality_container.py", line 53, in testset
    set([1, 3, 2, 4]),
assertionerror: items in the second set but not the first:
4
================================================================
fail: testtuple
(unittest_equality_container.containerequalitytest)
----------------------------------------------------------------
traceback (most recent call last):
  file ".../unittest_equality_container.py", line 59, in
testtuple
    (1, 'b'),
assertionerror: tuples differ: (1, 'a') != (1, 'b')
first differing element 1:
'a'
'b'
- (1, 'a')
?      ^
  (1, 'b')
?      ^
----------------------------------------------------------------
ran 7 tests in 0.005s
failed (failures=7)

使用 assertin() 测试容器成员。

unittest_in.py

import unittest
class containermembershiptest(unittest.testcase):
    def testdict(self):
        self.assertin(4, {1: 'a', 2: 'b', 3: 'c'})
    def testlist(self):
        self.assertin(4, [1, 2, 3])
    def testset(self):
        self.assertin(4, set([1, 2, 3]))

任何支持 in 操作符或容器 api 的对象都可以使用 assertin()

$ python3 -m unittest unittest_in.py
fff
================================================================
fail: testdict (unittest_in.containermembershiptest)
----------------------------------------------------------------
traceback (most recent call last):
  file ".../unittest_in.py", line 12, in testdict
    self.assertin(4, {1: 'a', 2: 'b', 3: 'c'})
assertionerror: 4 not found in {1: 'a', 2: 'b', 3: 'c'}
================================================================
fail: testlist (unittest_in.containermembershiptest)
----------------------------------------------------------------
traceback (most recent call last):
  file ".../unittest_in.py", line 15, in testlist
    self.assertin(4, [1, 2, 3])
assertionerror: 4 not found in [1, 2, 3]
================================================================
fail: testset (unittest_in.containermembershiptest)
----------------------------------------------------------------
traceback (most recent call last):
  file ".../unittest_in.py", line 18, in testset
    self.assertin(4, set([1, 2, 3]))
assertionerror: 4 not found in {1, 2, 3}
----------------------------------------------------------------
ran 3 tests in 0.001s
failed (failures=3)

测试异常

如前所述,如果测试引发 assertionerror 以外的异常,则会被视为错误。这对于在修改具有测试代码的代码时发现错误非常有用。但是,在某些情况下,测试应该验证某些代码确实会产生异常。例如,如果一个无效的值被赋予一个对象的属性。在这种情况下,使用 assertraises() 比在测试中捕获异常更清晰。比较这两种测试:

unittest_exception.py

import unittest
def raises_error(*args, **kwds):
    raise valueerror('invalid value: '   str(args)   str(kwds))
class exceptiontest(unittest.testcase):
    def testtraplocally(self):
        try:
            raises_error('a', b='c')
        except valueerror:
            pass
        else:
            self.fail('did not see valueerror')
    def testassertraises(self):
        self.assertraises(
            valueerror,
            raises_error,
            'a',
            b='c',
        )

这两种测试的结果是相同的,但是使用 assertraises() 的第二个测试更简洁。

$ python3 -m unittest -v unittest_exception.py
testassertraises (unittest_exception.exceptiontest) ... ok
testtraplocally (unittest_exception.exceptiontest) ... ok
----------------------------------------------------------------
ran 2 tests in 0.000s
ok

test fixtures

译者注:fixtures 不太好翻译,暂且不翻

fixtures 是测试所需的外部资源。例如,对一个类的所有测试方法可能都需要另一个类的实例来提供配置或资源。其他 fixtures 包括数据库连接和临时文件(许多人认为使用外部资源使此类测试不是「单元」测试,但它们仍然是测试,仍然有用)。

unittest 有用于设置和清理测试所需的任何 fixtures 的特殊勾子。若要为每个测试用例设置 fixtures,请重写 testcase 类的 setup() 方法。若要清理它们,请重写 teardown() 方法。若要为测试类的所有实例设置一组固定 fixtures,请重写类 testcasesetupclass()teardownclass() 方法。要处理模块内所有测试的设置操作,请使用模块级别的方法 setupmodule()teardownmodule()

unittest_fixtures.py

import random
import unittest
def setupmodule():
    print('in setupmodule()')
def teardownmodule():
    print('in teardownmodule()')
class fixturestest(unittest.testcase):
    @classmethod
    def setupclass(cls):
        print('in setupclass()')
        cls.good_range = range(1, 10)
    @classmethod
    def teardownclass(cls):
        print('in teardownclass()')
        del cls.good_range
    def setup(self):
        super().setup()
        print('\nin setup()')
        # pick a number sure to be in the range. the range is
        # defined as not including the "stop" value, so make
        # sure it is not included in the set of allowed values
        # for our choice.
        self.value = random.randint(
            self.good_range.start,
            self.good_range.stop - 1,
        )
    def teardown(self):
        print('in teardown()')
        del self.value
        super().teardown()
    def test1(self):
        print('in test1()')
        self.assertin(self.value, self.good_range)
    def test2(self):
        print('in test2()')
        self.assertin(self.value, self.good_range)

当运行此示例测试时,fixtures 和测试方法的执行顺序是显而易见的。

$ python3 -u -m unittest -v unittest_fixtures.py
in setupmodule()
in setupclass()
test1 (unittest_fixtures.fixturestest) ...
in setup()
in test1()
in teardown()
ok
test2 (unittest_fixtures.fixturestest) ...
in setup()
in test2()
in teardown()
ok
in teardownclass()
in teardownmodule()
----------------------------------------------------------------
ran 2 tests in 0.000s
ok

如果清理 fixtures 的过程中出现错误,则 teardown 方法可能不会被全部调用。要确保始终正确释放 fixtures,请使用 addcleanup() 方法。

unittest_addcleanup.py

import random
import shutil
import tempfile
import unittest
def remove_tmpdir(dirname):
    print('in remove_tmpdir()')
    shutil.rmtree(dirname)
class fixturestest(unittest.testcase):
    def setup(self):
        super().setup()
        self.tmpdir = tempfile.mkdtemp()
        self.addcleanup(remove_tmpdir, self.tmpdir)
    def test1(self):
        print('\nin test1()')
    def test2(self):
        print('\nin test2()')

这个测试示例创建了一个临时目录,然后当测试结束时使用  进行清理。

$ python3 -u -m unittest -v unittest_addcleanup.py
test1 (unittest_addcleanup.fixturestest) ...
in test1()
in remove_tmpdir()
ok
test2 (unittest_addcleanup.fixturestest) ...
in test2()
in remove_tmpdir()
ok
----------------------------------------------------------------
ran 2 tests in 0.002s
ok

不同输入的重复测试

使用不同的输入运行相同的测试逻辑通常是有用的。与其为每个小案例定义单独的测试方法,还不如在一个测试方法中包含多个测试断言。这种方法的问题是,一旦一个断言失败,其余的就会被跳过。更好的金年会app官方网的解决方案是使用 subtest()为测试方法中的每个断言创建上下文。如果测试失败,则报告错误,其余测试继续进行。

unittest_subtest.py

import unittest
class subtest(unittest.testcase):
    def test_combined(self):
        self.assertregex('abc', 'a')
        self.assertregex('abc', 'b')
        # the next assertions are not verified!
        self.assertregex('abc', 'c')
        self.assertregex('abc', 'd')
    def test_with_subtest(self):
        for pat in ['a', 'b', 'c', 'd']:
            with self.subtest(pattern=pat):
                self.assertregex('abc', pat)

在这个示例中,test_combined() 方法中关于 'c''d' 的断言从未被执行。test_with_subtest() 则不然,不仅执行了所有测试,而且报告了所有的失败。需要注意的是,虽然报告了三个失败,但是测试运行程序仍然认为只运行了两个测试。

$ python3 -m unittest -v unittest_subtest.py
test_combined (unittest_subtest.subtest) ... fail
test_with_subtest (unittest_subtest.subtest) ...
================================================================
fail: test_combined (unittest_subtest.subtest)
----------------------------------------------------------------
traceback (most recent call last):
  file ".../unittest_subtest.py", line 13, in test_combined
    self.assertregex('abc', 'b')
assertionerror: regex didn't match: 'b' not found in 'abc'
================================================================
fail: test_with_subtest (unittest_subtest.subtest) (pattern='b')
----------------------------------------------------------------
traceback (most recent call last):
  file ".../unittest_subtest.py", line 21, in test_with_subtest
    self.assertregex('abc', pat)
assertionerror: regex didn't match: 'b' not found in 'abc'
================================================================
fail: test_with_subtest (unittest_subtest.subtest) (pattern='d')
----------------------------------------------------------------
traceback (most recent call last):
  file ".../unittest_subtest.py", line 21, in test_with_subtest
    self.assertregex('abc', pat)
assertionerror: regex didn't match: 'd' not found in 'abc'
----------------------------------------------------------------
ran 2 tests in 0.001s
failed (failures=3)

跳过测试

经常需要在某些条件不满足时跳过一些测试。比如,为了测试某个库在特定版本的 python 下的行为,就不需要在其他版本的 python 环境下运行测试。测试类和方法可以通过使用装饰器 skip() 来跳过。装饰器 skipif() 和 skipunless() 可以用来根据条件判断是否需要跳过。

unittest_skip.py

import sys
import unittest
class skippingtest(unittest.testcase):
    @unittest.skip('always skipped')
    def test(self):
        self.asserttrue(false)
    @unittest.skipif(sys.version_info[0] > 2,
                     'only runs on python 2')
    def test_python2_only(self):
        self.asserttrue(false)
    @unittest.skipunless(sys.platform == 'darwin',
                         'only runs on macos')
    def test_macos_only(self):
        self.asserttrue(true)
    def test_raise_skiptest(self):
        raise unittest.skiptest('skipping via exception')

对于不能用简单语句表示的复杂条件,测试用例可以通过抛出 skiptest 异常来跳过测试。

$ python3 -m unittest -v unittest_skip.py
test (unittest_skip.skippingtest) ... skipped 'always skipped'
test_macos_only (unittest_skip.skippingtest) ... skipped 'only
runs on macos'
test_python2_only (unittest_skip.skippingtest) ... skipped 'only
runs on python 2'
test_raise_skiptest (unittest_skip.skippingtest) ... skipped
'skipping via exception'
----------------------------------------------------------------
ran 4 tests in 0.000s
ok (skipped=4)

忽略失败的测试

与其删除必然失败的测试,还可以使用装饰器 expectedfailure() 对其进行标记,忽略其失败。

unittest_expectedfailure.py

import unittest
class test(unittest.testcase):
    @unittest.expectedfailure
    def test_never_passes(self):
        self.asserttrue(false)
    @unittest.expectedfailure
    def test_always_passes(self):
        self.asserttrue(true)

如果预期失败的测试通过了,则将其视为一种特殊类型的失败,并报告为「不期望的成功」。

$ python3 -m unittest -v unittest_expectedfailure.py
test_always_passes (unittest_expectedfailure.test) ...
unexpected success
test_never_passes (unittest_expectedfailure.test) ... expected
failure
----------------------------------------------------------------
ran 2 tests in 0.001s
failed (expected failures=1, unexpected successes=1)

参见

  •  -- 一种运行嵌入到 docstring 或外部文档中的测试的方法。
  •  -- 具有复杂发现功能的第三方测试运行程序。
  •  -- 一个流行的第三方测试运行程序,支持分布式执行和备用 fixtures 管理系统。
  •  -- openstack 项目使用的第三方测试运行程序,支持并行执行和失败跟踪。

本文章首发在 金年会app官方网 网站上。

本译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 cc 协议,如果我们的工作有侵犯到您的权益,请及时联系金年会app官方网。

原文地址:https://learnku.com/docs/pymotw/unittest...

译文地址:https://learnku.com/docs/pymotw/unittest...

上一篇 下一篇
讨论数量: 0



暂无话题~
网站地图