【发布时间】:2013-07-21 06:28:44
【问题描述】:
我有一个名为 get_account(param1,param2) 的函数 在运行时我需要用函数 mock_get_account(param1,param2) 替换这个函数 所以当系统调用 get_account(param1,param2) 我需要调用 mock_get_account(param1,param2) 来代替。
我试过这段代码: package.get_account=self.mock_get_account package.get_account(x,y) 但仍然运行 get_account 而不是 mock_get_account 我是 python 新手,我什至不知道这是否可能,但我已经看到了 lamda 函数,我知道函数编程在 python 中是可能的。谢谢 编辑: 如果我执行以下操作:
package.get_account=self.mock_get_account
package.get_account(x,y)
然后一切正常,这意味着调用了 mock_get_account,但是在 mu 代码中我下面的代码我做了一个 post self.client.post(url, data=data, follow=True) 触发 package.get_account 和这不起作用:
package.get_account=self.mock_get_account
package.get_account(x,y)
#the folowing call will trigger the package.get_account(x,y) function in a django url #callback
self.client.post(url, data=data, follow=True)
意味着它调用旧函数,get_account(param1,param2) 也定义在文件中,不是类的子函数,mock_get_account(self,param1,param2) 定义在类 Test 中并且是在 Test.test_account 内部调用 - 函数
【问题讨论】:
-
您所描述的应该可以正常工作。请给我们实际的代码和结果。
-
你能贴出一些实际的代码吗?像这样的猴子补丁在许多分布式包中使用,所以如果正确完成它确实可以工作。
-
如果我执行以下操作: package.get_account=self.mock_get_account package.get_account(x,y) 然后运行 package.get_account 一切正常,在下面的代码中我会发布自我。触发 package.get_account 的 client.post(url, data=data, follow=True) 并且这不起作用,这意味着它打印旧函数,并且 get_account(param1,param2) 在文件中定义,而不是类的子函数和 mock_get_account(self,param1,param2) 在类 Test 中定义,并在 Test.test_account - 函数中调用
标签: python lambda functional-programming mocking