我必须测试从远程API获取数据的解析器的行为。数据是分页的,这意味着我收到一个JSON,其中包含关于当前页面和最后一页的元信息。因此,我想用不同的数据页来测试解析器。
import unittest
from unittest.mock import patch
def load():
file_name = f"plants_info_{load.counter}.json"
print(file_name)
with open(f"./{file_name}", "r") as file:
data = json.load(file)
load.counter += 1
return (data['data'], data['meta'])
load.counter = 1
class TestCase(unittest.TestCase):
backend = Backend()
@patch.object(backend, "get_info", side_effect=load())
def test_get_info(self, nothing):
"""Testing get_stations"""
data = self.backend.get_stations(community_id=1)
# doing asserts...
backend.get_stations_info的函数如下:def get_stations_info(community_id=0(:第1页植物,meta=self.get_info(url=url,字段="数据"(
while meta["current_page"] < meta["last_page"]:
page += 1
_, meta = self.get_info(params={"page": page})
....
而打补丁/模拟的函数get_info应该返回一个简单的JSON结构。
我有两个问题:
1-load函数返回最后一个值,即文件plants_info_2.json的内容。同时,我会在不同的调用中获得不同的文件:
2-如果我去掉";什么都没有";来自def test_get_info(self, nothing)
的变量TypeError: TestCase.test_get_stations_info() takes 1 positional argument but 2 were given
只需更改调用即可:
@patch.object(backend, "get_info", side_effect=load())
至
@patch.object(backend, "get_info", side_effect=load)