问题描述
我正在尝试模拟一个类,该类用作进行网络调用的上下文管理器。具体来说,它的Read方法通过网络返回PLC标签的值。
这是我要在main.py
中测试的功能的示例:
from pylogix import PLC
def read_counter(counter_entry):
with PLC() as comm:
count = comm.Read(counter_entry['tag'])
if count.Status == 'Success':
log_count(count.Value)
counter_entry['last_count'] == count.Value
我的测试如下:
import unittest
from unittest.mock import Mock,patch,Magicmock
from random import randint
import main
class MockComm():
def __init__(self):
self.tag_dict = {}
def __enter__(self):
print('__enter__ called')
return self
def __exit__(self):
print('__exit__ called')
def add(self,tag,value):
print('Added ',' as ',value)
self.tag_dict[tag] = value
def Read(self,tag):
print('Reading ',tag)
if tag in self.tag_dict:
print('returned ',self.tag_dict[tag])
return Response(tag,Value=self.tag_dict[tag])
else:
print('returned Connection Failure')
return Response(tag,Value=None,Status='Connection failure')
class Response():
def __init__(self,Status='Success'):
self.TagName = tag
self.Value = Value
self.Status = Status
class ReadPylogixCounterTestSuit(unittest.TestCase):
def setUp(self):
self.counter_entry = {
'type': 'pylogix_counter','tag': 'Program:Production.DailyTotal','Part_Type_Tag': 'Stn010.PartType','Part_Type_Map': {'0': '50-4865','1': '50-5081'},# used internally to track the readings
'nextread': 0,# timestamp of the next reading
'lastcount': 0,# last counter value
'lastread': 0 # timestamp of the last read
}
@patch('main.PLC',new_callable=MockComm)
def test_read_tag(self,mock_PLC):
FirsT_COUNTER_VALUE = randint(1,2500)
mock_PLC.add(self.counter_entry['tag'],FirsT_COUNTER_VALUE)
mock_PLC.add(self.counter_entry['Part_Type_Tag'],0)
main.read_counter(self.counter_entry)
assert self.counter_entry['lastcount'] == FirsT_COUNTER_VALUE
编辑:将问题中的代码更新为完整的可运行示例。
当我逐步执行以上代码时,mock_PLC是Mock_Comm的实例。当我点击with PLC() as comm
行时,就会得到以下回溯:
=====================================================================
ERROR: test_read_tag (test_read_counter.ReadPylogixCounterTestSuit)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\cstrutto\AppData\Local\Programs\Python\python37\lib\unittest\mock.py",line 1256,in patched
return func(*args,**keywargs)
File "c:\programing\python-testing\test_context_manager\test_read_counter.py",line 81,in test_read_tag
main.read_counter(self.counter_entry)
File "c:\programing\python-testing\test_context_manager\main.py",line 4,in read_counter
with PLC() as comm:
TypeError: 'MockComm' object is not callable
----------------------------------------------------------------------
Ran 1 test in 34.908s
Failed (errors=1)
我有必需的__enter__
和__exit__
方法。为什么它不能用作上下文管理器?
解决方法
我无法像上面所做的那样替换对象,但是,我确实找到了一种在模拟对象中为Read方法设置side_effect的方法。
我仍将尝试用自己的对象替换该对象,但目前,以下代码可以正常工作:
@patch('main.PLC',autospec=True)
def test_read_tag(self,mock_PLC):
FIRST_COUNTER_VALUE = randint(1,2500)
def mock_Read(tag):
tag_dict={
self.counter_entry['tag']: FIRST_COUNTER_VALUE,self.counter_entry['Part_Type_Tag']: 0
}
print('Reading ',tag)
if tag in tag_dict:
print('returned ',tag_dict[tag])
return Response(tag,Value=tag_dict[tag])
else:
print('returned Connection Failure')
return Response(tag,Value=None,Status='Connection failure')
mock_client = MagicMock(spec=main.PLC)
mock_client.Read.side_effect = mock_Read
mock_client.__enter__.return_value = mock_client
mock_PLC.return_value = mock_client
main.read_counter(self.counter_entry)