使pytest fixture 实现setup、teardown、多次执行

使用fixture 实现setup功能

  • setup
@pytest.fixture(scope='function')
def db_news(request):
    n = get_one_news_from_db()
    assert n,'Get news failed'
    return n
  • 测试方法执行前,执行该方法
def test_read(db_news):
    resp = post_read(db_news,token)
    assert resp.code == 200 ,"read failed"

使用fixture 实现teardown功能

  • fin 方法,即为teardown方法
@pytest.fixture(scope='function')
def db_news(request):
    n = get_one_news_from_db()
    assert n,'Get news failed'
    def fin():
        print ("teardown")
    request.addfinalizer(fin)
    return n

给setup方法传递参数

  • 传递的参数保存在request.param 中
@pytest.fixture(scope='function')
def server_news(request):
    token = request.param
    params = request.param
    n = get_one_news_from_server()
    assert n,'Get news failed'
    return n
  • 测试函数中,通过 parametrize 传递参数,也可以传递多个。此处注意一定要添加indirect=True参数,否则不会把server_news 当做一个函数来执行
@pytest.mark.parametrize('server_news', [token],indirect=True)
def test_read(server_news):
    resp = post_read(server_news,token)
    assert resp.code == 200 ,"read failed"

参数化测试方法,使得测试方法用不同的参数执行多次,下面的测试方法会被执行3次

@pytest.mark.parametrize(
    "read_time, words,height", [
        (constants.READ_TIME-1,constants.WORDS,constants.HEIGHT),
        (constants.READ_TIME,constants.WORDS-1,constants.HEIGHT),
        (constants.READ_TIME,constants.WORDS,constants.HEIGHT-1),
    ])
def test_invalid_read(news_server,read_time,words,height):
    data = promotion.get_encrypt_read_data(news_server,read_time=read_time,words=words,height=height)
    postReq =promotion.post_read(token1,params1,news_id=news_server,data=data)
    assert postReq.getHttpCode() == 200
    assert postReq.getHttpContent()['code']==0
    assert postReq.getHttpContent()['msg']=='invalid read behaviour'

可以给一个方法同时设置多个“setup”放,多个parametrize

@pytest.mark.parametrize('userinfo,reach_goal', [(3,3),(4,4),(5,5),(6,6),(7,7)],indirect=True)
@pytest.mark.parametrize('data', [[{'token':token2,'params':params2}]],indirect=True)
def test_xxxxx(data,userinfo,news_ids,reach_goal):
    .....
  • 其中 data、userinfo,new_ids都fixture方法,执行真正的测试前,会依次执行这三个方法。
  • 测试方法供执行4次,第一次向userinfo传递参数3,第二次传递4,第三次传递5,第4次传递6。四次执行中,都会执行data方法,向其传递固定的token和params参数

你可能感兴趣的:(使pytest fixture 实现setup、teardown、多次执行)