python - 用于单元测试或 pytest 的 Python 检测
问题描述
我的目标是改变在我的 virtualenv 中运行的每个测试,首先打印(“开始测试”),一旦测试完成就打印(“测试结束”)。
例如:
def test_numpy_func1():
print("Start test")
method_to_test.run()
print("End test")
我的问题是我需要为 pytest 或 unittest 执行的每个测试执行此任务(手动插入不是一个选项)。
unittest 中是否有任何特定方法可以修改以实现我的目标?我愿意接受建议。
提前感谢所有帮助者
解决方案
一个简单的装饰器就足够了,尽管这种特性是测试运行器应该提供的。(不过,装饰器比自定义测试运行器更容易定义。)
from functools import wraps
def start_stop_logging(f):
@wraps(f)
def _(*args, **kwargs):
print("Start test")
f(*args, **kwargs)
print("End test")
return _
@start_stop_logging
def test_numpy_func1():
method_to_test.run()
更好的解决方案可能特定于特定的测试框架。
推荐阅读
- simulation - 有没有办法存储在 ltspice 中模拟的电路的中间输出值?
- javascript - 弹性搜索如何添加到 _source 新创建的属性
- c++ - 如何仅使用 .dll 文件在 c++ 项目中使用动态库
- python - 创建干净的文本(不带 \n )并添加语言:HTTPError: HTTP Error 403: Forbidden Python
- javascript - 将 OpenLayers 中的 esc 键重新定义为自定义功能
- php - 为什么使用 unset() 函数将数组转换为对象?
- php - 如何上传 .webp 图片
- redis - NestJs 从 redis 流中读取
- java - getText 方法的输出不能存储在 String 变量中,怎么办?
- ios - 对所有文本字段使用一个通用文本字段时如何转到下一个文本字段?