我有一个用于测试我的一些代码的类.我想参数化设置并使用不同的参数重新运行类:
class TestNormalLTEPlasma:
def setup(self, t=10000):
self.plasma = plasma.LTEPlasma.from_abundance(t, {'Si':1.0}, 1e-13, atom_data, 10*86400)
def test_beta_rad(self):
assert self.plasma.beta_rad == 1 / (10000 * constants.k_B.cgs.value)
def test_t_electron(self):
assert self.plasma.t_electron == 0.9 * self.plasma.t_rad
def test_saha_calculation_method(self):
assert self.plasma.calculate_saha == self.plasma.calculate_saha_lte
Run Code Online (Sandbox Code Playgroud)
我希望运行这个类从t = 2000到t = 20000,步长为1000
我问了这个问题,关于如何写一个pytest来检查输出stdout并得到一个解决方案.现在我需要写一个test case,检查内容是否写入文件,内容是否按预期写入,例如:
def writetoafile():
file = open("output.txt",w)
file.write("hello\n")
file.write("world\n")
file.close()
Run Code Online (Sandbox Code Playgroud)
现在是一个pytest函数来检查它是否写入:
def test_writeToFile():
file = open("ouput.txt",'r')
expected = "hello\nworld\n"
assert expected==file.read()
Run Code Online (Sandbox Code Playgroud)
虽然这似乎有效,但我认为这不是理想的,尤其是硬编码.这些test functions写入文件通常是如何编写的?
同时采用了接受的答案的代码,我是有问题在这里.
代码的工作原理取决于我如何导入datetime.这是为什么?是否可以嘲笑它以便它可以双向工作?
我在用Python 3.4.以下代码说明了该问题:
import pytest
from datetime import datetime
mockdate = datetime(2000, 1, 1, 0, 0, 0)
@pytest.fixture(autouse=True)
def patch_datetime_now(monkeypatch):
class mydatetime:
@classmethod
def now(cls):
return mockdate
monkeypatch.setattr('datetime.datetime', mydatetime)
def test_doesnt_work():
assert datetime.now() == mockdate
def test_works():
import datetime
assert datetime.datetime.now() == mockdate
Run Code Online (Sandbox Code Playgroud) unittest.TestCase有一个assertCountEqual方法(assertItemsEqual在Python 2中,可以说是一个更好的名称),它比较两个迭代并检查它们是否包含相同数量的相同对象,而不考虑它们的顺序.
pytest提供类似的东西吗?所有明显的替代方案(例如调用set(x),sorted(x)或Counter(list(x))文档中提到的每一方)都不起作用,因为我正在比较的是字典列表,而且字典不可清除.
我正在尝试使用覆盖模块为django项目找到覆盖范围,但得到"Coverage.py警告:没有收集数据.(无数据收集)".我的项目文件夹有src和tests文件夹.
我跑的时候
覆盖运行-m pytest &&覆盖率报告
它生成一个100%覆盖率的报告,其中包含tests文件夹中的文件列表.而我跑的时候
覆盖运行--source = src -m pytest &&覆盖率报告
它说
Coverage.py警告:未收集任何数据.(无数据收集)
无数据报告.
当我尝试在.coveragerc中给出source = src或include = src时,也会发生相同的警告.上述所有案例均通过测试.
我想要src文件夹的覆盖范围.是因为我错过了一些路径设置吗?
我尝试运行时收到以下错误pytest repo/tests/test_file.py:
$ pytest repo/tests/test_file.py
Traceback (most recent call last):
File "/Users/marlo/anaconda3/envs/venv/lib/python3.6/site-packages/_pytest/config.py", line 329, in _getconftestmodules
return self._path2confmods[path]
KeyError: local('/Users/marlo/repo/tests/test_file.py')
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/marlo/anaconda3/envs/venv/lib/python3.6/site-packages/_pytest/config.py", line 329, in _getconftestmodules
return self._path2confmods[path]
KeyError: local('/Users/marlo/repo/tests')
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/marlo/anaconda3/envs/venv/lib/python3.6/site-packages/_pytest/config.py", line 362, in _importconftest
return self._conftestpath2mod[conftestpath]
KeyError: local('/Users/marlo/repo/conftest.py')
During handling of the above exception, another exception occurred:
Traceback …Run Code Online (Sandbox Code Playgroud) 我有 2 个 pyspark 数据框,如所附文件所示。预期 df 和实际 df
在我的单元测试中,我试图检查两者是否相等。
我的代码是
expected = map(lambda row: row.asDict(), expected_df.collect())
actual = map(lambda row: row.asDict(), actaual_df.collect())
assert expected = actual
Run Code Online (Sandbox Code Playgroud)
由于两个 dfs 相同但行顺序不同,因此断言此处失败。比较此类 dfs 的最佳方法是什么?
我在包中有一个文件名中带有“test”,当我运行 pytest 时出现错误
import file mismatch:
imported module 'my_project.my_file_test' has this __file__ attribute:
/my_project/src/my_project/build/lib/python2.7/site-packages/foo/my_file_test.py
which is not the same as the test file we want to collect:
/my_project/src/my_project/build/private/python2.7/lib/foo/my_file_test.py
HINT: remove __pycache__ / .pyc files and/or use a unique basename for your test file modules
Run Code Online (Sandbox Code Playgroud)
如果我从文件中删除“测试”,它可以正常工作,但不幸的是我无法更改它。
所以问题是如何告诉pytest忽略这个文件?
在从 shell调用pytest期间,我得到以下输出,因为我的测试存储在apps.business.metrics.tools.tests.py 中,并且在模块导入期间
apps/business/metrics/widgets/employees/utilization.py
在模块调用期间实时调用 SQL。这是由
get_metric_columns('EmployeeUtilization', shapers=SHAPERS)
和 pytest 投诉:
? pytest
=========================================================================== test session starts ===========================================================================
platform linux -- Python 3.6.8, pytest-4.0.0, py-1.7.0, pluggy-0.8.0
Django settings: config.settings.local (from ini file)
rootdir: /home/dmitry/Projects/analytics/backend, inifile: pytest.ini
plugins: django-3.4.7, pylama-7.6.6, django-test-plus-1.1.1, celery-4.2.1
collected 60 items / 1 errors
================================================================================= ERRORS ==================================================================================
__________________________________________________________ ERROR collecting apps/business/metrics/tools.tests.py __________________________________________________________
../../../.pyenv/versions/3.6.8/envs/cam/lib/python3.6/site-packages/py/_path/local.py:668: in pyimport
__import__(modname)
apps/business/metrics/__init__.py:3: in <module>
from .widgets import * # noqa
apps/business/metrics/widgets/__init__.py:1: in <module>
from . import help # …Run Code Online (Sandbox Code Playgroud) 在pytest虚拟环境中安装模块后,我使用python代码调用并运行提示找到pytest模块。
我在虚拟环境之外安装了 pytest 模块。我可以用python正常调用它。
import pytest
def test_main():
assert 5!=5
if __name__ == "__main__":
pytest.main()
Run Code Online (Sandbox Code Playgroud)
错误如下?
[运行] python -u "d:\MyPytest\test_sample.py" 回溯(最近一次调用):文件“d:\MyPytest\test_sample.py”,第 1 行,在 import pytest ModuleNotFoundError: No module named 'pytest' [完成] 在 0.185 秒内以代码 = 1 退出
pytest ×10
python ×8
python-3.x ×2
coverage.py ×1
django ×1
file-io ×1
function ×1
mocking ×1
pyspark ×1
pytest-cov ×1
unit-testing ×1