美文网首页
pytest 快速入门说明

pytest 快速入门说明

作者: 乐活北京 | 来源:发表于2023-02-08 16:16 被阅读0次

快速开始

pytest是目前比较流行的单元测试工具,可以帮助研发做单元测试, 可以帮助测试构造自动化测试case。pytest结合报告生成工具Allure,可以让我们更好的查看测试结果。

image

1、用例文件:所有文件名为 test_ 开头 或者 _test 开头的文件会被识别为用例文件。
2、用例类,测试文件中每个Test开头的类就是一个测试用例类。
3、测试用例:测试类中每个test开头的方法就是一条测试用例,测试文件中每个test开头的函数也是一条测试用例
4、执行用例:pytest 会递归查找当前目录下所有以 test 开始或结尾的 Python 脚本,并执行文件内的所有以 test 开始或结束的函数和方法。

Case 1

1. 编写用例

用例函数

def add(a, b):
    return a + b

def test_add():
    assert add(1, 2) == 3

2. 执行测试

测试文件test_learn.py文件夹下执行pytest

PyTest$  pytest 
============================================================================= test session starts =============================================================================
platform darwin -- Python 3.9.6, pytest-7.2.1, pluggy-1.0.0
rootdir: /Users/**/technical-operation-master/FSHandle/PyTest
plugins: allure-pytest-2.12.0
collected 1 item                                                                                                                                                              

test_learn.py .   
============================================================================== 1 passed in 0.02s ==============================================================================

test_learn.py . 测试结果中 .代表测试通过S代表测试跳过,<font color='red'> F代表测试失败</font>

Case 2

1. 编写用例 test_ 开头 或者 _test 开头

用例类和函数

def add(a, b):
    return a + b


def test_add():
    assert add(1, 2) == 3


class TestCalculateMethod:

    def subtraction(self, a, b):
        return a - b

    def test_subtraction(self):
        return self.subtraction(2, 1) == 1

    def test_add(self):
        assert add(1, 2) == 4

执行测试pytest

========== test session starts ==========
platform darwin -- Python 3.9.6, pytest-7.2.1, pluggy-1.0.0
rootdir: /Users/**/technical-operation-master/FSHandle/PyTest
plugins: allure-pytest-2.12.0
collected 3 items                                                                                                                                                             

test_learn.py ..F [100%]                                                                                                          

========== FAILURES ==========

一共3个test case, 2个成功,1个失败

测试函数

断言

assert **  判断**为真
assert not ** 判断**不为真
assert a in b 判断b包含a
assert a == b 判断a等于b
assert a != b 判断a不等于b

测试异常捕获 pytest.raises(CustomException)

有些case需要测试,异常情况下是否可以正常抛出异常

import pytest

class CustomException(Exception):
    pass

class TestPytest:
    def test_exception_catch(self):         
        with pytest.raises(CustomException) as e:
            raise CustomException("custom exception")
        assert e.value.args[0] == "custom exception"

参数化 pytest.mark.parametrize("param_name", params)

比如登录模块,我们要验证正常用户名、密码、错误的用户名密码、还有异常的用户名密码等case,无需再写多个case,或者在测试方法里边构造循环,只需引入参数化即可实现。


@pytest.mark.parametrize("user_name, user_pass",
                         [("jack001", "eflds8fse30f4lfj"),
                          ("jack01", "sdfssfef"),
                          ("jack", "sdfs"),
                          ("jack", "sdfsdfsdf")])
def test_login(user_name, user_pass):
    assert len(user_name) > 5
    assert len(user_pass) > 5

执行测试

⚡  pytest
=================== test session starts ===================
platform darwin -- Python 3.9.6, pytest-7.2.1, pluggy-1.0.0
rootdir: /Users/**/technical-operation/FSHandle
plugins: allure-pytest-2.12.0
collected 4 items                                                                                                                                                             

test_function.py ..FF  [100%]  

=================== FAILURES ===================

一共收集到了4个Case,2个成功,2个失败

