pytest灵魂产物

1.pytest:

默认命名规则:

  1. 测试类必须以TestXxx形式书写,即以Test开头,不能带有init方法
  2. 测试文件以test_*.py开头(以*_test.py结尾也可以)
  3. 测试函数以test_开头
  4. 断言使用基本的 assert 即可

实现一个简单的pytest project:

 pydemo

--cases

  --__init__.py

  --test_order.py

  --test_shipping.py

--conftest.py

--pytest.ini

--pytest.log

 

conftest.py:

作用提供全局灯具函数和全局调用工具方法

如接口登陆获取token

import  pytest
import uuid
@pytest.fixture()
def get_token():
    return uuid.uuid1().hex

 

pytest.ini:

pytest 的配置文件:

作用配置pytest的参数配置

[pytest] ini-options in the first pytest.ini|tox.ini|setup.cfg file found:

  markers (linelist):   markers for test functions
  empty_parameter_set_mark (string):
                        default marker for empty parametersets
  norecursedirs (args): directory patterns to avoid for recursion
  testpaths (args):     directories to search for tests when no files or directories are given in the command line.
  filterwarnings (linelist):
                        Each line specifies a pattern for warnings.filterwarnings. Processed after -W/--pythonwarnings.
  usefixtures (args):   list of default fixtures to be used with this project
  python_files (args):  glob-style file patterns for Python test module discovery
  python_classes (args):
                        prefixes or glob names for Python test class discovery
  python_functions (args):
                        prefixes or glob names for Python test function and method discovery
  disable_test_id_escaping_and_forfeit_all_rights_to_community_support (bool):
                        disable string escape non-ascii characters, might cause unwanted side effects(use at your own risk)
  console_output_style (string):
                        console output: "classic", or with additional progress information ("progress" (percentage) | "count").
  xfail_strict (bool):  default for the strict parameter of xfail markers when not given explicitly (default: False)
  enable_assertion_pass_hook (bool):
                        Enables the pytest_assertion_pass hook.Make sure to delete any previously generated pyc cache files.
  junit_suite_name (string):
                        Test suite name for JUnit report
  junit_logging (string):
                        Write captured log messages to JUnit report: one of no|log|system-out|system-err|out-err|all
  junit_log_passing_tests (bool):
                        Capture log information for passing tests to JUnit report:
  junit_duration_report (string):
                        Duration time to report: one of total|call
  junit_family (string):
                        Emit XML for schema: one of legacy|xunit1|xunit2
  doctest_optionflags (args):
                        option flags for doctests
  doctest_encoding (string):
                        encoding used for doctest files
  cache_dir (string):   cache directory path.
  log_level (string):   default value for --log-level
  log_format (string):  default value for --log-format
  log_date_format (string):
                        default value for --log-date-format
  log_cli (bool):       enable log display during test run (also known as "live logging").
  log_cli_level (string):
                        default value for --log-cli-level
  log_cli_format (string):
                        default value for --log-cli-format
  log_cli_date_format (string):
                        default value for --log-cli-date-format
  log_file (string):    default value for --log-file
log_file_level (string):
default value for --log-file-level
log_file_format (string):
default value for --log-file-format
log_file_date_format (string):
default value for --log-file-date-format
log_auto_indent (string):
default value for --log-auto-indent
faulthandler_timeout (string):
Dump the traceback of all threads if a test takes more than TIMEOUT seconds to finish.
addopts (args):       extra command line options
minversion (string):  minimally required pytest version
required_plugins (args):
plugins that must be present for pytest to run
render_collapsed (bool):
Open the report with all rows collapsed. Useful for very large reports
max_asset_filename_length (string):
set the maximum filename length for assets attached to the html report.
environment variables:
PYTEST_ADDOPTS           extra command line options
PYTEST_PLUGINS           comma-separated plugins to load during startup
PYTEST_DISABLE_PLUGIN_AUTOLOAD set to disable plugin auto-loading
PYTEST_DEBUG             set to enable debug tracing of pytest's internals

简单配置举例:

[pytest]
addopts = -s --pytest_report=pytest.html
testpaths=cases
console_output_style= classic
# SET LOGGER
log_cli = true
log_cli_level = DEBUG
log_format = %(asctime)s (%(filename)-4s: AT LINE %(lineno)-4s) %(levelname)-4s %(message)s
log_date_format = %Y-%m-%d %H:%M:%S
log_file=pytest.log


markers =
order: for order
logstics: for logstics
python_files = test_* *_test test*
python_classes = Test* test*
python_functions = test_* test*

  

1.addopts 主要配置参数命令行参数,可以不用每次重复敲默认执行配置好的参数可以指定报告生成目录和重跑次数,还有打印详细程度

  --pytest_report=pytest.html  指定html报告文件名称,默认在当前pytest.ini所在目录

2.testpaths 主要指要覆盖的测试目录,也就是跑那些测试目录

3.log_cli = true 设置日志控制台开关,打印日志作用

4.log_file 指定日志保存到文件的文件名

5.markers pytest的标记测试cases神器,可以只跑你标记的那部分特定模块case

6.对于测试执行顺序参考pytest-ordering

pip install pytest-ordering

用法:

第一个执行:@ pytest.mark.run(order=1)
第二个执行:@ pytest.mark.run(order=2)
倒数第二个执行:@ pytest.mark.run(order=-2)
最后一个执行:@ pytest.mark.run(order=-1)

@pytest.mark.run(order=2)
def test_laa():
    assert True


@pytest.mark.run(order=1)
def test_aaxx():
    assert True

  

7.markers 自定义标记:

多个标记换行书写

markers =

   order: for order

   logstics: for logstics

 

 pytest mark testcase 案例:

pytest   -m "order or logstics"

pytest -k 关键字匹配:

比如test case包含某些关键字的可以模糊匹配去执行:

接口参数化:

conftest.py:

import  pytest
import uuid
@pytest.fixture()
def get_token():
    return uuid.uuid1().hex

  

test_order.py

import pytest
import logging
logger=logging.getLogger('pytest')

@pytest.mark.order
@pytest.fixture()
def test_1(get_token):
    """ 为test_1的返回值给其他测试例用,通过pytest.fixture进行灯具化使其全局可用,pytest灵魂产物"""
    logger.debug("hello debug ")
    print('hello order订单 ..... {}'.format(get_token))
    return 329
@pytest.mark.order
def test_2(test_1):
    print("got is {}".format(test_1))

@pytest.mark.logstics
def test_logstics(get_token):
    logger.info("hello info ...")
    print('hello 物流..... {}'.format(get_token))

  

image.png

 

 报告:

依赖库:

pytest 6.2.2
pytest-cov 2.11.1
pytest-html 3.1.1
pytest-metadata 1.11.0
PyTestReport 0.2.1

 

 

原文地址:https://www.cnblogs.com/SunshineKimi/p/14432457.html