python assert简述

assert断言

1.基本用法

>>> assert 1 + 1 == 2
>>> assert isinstance('Hello', str)
>>> assert isinstance('Hello', int)

执行结果:

Traceback (most recent call last):
  File "", line 1, in <module>
AssertionError

只是简单说明了assert报错

2.升级+1用法:

对断言的错误简单的自定义描述

>>> s = "nothin is impossible."
>>> key = "nothing"
>>> assert key in s, "Key: '{}' is not in Target: '{}'".format(key, s)

执行结果

Traceback (most recent call last):
  File "", line 1, in <module>
AssertionError: Key: 'nothing' is not in Target: 'nothin is impossible.'

3.python 测试框架自带断言能力

A.pytest

import pytest

def test_case():
    expected = "Hello"
    actual = "hello"
    assert expected == actual

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

B.unittest

import unittest

class TestStringMethods(unittest.TestCase):

    def test_upper(self):
        self.assertEqual('foo'.upper(), 'FoO')

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

C.ptest

from ptest.decorator import *
from ptest.assertion import *

@TestClass()
class TestCases:
    @Test()
    def test1(self):
        actual = 'foo'
        expected = 'bar'
        assert_that(expected).is_equal_to(actual)

拓展:

assertpy库下载位置

from assertpy import assert_that

def test_something():
    assert_that(1 + 2).is_equal_to(3)
    assert_that('foobar')\
        .is_length(6)\
        .starts_with('foo')\
        .ends_with('bar')
    assert_that(['a', 'b', 'c'])\
        .contains('a')\
        .does_not_contain('x')

你可能感兴趣的:(测试)