python - 如何使用 Python 3 单元测试模拟模拟来自串行端口的数据?

标签 python unit-testing mocking

我想为从串行端口读取 unicode 文本字符串的 Python 3 方法创建单元测试。我想测试该方法对各种字符串的响应。我想要模拟的代码行是:

comm_buffer = serial_port.readline().decode("utf-8").strip()

其中“serial_port”是传递给该方法的串行端口的实例。我想使用unittest.mock模块将comm_buffer变量设置为unicode字符串,但是我一整天都在努力没有成功。我第一次尝试使用模拟,但我已经超出了我的能力范围。

整个方法的代码为:

def wait_for_data(serial_port, comm_flag = ""):
"""Read lines of data from the serial_port

Receives optional comm_flag (single character to check for at beginning of string)"""
logging.debug("Start wait_for_data  " + comm_flag)
timeout_count = 0
while True:
    # Get a line from the buffer and convert to string and strip line feed
    logging.debug("Waiting for data…")
    comm_buffer = serial_port.readline().decode("utf-8").strip()
    if len(comm_buffer) == 0:
        timeout_count += 1
        logging.warning("Serial port timeout - no data received. Timeout count = " + str(timeout_count))
        if timeout_count > 10:
            raise TimeoutError(["Too many timeouts"])
    # If no id character was specified, just return the string
    elif comm_flag == "":
        logging.debug("Returning no comm_flag")
        return comm_buffer
    # If an id character was specified, return the string if it's present (strip id), otherwise wait for another string
    elif comm_buffer[0] == comm_flag:
        logging.debug("Returning with comm_flag")
        return comm_buffer[1:]

最佳答案

Serial_port 不是串行端口的实例,而是具有 readline() 方法的对象。因此,不要关心诸如串行端口之类的东西,您的模拟对象是一个具有 readline() 方法的对象,该方法提供您想要测试的值类型。 所以你只需要创建类似的东西:

port = Mock()
port.readline = Mock(return_value="my string")

这是您调用的第一个参数。 因此,如果我将您的函数复制到名为 test.port 的模块中,则此测试是可以的:

class TestWaitData(unittest.TestCase):

    def testFunc(self):
        port = mock.Mock()
        port.readline = mock.Mock(return_value="my string".encode('utf-8')) # as you use a decode call

        self.assertEqual(test.port.wait_for_data(port), "my string")

    def testBufferEmpty(self):
        port = mock.Mock()
        port.readline = mock.Mock(return_value="".encode('utf-8'))

        with self.assertRaises(TimeoutError):
            test.port.wait_for_data(port)

    def testWithFlag(self):
        port = mock.Mock()
        port.readline = mock.Mock(return_value="fmy string".encode('utf-8'))

        self.assertEqual(test.port.wait_for_data(port, 'f'), "my string")

关于python - 如何使用 Python 3 单元测试模拟模拟来自串行端口的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46492209/

相关文章:

python - 为文件系统上的每个文件创建哈希

python - [姓名标记、标记表中的标记] 的目的是什么

c# - 暂时设置DbContext的CommandTimeout

.net - 任何类似 JMockit 的 .net 框架,它甚至可以模拟静态类、私有(private)方法等

python - 遍历字典并获取键

java - 在 JUnit 测试类中使用随机值

javascript - 如何使用 mocha 和 rewire 模拟 Node.js 单元测试中的 Q 方法?

java - Scala 如何将模拟对象注入(inject) ScalatraFlatSpec

spring - 使用 Junit 和 EasyMock 对具有 Autowiring 符号的类进行单元测试?

python - 语法错误无法找出原因