在 python unittest 中,我尝试了解如果我更改测试方法中的变量,该变量是否会在其他测试方法中更改。或者是否为每个方法运行setUp和tearDown方法,以便为每个方法再次设置变量?
我是说
AsdfTestCase(unittest.TestCase):
def setUp(self):
self.dict = {
'str': 'asdf',
'int': 10
}
def tearDown(self):
del self.dict
def test_asdf_1(self):
self.dict['str'] = 'test string'
def test_asdf_2(self):
print(self.dict)
Run Code Online (Sandbox Code Playgroud)
所以我问哪个输出test_asdf_2()将打印 'asdf'或'test_string'
我在主模块中有一个函数,它接受两个值并对它们执行操作。这使用在调用此函数之前创建的全局变量
def calc(keys,values):
if globalvar == "calc":
return sum(keys)
else:
return sum(values)
Run Code Online (Sandbox Code Playgroud)
现在正在单元测试中
class Testcalc(TestCase):
@mock.patch('module.globalvar ', "calc")
def test_unit(self,calc):
keys=[1,2,3]
values=[4,5,6]
sum=module.calc(keys,values)
"""
check asserts
"""
Run Code Online (Sandbox Code Playgroud)
我收到无效参数的类型错误。
TypeError('test_unit() takes exactly 2 arguments (1 given)',)
Run Code Online (Sandbox Code Playgroud)
谁能告诉我模拟全局变量的正确方法
更新:这对我有用,不知道为什么
class Testcalc(TestCase):
@mock.patch('module.globalvar')
def test_unit(self,var):
keys=[1,2,3]
values=[4,5,6]
var="calc"
sum=module.calc(keys,values)
"""
check asserts
"""
Run Code Online (Sandbox Code Playgroud)
谢谢大家
我正在编写一个测试来验证我的程序是否能够解决不同复杂程度的问题。预期结果始终相同(解决方案已完成),因此单个测试定义适用于所有问题。
如何对从文件中读取的值列表运行相同的测试,但告诉 unittest 将每个问题视为单独的测试,以便我可以查明所有失败/通过的情况?(最好没有外部库)
为了避免显式地拥有test_solution_1, test_solution_2... test_solution_n,我最初的想法是让 for 循环遍历列表中的每一项,并一次运行一个断言:
class TestProblem(unittest.TestCase):
def test_all(self):
results = Counter()
rng = 50
for i in range(rng):
p = Problem(matrix_index=i) # generate instance of problem.
p.solve()
results[p.is_complete()] += 1 # log result of test.
self.assertTrue(p.is_complete(), msg="Failed at %s" % str(i))
# Now ensure all instances passed (useful when above assertion not included).
self.assertEqual(results[True], rng, msg="SCORE: %s / %s" % (results[True], rng))
Run Code Online (Sandbox Code Playgroud)
这种方法的问题在于,第一次故障会导致其余故障停止运行,因此更难以全面了解问题所在。
当我使用mock.return_value.method.side_effect = [1, 2].
它工作完美。我接听每个电话1,然后2接听下一个电话。
但是,我该如何做属性呢?
我用object.text = "some-text"。并且有效。但我需要属性的 side_effect text。是否可以?
我正在在线阅读并试图理解一些图书馆,我遇到了以下内容:
我在网上阅读,发现了一个tox.ini文件,如下所示:
[tox]
envlist =
py27
py35
py36
py37
flake8
[testenv:flake8]
basepython = python
deps = flake8
commands = flake8 related
[testenv]
setenv =
PYTHONPATH = {toxinidir}:{toxinidir}/related
deps =
-r{toxinidir}/dev-requirements.txt
commands =
pip install -U pip
py.test --basetemp={envtmpdir}
Run Code Online (Sandbox Code Playgroud)
我仍然无法让它运行。我做了以下事情:
pip install -U pip
py.test --basetemp={envtmpdir}
py.tests --basetemp={py37}
usage: py.test [options] [file_or_dir] [file_or_dir] [...]
py.test: error: unrecognized arguments: --mccabe --pep8 --flake8
inifile: /home/tmhdev/Documents/related/pytest.ini
rootdir: /home/tmhdev/Documents/related
Run Code Online (Sandbox Code Playgroud)
如何运行此文件中的测试?该库称为相关: https: //github.com/genomoncology/lated/tree/master/tests
下面的代码:
class BoxListOpsTest(unittest.TestCase):
"""Tests for common bounding box operations."""
def test_area(self):
corners = tf.constant([[0.0, 0.0, 10.0, 20.0], [1.0, 2.0, 3.0, 4.0]])
exp_output = [200.0, 4.0]
boxes = box_list.BoxList(corners)
areas = box_list_ops.area(boxes)
with tf.Session() as sess:
areas_output = sess.run(areas)
np.testing.assert_allclose(areas_output, exp_output)
if __name__ == '__main__':
unittest.main()
Run Code Online (Sandbox Code Playgroud)
被解释为具有单个测试的测试用例:
.
----------------------------------------------------------------------
Ran 1 test in 0.471s
OK
Run Code Online (Sandbox Code Playgroud)
但是,切换到tf.test.TestCase:
class BoxListOpsTest(tf.test.TestCase):
"""Tests for common bounding box operations."""
def test_area(self):
corners = tf.constant([[0.0, 0.0, 10.0, 20.0], [1.0, 2.0, 3.0, 4.0]])
exp_output = [200.0, …Run Code Online (Sandbox Code Playgroud) 我正在使用 python unittest 来测试我的代码。作为我的代码的一部分,我正在使用这些
boto3.client('sts')
boto3.client('ec2')
boto3.client('ssm', arg1, arg2)
Run Code Online (Sandbox Code Playgroud)
所以我在编写测试用例之前嘲笑了 boto3 并将其作为参数。现在我可以断言 boto3.client 是否被调用。
但我想检查 boto3.client 是否使用 sts 调用,boto3.client 是否调用 wit ec2 以及 ssm、arg1、arg2。
当只有一个电话时,我可以使用boto3.client.assert_called_with('my parameters'). 但面临每次使用不同参数检查多个调用的问题。
@patch('createCustomer.src.main.boto3')
def test_my_code(self, mock_boto3):
# Executing main class
mainclass(arg1, arg2)
# Verifing
mock_boto3.client.assert_called()
Run Code Online (Sandbox Code Playgroud)
我想实现像
mock_boto3.client.assert_called_once_with('sts')
mock_boto3.client.assert_called_once_with('ec2')
mock_boto3.client.assert_called_once_with('ssm',arg1,arg2)
Run Code Online (Sandbox Code Playgroud)
但这仅在第一个断言中给出错误,说 boto3.client 调用了 3 次,并且显示了最后一次调用的参数,即“ssm”、arg1、arg2
我为 Visual Studio 代码安装了覆盖范围扩展,但没有显示行覆盖范围,当我按覆盖范围显示覆盖范围或按页脚中的“监视”选项时,它显示“找不到覆盖范围文件”
在此 github 中没有提及任何有关配置覆盖文件或任何内容
https://github.com/ryanluker/vscode-coverage-gutters
这是我正在使用unittest的测试之一的代码
class Test_SetValuesService(unittest.TestCase):
def test_given_none_property_when_checking_if_none_return_empty(self):
#ASSERT
self.assertEqual(" ", setValuesService.check_if_json_property_is_null(""))
Run Code Online (Sandbox Code Playgroud)
我收到的错误是一条消息“无法找到覆盖文件!”
python coverage.py python-3.x python-unittest visual-studio-code
我有这个版本的Python:
3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)]
Run Code Online (Sandbox Code Playgroud)
在 Windows 10 上运行 PyCharm CE 2020.1.1。使用非常简单unittest:
3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)]
Run Code Online (Sandbox Code Playgroud)
我可以运行python -m coverage run -m unittest,它会完成并生成一个.coverageSQLite 文件;我可以从 IDE 运行测试,生成测试结果树;但运行/运行覆盖范围显示为灰色,没有任何解释。
我已按照(相当分散的)PyCharm 文档进行设置/构建、执行、部署、激活覆盖视图启用、在将覆盖范围应用到编辑器之前显示选项,但这没有帮助。
为什么覆盖范围呈灰色,如何修复?
我想知道如何在 pytest 中迭代 test_funtion() 以获得不同的值?例如。
list = ['ls','ps', 'df' ,'du'] #list of Linux commands
def test_method(self):
for I in list:
r=subprocess.check_output(I)
if r:
assert True
else:
assert False
Run Code Online (Sandbox Code Playgroud)
现在,当我运行 pytest -k test_method 时,它显示仅通过了一个测试用例。但我希望所有 4 个案例都使用单个函数运行,并且需要在输出中传递 4 个测试用例。我怎样才能实现它?
python-unittest ×10
python ×8
python-3.x ×5
unit-testing ×3
mocking ×2
pytest ×2
coverage.py ×1
linux ×1
pycharm ×1
python-2.7 ×1
python-3.7 ×1
tensorflow ×1
tox ×1