我想为从串行端口读取 unicode 文本字符串的 Python 3 方法创建单元测试。我想测试该方法对各种字符串的响应。我要模拟的代码行是:
comm_buffer = serial_port.readline().decode("utf-8").strip()
Run Code Online (Sandbox Code Playgroud)
其中“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 …Run Code Online (Sandbox Code Playgroud)