所以,假设我有以下内容:
import unittest
class MyTests(unittest.TestCase):
def test001(self):
print 'This is test001'
def test002(self):
print 'This is test002'
if __name__ == '__main__':
unittest.main()
print 'Done'
Run Code Online (Sandbox Code Playgroud)
输出是:
>> This is test001
>> This is test002
>> ----------------------------------------------------------------------
>> Ran 2 tests in 0.001s
>> OK
Run Code Online (Sandbox Code Playgroud)
我想知道为什么不打印"完成"(或任何后来的东西)?
我已经浏览了https://docs.python.org/3/library/unittest.mock-examples.html页面,我看到他们已经列出了如何模拟生成器的示例
我有一个代码,我调用生成器给我一组值,我保存为字典.我想在单元测试中模拟对这个生成器的调用.
我写了以下代码,但它不起作用.
我哪里错了?
In [7]: items = [(1,'a'),(2,'a'),(3,'a')]
In [18]: def f():
print "here"
for i in [1,2,3]:
yield i,'a'
In [8]: def call_f():
...: my_dict = dict(f())
...: print my_dict[1]
...:
In [9]: call_f()
"here"
a
In [10]: import mock
In [18]: def test_call_f():
with mock.patch('__main__.f') as mock_f:
mock_f.iter.return_value = items
call_f()
....:
In [19]: test_call_f()
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-19-33ca65a4f3eb> in <module>()
----> 1 test_call_f()
<ipython-input-18-92ff5f1363c8> in test_call_f()
2 with mock.patch('__main__.f') as …Run Code Online (Sandbox Code Playgroud) 根据工作环境中pandas包的可用性,方法返回两个不同的输出:
pandas.DataFrame,如果大熊猫可用numpy.recarray对象.我该如何为这堂课写单元测试?
我能想到的一个解决方案是为两种情况编写测试(有和没有安装pandas)并相应地跳过测试,如下所示:
try:
import pandas
HAVE_PANDAS = True
except ImportError:
HAVE_PANDAS = False
import unittest
class TestClass(unittest.TestCase):
@unittest.skipUnless(HAVE_PANDAS, "requires pandas")
def tests_using_pandas(self):
# do something
@unittest.skipUnless(not HAVE_PANDAS, "doesn't require pandas")
def tests_without_pandas(self):
# do something
Run Code Online (Sandbox Code Playgroud)
但由于测试覆盖率和跳过测试的减少,我不太喜欢这个解决方案.我想对两种情况都进行测试.如果有人可以为此提出更好的替代解决方案,将会很有帮助.
例如,我有一些foo.py带有以下代码的 module( ):
import requests
def get_ip():
return requests.get('http://jsonip.com/').content
Run Code Online (Sandbox Code Playgroud)
和bar.py具有类似代码的模块:
import requests
def get_fb():
return requests.get('https://fb.com/').content
Run Code Online (Sandbox Code Playgroud)
我只是不明白为什么接下来会发生:
from mock import patch
from foo import get_ip
from bar import get_fb
with patch('foo.requests.get'):
print(get_ip())
print(get_fb())
Run Code Online (Sandbox Code Playgroud)
他们两个被嘲笑:
<MagicMock name='get().content' id='4352254472'>
<MagicMock name='get().content' id='4352254472'>
似乎只修补foo.get_ip方法with patch('foo.requests.get'),但事实并非如此。我知道我可能会bar.get_fb超出with范围进行调用,但在某些情况下,我只在上下文管理器中运行一种调用许多其他方法的方法,并且我只想requests在一个模块中进行修补。有什么办法可以解决这个问题吗?不改变模块中的导入
python python-3.x python-mock python-unittest python-unittest.mock
我有代码和测试文件:
代码.py
class Code:
def do_something_inside(self, a, b, c):
return a-b-c
def do_something(self, b, c):
self.do_something_inside(30, b, c)
Run Code Online (Sandbox Code Playgroud)
测试文件
import unittest
import unittest.mock as mock
from code import Code
class TestStringMethods(unittest.TestCase):
def setUp(self):
self.code = Code()
def do_something_inside_stub(self, a, b, c):
return a+b+c
@mock.patch('code.Code.do_something_inside', new_callable=do_something_inside_stub)
def test_add(self):
self.assertEquals(self.code.do_something(10, 5), 45)
if __name__ == '__main__':
unittest.main()
Run Code Online (Sandbox Code Playgroud)
我想使用 do_something_inside_stub 模拟 do_something_inside 方法,但执行失败:
E
======================================================================
ERROR: test_add (__main__.TestStringMethods)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/lib/python3.6/unittest/mock.py", line 1171, in patched
arg = patching.__enter__() …Run Code Online (Sandbox Code Playgroud) 我的代码如下:
import pytest
import requests
from unittest import mock
@mock.patch('requests.get')
def test_verify(mock_request):
mock_resp = mock.Mock()
mock_resp.status_code = 404
mock_request.return_value = mock_resp
r = requests.get()
with pytest.raises(requests.exceptions.HTTPError) as err_msg:
r.raise_for_status()
print(err_msg)
Run Code Online (Sandbox Code Playgroud)
由于响应的状态代码设置为 404,我预计会引发 HTTPError。但是,有一个错误说明
Failed: DID NOT RAISE <class 'requests.exceptions.HTTPError'>
Run Code Online (Sandbox Code Playgroud)
输出如下:
======================================== 测试会话开始====== ================================== 平台达尔文 -- Python 3.6.4, pytest-3.7.0, py- 1.5.2, pluggy-0.7.1 rootdir: /Users/michael/Code/youtube-data-api, inifile: plugins: requests-mock-1.5.2 收集了1个项目
temp_test.py F
[100%]==============================================失败==== ======================================================================
模拟请求 =
Run Code Online (Sandbox Code Playgroud)@mock.patch('requests.get') def test_verify(mock_request): mock_resp = mock.Mock() mock_resp.status_code = 404 mock_request.return_value = mock_resp r = requests.get() #print(r.status_code) …
我顽固地尝试将Python模块https://github.com/theatlantic/python-active-directory转换为Python3。您可以在这里查看我的工作https://github.com/nbmorgan/python-active-directory/树/母版3。
我已经弄清楚了以下几点,我可以通过以下任一方法在克隆的项目中运行测试套件:
export TEST_CONF_NAME="test.conf" ; python setup.py test
要么export TEST_CONF_NAME="../test.conf" ; python setup.py nosetests这在顶部的第一个简单测试中产生了巨大的输出。我试图使用安装程序或鼻子测试帮助中描述的多种形式的运行单项测试变体,但通常会遇到module not found错误或的某些变体test not defined。
如果有人可以将我的命令行指向我,那将使我正常运行:test_client.TestADClient.test_domains那真是太棒了。
目前,我使用的是:export TEST_CONF_NAME="../test.conf" ; python setup.py nosetests 2>&1 | cat -n | head -80 | tail -31这很俗气,但可以获取信息。
我要感谢作者的测试-这使重构的冷方法成为可能。我不是Python模块构建者,只是试图提供帮助的模块用户。
我正在尝试执行以下操作:
def test_fn(self):
cool_dict = {}
blah = Mock(spec=DictField, wraps=cool_dict)
blah['key'] = 'val'
print(cool_dict))
return False
Run Code Online (Sandbox Code Playgroud)
基本上,我想确保blaha 允许发生的任何事情DictField,但我希望发生的任何事情blah实际发生在cool_dict,因此我可以看到断言它具有某种状态。
我怎样才能做到这一点?上面的代码失败:
FAILED (errors=1)
Error
Traceback (most recent call last):
File "C:\Program Files\Python 3.5\Lib\unittest\case.py", line 59, in testPartExecutor
yield
File "C:\Program Files\Python 3.5\Lib\unittest\case.py", line 605, in run
testMethod()
File "C:\Users\danie01.AD\PycharmProjects\component\component\Default\Functional\pam_team_management\test\test_team_create.py", line 23, in test_populate_info_page
blah['key'] = 'val'
TypeError: 'Mock' object does not support item assignment
Run Code Online (Sandbox Code Playgroud)
我也尝试过MagicMock:
def test_populate_info_page(self):
cool_dict = {}
blah = …Run Code Online (Sandbox Code Playgroud) mock.Mock()使用vs 和有什么区别mock.patch()?
何时使用mock.Mock()以及何时使用mock.patch()
我读过 Mock 用于替换当前作用域中使用的内容,而 patch 用于替换在另一个作用域中导入和/或创建的内容。有人能解释一下这是什么意思吗?
python patch python-3.x python-unittest python-unittest.mock
在修补虚拟类时,我观察到不一致的行为:
class A:
def f(self, *args, **kwargs):
pass
Run Code Online (Sandbox Code Playgroud)
如果我手动修补该功能:
call_args_list = []
def mock_fn(*args, **kwargs):
call_args_list.append(mock.call(*args, **kwargs))
with mock.patch.object(A, 'f', mock_fn):
A().f(1, 2)
print(call_args_list) # [call(<__main__.A object at 0x7f0da0c08b50>, 1, 2)]
Run Code Online (Sandbox Code Playgroud)
正如预期的那样mock_fn,使用self参数 ( mock_fn(self, 1, 2)) 进行调用。
但是,如果我使用对象mock.Mock,则会以某种方式self从调用中删除参数:
mock_obj = mock.Mock()
with mock.patch.object(A, 'f', mock_obj):
A().f(1, 2)
print(mock_obj.call_args_list) # [call(1, 2)]
Run Code Online (Sandbox Code Playgroud)
这种感觉很不协调。mock_obj被称为mock_obj(self, 1, 2), 还mock_obj.call_args == call(1, 2)。它self从 中删除了参数call_args。如何访问有界方法实例?
python ×10
python-unittest ×10
python-3.x ×4
python-mock ×3
nose ×2
unit-testing ×2
generator ×1
mocking ×1
patch ×1
pytest ×1
python-3.6 ×1
setup.py ×1
testing ×1