1.Python简单例子
import pytest
def inc(x):
return x + 1
def test_answer():
assert inc(3) == 5
if __name__ == '__main__':
pytest.main()
2.断言
#功能: 用于计算a与b相加的和
def add(a, b):
return a + b
#功能: 用于判断素数
def is_prime(n):
if n <= 1:
return False
for i in range(2, n):
if n % i == 0:
return False
return True
#测试相等
def test_add_1():
assert add(3, 4) == 7
#测试不相等
def test_add_2():
assert add(17, 22) != 50
#测试小于或等于
def test_add_3():
assert add(17, 22) <= 50
#测试大于或等于
def test_add_4():
assert add(17, 22) >= 38
#测试包含
def test_in():
a = "hello"
b = "he"
assert b in a
#测试不包含
def test_not_in():
a = "hello"
b = "hi"
assert b not in a
#判断是否为True
def test_true_1():
assert is_prime(13)
#判断是否为True
def test_true_2():
assert is_prime(7) is True
#判断是否不为True
def test_true_3():
assert not is_prime(4)
#判断是否不为True
def test_true_4():
assert is_prime(6) is not True
#判断是否为False
def test_fasle_1():
assert is_prime(8) is False
3.Fixture
import pytest
def multiply(a,b):
return a * b
def setup_module(module):
print("setup_module===================>")
def teardown_module(module):
print("teardown_module==================>")
def setup_function(function):
print("setup_function=================>")
def teardown_function(function):
print("teardown_function===============>")
def setup():
print("setup==================>")
def teardown():
print("teardown==================>")
# ==============测试用例==================
def test_multiply_3_4():
print('test_numbers_3_4')
assert multiply(3,4) == 12
def test_multiply_a_3():
print('test_strings_a_3')
assert multiply('a',3) == 'aaa'
#功能函数
def multiply(a, b):
return a * b
class TestMultiply:
# ======Fixture======
@classmethod
def setup_class(cls):
print("setup_class=============>")
@classmethod
def teardown_class(cls):
print("teardown_class===============>")
def setup_method(self,method):
print("setup_method-------->>")
def teardown_method(self,method):
print("teardown_method-->>")
def setup(self):
print("setup----->")
def teardown(self):
print("teardown----->")
# ===========测试用例===========
def test_numbers_5_6(self):
print('test_numbers_5_6')
assert multiply(5,6) == 30
def test_strings_b_2(self):
print('test_strings_b_2')
assert multiply('b',2) == 'bb'
4.参数化
import pytest
import math
#pytest 参数化
@pytest.mark.parametrize(
"base, exponent, expected",
[(2, 2, 4),
(2, 3, 8),
(1, 9, 1),
(0, 9, 0)],
ids = ["case1","case2","case3","case4"]
)
def test_pow(base,exponent,expected):
assert math.pow(base, exponent) == expected
5.conftest.py
import pytest
@pytest.fixture()
def test_url():
return "http://www.baidu.com"
def test_baidu(test_url):
print(test_url)
6.pytest-rerunfailures
pytest -v test_rerunfailures.py --reruns 3
def test_fail_rerun():
assert 2 + 2 == 5
7.pytest-parallel
pytest -q test_parallel.py --test-per-worker auto
from time import sleep
def test_01():
sleep(3)
def test_02():
sleep(5)
def test_03():
sleep(6)