Pytest使用经验

一.调用前置后置(Setup,Teardown):
@pytest.fixture(scope=‘session’, autouse=True)
函数-function,类-class,模块-module, 整个项目-session

yield后直接跟teardown内容

二.命令行参数
pytest -v 输出用例更加详细的执行信息,比如用例所在的文件及用例名称等
pytest -s 输出print的打印信息,一般与-v联合使用
pytest -x 一旦断言失败或有异常就停止运行,执行下一条测试用例
pytest -m 标记测试并分组,执行特定的测试用例,这个需要和pytest标记功能搭配使用(@pytest.mark.标记名)
pytest -k “类名” 任意位置模糊匹配类名的所有类,并执行匹配到的这些类的所有方法
pytest -k “方法名” 任意位置模糊匹配方法名的所有方法,并执行匹配到的这些方法

三.参数化
1、传一个参数 @pytest.mark.parametrize(‘参数名’,list) 进行参数化
2、传两个参数@pytest.mark.parametrize(‘参数名1,参数名2’,[(参数1_data[0], 参数2_data[0]),(参数1_data[1], 参数2_data[1])]) 进行参数化

四.常用插件
pip install pytest-ordering —用例执行顺序排序
@pytest.mark.run(order=2)

pip install pytest-random-order —用例随机执行

pip install pytest-xdist —分布式执行

pip install pytest-dependency —用例依赖
@pytest.mark.dependency(name=None, depends=[“test_abc”], scope=‘session’)

pip install pytest-rerunfailures —失败重跑

pip install pytest-assume —多重断言

pip install pytest-html —html报告

五.命名
1.测试用例必须以 test_ 开头或者以 _test 结尾

六.用例分类
1.可以使用@pytest.mark标记,执行部分用例

七.部分contest内容

import inspect
import os
import allure
import pytest
from _pytest.assertion.util import assertrepr_compare
from selenium.webdriver.remote.command import Command
from selenium.webdriver.remote.webelement import WebElement
from uiautomation import Logger
from utilities import settings, save
from utilities.config import DRIVER
from utilities.log import LogFormat, set_log, get_log
from utilities.screenshot import set_directory, get_directory, fail_on_assert_screenshot


@pytest.fixture(scope='session', autouse=True)
def setup():
    """
    start explorer before session
    maximize explorer
    stop explorer after session
    """
    DRIVER.maximize_window()

    yield
    DRIVER.quit()


@pytest.fixture(scope='function', autouse=True)
def teardown():
    """ url get data:, after every function """
    yield
    DRIVER.get("data:,")


@pytest.fixture(scope='session', autouse=True)
def get_option(pytestconfig):
    """ get build num """
    return [pytestconfig.getoption('--build_num'), pytestconfig.getoption('--job_name'), pytestconfig.getoption('--id'),
            pytestconfig.getoption('--username'), pytestconfig.getoption('--password')]


@pytest.fixture(scope='session', autouse=True)
def get_dir(get_option):
    """ get log directory """
    path = settings.SNAPSHOT_LOG_DIRECTORY
    if get_option[0] != '' and get_option[1] != '':
        path = os.path.join(path, get_option[1], get_option[0])
    if not os.path.exists(path):
        os.makedirs(path)
    set_directory(path)
    if get_option[2] != '':
        save.save_confirmation([get_option[2]])
    if get_option[3] != '' and get_option[4] != '':
        save.save_domain_username_and_password(get_option[3], get_option[4])


@pytest.fixture(scope='session', autouse=True)
def logger_set():
    """ get logger """
    logger_name = 'log.txt'
    log_level = 'debug'
    log_g = LogFormat(logger_name, log_level, get_directory()).logger
    set_log(log_g)


@pytest.fixture(scope='session', autouse=True)
def ui_automation_logger_set():
    """设置log"""
    Logger.SetLogFile(os.path.join(get_directory(), 'log.txt'))


def pytest_assertrepr_compare(config, op, left, right):
    """ pytest assert modify """
    left_name, right_name = inspect.stack()[7].code_context[0].lstrip().lstrip('assert').rstrip('\n').split(op)
    pytest_output = assertrepr_compare(config, op, left, right)
    log = get_log()
    log.error("{0} is {1}".format(left_name, left))
    log.error("{0} is {1}".format(right_name, right))
    fail_on_assert_screenshot()
    with allure.step("result:"):
        allure.attach(str(left), left_name)
        allure.attach(str(right), right_name)
    return pytest_output


def pytest_addoption(parser):
    """ add option """
    parser.addoption('--build_num', action='store', default='')
    parser.addoption('--job_name', action='store', default='')
    parser.addoption('--id', action='store', default='')
    parser.addoption('--username', action='store', default='')
    parser.addoption('--password', action='store', default='')


def web_element_click(self):
    """ click web element """
    try:
        self._execute(Command.CLICK_ELEMENT)
    except Exception as ex:
        fail_on_assert_screenshot()
        get_log().error("点击页面元素异常: [{}].".format(ex))
        raise ex


def web_element_clear(self):
    """ clear web element """
    try:
        self._execute(Command.CLEAR_ELEMENT)
    except Exception as ex:
        fail_on_assert_screenshot()
        get_log().error("清除页面元素异常: [{}].".format(ex))
        raise ex


WebElement.click = web_element_click
WebElement.clear = web_element_clear
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值