我的目标是为与设备上的闪存接口的REST API编写单元测试。为此,我需要一种方法来模拟与闪存接口的类。
我试图通过在Mock中使用Python Dataclass来做到这一点,但我发现没有任何方法可以在每次测试之前设置初始值。因此,每个测试用例都会获得由上一个测试用例设置的值。我需要解决这个问题。
为了测试API,我使用了以下代码:
@dataclass
class FlashMemoryMock:
mac_address: str = 'ff:ff:ff:ff:ff:ff'
@pytest.fixture
def client(mocker):
mocker.patch('manufacturing_api.bsp.flash_memory.FlashMemory', new=FlashMemoryMock)
app = connexion.App(__name__, specification_dir='../openapi_server/openapi/')
app.app.json_encoder = JSONEncoder
app.add_api('openapi.yaml', pythonic_params=True)
app.app.config['TESTING'] = True
with app.app.test_client() as client:
yield client
def test_get_mac_address(client):
"""Test case for get_mac_address
Get the MAC Address
"""
headers = {
'Accept': 'application/json',
}
response = client.open(
'/mac_address',
method='GET',
headers=headers)
assert response.status_code == 200
assert response.is_json
assert response.json.get('status') == 'success'
assert response.json.get('mac_address') == 'ff:ff:ff:ff:ff:ff'这个测试用例将通过,因为FlashMemoryMock数据类将mac_address初始化为ff:ff:ff:ff:ff:ff。不幸的是,如果我在一个test_put_mac_address测试用例之后运行它,并且该测试更改了mac_address的值,那么它将失败。
闪存控制器代码如下所示:
flash_memory = FlashMemoryWrapper()
def get_mac_address(): # noqa: E501
return flash_memory.get_mac_address()FlashMemoryWrapper类验证输入(即用户是否尝试设置有效的Mac地址),并包括以下代码:
class FlashMemoryWrapper:
def __init__(self):
# Initialize the Flash controller
self.flash_memory = FlashMemory()我正在尝试用一个模拟来替换这个FlashMemory类。当我调试测试用例时,我已经验证了FlashMemoryWrapper.flash_memory是否引用了FlashMemoryMock。不幸的是,我再也没有办法在FlashMemoryMock数据类中设置初始值了。
有没有办法设置初始值?或者我应该用一种不同的方式设置Mock?
发布于 2020-11-21 03:49:46
我认为你正在寻找的东西可以通过一些元编程和fixture的参数化来实现。
def initializer(arg):
@dataclass
class FlashMemoryMock:
mac_address: str = arg
return FlashMemoryMock
@pytest.fixture
def client(mocker, request):
mocker.patch('manufacturing_api.bsp.flash_memory.FlashMemory', new=initializer(request.param))
app = connexion.App(__name__, specification_dir='../openapi_server/openapi/')
app.app.json_encoder = JSONEncoder
app.add_api('openapi.yaml', pythonic_params=True)
app.app.config['TESTING'] = True
with app.app.test_client() as client:
yield client
@pytest.mark.parametrize('client', ['ff:ff:ff:ff:ff:ff'], indirect=['client'])
def test_get_mac_address(client):
"""Test case for get_mac_address
Get the MAC Address
"""
headers = {
'Accept': 'application/json',
}
response = client.open(
'/mac_address',
method='GET',
headers=headers)
assert response.status_code == 200
assert response.is_json
assert response.json.get('status') == 'success'
assert response.json.get('mac_address') == 'ff:ff:ff:ff:ff:ff'
# some other test with a different value for mac address
@pytest.mark.parametrize('client', ['ab:cc:dd'], indirect=['client'])
def test_put_mac_address(client):
# some code herehttps://stackoverflow.com/questions/64915733
复制相似问题