运行单元测试
pipenv run python -m pytest xx.py
pytest -q xx.py
例子1
## 测试加减法
class TestDemo:
@pytest.mark.parametrize("a, b, expected",
[(1, 2, 3), (2, 3, 5), (3, 4, 8)])
def test_add(self, a, b, expected):
sum = a+b
assert sum == expected
@pytest.mark.parametrize("a, b, expected",
[(1, 2, -1), (8, 3, 5), (3, 4, 8)])
def test_sub(self, a, b, expected):
sub = a-b
assert sub == expected
你看,一下子就找出错误啦~
例子2 pytest+requests
# 基于pytest requests测试接口
class TestRequestsDemo:
# 初始化
url = "http://jsonplaceholder.typicode.com"
session = requests.session()
#测试获得所有用户信息接口
def test_get_posts(self):
r = self.session.get(self.url+'/posts')
# 断言状态码
assert r.status_code == 200
#断言响应头信息
assert r.headers['Content-Type'] == "application/json; charset=utf-8"
#断言用户总数
assert len(r.json()) == 100
# 获得指定用户的信息接口
def test_get_posts_by_id(self):
r = self.session.get(self.url+'/posts/1')
#断言状态码
assert r.status_code == 200
#断言响应头信息
assert r.headers["Content-Type"] == "application/json; charset=utf-8"
#验证用户id
data = r.json()
assert data['userId'] == 1
#测试删除指定用户信息接口
def test_delete_posts_by_id(self):
r = self.session.delete(self.url+'/posts/1')
#断言状态码
assert r.status_code == 200
#断言响应头信息
assert r.headers['Content-Type'] == "application/json; charset=utf-8"
执行结果: