我想从串行端口读取一个多行字符串,然后将其与reference.txt文件逐行比较。compare函数本身使用了第二个.txt文件,我在其中定义了应该对每一行执行的操作(例如1:1 diff或比较具有容差的值(——我的id文件。
对于这一行一行的事情,我用一个行参数化了test_function。所以我可以断言每一行。现在的问题是,每次我的fixture被再次调用时,读取串行端口都需要一些时间
有没有比我目前的解决方法更顺畅的方法?
#test_class.py
import pytest
import serial
buffered_port_readback = []
@pytest.mark.basic
@pytest.mark.parametrize("line", range(8))
def test_portname_command(fix_port_readback, fix_port_reference, fix_port_ids, line):
if (line == 0):
get_port_readback(fix_port_readback)
port_compare(fix_port_reference[line], fix_port_ids[line], buffered_port_readback[line])
#conftest.py
import pytest
import serial
import os
import datetime
import socket
import subprocess
import sys
@pytest.fixture(scope="function")
def fix_port_readback(request, fix_port_command, fix_port, line):
if(line == 0):
fix_port.reset_input_buffer()
fix_port.write(fix_port_command)
readback = fix_port.read_until(b'usb>')
readback_decode = readback.decode("utf-8")
readback_lines = readback_decode.split("n")
new_readback_lines = []
for entry in readback_lines:
mod_entry = entry.replace('r', '')
new_readback_lines.append(mod_entry)
return new_readback_lines
正如您所看到的,我目前的解决方法是只在第一个循环中读取端口,确保行==0并将其保存在缓冲区中。我认为这不是最好的方法。
最简单的可能是增加固定装置的范围,粒度有点有限(类、模块、包和会话(,但如果它有效。。。。
一个相关的替代方案是让函数fixture依赖于一个更大的"缓存"fixture并检查请求,这样它就可以检查请求者的属性,并创建一个新值或从缓存中获取一个值。
最后,"大锤子"是通过插入pytest_fixture_setup
或pytest_generate_tests
之类的东西来动态生成夹具结果,然后在运行中做任何你想做的事情。