简体   繁体   English

在python中模拟成员对象方法

[英]Mocking member object methods in python

I want to mock the read and write functions of the Serial object from pyserial, which is used inside my class, to check for call arguments and edit the return values, but it doesn't seem to work. 我想从pyserial中模拟Serial对象的读取和写入功能,该类用于我的类中,以检查调用参数并编辑返回值,但这似乎不起作用。

Currently I have a file 'serialdevice.py', like this: 当前,我有一个文件“ serialdevice.py”,如下所示:

import serial

class SerialDevice:
    def __init__(self):
        self._serial = serial.Serial(port='someport')

    def readwrite(self, msg):
        self._serial.write(msg)
        return self._serial.read(1024)

Then I have a file 'test_serialdevice.py', like this: 然后,我有一个文件“ test_serialdevice.py”,如下所示:

import mock
from serialdevice import SerialDevice

@mock.patch('serialdevice.serial.Serial.read')
@mock.patch('serialdevice.serial.Serial.write')
@mock.patch('serialdevice.serial.Serial')
def test_write(mock_serial, mock_write, mock_read):
    mock_read.return_value='hello'
    sd = SerialDevice()
    resp = sd.readwrite('test')

    mock_write.assert_called_once_with('test')
    assert resp == 'hello'

But both asserts fail. 但是两个断言都失败了。 Somehow the mock_write is not called with the argument 'test' and the write method returns a mock object instead of the 'hello' string. 不知何故,mock_write不会用参数'test'调用,并且write方法返回一个模拟对象而不是'hello'字符串。 I've also tried using @patch('serial.Serial.write) etc. with the same results. 我也尝试过使用@patch('serial.Serial.write)等获得相同的结果。 Also using the return objects of mock_serial , so eg mock_read = mock_serial.read() does not seem to work. 还使用了mock_serial的返回对象,因此,例如mock_read = mock_serial.read()似乎不起作用。

The constructor, ie mock_serial , does seem to be called with the expected arguments however. mock_serial ,似乎使用预期的参数调用了构造函数,即mock_serial

How can I achieve what I want in this case? 在这种情况下如何实现我想要的?

The python version is 2.7.9 python版本是2.7.9

Apparently you have to use the return value of the mock_serial object as the instance returned by the constructor, so something like 显然,您必须使用mock_serial对象的返回值作为构造函数返回的实例,所以类似

mock_serial.return_value.read.return_value = 'hello'

This works, but I still wonder if there is a better way to do this 这可行,但是我仍然想知道是否有更好的方法可以做到这一点

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM