• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

python +pytest+allure笔记方便自己copy

武飞扬头像
test明成长记
帮助1

 pytest一些用法

  1.  
    import pytest
  2.  
    #测试文件以test_开头(以_test结尾也可以)
  3.  
    #测试类以Test开头,并且不能带有 init 方法
  4.  
    #测试函数以test_开头
  5.  
    """
  6.  
    pytest插件
  7.  
    pytest-html ==生成html格式的测试报告
  8.  
    pytest-xdist 多线程
  9.  
    pytest-ordering 指定测试用例的执行顺序
  10.  
    pytest-rerunfailures 失败重执行
  11.  
    allure-pytest 生成allure测试报告
  12.  
    复制python 包
  13.  
    pip freeze > requirements.txt
  14.  
    PS:在pytest项目下创建一个a.txt文件,将这些参数放进去,使用 pip install -r a.txt 一次性全部安装
  15.  
    ==============================================================================================
  16.  
    1.pytest 参数化
  17.  
    @pytest.mark.parametrize()
  18.  
    1.1单个参数化
  19.  
    1.2多个参数化
  20.  
    2.pytest执行测试用例的顺序
  21.  
    2.1 默认顺序:默认从上到下
  22.  
    2.2自定义顺序 ps:需下载插件pip install pytest-ordering
  23.  
    3.跳过用例执行
  24.  
    @pytest.mark.skip('跳过说明,可不填')
  25.  
    @pytest.mark.skipif(条件成立跳过,reason=)
  26.  
    @pytest.mark.skipif(con == '冒烟', reason='我是skipif,因为条件成立被跳过了')
  27.  
    4.失败不计入失败用例中
  28.  
    @pytest.mark.xfail()
  29.  
    5.参数传递
  30.  
    5.1单个参数 将上一个方法里面的返回传递给下一个方法,调用的时候传入方法名
  31.  
    pytest.fixture()
  32.  
    5.2多个参数
  33.  
    定义一个全局变量和一个空列表,将需要返回的值追加到列表中然后return返回列表,下一个方法再遍历列表
  34.  
    6.pytest执行参数详解
  35.  
    -r 用于skip方法中打印不执行的理由
  36.  
    -v 显示更详细的信息
  37.  
    -s 输出调试信息,包括print打印的信息,一般 -vs一起用
  38.  
    -n 支持多线程或者分布式运行测试用例
  39.  
    '-n=2' 2个线程
  40.  
    --reruns 次数 失败用例重新执行多少次
  41.  
    '--reruns=5' 失败用例重新执行5次
  42.  
    -x 表示只要有一个用例报错,那么测试停止
  43.  
    --maxfail=次数 表示出现多少个报错就停止
  44.  
    -k 根据测试用例的部分字符串执行测试用例
  45.  
    -k='包含的字符串'
  46.  
    7.pytest的命令行执行方式
  47.  
    7.1 指定目录下的py文件执行
  48.  
    pytest.main(['-vs','./testcase'])
  49.  
    7.2指定py文件执行
  50.  
    pytest.main(['-vs','py文件'])
  51.  
    7.3通过nodeid指定用例执行,nodeid由模块名,分隔符,类名,方法名,函数名组成
  52.  
    (::双冒号为分隔符)
  53.  
    #目录下指定的测试用例(没有类)
  54.  
    pytest.main(['-vs','./testcase::test_01'])
  55.  
    #目录下指定的测试类下面的测试用例
  56.  
    pytest.main(['-vs','./testcase::Testpy::test_01'])
  57.  
    8.pytest.main()执行方法 单独的py文件中的pytest.main()
  58.  
    8.1用来读取pytest.ini文件
  59.  
    8.2可指定参数执行 pytest.main(['-vs','py文件'])
  60.  
    ps:该文件名最好不要以test开头,该文件最好与pytest.ini文件在同一项目路径下,与测试用例属于同一目录,会优先读取pytest.ini文件
  61.  
    9.conftest.py文件的作用及用法
  62.  
    9.1 conftest.py文件名字固定不能修改
  63.  
    9.2 congftest.py文件所在目录必须存在__init__.py文件
  64.  
    9.3 不能被其他模块导入
  65.  
    9.4 所有目录测试文件执行前都会执行一遍conftest.py文件
  66.  
    9.5 结合@pytest.fixture使用
  67.  
    9.5.1 fixture的作用范围
  68.  
    pytest.fixture(scope='function')
  69.  
    fixture里面的scope参数可以控制fixture的作用范围:session>module>class>functon
  70.  
    -function:每一个函数或方法都会调用(默认就是function)
  71.  
    -class:每一个类都会调用一次
  72.  
    -module:每一个.py文件都会调用一次
  73.  
    -session:多个文件调用一次,可以跨.py文件调用
  74.  
    9.5.2 使用场景
  75.  
    每个接口需要共用的token
  76.  
    每个接口需要共用到的测试用例数据(如参数化数据,数据驱动)
  77.  
    每个接口需要共用到的配置信息
  78.  
    ======================================================================================================
  79.  
    pytest配置文件 pytest.ini
  80.  
    #可以改变pytest的默认规则,比如测试类以Test开头,测试用例以test_开头
  81.  
    #文件位置 一般放在项目的根目录下
  82.  
    #编码:必须是ansi,可以用notepad 转换
  83.  
    #作用:修改pytest默认的行为
  84.  
    #运行规则:不管是主函数模式还是命令行模式都会去读这个配置文件
  85.  
    [pytest]
  86.  
    #命令行的参数
  87.  
    addopts=-vs
  88.  
    #测试用例的路径,多个路径用空格隔开
  89.  
    testpaths=./testcase ./testcase2
  90.  
    #模块名的规则(可自定义)
  91.  
    python_files=test_*.py
  92.  
    #类名的规则 (可自定义)
  93.  
    python_classes=Test*
  94.  
    #方法名的规则 (可自定义)
  95.  
    python_functions=test
  96.  
     
  97.  
     
  98.  
    """
  99.  
     
  100.  
    class Test_pytest_1():
  101.  
    #将上一个方法里面的返回传递给下一个方法,调用的时候传入方法名
  102.  
    global a
  103.  
    a = 5
  104.  
    @pytest.fixture()
  105.  
    def test_1(self):
  106.  
    list = []
  107.  
    for i in range(1,a):
  108.  
    list.append(i)
  109.  
    return list
  110.  
     
  111.  
    def test_2(self,get_data):
  112.  
    for res in get_data:
  113.  
    print(res)
  114.  
     
  115.  
     
  116.  
     
  117.  
    # @pytest.mark.skip('我被无条件跳过')
  118.  
    # def test_b(self):
  119.  
    # print('我是order2')
  120.  
    # @pytest.mark.skipif(con == '冒烟', reason='我是skipif,因为条件成立被跳过了')
  121.  
    # def test_a(self):
  122.  
    # print('我是order1')
  123.  
    # @pytest.mark.skipif(con == '冒烟1', reason='我是skipif,因为条件不成立没有被跳过')
  124.  
    # @pytest.mark.xfail()
  125.  
    # def test_c(self):
  126.  
    # assert 1==2
  127.  
     
  128.  
     
  129.  
    # def setup_method(self):
  130.  
    # print('每个用例执行前我都会执行')
  131.  
    # def setup_class(self):
  132.  
    # print('我只执行一次,在用例执行前执行')
  133.  
    # def test1(self):
  134.  
    # print('我是第一条用例')
  135.  
    # def test2(self):
  136.  
    # print('我是第二条用例')
  137.  
    # def teardown_class(self):
  138.  
    # print('我只执行一次,在用例执行完后执行')
  139.  
    # def teardown_method(self):
  140.  
    # print('每个用例执行后我都会执行')
  141.  
    #单个参数化
  142.  
    # @pytest.mark.parametrize('a', (1, 2, 3, 4))
  143.  
    # def test_para(self,a):
  144.  
    # print(a)
  145.  
    #多个参数化
  146.  
    #如下3个参数,分别去对应的列表中的下标,如b取值完的结果1,4,7
  147.  
    # @pytest.mark.parametrize('b,c,d',([1,2,3],[4,5,6],[7,8,9]))
  148.  
    # def test_paramore(self,b,c,d):
  149.  
    # print(b,c,d)
  150.  
     
  151.  
     
  152.  
     
  153.  
     
  154.  
    if __name__ == '__main__':
  155.  
    pytest.main(['-vs','-r''test_pytest.py'])
