簡體   English   中英

如何使用Python 3 unittest模擬從串行端口模擬數據?

[英]How to emulate data from a serial port using Python 3 unittest mocks?

我想為從串行端口讀取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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM