pytest(8):fixture与conftest.py结合使用

前言

   上一篇介绍了fixture scope的几种使用方式,除了直接写到用例脚本页,也可以使用conftest.py文件达到同样的效果。

conftest.py的使用:

  1.conftest.py名称是固定的,必须是这个不能变。

  2.与要调用的包在一个目录下,并且这个包下要有__init__.py 

  3.使用的时候不需要导入 conftest.py,pytest 会自动识别到这个文件

  4.放到项目的根目录下可以全局调用,放到某个 package 下,就在这个 package 内有效。

测试场景:

# Author xuejie zeng
# encoding utf-8

#conftest.py
import pytest
@pytest.fixture()
def login():
    print("输入登录的用户名和密码")
    return ('username','password')

#test_fixture.py

class Test_login():
    def test_1(self,login):
        print("test_1,需要登录")

    def test_2(self,login):
        print("test_2,需要登录 ")

    def test_3(self):
        print("test_case3,不需要登录")

#testdemo.py

class Test_login2():
    def test_a(self,login):
        print("test_a,需要登录")

    def test_b(self):
        print("test_b,不需要登录 ")

写到conftest.py文件之后,test_fixture.py,testdemo.py这两个文件都可以分别调用conftest.py里的这个方法,就不用每个用例里都写一遍了。

yield 使用

yield 的方法相当于 setup 和 teardown 方法

# Author xuejie zeng
# encoding utf-8

import pytest
@pytest.fixture()
def login():
    print("输入登录的用户名和密码")
    print ('username','password')
    yield
    print("登录结束")

运行testdemo.py结果:

testdemo.py::Test_login2::test_a 输入登录的用户名和密码
username password
test_a,需要登录
PASSED登录结束

testdemo.py::Test_login2::test_b test_b,不需要登录
PASSED

代码运行之后调用了 yield 后面的打印语句“登录结束”。yield 相当于来唤醒 teardown 的执行。

关注个人公众号:测试开发进阶之路

  

原文地址:https://www.cnblogs.com/zengxuejie/p/13710273.html