Python测试代码

Python测试代码



测试函数

使用pytest对函数进行测试

pytest测试需要新建一个以"test_"打头的文件,并在里面撰写以"test_"打头的函数,在函数中调用被测试函数并使用断言

在命令行中输入"pytest",pytest将会收集所有"test_"打头的文件,并调用其中"test_"打头的函数,并显示测试结果,如果在pytest后加入文件名作为参数,那么pytest将只调用指定文件中的测试函数

文件FastPower

def fastPower(base, exp):
    res = 1
    while exp:
        if exp & 1:
            res = res * base
            base = base * base
        exp >>= 1
    return res

文件test_fastPower

import pytest

from FastPower import fastPower


def test_fastPower():
    assert 1 == fastPower(1, 0)

在命令行中输入"pytest",运行结果如下

========================================================================================= test session starts >==========================================================================================
platform win32 -- Python 3.11.5, pytest-7.4.4, pluggy-1.0.0
rootdir: D:\VSCodeData\PythonCodes
plugins: anyio-4.2.0
collected 1 >item
test_fastPower.py . [100%]

========================================================================================== 1 passed in 30.59s >==========================================================================================

夹具fixture

有的时候多个测试函数需要使用同一个测试对象(比如对类进行测试)

在测试文件中使用@pytest.fixture装饰器来修饰函数,将函数作为形参传入测试函数中,测试函数在运行时便会自动调用夹具,并获取夹具返回的对象

posted @ 2026-01-25 20:29  DuckingWJ  阅读(0)  评论(0)    收藏  举报