欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

pytest学习

程序员文章站 2024-02-27 14:07:03
...

pip install pytest后,测试用例中import报错,纠结死了,找了半天才搞清楚这个虚拟环境解释器

https://www.jianshu.com/p/9866cea7c9f4

pytest中的前置和后置可以通过装饰器@pytest.fixture()来实现

可以定义一个conftest.py单独存放

#文件名是conftest.py
#conding=utf-8

import pytest

@pytest.fixture()
def myfixtureall():
    print("执行conftest.py myfixtureall")
    return "return myfixtureall"

@pytest.fixture()
def myfixture1():
    print("执行conftest.py myfixture1 前置")
    return "return myfixture 前置"
    yield
    print("执行conftest.py myfixture1 后置")
    return "return myfixture 后置"

@pytest.fixture(params=["参数1","参数2"])
def myfixture2(request):
    print("执行conftest.py myfixture2,%s" % request.param)
    return "return myfixture2,%s" % request.param

全局执行可以在测试用例里添加一行

pytestmark=pytest.mark.usefixtures("myfixtureall")

每个测试用例独自添加可以用注解或是传参方式

#test_Pytest.py文件
#coding=utf-8

import pytest

pytestmark=pytest.mark.usefixtures("myfixtureall")
params1=["love","hate"]
params2=["you","him"]

@pytest.fixture()
def myfixture1():
    print ("执行固件myfixture1")
    return "myfixture1"

@pytest.fixture()
def myfixture2():
    print ("执行固件myfixture2")
    return "myfixture2"

import pytest

class Test_Pytest1():

        def test_one(self,myfixture1):
                str = myfixture1
                print("test_one方法执行---%s" % str)
                assert 1==1

        def test_two(self,myfixture2):
                print("test_two方法执行---%s" % myfixture2)
                assert "o" in "love"

        def test_three(self,myfixture1,myfixture2):
                print("test_three方法执行---%s---%s" % (myfixture1,myfixture2))
                assert 3-2==1


class Test_Pytest2():

        @pytest.mark.parametrize("message1", params1)
        @pytest.mark.parametrize("message2", params2)
        def test_one(self,message1,message2):
                print("test_one方法执行---%s---%s" % (message1,message2) )
                assert 1==1

        def test_two(self):
                print("test_two方法执行" )
                assert "o" in "love"

        def test_three(self):
                print("test_three方法执行" )
                assert 3-2==1


if __name__=="__main__":
    pytest.main(['-s','test_fixtures.py'])

跳过测试用例可以用@pytest.mark.skip()或者@pytest.mark.xfail

写用例时可以根据场景给用例设置标签@pytest.mark.xxx  例如web和server这种

if __name__=="__main__":
    pytest.main(['-s','test_firstFile.py'])
    pytest.main(['-s','--lf','test_firstFile.py'])
    pytest.main(['-s','--ff','test_firstFile.py'])

--lf 【last fai】执行上次失败的用例

--ff【fail first】执行所有用例,失败的优先

pytest.main(['-s','-v','-n','3','test_firstFile.py'])

并行运行

pytest.main(['-s','-v','-n','3','--looponfail','test_firstFile.py'])

监听失败用例修改后自动运行

用allure2生成测试报告

jacoco查看覆盖率