Pytest基础01: 入门demo脚本

发布于:2025-02-11 ⋅ 阅读:(48) ⋅ 点赞:(0)

目录

1 Pytest接口测试

1.1 最简单版hello world

1.2 pytest.ini

2 pytest兼容unittest

3 封装pytest执行入口


1 Pytest接口测试

Pyest是一个可以用于接口测试的强大框架,开源社区也有非常多的pytest插件。

按江湖传统,学习一个新语言或者新框架,都要先实现一个简单的hello world。

1.1 最简单版hello world

新建test_hello_world.py文件,文件内容如

def test_hello_world():
    output = 'hello world'
    print(output)
    assert output == 'hello world'

直接在pycharm上点击绿色三角形按钮运行,或者命令行运行pytest test_hello_world.py。

测试用例都会有结果判断,一般通过assert来做判断,不符合判断条件用例就失败。

1.2 pytest.ini

pytest很多行为可以通过命令行参数控制,为了方便可以先在pytest.ini配置好一些默认值。

pytest.ini的文件名固定就是这个,不能使用其他名称,然后文件的位置是在最上层目录,用例脚本跟pytest.ini同一个目录或者在子目录中。

例如创建如下目录结构,

上面pytest.ini的三个参数是指定哪些文件、类、函数会被pytest当做测试用例执行。

假如不配置的话默认是目录下所有py文件、Test开头的类、test_开头的函数会被当做用例。

lib_utils.py内容:

test_hello_world.py内容:

通过pytest  01_pytest_proj执行用例的时候,只有test_hello_world会被当做用例执行,因为只有它满足了pytest.ini三个参数指定的条件,python_files = test_*.py 指定test_开头的py文件、python_classes指定Test开头的类、pytest_functions指定test_开头的函数。

如果去掉python_files = test_*.py这个配置,那lib_utils里面的test_not_executed函数也会被当成用例执行。

2 pytest兼容unittest

假如以前习惯了用unittest写单元测试用例,使用pytest也可以兼容之前的unittest用例。

比如针对上面的pytest写单元测试用例,创建如下目录:

pytest.ini内容跟上面pytest用例里面的一样,test_lib_utils.py内容如下:

import unittest
import sys
sys.path.append('01_pytest_proj')
from lib_utils import output_func


class TestLibUtils(unittest.TestCase):
    def test_output_func_01(self):
        info = output_func('candy')
        self.assertEqual(info, 'hello world from candy')

    def test_output_func_02(self):
        info = output_func('')
        self.assertEqual(info, 'invalid name')

通过pytest 02_utest_proj可以执行test_output_func_01和test_output_func_02两个用例。

3 封装pytest执行入口

简单的场景使用pytest命令直接执行测试用例脚本就行,假如基于pytest做了些二次开发、或者有些其他依赖逻辑要处理,那一般会需要用一个py脚本来作为用例执行入口。

比如创建个这样的目录结构:

run_tests.py内容如下:

import argparse
import pytest

def run_test():
    parser = argparse.ArgumentParser(description='Demo script')
    parser.add_argument('--test-root-path', default='', help='Test scripts folder')
    args = parser.parse_args()
    params = ['-v', args.test_root_path]
    pytest.main(params)

if __name__ == "__main__":
    run_test()

可以通过参数--test-root-path来制定用例的目录,

下面命令分别执行pytest用例、单元测试用例

python run_tests.py --test-root-path 01_pytest_proj #等同pytest -v  01_pytest_proj

python run_tests.py --test-root-path 02_utest_proj