预见错误 pytest.mark.xfail

import sys
@pytest.mark.xfail(sys.platform != 'darwin',
                   reason='other version is not implement')
def test_new_method():
    print(sys.platform)

Case跳过 @pytest.mark.skip(reason='')


@pytest.mark.skip(reason='method is not ready')
def test_skip():
    assert True


@pytest.mark.skipif(sys.platform != 'darwin',
                    reason='other platform is not support')
def test_skip_if():
    assert True

通过运行测试时制定测试内容

pytest.main (['./path/test_module.py::TestClass::test_method'])
pytest ./path/test_module.py::TestClass::test_method
pytest.main(['-k','new','./path/test_module.py'])

预处理和后处理



@pytest.fixture(scope='function')
def func_scope():
    print('before')
    yield
    print('after')

@pytest.fixture(scope='module')
def mod_scope():
    print('before')
    yield
    print('after')

@pytest.fixture(scope='session')
def sess_scope():
    print('before')
    yield
    print('after')

@pytest.fixture(scope='class')
def class_scope():
    print('before')
    yield
    print('after')


class TestScope(object):
    def test_scope(self, class_scope, sess_scope, mod_scope, func_scope):
        pass

    def test_scope01(self, class_scope, sess_scope, mod_scope, func_scope):
        pass


运行测试

⚡  pytest -s --setup-show
========== test session starts ==========
platform darwin -- Python 3.9.6, pytest-7.2.1, pluggy-1.0.0
rootdir: /Users/Developer/technical-operation/FSHandle
plugins: allure-pytest-2.12.0
collected 2 items                                                                                                                                                             

test_function.py before

SETUP    S sess_scopebefore

    SETUP    M mod_scopebefore

      SETUP    C class_scopebefore

        SETUP    F func_scope
        test_function.py::TestScope::test_scope (fixtures used: class_scope, func_scope, mod_scope, sess_scope).after

        TEARDOWN F func_scopebefore

        SETUP    F func_scope
        test_function.py::TestScope::test_scope01 (fixtures used: class_scope, func_scope, mod_scope, sess_scope).after

        TEARDOWN F func_scopeafter

      TEARDOWN C class_scopeafter

    TEARDOWN M mod_scopeafter

TEARDOWN S sess_scope

=========== 2 passed in 0.02s ===========

按照如下顺序执行:

  1. scope = session 被执行了一次
  2. scope = module 被执行了一次
  3. scope = class 如果func被放在class中, 则只执行一次
  4. scope = class 如果func没被放在class中, 则每个函数执行前,都执行一次
  5. scope = function 每次执行方法前都会执行

pytest参数说明

-v  说明:可以输出用例更加详细的执行信息,比如用例所在的文件及用例名称等
-s  说明:输入我们用例中的调式信息,比如print的打印信息等
-x:遇到错误的用例,立即退出执行,并输出结果
-k  "关键字" 说明:执行用例包含“关键字”的用例,允许使用or、and
-q  说明:简化控制台的输出,可以看出输出信息和上面的结果都不一样,下图中有两个..点代替了pass结果


# 如果要运行多个标识的话,用表达式,如下
pytest -k "slow or faster" test_1.py  运行有slow标识或 faster标识用例

通过pytest.main()执行测试

pytest.main(['./'])
# 指定路径、模块、类、方法
pytest.main (['./path/test_module.py::TestClass::test_method']) 
# 指定关键字
pytest.main(['-k','new','./path/test_module.py']) 

# -s,测试结果中显示测试用例里print的内容
pytest.main(["-s", "testcase/test_case.py"])
# -v,设置测试结果显示的详细程度
pytest.main(["-v", "testcase/test_case.py"])
# -q,设置测试结果显示的详细程度
pytest.main(["-q", "testcase/test_case.py"])

祝你好运

相关文章

网友评论

      本文标题:pytest 快速入门说明

      本文链接:https://www.haomeiwen.com/subject/kwvqkdtx.html