def do_stuff(self): # get a new instance of A a = get_a() while True: a.update() if a.state == 'state': break
这个类的简单版本(我无法更改类,因为它是第三方库):
class A(object): def __init__(self): self.state = '' def update(self): # call to external system self.state = extern_func()
现在我想通过模拟类A来测试我的函数do_stuff().为了测试函数的每个方面,我想拥有所有不同的状态值,并且它应该在每次调用a.update()之后改变(迭代不同的状态).
我开始使用这个设置进行单元测试:
from mock import Mock,patchimport unittestclass TestClass(unittest.TestClass): @patch('get_a') def test_do_stuff(self,mock_get_a): mock_a = Mock(spec=A) mock_get_a.return_value = mock_a # do some assertions
我能用Mock实现这种行为吗?
我知道Mock有sIDe_effect为连续的函数调用返回不同的值.但是我无法找到一种方法来在函数调用后更改实例变量的值?
from mock import Mock,Magicmock,patchsep = '***********************\n'# non-mock mocksdef get_a(): return A()def extern_func(): return 'foo'def do_stuff(self): # get a new instance of A a = get_a() while True: a.update() print a.state if a.state == 'state': breakclass A(object): def __init__(self): self.state = '' def update(self): # call to external system self.state = extern_func()
正如@Simeon Viser所提到的,模拟extern_func会起作用:
print sep,'patch extern'mock = Magicmock(sIDe_effect = [1,2,3,4,'state'])@patch('__main__.extern_func',mock)def foo(): do_stuff(3)foo()>>> ***********************patch extern1234state
sIDe_effect可以是一个函数,您可以使用auto_spec = True参数模拟未绑定的方法A.update.
使用上下文管理器:
print sep,'patch update context manager call do_stuff'def update_mock(self): self.state = mock()mock = Magicmock(sIDe_effect = [1,'state'])with patch.object(A,'update',autospec = True) as mock_update: mock_update.sIDe_effect = update_mock do_stuff(3)>>>***********************patch update context manager call do_stuff1234state
使用装饰者:
print sep,'patch update decorator test_do_stuff'def update_mock(self): self.state = mock()mock = Magicmock(sIDe_effect = [1,'state'])@patch.object(A,autospec = True,sIDe_effect = update_mock)def test_do_stuff(self): do_stuff(3)test_do_stuff()>>>***********************patch update decorator test_do_stuff1234state
警告:我从来没有编写过全面的单元测试,而且最近才开始阅读模拟文档,所以尽管我似乎完成了这项工作,但我无法评论它在你的测试方案中的功效.编辑欢迎.
总结以上是内存溢出为你收集整理的模拟一个在方法调用后更改实例变量的python类?全部内容,希望文章能够帮你解决模拟一个在方法调用后更改实例变量的python类?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)