学新通

pytest参数化打样

单个参数化,如下:会执行4次

学新通

多个参数化

学新通

初始化方法,结束方法

学新通

自定义测试用例执行顺序

下载插件pip install pytest-ordering

@pytest.mark.run(order=num)

               ps:都要做标记才生效

学新通

跳过测试用例执行

@pytest.mark.skip(‘跳过的理由’)

@pytest.mark.skipif(con==条件,reason=条件成立时跳过)

 学新通

Pytest.fixture()

单个参数传递

学新通

多个参数传递

定义一个全局变量和一个空列表,将需要返回的值追加到列表中然后return返回列表,下一个方法再遍历列表

学新通

allure的一些用法

        allure安装教程(随便找了个,到时候百度一堆)https://www.cnblogs.com/hantongxue/p/14372291.html

要导入os模块,放在mian方法里面执行

ps:生成allure报告需在这里设置为unittest运行才行

学新通

  1.  
    # 执行pytest单元测试,生成 Allure 报告需要的数据存在 /temp 目录
  2.  
    pytest.main(['--alluredir', './temp'])
  3.  
    # 执行命令 allure generate ./temp -o ./report --clean ,生成测试报告
  4.  
    os.system('allure generate ./temp -o ./report --clean')
  1.  
    import pytest
  2.  
    import allure
  3.  
    """
  4.  
    @allure.step
  5.  
    pytest支持使用@allure.step修饰某些测试用例中需要的函数,使测试用例在allure报告中能够更加详细的显示测试过程
  6.  
    @allure.step("输入的用户名")
  7.  
    @allure.attach
  8.  
    使用allure.attach可以给报告中添加文件,图片,log,html代码等
  9.  
    @allure.description
  10.  
    如果想在测试报告中展示测试用例的描述信息
  11.  
    @allure.description('这是测试用例的描述信息')
  12.  
    @allure.title
  13.  
    使用allure.title()可以重命名测试用例在allure报告中的名称
  14.  
    @allure.title('登录成功的场景')
  15.  
    @allure.link
  16.  
    @allure.testcase
  17.  
    @allure.issue
  18.  
    这三种特性都可以给测试用例添加一个链接
  19.  
    @allure.testcase('http:www.百度.com/','测试用例地址')
  20.  
    @allure.feature
  21.  
    @allure.story
  22.  
    feature和story被称为行为驱动标记,因为使用这两个标记,通过报告可以更加清楚的掌握每个测试用例的功能和每个测试用例的测试场景
  23.  
    @allure.feature('测试类用feature')
  24.  
    @allure.story('测试方法用story')
  25.  
    @allure.severity
  26.  
    此标记用来标识测试用例或者测试类的严重级别,分为blocker,critical,normal,minor,trivial 5个级别
  27.  
    """
  28.  
    @allure.feature("这是登录模块测试用例")
  29.  
    class Test_login():
  30.  
    @allure.story("用户名正确,登录成功")
  31.  
    @allure.severity(allure.severity_level.BLOCKER) #阻塞
  32.  
    def test_logina(self):
  33.  
    allure.attach("这是一个纯文本",name="文本信息",attachment_type=allure.attachment_type.TEXT) #添加文本
  34.  
    print("这是登录,用户名正确,登录成功")
  35.  
    pass
  36.  
     
  37.  
    @allure.story("密码正确,登录成功")
  38.  
    @allure.severity(allure.severity_level.CRITICAL) #严重
  39.  
    def test_loginb(self):
  40.  
    allure.attach("<body>这是一个网页</body>",name="HTML测试模块",attachment_type=allure.attachment_type.HTML) #添加网页
  41.  
     
  42.  
    print("这是登录,密码正确,登录成功")
  43.  
    pass
  44.  
     
  45.  
    @allure.story("用户名错误,登录失败")
  46.  
    # --allure-link-pattern=issue:https:www.badu.com
  47.  
    @allure.issue("10086","这是一个bug,需要修复")
  48.  
    @allure.severity(allure.severity_level.NORMAL) #正常问题
  49.  
    def test_loginc(self):
  50.  
    allure.attach.file("./picture/微信头像.jpg",name="这是一个图片",attachment_type=allure.attachment_type.JPG) #添加图片
  51.  
    print("这是登录,用户名错误,登录失败")
  52.  
    pass
  53.  
     
  54.  
    @allure.story("密码错误,登录失败")
  55.  
    @allure.link("https:www.badu.com",name="百度网址")
  56.  
    @allure.severity(allure.severity_level.MINOR) #不太重要
  57.  
    def test_logind(self):
  58.  
    with allure.step("点击用户名输入框"):
  59.  
    print("输入用户名")
  60.  
    with allure.step("点击输入密码输入框"):
  61.  
    print("输入密码")
  62.  
    print("点击登录按钮")
  63.  
    with allure.step("点击登录后登录失败"):
  64.  
    assert "1" == 1
  65.  
    print("这是登录,密码错误,登录失败")
  66.  
    pass
  67.  
     
  68.  
    Testcase_link = "https://www.百度.com"
  69.  
    @allure.story("用户不存在,登录失败")
  70.  
    @allure.testcase(Testcase_link,"测试用例地址")
  71.  
    @allure.severity(allure.severity_level.TRIVIAL) #不重要
  72.  
    def test_logine(self):
  73.  
    print("这是登录,用户不存在,请重新注册")
  74.  
    pass
  75.  
     
  76.  
    @allure.story("密码已锁定,登录失败")
  77.  
    def test_loginf(self):
  78.  
    print("这是登录,密码已锁定,请重置密码")
  79.  
    pass
  80.  
     
  81.  
    @allure.story("密码为空,登录失败")
  82.  
    def test_loging(self):
  83.  
    print("这是登录,密码为空,请输入密码")
  84.  
    pass
  85.  
     
  86.  
    if __name__ =='__main__':
  87.  
    pytest.main("-v -s")
