PYTEST:UNITSEST错误对象没有属性' assert_called_once_with
我正在用pytest编写单元测试,并在assert_called_once_with上获得错误。 我厌倦了使用Pytest文档中所示的相同方式,但似乎我缺少一些东西。
# Class which I am trying to mock. (./src/Trading.py)
class BaseTrade:
def __init__(self, name):
self.name = name
class Trade(BaseTrade):
def __init__ (self, name):
BaseTrade.__init__(self, name)
def get_balance(self, value):
# do calculation and return some value
# for demo purpose hard-coding it
return value * 10
#unit test (./unitest/test_test.py
import mock
import unittest
import sys
sys.path.append("../src")
import Trading
class TestTradeClass(unittest.TestCase):
@classmethod
def setUpClass(self):
self.expected_balance = 100
@classmethod
def tearDownClass(self):
pass
def test_trade(self):
with mock.patch.object(Trading.Trade, 'get_balance', new = lambda self, x: (x * 10) ) as mock_method:
obj = Trading.Trade("AAPL")
value = obj.get_balance(10)
assert value == 100
mock_method.assert_called_once_with(100)
Error on mock_method.assert_called_once_with(100)
AttributeError: 'function' object has no attribute 'assert_called_once_with'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我现在相信您想要 side_effect 。这怎么样?一个文件,假设
test.py
:chmod +x test.py
./ test.py
输出:
说明:
side> side_fect < /code>而不是
新
trade.trade
@classmethod
使用cls
而不是self
。MOCK_METHOD.ASSERT_CALLED_ONCE_WITH(10)
,ASside_feft
关心通过obj.get_balance(10)
和存在以更改输出的值。更近?如果没有,您可以澄清您要嘲笑什么?
I'm now of the belief you want
side_effect
. How is this? One file, assumetest.py
:chmod +x test.py
./test.py
Output:
Explanation:
side_effect
instead ofnew
Trading.Trade
@classmethod
to usecls
and notself
.mock_method.assert_called_once_with(10)
, asside_effect
cares about the value passed viaobj.get_balance(10)
and exists to alter the output.Closer? If not can you clarify what you're trying to mock?
这并不容易,但是如果
trade.trade.get_method()
实际上是一种香草功能,而不是一种方法 - 您可能需要unittest.mock.create_autospec()
是否有任何帮助?
'function'对象没有属性'assert_called_once_with'
不清楚whaat
trade.trade.trade.trade
是。如果偶然,
交易
是一个具有self.trade = Trade(...)
内部的类,您的问题将大不相同。然后,您需要进行更深入的修补trade.get_method
。您可能想从同一模块中导入交易
类交易使用它(例如,从.trading Import Trading,Trade Trade ) - 不是从其中trade
从 - 然后修补trade.get_method
。It's not easy to tell, but if
Trading.Trade.get_method()
is actually a vanilla function and not a method - you may needunittest.mock.create_autospec()
Are any of these of assistance?
'function' object has no attribute 'assert_called_once_with'
It's not clear whaat
Trading.Trade
is.If by chance,
Trading
is a class that has aself.trade = Trade(...)
inside, your question would be substantially different. You'd need to get in deeper, patchingTrade.get_method
, then. You'd likely want to importTrade
from the same moduleclass Trading
uses it (e.g.from .trading import Trading, Trade
) - not from whereTrade
is declared from - then patch theTrade.get_method
.