pytest框架学习2-cmd运行pytest规则

it2024-08-23  74

系列文章目录

pytest框架学习1-环境准备及入门


文章目录

系列文章目录前言一、pytest常识1. 用例设计原则2. cmd中help帮助3. cmd中运行方式4. 执行用例规则 二、cmd运行常用参数1. 运行的代码2. -x 遇到错误时停止测试3. --maxfail=num 总结


前言

最近在学习python中的pytest框架,就想着写个博客记录下学习过程,收获。并加深下印象,参考:上海-悠悠-pytest 前面已经学习了pytest入门,现在做个笔记,记录下使用命令行运行pytest的各种规则


一、pytest常识

1. 用例设计原则

文件名以test_.py文件和_test.py以test_开头的函数以Test开头的类以test_开头的方法所有的包package必须要有__init__.py文件

2. cmd中help帮助

查看pytest命令行参数,可以用pytest -h 或pytest --help查看

D:\Test\zx\基础\pytest基础>pytest -h usage: pytest [options] [file_or_dir] [file_or_dir] [...] positional arguments: file_or_dir general: -k EXPRESSION only run tests which match the given substring expression. An expression is a python evaluatable expression where all names are substring-matched against test names and their parent classes. Example: -k 'test_method or test_other' matches all test functions and classes whose name contains 'test_method' or 'test_other', while -k 'not test_method' matches those that don't contain 'test_method' in their names. -k 'not test_method and not test_other' will eliminate the matches. Additionally keywords are matched to classes and functions containing extra names in their 'extra_keyword_matches' set, as well as functions which have names assigned directly to them. The matching is case-insensitive. -m MARKEXPR only run tests matching given mark expression. For example: -m 'mark1 and not mark2'. --markers show markers (builtin, plugin and per-project ones). -x, --exitfirst exit instantly on first error or failed test. --fixtures, --funcargs show available fixtures, sorted by plugin appearance (fixtures with leading '_' are only shown with '-v') --fixtures-per-test show fixtures per test --pdb start the interactive Python debugger on errors or KeyboardInterrupt. --pdbcls=modulename:classname start a custom interactive Python debugger on errors. For example: --pdbcls=IPython.terminal.debugger:TerminalPdb --trace Immediately break when running each test. --capture=method per-test capturing method: one of fd|sys|no|tee-sys. -s shortcut for --capture=no. --runxfail report the results of xfail tests as if they were not marked --lf, --last-failed rerun only the tests that failed at the last run (or all if none failed) --ff, --failed-first run all tests, but run the last failures first. This may re-order tests and thus lead to repeated fixture setup/teardown. --nf, --new-first run tests from new files first, then the rest of the tests sorted by file mtime --cache-show=[CACHESHOW] show cache contents, don't perform collection or tests. Optional argument: glob (default: '*'). --cache-clear remove all cache contents at start of test run. --lfnf={all,none}, --last-failed-no-failures={all,none} which tests to run with no previously (known) failures. --sw, --stepwise exit on test failure and continue from last failing test next time --stepwise-skip ignore the first failing test but stop on the next failing test reporting: --durations=N show N slowest setup/test durations (N=0 for all). --durations-min=N Minimal duration in seconds for inclusion in slowest list. Default 0.005 -v, --verbose increase verbosity. --no-header disable header --no-summary disable summary -q, --quiet decrease verbosity. --verbosity=VERBOSE set verbosity. Default is 0. -r chars show extra test summary info as specified by chars: (f)ailed, (E)rror, (s)kipped, (x)failed, (X)passed, (p)assed, (P)assed with output, (a)ll except passed (p/P), or (A)ll. (w)arnings are enabled by default (see --disable-warnings), 'N' can be used to reset the list. (default: 'fE'). --disable-warnings, --disable-pytest-warnings # 只贴了一部分

3. cmd中运行方式

cmd执行pytest用例有三种方法,以下三种方法都可以,一般推荐第一个

pytestpy.testpython -m pytest

4. 执行用例规则

(1).执行某个目录下所有的用例

pytest 文件名/

(2).执行某一个py文件下用例