学新通

pytest钩子函数的一些用法(直接用,不要记)

  1.  
    Pytest 测试报告相关钩子函数使用说明
  2.  
     
  3.  
    1、在测试报告中追加测试执行人描述信息:
  4.  
    1.1 进入conftest.py文件(放在框架根目录下)
  5.  
    1.2 添加以下代码
  6.  
    from py.xml import html
  7.  
    import pytest
  8.  
     
  9.  
    #*********************************************************
  10.  
    #在html测试报告中添加测试人信息
  11.  
    @pytest.mark.optionalhook
  12.  
    def pytest_html_results_summary(prefix, summary, postfix):
  13.  
    prefix.extend([html.p("测试人: 测试人姓名")])
  14.  
     
  15.  
    执行测试报告,可以使用指令也可以使用main方法如下:
  16.  
    if __name__ == '__main__':
  17.  
    pytest.main(['XXX.py','--html=XXReport.html'])
  18.  
     
  19.  
    2、在测试报告中追加每个测试方法的执行时间:
  20.  
    2.1 进入conftest.py
  21.  
    2.2 添加以下代码
  22.  
    #在html测试报告中添加测试执行时间
  23.  
    @pytest.mark.optionalhook
  24.  
    def pytest_html_results_table_row(report, cells):
  25.  
    cells.insert(1, html.td(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), class_='col-time'))
  26.  
    cells.pop()
  27.  
     
  28.  
    3、在测试报告中添加错误截图:
  29.  
    3.1进入conftest.py
  30.  
    3.2 添加以下代码
  31.  
    #导入selenium类库
  32.  
    from selenium import webdriver
  33.  
     
  34.  
    #定义全局的driver变量
  35.  
    driver = None
  36.  
    #设置一个browser固件
  37.  
    @pytest.fixture(scope='session', autouse=True)
  38.  
    def browser():
  39.  
    global driver
  40.  
    if driver is None:
  41.  
    driver = webdriver.Chrome()
  42.  
    return driver
  43.  
     
  44.  
    #定义截屏方法
  45.  
    def _capture_screenshot():
  46.  
    return driver.get_screenshot_as_base64()
  47.  
     
  48.  
    #定义添加错误图片的钩子函数
  49.  
    @pytest.mark.hookwrapper
  50.  
    def pytest_runtest_makereport(item):
  51.  
    """
  52.  
    当测试失败的时候,自动截图,展示到html报告中
  53.  
    :param item:
  54.  
    """
  55.  
    pytest_html = item.config.pluginmanager.getplugin('html')
  56.  
    outcome = yield
  57.  
    report = outcome.get_result()
  58.  
    extra = getattr(report, 'extra', [])
  59.  
     
  60.  
    if report.when == 'call' or report.when == "setup":
  61.  
    xfail = hasattr(report, 'wasxfail')
  62.  
    if (report.skipped and xfail) or (report.failed and not xfail):
  63.  
    file_name = report.nodeid.replace("::", "_") ".png"
  64.  
    screen_img = _capture_screenshot()
  65.  
    if file_name:
  66.  
    html = '<div><img src="https://img-blog.csdnimg.cn/2022010622350215226.png" alt="screenshot" style="width:600px;height:300px;" ' \
  67.  
    'onclick="window.open(this.src)" align="right"/></div>' % screen_img
  68.  
    extra.append(pytest_html.extras.html(html))
  69.  
    report.extra = extra
  70.  
     
学新通

pytest 配置文件之 conftest.py

  1.  
    #随便搞的个,到时候用的时候详见@pytest.fixture()的用法
  2.  
    import pytest
  3.  
    import csv
  4.  
    @pytest.fixture(scope='session')
  5.  
    def get_data():
  6.  
    list_data=[]
  7.  
    file_row = open('ccssvv.csv', 'r')
  8.  
    table = csv.reader(file_row)
  9.  
    # 跳过首行读取
  10.  
    table.__next__()
  11.  
    # 逐行读取csv文件
  12.  
    for row in table:
  13.  
    list_data.append(row[0])
  14.  
    return list_data

        

        conftest.py结合fixture

        fixture conftest中返回的数据传到调用的方法中,调用方的传参即conftest中的方法名

        学新通

学新通

pytest 配置文件之pytest.ini文件

学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgcffji
系列文章
更多 icon
同类精品
更多 icon
继续加载