pytest 快速入门说明

快速开始

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"])

祝你好运

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 196,165评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,503评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,295评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,589评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,439评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,342评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,749评论 3 387
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,397评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,700评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,740评论 2 313
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,523评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,364评论 3 314
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,755评论 3 300
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,024评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,297评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,721评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,918评论 2 336

推荐阅读更多精彩内容