pytest笔记(二):fixture的使用

用法

用法一:直接调用

import os

import sys

import json

import pytest

@pytest.fixture()

def login():

print("登录系统")

yield

    print("退出系统")

def test_bilibili(login):

print("访问首页")

if __name__ =="__main__":

pytest.main(["-s", "test_run.py"])

运行效果:

test_run.py 登录系统

访问首页

.退出系统

用法(二):

@pytest.fixture()

def login():

print("登录系统")

yield

    print("退出系统")

@pytest.mark.usefixtures("login")

def test_bilibili():

print("访问首页")

运行效果:test_run.py 登录系统

访问首页

.退出系统

抽象:conftest.py  共享fixture函数

所有的fixture 函数放到conftest.py中,可以直接调用;

fixture函数的发现顺序从测试类开始,然后是测试模块,然后是conftest.py文件,最后是内置和第三方插件。

@pytest.fixture调用中添加scope ="module"参数,以使每个测试模块只调用一次修饰的smtp_connectionfixture函数(默认情况下,每个测试函数调用一次)。 因此,测试模块中的多个测试方法将各自注入相同的smtp_connectionfixture对象,从而节省时间。scope参数的可选值包括:function(函数), class(类), module(模块), package(包)及 session(会话)。

fixture函数的调用

#!/usr/bin/env python

# -*- coding:utf-8 -*-

# Author:wzj

import os

import sys

import json

import pytest

@pytest.fixture()

def username():

return 'wangzxe'

def test_bilibili(username):

print(username)

if __name__ =="__main__":

pytest.main(["-s", "test_run.py"])

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容