python - 如何在python3.6中用pytest测试两个json文件
问题描述
pytest
使用python3
(3.6}+)测试以下案例的最佳方法是什么?
json_data_one = {
"id": 1,
"status": True,
"name": "Jhon"
}
json_data_two = {
"id": 2,
"status": False,
"name": "Dave"
}
def foo(json_data_one, json_data_two):
# not the best way to show this
# but i want to loop through each json data then
# show the result based on `status` is either `True` or `False`
if json_data_one["status"] == True:
return json_data_one
elif json_data_two["status"] == False:
return json_data_two
@pytest.mark.parametrize("status, name", [(True, "John"), (False, "dave")])
def test_foo(status, name):
assert foo(status) == name
以上产生错误
status = True, name = 'John'
@pytest.mark.parametrize("status, name", [(True, "John"), (False, "dave")])
def test_foo(status, name):
> assert foo(status) == name
E TypeError: foo() missing 1 required positional argument: 'json_data_two'
test_start.py:46: TypeError
___________________________________________________________________________________________ test_foo[False-dave] ___________________________________________________________________________________________
status = False, name = 'dave'
@pytest.mark.parametrize("status, name", [(True, "John"), (False, "dave")])
def test_foo(status, name):
> assert foo(status) == name
E TypeError: foo() missing 1 required positional argument: 'json_data_two'
test_start.py:46: TypeError
========================================================================================= short test summary info ==========================================================================================
FAILED test_start.py::test_foo[True-John] - TypeError: foo() missing 1 required positional argument: 'json_data_two'
FAILED test_start.py::test_foo[False-dave] - TypeError: foo() missing 1 required positional argument: 'json_data_two'
我对如何实现它有点迷茫,但我想要完成的是检查每个 json 数据,然后如果status == True
返回"name" == "John"
,但如果status == False
返回"name" == "dave"
我相信parametrize
可以使用,但我很难弄清楚。
谢谢你。
解决方案
首先,您的实际函数应该看起来像这样:
def foo(json_data):
if json_data["status"]:
return json_data["name"]
elif:
return "Nope"
我不知道您实际上想做什么,但是按原样执行的功能没有意义。当然,您必须替换您的实际功能。
然后您的测试可能如下所示:
@pytest.mark.parametrize("data, result", [(json_data_one, "John"),
(json_data_two, "Nope")])
def test_foo(data, result):
assert foo(data) == result
同样,您的实际结果肯定是另一回事,但我不明白您要做什么,所以您必须适应这一点。
推荐阅读
- java - 从依赖项加载外部资源包
- amazon-web-services - AWS API Gateway 在私有 VPC 中调用 api
- mediawiki - 无法更新用户
- c++ - 不同对象类型之间的参数传递
- react-redux - 如何使用 Jest 测试调度的反应函数
- distance - 无论高度差异如何,如何在现实世界中获得距离 bw 2 点?
- c# - ADO.NET 的 C# 并发问题并触发显式禁用
- batch-file - 批量变量
- azure-web-app-service - ASE 环境中的 BOT 可以部署在 MS Team 应用程序中吗?
- sql - 如何获得不存在的值