我做了一个叫做demo的小项目,里面有一个测试
import unittest
class Test(unittest.TestCase):
def testName1(self):
self.assertEqual(5+9, 14)
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
Run Code Online (Sandbox Code Playgroud)
但是,从命令行
ThinkPad-T520:~/workspacep/demo$ python -m unittest
----------------------------------------------------------------------
Ran 0 tests in 0.000s
OK
Run Code Online (Sandbox Code Playgroud)
为什么这不起作用?一般而言,如何使用一行从命令行运行所有单元测试?
目录的结构是
demo
tests
demo_test1.py __init__.py
Run Code Online (Sandbox Code Playgroud) 我有一个简单的FastAPI应用程序,我正在尝试为其创建测试pytest。
我的目标是测试应用程序在出现不同错误时的行为方式。
\n\n我的应用程序中有一个简单的健康检查路线:
\n\nfrom fastapi import APIRouter\n\nrouter = APIRouter()\n\n\n@router.get("/health")\nasync def health():\n return "It\'s working \xe2\x9c\xa8"\nRun Code Online (Sandbox Code Playgroud)\n\n现在在我的 pytest 模块中,我正在尝试修补上述函数,以便它引发不同的错误。\n我正在使用,unittest.mock但我得到了非常奇怪的行为。
import pytest\nfrom unittest import mock\n\nfrom fastapi import HTTPException\nfrom starlette.testclient import TestClient\n\nimport app.api.health\nfrom app.main import app # this is my application (FastAPI instance) with the `router` attached\n\n\n@pytest.fixture()\ndef client():\n with TestClient(app) as test_client:\n yield test_client\n\n\ndef test_simple(client):\n def mock_health_function():\n raise HTTPException(status_code=400, detail=\'gibberish\')\n\n with mock.patch(\'app.api.health.health\', mock_health_function):\n response = client.get(HEALTHCHECK_PATH)\n\n with pytest.raises(HTTPException): # this check passes …Run Code Online (Sandbox Code Playgroud) 我正在尝试想出一种方法来测试多个 Jupyter 笔记本。当在 Github 分支中实现新笔记本并提交拉取请求时,应该运行测试。测试并不那么复杂,它们主要只是测试笔记本是否端到端运行并且没有任何错误,也许还有一些断言。然而:
我愿意使用任何测试库,例如“pytest”或unittest,尽管pytest这是首选。
我查看了一些用于测试笔记本的库,例如nbmake、treon和testbook,但我无法使它们工作。我还尝试将笔记本转换为 python 文件,但神奇单元被转换为get_ipython().run_cell_magic(...)调用,这成为一个问题,因为pytest使用 python 而不是 ipython,并且get_ipython()仅在 ipython 中可用。
所以,我想知道考虑到所有这些,测试 Jupyter Notebook 的好方法是什么。任何帮助表示赞赏。
哇.我今晚发现使用该unittest模块编写的Python单元测试与模块下的覆盖率分析不trace相符.这是最简单的单元测试,在foobar.py:
import unittest
class Tester(unittest.TestCase):
def test_true(self):
self.assertTrue(True)
if __name__ == "__main__":
unittest.main()
Run Code Online (Sandbox Code Playgroud)
如果我运行它python foobar.py,我得到这个输出:
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
Run Code Online (Sandbox Code Playgroud)
大.现在我也想进行覆盖测试,所以我再次运行它python -m trace --count -C . foobar.py,但现在我得到了这个:
----------------------------------------------------------------------
Ran 0 tests in 0.000s
OK
Run Code Online (Sandbox Code Playgroud)
不,Python,它不行 - 你没有运行我的测试!似乎在trace某种程度上运行gums up unittest的测试检测机制.这是我提出的(疯狂)解决方案:
import unittest
class Tester(unittest.TestCase):
def test_true(self):
self.assertTrue(True)
class Insane(object):
pass
if __name__ == "__main__":
module = Insane()
for k, v in locals().items():
setattr(module, k, v) …Run Code Online (Sandbox Code Playgroud) 在我的Python项目中,我们有大量的单元测试(数千个).虽然它们在逻辑上分布在文件和类之间,但我有时需要花费大量时间来查找它们,这些内容涵盖了我正在改变的功能.
当然,我可以从一些特定的文件/类中运行所有测试,但是由于大量的测试,再次运行它们会非常耗时(我在每次保存文件后都执行单元测试)我的IDE).
所以一般来说我需要一些解决方案,一次做以下活动:
有没有人对类似的东西有所了解?
python dependencies unit-testing code-coverage python-unittest
嗨我如何动态生成测试方法列表或文件数量.假设我在json中有file1,file2和filen以及输入值.现在我需要为下面的多个值运行相同的测试,
class Test_File(unittest.TestCase):
def test_$FILE_NAME(self):
return_val = validate_data($FILE_NAME)
assert return_val
Run Code Online (Sandbox Code Playgroud)
我使用以下命令运行py.test来生成html和junit报告
py.test test_rotate.py --tb=long --junit-xml=results.xml --html=results.html -vv
Run Code Online (Sandbox Code Playgroud)
目前我手动定义如下方法,
def test_lease_file(self):
return_val = validate_data(lease_file)
assert return_val
def test_string_file(self):
return_val = validate_data(string_file)
assert return_val
def test_data_file(self):
return_val = validate_data(data_file)
assert return_val
Run Code Online (Sandbox Code Playgroud)
请告诉我如何指定py测试以在报告时动态生成test_came方法.
我期待本博客中提到的确切内容" http://eli.thegreenplace.net/2014/04/02/dynamically-generating-python-test-cases "
但上面的博客使用unittest,如果我使用它,我无法生成html和junit报告
当我们使用如下夹具时,我得到的错误就像需要2个参数一样,
test_case = []
class Memory_utlization(unittest.TestCase):
@classmethod
def setup_class(cls):
fname = "test_order.txt"
with open(fname) as f:
content = f.readlines()
file_names = []
for i in content:
file_names.append(i.strip())
data = tuple(file_names)
test_case.append(data)
logging.info(test_case) # here test_case=[('dhcp_lease.json'),('dns_rpz.json'),]
@pytest.mark.parametrize("test_file",test_case) …Run Code Online (Sandbox Code Playgroud) 考虑下面的代码块(在Jupyter笔记本中开发),AssertionError由于UserWarning没有触发,因此需要引发一个代码:
%%writefile Game/tests/tests.py
import unittest
import pandas as pd
class TestGame(unittest.TestCase):
def test_getters(self):
print('Just before the critical line.')
with self.assertWarns(UserWarning):
print('Just testing...')
suite = unittest.TestLoader().loadTestsFromTestCase(TestGame)
unittest.TextTestRunner().run(suite)
Run Code Online (Sandbox Code Playgroud)
对于那些不熟悉jupyter笔记本的人,第一行只是将所有后续行导出到指定的文件中.
现在,如果我执行命令:
python3 tests.py
Run Code Online (Sandbox Code Playgroud)
从终端(我在Ubuntu 14.04上使用Python 3.5.1),我得到一个Runtime Error- 堆栈跟踪如下:
Just before the critical line:
E
======================================================================
ERROR: test_getters (__main__.TestGame)
----------------------------------------------------------------------
Traceback (most recent call last):
File "tests.py", line 8, in test_getters
with self.assertWarns(UserWarning):
File "/opt/anaconda3/lib/python3.5/unittest/case.py", line 225, in __enter__
for v in sys.modules.values():
RuntimeError: dictionary changed size during …Run Code Online (Sandbox Code Playgroud) 我正在使用python,unittest并希望编写一个测试,启动一些线程并等待它们完成.线程执行一个具有一些unittest断言的函数.如果任何断言失败,我希望测试失败.似乎并非如此.
编辑:最小的可运行示例(python3)
import unittest
import threading
class MyTests(unittest.TestCase):
def test_sample(self):
t = threading.Thread(target=lambda: self.fail())
t.start()
t.join()
if __name__ == '__main__':
unittest.main()
Run Code Online (Sandbox Code Playgroud)
输出是:
sh-4.3$ python main.py -v
test_sample (__main__.MyTests) ... Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib64/python2.7/threading.py", line 813, in __bootstrap_inner
self.run()
File "/usr/lib64/python2.7/threading.py", line 766, in run
self.__target(*self.__args, **self.__kwargs)
File "main.py", line 7, in <lambda>
t = threading.Thread(target=lambda: self.fail())
File "/usr/lib64/python2.7/unittest/case.py", line 450, in fail
raise self.failureException(msg)
AssertionError: None
ok
---------------------------------------------------------------------- …Run Code Online (Sandbox Code Playgroud) 这些进口有什么区别?
from mock import patch
Run Code Online (Sandbox Code Playgroud)
对比
from unittest.mock import patch
Run Code Online (Sandbox Code Playgroud)
他们是一样的吗?
我最近在几个项目中成功使用了标准的Python单元测试框架,但是在过去的几天里它无法像以前一样工作。一个问题是,尽管我从未使用过pytest ,但它现在似乎尝试在全新项目中的测试发现中使用pytest。
重现步骤,请参阅以下文章在 Visual Studio Code 中测试 Python以了解文件内容的详细信息:
inc_dec.py (请参阅上面链接的文章)teststest_unittest.py和空文件__init__.py(请参阅上面链接的文章)tests文件夹test_*.py对我来说,尽管设置清楚地显示单元测试已启用而pytest未启用,但这会产生“Pytest 发现错误”
Python OUTPUT 日志也表明了这一点,例如
2023-07-14 13:08:29.745 [info] Running discovery for unittest using the new …Run Code Online (Sandbox Code Playgroud) python-unittest ×10
python ×7
unit-testing ×5
pytest ×3
mocking ×2
python-3.x ×2
dependencies ×1
fastapi ×1
pandas ×1
patch ×1
starlette ×1
testing ×1