pytest测试用例编写----参数化测试(Parametrized Tesing)
1 def test_add_1(): 2 """tasks.get() using id returned from add() works.""" 3 task = Task('breathe', 'BRIAN', True) 4 task_id = tasks.add(task) 5 t_from_db = tasks.get(task_id) 6 # everything but the id should be the same 7 assert equivalent(t_from_db, task) 8 9 10 def equivalent(t1, t2): 11 """Check two tasks for equivalence.""" 12 # Compare everything but the id field 13 return ((t1.summary == t2.summary) and 14 (t1.owner == t2.owner) and 15 (t1.done == t2.done)) 16 17 18 @pytest.fixture(autouse=True) 19 def initialized_tasks_db(tmpdir): 20 """Connect to db before testing, disconnect after.""" 21 tasks.start_tasks_db(str(tmpdir), 'tiny') 22 yield 23 tasks.stop_tasks_db()
1.新建的Task对象,其id会被置为None,只有在发生数据库交互之后其id才会被填入相应的值。
2.equivalent()方法检查id之外的所有属性是否相等
3.autouse的fixture能确保数据库可访问
运行结果:
@pytest.mark.parametrize(argnames, argvalues)装饰器达到批量传送参数的目的
1 @pytest.mark.parametrize('task', 2 [Task('sleep', done=True), 3 Task('wake', 'brian'), 4 Task('breathe', 'BRIAN', True), 5 Task('exercise', 'BrIaN', False)]) 6 def test_add_2(task): 7 """Demonstrate parametrize with one parameter.""" 8 task_id = tasks.add(task) 9 t_from_db = tasks.get(task_id) 10 assert equivalent(t_from_db, task)
parametrize()的第一个参数是用逗号分隔的字符串列表'task';第二个参数是一个值列表‘Task对象列表’,pytest会对每个task做测试,并分别报告每一个测试用例结果。
将parametrize()的task对象列表替换为几组键值对
1 @pytest.mark.parametrize('summary, owner, done', 2 [('sleep', None, False), 3 ('wake', 'brian', False), 4 ('breathe', 'BRIAN', True), 5 ('eat eggs', 'BrIaN', False), 6 ]) 7 def test_add_3(summary, owner, done): 8 """Demonstrate parametrize with multiple parameters.""" 9 task = Task(summary, owner, done) 10 task_id = tasks.add(task) 11 t_from_db = tasks.get(task_id) 12 assert equivalent(t_from_db, task)
运行结果: