配置文件pytest.ini的详细使用

举报
Tester_muller 发表于 2023/09/07 11:17:57 2023/09/07
【摘要】 使用 pytest.ini 定制化和管理 pytest 测试框架的配置 前言在使用 pytest 进行测试时,我们经常需要根据项目的需求进行定制化配置。pytest 提供了丰富的配置选项,使我们可以灵活地调整测试框架的行为。其中,pytest.ini 文件是一种方便的方式来定义和管理 pytest 的配置。本文将详细介绍 pytest.ini 的作用和使用方法,帮助您定制化和管理 pyte...

使用 pytest.ini 定制化和管理 pytest 测试框架的配置

前言

在使用 pytest 进行测试时,我们经常需要根据项目的需求进行定制化配置。pytest 提供了丰富的配置选项,使我们可以灵活地调整测试框架的行为。其中,pytest.ini 文件是一种方便的方式来定义和管理 pytest 的配置。本文将详细介绍 pytest.ini 的作用和使用方法,帮助您定制化和管理 pytest 测试框架的配置。

pytest.ini配置文件

pytest配置文件可以改变pytest的运行方式,它是一个固定的文件pytest.ini文件,读取配置信息,按指定的方式去运行,它有如下作用:

  • 定制化配置:通过 pytest.ini 文件,可以定义和修改 pytest 的各种配置选项,包括测试运行环境、插件设置、标记规则、报告输出等。
  • 项目级配置:pytest.ini 文件位于项目的根目录下,它的配置会被应用于整个项目中的测试。这样可以保持一致的配置,方便多个测试模块的管理和维护。
  • 覆盖默认配置:pytest.ini 文件允许覆盖 pytest 默认的配置选项。通过在 pytest.ini 中定义相同的配置项,可以修改默认行为,以满足项目的需求。

pytest.ini文件的创建和配置

  1. 创建 pytest.ini 文件:在项目的根目录下创建一个名为 pytest.ini 的文件。
  2. 定义配置选项:在 pytest.ini 中,使用标准的 INI 格式,定义需要修改或添加的配置选项。例如:
[pytest]
addopts = -s -v
markers =
    slow: marks tests as slow

在上面的示例中,我们修改了 addopts选项,指定了 pytest 的运行参数;并定义了一个名为 “slow” 的标记,用于标记耗时较长的测试。

  1. 配置插件:如果项目使用了第三方插件,可以在 pytest.ini 中配置插件的选项。例如:
[pytest]
plugins =
    pytest-ordering

在上面的示例中,我们配置了 pytest-ordering 插件,可以控制用例的执行顺序。

全部配置项如下:

[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
  pythonpath (paths):   Add paths to sys.path
  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

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.ini文件如下:

[pytest]
addopts = -vs

被测程序如下:

class Calculator: 
    def add(self, a, b):

        if a > 99 or a < -99 or b > 99 or b < -99:
            print("请输入范围为【-99, 99】的整数或浮点数")
            return "参数大小超出范围"

        return a + b

    def div(self, a, b):
        if a > 99 or a < -99 or b > 99 or b < -99:
            print("请输入范围为【-99, 99】的整数或浮点数")
            return "参数大小超出范围"

        return a / b

测试脚本如下:

class TestCalc:

    def setup(self):
        self.calc=Calculator()

    def test_add1(self):
        result = self.calc.add(1, 1)
        print(f"实际结果为:{result}")
        expect = 2
        assert result == expect

    def test_add2(self):
        result = self.calc.add(-0.01, 0.02)
        print(f"实际结果为:{result}")
        # 期望结果
        expect = 0.01
        # 断言
        assert result == expect

    def test_div1(self):
        result = self.calc.div(1,1)
        assert result == 1

    def test_div2(self):
        try:
            result = self.calc.div(1,0)
        except ZeroDivisionError as e:
            print(f'除数为0{e}')
        assert False

输出结果如下图:

image.png

总结

pytest.ini 文件是 pytest 的一个强大特性,可以帮助我们定制化和管理 pytest 测试框架的配置。通过定义和修改 pytest 的配置选项,我们可以灵活调整测试运行环境、插件设置、标记规则和报告输出等,以满足项目的需求。

在本文中,我们介绍了 pytest.ini 文件的作用和使用方法。现在您可以创建自己的 pytest.ini 文件,并根据项目的需求进行定制化配置了。享受 pytest 提供的灵活性和便利性,提高测试的效率和质量吧!

【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。