pytest测试框架快速搭建

pytest测试框架快速搭建一 介绍 pytest 是一个非常成熟的 Python 测试框架 能够支持简单的单元测试和复杂的功能测试 还可以用来做 selenium appnium 等自动化测试 接口自动化测试 pytest requests pytest 具有很多第三方插件 并且可以自定义扩展 比较好用的如 pytest selenium 集成 selenium pytest html 完美 html 测试报告生成 pytest rerunfailure 失败 case 重复执行 pytest xdist 多 CPU 分发 等

一、介绍

        pytest是一个非常成熟的Python测试框架,能够支持简单的单元测试和复杂的功能测试,还可以用来做selenium/appnium等自动化测试、接口自动化测试(pytest+requests);pytest具有很多第三方插件,并且可以自定义扩展,比较好用的如pytest-selenium(集成selenium)、pytest-html(完美html测试报告生成)、pytest-rerunfailures(失败case重复执行)、pytest-xdist(多CPU分发)等。

二、安装

import pytest # 被测试函数 def add(a, b): return a + b class TestCase: # 测试脚本 def test_add(self): assert 3 == add(1, 2) if __name__ == '__main__': pytest.main()

 collected 2 items :表示加载到两个测试用例;

七、参数化

        例如进行接口测试时,测试登录功能,上传图片功能等;可能只是字符串长度不一样、字符种类不一样,文件大小不一样,或是否为空等,但是执行的用例是一样的,这样为了方便,不用重复写;可以使用参数化,把不同的参数,传到同一个用例里。       

@pytest.mark.parametrize('a',[1,2,3,4,5]) def test(a): print(a) if __name__ == '__main__': pytest.main()

八、前置后置

        模块级:该方法表示只能类外面执行用例过程中,作用范围为当前模块,当前模块执行前后都运行一次前置和后置;无论有多少个用例,模块级的前置和后置都只跑一遍。
        setup_module(),前置,模块执行前运行一次;
        teardown_module(),后置,模块执行后运行一次;




        函数级:该方法表示在类外面执行用例过程中,作用范围为当前面模块中的每一个测试函数,模块中的每个用例执行前后分别运行一次。
        setup_function(),前置,每个用例执行前运行一次
        teardown_function,后置,每个执行后运行一次;




        类级别:作用范围为当前类中的每一个测试用例,当前类执行前后分别运行一次。只执行1次测试前置和测试后置
        setup_class(),前置,类中执行前运行一次
        teardown_class,后置,类中执行后运行一次;




        

import pytest def setup_module(): print("\n模块前置!") def teardown_module(): print("模块后置!") def setup_function(): print("函数前置!") def teardown_function(): print("函数后置!") @pytest.mark.parametrize('a',[1,2,3,4,5]) def testModule(a): print(a) @pytest.mark.parametrize('a',[6,7]) def testAdd(a): print(a) class Testcase: def setup_class(self): print("类前置") def teardown_class(self): print("类后置") def setup_method(self): print("方法前置!") def teardown_method(self): print("方法后置!") @pytest.mark.parametrize('a', [8, 9]) def test(self,a): print(a) if __name__ == '__main__': pytest.main() 

九、测试实例

        一、验证登录的 测试用例

import pytest
import requests

#创建session对象,用于实现会话保持
req = requests.session()

#登录 接口
#提前在模块前置把要测试登录接口的数据录入到data里,如用户名过长、非法字符、过短,及密码、预期结果等;data的每组数据为用户名、密码、预期结果
#通过参数化,就可以对所有用例运行一遍,把返回结果与预期结果比对;
#@pytest.mark.parametrize('data',data)
def test_login(data)
    url = 'http://192.168.0.1:8080/login'
    data ={'username':data[0],'pwd':data[1]}
    r = requests.post(url,data)
    assert data[2] == r.text
    print(r.text)


if __name__ == '__main__':
    #运行,并保存报告
    pytest.main(['-v',-f'--html={report_path}/{t}.html',case_path])
import xlrd import pytest import requests #获取工作薄文件对象 wb = xlrd.open_workbook("E:/automationtest/searchParameter.xls") #返回Excel文件中所有的sheet对象,通过对象调用 name 返回sheet名称 sheets = wb.sheets() #sheet名获取指定的表 sheet = wb.sheet_by_name("Sheet1") #用list 保存从xls表读取出来的数据,这些都是要做接口测试的参数; list=[] for index in range(1,sheet.nrows): list.append(sheet.row_values(index,7,14)) index = index + 1 for index in list: print(index) #第n行,第m列的元素 # value = sheet.cell(n,m).value #取出所有参数,做参数化; ''' #不能用下面这种方式做;否则就是所有参数的全组合; #这种类型的参数化是所有的组合;不是4列; @pytest.mark.parametrize("platf", platf) @pytest.mark.parametrize("excludePayTemplate", excludePayTemplate) @pytest.mark.parametrize("is_excluded", is_excluded) @pytest.mark.parametrize("excluded_member_discount", excluded_member_discount) @pytest.mark.parametrize("keyword", keyword) @pytest.mark.parametrize("start", start) @pytest.mark.parametrize("count", count) ''' @pytest.mark.parametrize("list", list) def testSearch(list): url = "https://template.wps.com/server/pf/template" param = {'platf': list[0],'excludePayTemplate':list[1],'is_excluded':list[2],'excluded_member_discount':list[3],'keyword':list[4],'start':list[5],'count':list[6]} response = requests.get(url=url,params=param) #输出响应码和响应信息;也可以把预期结果当做一个参数传进来做断言判断 print(response.status_code,' ',response.text,'\n') if __name__ == "__main__": pytest.main(["-s", "testSearch.py"]) 

        介绍:

        前面提到前置、后置;编写用例时候需要用到用例的前置和用例的后置,可以用setup_class和teardown_class等帮助我们完成,但是不够完善而且灵活性不够强。例如:一个calss中有3条用例,其中2条需要登录,1条不需要登录,这个时候如果在用setup和teardown来做就有点不方便。fixture可以用做测试 用例的前置和后置操作,且fixture命令规范没有setup、teardown的格式。可以随意命名。控制fixture的前置和后置操作是通过yield关键字进行区分,代码在yield前面的属于前置操作,代码在yield后面的属于后置操作。且fixture不要求前后置同时存在,可以只存在前置或只存在后置。fixture如果有后置内容,无论遇到什么问题,都会进行执行后置的代码。

        使用:

   用 @pytest.fixture()  装饰器声明一个函数是 fixture,如果测试函数的参数列表中包含 fixture 名,那么 pytest 就会检测到,并在运行测试函数之前运行它,fixture 可以返回数据给测试函数。
        
        参数列表:
        @pytest.fixture(scope=”function”, params=None, autouse=False, ids=None, name=None)
         scope 可选参数,默认为 function ,可选值为 function、class、module、session,范围依次增加。session的作用域是整个测试会话,即开始执行pytest到结束测试。
        autouse:默认:False,需要用例手动调用该fixture;如果是True,所有作用域内的测试用例都会自动调用该fixture
        name:默认:装饰器的名称,同一模块的fixture相互调用建议写个不同的name












import pytest @pytest.fixture def login(): print("先登录") yield print("退出登录 ") def test_s1(login): print("测试用例 1:登录后的其它操作!") def test_s2(): # 不传 login print("测试用例 2:不需要登录,") if __name__ == '__main__': pytest.main() 

十一、HTML报告生成

        一种是Pytest的 pytest-html插件,另一种是 allure-pytest插件;

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/230158.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月16日 下午3:00
下一篇 2026年3月16日 下午3:00


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号