先问题,然后解释一下你是否感兴趣.
在py.test的上下文中,如何从一小组测试函数模板生成大量测试函数?
就像是:
models = [model1,model2,model3]
data_sets = [data1,data2,data3]
def generate_test_learn_parameter_function(model,data):
def this_test(model,data):
param = model.learn_parameters(data)
assert((param - model.param) < 0.1 )
return this_test
for model,data in zip(models,data_sets):
# how can py.test can see the results of this function?
generate_test_learn_parameter_function(model,data)
Run Code Online (Sandbox Code Playgroud)
说明:
我正在努力进行单元测试.我为"科学"编写代码,因为我编写的代码在数学上是复杂的,但从编程的角度来看并不是那么糟糕,即我可能有五个函数需要测试.我来自'科学'意味着我对单元测试很陌生,但已经说服了我的CS好友,这就是要做的事情.
我正在编写的代码采用模型结构,一些数据,并学习模型的参数.所以我的单元测试包括一堆模型结构和预先生成的数据集,然后是一组约5个机器学习任务来完成每个结构+数据.
因此,如果我手动编码,每个任务每个模型需要一次测试.每次我想出一个新模型时,我都需要复制并粘贴5个任务,改变我所指向的酸洗结构+数据.这对我来说感觉不好.理想情况下,我想要的是5个模板函数,它们定义了我的5个任务中的每一个,然后只为我指定的结构列表吐出测试函数.
谷歌搜索带来了a)工厂或b)闭包,这两者都加入了我的大脑,并告诉我必须有一个更简单的方法,因为这个问题必须由适当的程序员定期面对.那有吗?
编辑:所以这里是如何解决这个问题!
def pytest_generate_tests(metafunc):
if "model" in metafunc.funcargnames:
models = [model1,model2,model3]
for model in models:
metafunc.addcall(funcargs=dict(model=model))
def test_awesome(model):
assert model == "awesome"
Run Code Online (Sandbox Code Playgroud)
这将test_awesome测试应用于我的模型列表中的每个模型!谢谢@dfichter!
(注意:断言总是通过,顺便说一句)
我正面临一种情况,我想确保如果一个方法被修改,它运行不需要超过X毫秒(基本上如果该功能较慢,它将减慢我们网页上的搜索结果,并且对销售产生不良影响).
我们有单元测试(特别是代码是在python下完成的,我们使用py.test),第一个想法是断言如果函数没有在小于X ms内执行,那么将测试标记为失败(或者提升一个警告).
然而,这感觉很危险(例如,并非所有计算机都具有相同的速度),而且我也不确定这是单元测试的工作.
有人遇到过类似的情况吗?对我而言,速度是一项功能,我希望确保随着代码的发展,此功能在将来不会丢失.
如果单元测试不是答案,您会推荐哪些其他替代方案?
谢谢
我们目前py.test使用coverage插件在tests目录中运行我们的测试.
从主代码中提取doctests的最简单方法是什么? --doctest-modules不起作用(可能因为它只是运行doctests tests).请注意,我们希望在同一进程中包含doctests(而不是简单地运行单独的调用py.test),因为我们希望在代码覆盖率中考虑doctest.
我是Python的新手,试图学习工具集.
我已经弄清楚如何在py.test -f编码时观察我的测试.我无法弄清楚的一件事是,是否有办法做一个更聪明的观察者,就像Ruby的Guard库一样.
用后卫+ MINITEST我得到的行为是,如果我像保存一个文件my_class.rb,然后my_class_test.rb执行,如果我打enter在CLI中运行所有测试.
到目前为止,使用pytest我还没有找到一种方法来只运行与上次触摸的文件相对应的测试文件,从而避免等待整个测试套件运行,直到我获得当前文件为止.
你会怎么做pythonistas呢?
谢谢!
我目前正在关注这个py.test示例,当我不使用类时,它会工作,但是当我将测试用例引入类时,我失败了.
我设法编写的最小案例如下:
import unittest
import pytest
class FixtureTestCase(unittest.TestCase):
@pytest.mark.parametrize("test_input,expected", [
("3+5", 8),
("2+4", 6),
("6*9", 42),
])
def test_1(self, a, b):
self.assertEqual(a, b)
Run Code Online (Sandbox Code Playgroud)
不幸的是,当我执行
py.test test_suite.py
Run Code Online (Sandbox Code Playgroud)
我收到错误消息:
TypeError: test_1() takes exactly 3 arguments (1 given)
Run Code Online (Sandbox Code Playgroud)
如何生成一系列test_1测试?
我正在尝试编写一个pytest插件来自定义特定异常的外观 - 更具体地说,模拟异常(预期被调用的方法没有被调用等),因为在这些异常的追溯中存在大量无用的噪声.
这是我到目前为止所做的,它有效,但非常黑客:
import pytest
import flexmock
@pytest.hookimpl()
def pytest_exception_interact(node, call, report):
exc_type = call.excinfo.type
if exc_type == flexmock.MethodCallError:
entry = report.longrepr.reprtraceback.reprentries[-1]
entry.style = 'short'
entry.lines = [entry.lines[-1]]
report.longrepr.reprtraceback.reprentries = [entry]
Run Code Online (Sandbox Code Playgroud)
我认为我正在hookimpl使用简单的if语句检查异常类型.
我尝试report.longrepr用一个简单的字符串替换,这也有效,但后来我失去了格式化(终端中的颜色).
作为我想缩短的输出类型的一个例子,这是一个模拟断言失败:
=================================== FAILURES ====================================
_______________________ test_session_calls_remote_client ________________________
def test_session_calls_remote_client():
remote_client = mock.Mock()
session = _make_session(remote_client)
session.connect()
remote_client.connect.assert_called_once_with()
session.run_action('asdf')
> remote_client.run_action.assert_called_once_with('asdff')
tests/unit/executor/remote_test.py:22:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ …Run Code Online (Sandbox Code Playgroud) 我使用Connexion的框架瓶打造的microService.我想用我的应用程序编写测试py.test.
pytest-flask它在文档中说创建一个夹具,conftest.py就像这样创建应用程序:
conftest.pyimport pytest
from api.main import create_app
@pytest.fixture
def app():
app = create_app()
return app
Run Code Online (Sandbox Code Playgroud)
在我的测试中,我正在使用这样的client夹具:
test_api.pydef test_api_ping(client):
res = client.get('/status')
assert res.status == 200
Run Code Online (Sandbox Code Playgroud)
但是当我运行时,py.test我收到以下错误消息:
==================================== ERRORS ====================================
_______________________ ERROR at setup of test_api_ping ________________________
request = <SubRequest '_monkeypatch_response_class' for <Function 'test_api_ping'>>
monkeypatch = <_pytest.monkeypatch.MonkeyPatch instance at 0x7f9f76b76518>
@pytest.fixture(autouse=True)
def _monkeypatch_response_class(request, monkeypatch):
"""Set custom response class before test suite and restore the original …Run Code Online (Sandbox Code Playgroud) 我正在尝试设置被测目标@pytest.fixture并在模块中的所有测试中使用它。我能够正确修补测试,但是在我添加@pytest.fixture返回模拟对象并在其他单元测试中调用模拟对象后,该对象开始引用回原始函数。
以下是我拥有的代码。我期望mocked_worker单元测试中的 引用返回值,但它正在调用实际os.getcwd方法。
请帮我更正代码:
import os
import pytest
from unittest.mock import patch
class Worker:
def work_on(self):
path = os.getcwd()
print(f'Working on {path}')
return path
@pytest.fixture()
def mocked_worker():
with patch('test.test_module.os.getcwd', return_value="Testing"):
result = Worker()
return result
def test_work_on(mocked_worker):
ans = mocked_worker.work_on()
assert ans == "Testing"
Run Code Online (Sandbox Code Playgroud) 我正在使用 django 构建我的网站,并使用 django-pytest 来测试我的应用程序,但我收到此错误 注意我正在使用 python 3.9
================================================================== warnings summary
===================================================================
..\venv\lib\site-packages\_pytest\config\__init__.py:1233
c:\users\eng_diaa_shalaby\desktop\unittest\venv\lib\site-packages\_pytest\config\__init__.py:1233: PytestConfigWarning: Unknown config option: DJANGO_
SETTINGS_MODULE
self._warn_or_fail_if_strict(f"Unknown config option: {key}\n")
-- Docs: https://docs.pytest.org/en/stable/warnings.html
Run Code Online (Sandbox Code Playgroud)
这是我的 pytest.ini 文件内容
# -- FILE: pytest.ini (or tox.ini)
[pytest]
DJANGO_SETTINGS_MODULE = testing_settings
# -- recommended but optional:
python_files = tests.py test_*.py *_tests.py
Run Code Online (Sandbox Code Playgroud)
我运行这个命令
pytest
Run Code Online (Sandbox Code Playgroud)
这是我的 venv 包
Package Version
------------- -------
asgiref 3.3.4
atomicwrites 1.4.0
attrs 21.2.0
colorama 0.4.4
coverage 5.5
Django 3.2.4
django-pytest 0.2.0
iniconfig 1.1.1
packaging 20.9
pip 21.1.2
pluggy …Run Code Online (Sandbox Code Playgroud) 我尝试使用文件夹结构来组织我的 Python 项目。当我需要进行测试时,我使用类似以下的东西。
.
|-- src
| |-- b.py
| `-- main.py
`-- tests
`-- test_main.py
Run Code Online (Sandbox Code Playgroud)
这种方法有一个大问题。main.py如果正在导入,Pytest 将不会运行b.py。
到目前为止,我已经尝试将空__init__.py文件单独或一起放置在src和文件夹中,但其中任何一个似乎都有效。tests
在我看来,这是一个非常标准的项目,但我无法在网上找到解决方案。我应该使用不同的文件夹结构吗?有没有推荐的方法在此类项目中使用 pytest?
这是文件的内容:
# b.py
def triplicate(x):
return x * 3
Run Code Online (Sandbox Code Playgroud)
# main.py
from b import triplicate
def duplicate(x):
return x * 2
Run Code Online (Sandbox Code Playgroud)
# test_main.py
from src.main import duplicate
def test_duplicate():
assert duplicate(2) == 4
Run Code Online (Sandbox Code Playgroud)
这是我运行 pytest 时遇到的错误:
==================================================================================================== ERRORS ====================================================================================================
_____________________________________________________________________________________ ERROR collecting tests/test_main.py ______________________________________________________________________________________
ImportError while importing test module 'C:\Users\edwar\test_pytest\tests\test_main.py'. …Run Code Online (Sandbox Code Playgroud) python directory-structure working-directory pytest python-3.x
pytest ×10
python ×9
unit-testing ×4
python-3.x ×2
testing ×2
django ×1
doctest ×1
flask ×1
swagger ×1