pytest 脚本名称.py

(3).-k 按关键字匹配

pytest -k "MyClass and not method" 这将运行包含与给定字符串表达式匹配的名称的测试,其中包括Python 使用文件名,类名和函数名作为变量的运算符。 上面的例子将运行 TestMyClass.test_something但不运行TestMyClass.test_method_simple

(4).按节点运行

每个收集的测试都分配了一个唯一的nodeid,它由模块文件名和后跟说明符组成 来自参数化的类名,函数名和参数,由:: characters分隔。

运行.py模块里面的某个函数

pytest test_mod.py::test_func

运行.py模块里面,测试类里面的某个方法

pytest test_mod.py::TestClass::test_method

(5).标记表达式

pytest -m slow 将运行用@ pytest.mark.slow装饰器修饰的所有测试。 装饰器的作用,我之后会另外写一篇文章来记录

(6).从包里面运行

pytest --pyargs pkg.testing 这将导入pkg.testing并使用其文件系统位置来查找和运行测试。

二、cmd运行常用参数

1. 运行的代码

运行的代码为上次编写两个文件

test_sample.py

def func(x): return x + 1 def test_answer(): assert func(3) == 4

test_class.py

class TestClass: def test_one(self): x = "this" assert 'h' in x def test_two(self): x = "hello" assert hasattr(x, 'check') def test_three(self): a = 14 b = 14 assert a == b

2. -x 遇到错误时停止测试

cmd在对应的文件夹运行下面命令

pytest -x test_class.py

运行结果如下

D:\Test\zx\基础\pytest基础>pytest -x test_class.py ======================================= test session starts ======================================= platform win32 -- Python 3.6.6, pytest-6.1.0, py-1.9.0, pluggy-0.13.1 rootdir: D:\Test\zx\基础\pytest基础 plugins: html-2.1.1, metadata-1.10.0 collected 3 items test_class.py .F ============================================ FAILURES ============================================= _______________________________________ TestClass.test_two ________________________________________ self = <基础.pytest基础.test_class.TestClass object at 0x000001CEFB2DB198> def test_two(self): x = "hello" > assert hasattr(x, 'check') E AssertionError: assert False E + where False = hasattr('hello', 'check') test_class.py:9: AssertionError ===================================== short test summary info ===================================== FAILED test_class.py::TestClass::test_two - AssertionError: assert False !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! stopping after 1 failures !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! =================================== 1 failed, 1 passed in 0.08s ===================================

“collected 3 items” 可以看出有3个用例 "stopping after 1 failures"可以看出在一个失败后,就停止了,没继续往下执行了 “1 failed, 1 passed” 可以看出只跑了两个用例,一个成功,一个失败

3. --maxfail=num

pytest --maxfail=1

当用例错误个数达到指定数量时,停止测试,运行结果如下

D:\Test\zx\基础\pytest基础>pytest --maxfail=1 ======================================= test session starts ======================================= platform win32 -- Python 3.6.6, pytest-6.1.0, py-1.9.0, pluggy-0.13.1 rootdir: D:\Test\zx\基础\pytest基础 plugins: html-2.1.1, metadata-1.10.0 collected 4 items test_class.py .F ============================================ FAILURES ============================================= _______________________________________ TestClass.test_two ________________________________________ self = <基础.pytest基础.test_class.TestClass object at 0x00000119CE5C6A58> def test_two(self): x = "hello" > assert hasattr(x, 'check') E AssertionError: assert False E + where False = hasattr('hello', 'check') test_class.py:9: AssertionError ===================================== short test summary info ===================================== FAILED test_class.py::TestClass::test_two - AssertionError: assert False !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! stopping after 1 failures !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! =================================== 1 failed, 1 passed in 0.15s ===================================

总结

可以不用强行全部记忆下来,可以先有个大概印象,到时候用的时候再百度,加深印象。 这个还是比较简单的,重要的应该是 “用例设计原则” “执行用例规则”。 "用例设计原则"看一遍就差不多知道了,"执行用例规则"如果经常使用cmd运行pytest的话,也能很快熟悉。

最新回复(0)