Python 测试框架:pytest 与 nose2 详解
1. pytest 测试框架
在 Python 测试中,pytest 是一个强大且灵活的测试框架。它提供了丰富的功能,如使用 fixtures、跳过或标记测试、monkeypatching 等。
1.1 使用 fixtures
在 pytest 中,函数可以被装饰为 fixture。fixture 装饰器可以接受一个 scope 参数,用于指定 fixture 何时被调用,具体如下:
| Scope | Effect |
| — | — |
| session | 函数在会话开始时执行一次 |
| module | 函数在模块开始时执行一次 |
| class | 函数在类开始时执行一次 |
| function | 函数在每个测试用例之前执行 |
以下是一个使用 fixtures 的随机数测试类的示例代码:
import numpy as np
import myrand
import scipy.stats
import sys
import random
import pytest
class TestRandoms( ):
@classmethod
@pytest.fixture(scope="class")
def setUpClass(cls):
print("Doing setUpClass")
cls.numVals = 10000
@pytes
Python 测试框架:pytest 与 nose2 对比
超级会员免费看
订阅专栏 解锁全文
1229

被折叠的 条评论
为什么被折叠?



