I am trying to automate some API endpoints, but the JSON response is an array of data. How can I assert a specific user with all his data inside that JSON array?
I am trying with:
assert {
"user": "test1",
"userName": "John Berner",
"userid": "1"
} in response.json()
The JSON response is:
{
"data": [
{
"user": "test1",
"userName": "John Berner",
"userid": "1"
},
{
"user": "test2",
"userName": "Nick Morris",
"userid": "2"
}
],
"metadata": {
"current_page": 1,
"pages": 1,
"per_page": 100,
"total": 2
}
}
CodePudding user response:
Please try like this:
You can use loop over the data
within any to perform this check.
contents = json.loads(apiresponse_data)
assert any(i['user'] == 'test1' for i in contents['data'])
CodePudding user response:
If all the fields are in the response are part of your user_info
you can do what you are thinking of doing -
# response = json.loads(api_response_data)
response = {
"data": [
{
"user": "test1",
"userName": "John Berner",
"userid": "1"
},
{
"user": "test2",
"userName": "Nick Morris",
"userid": "2"
}
],
"metadata": {
"current_page": 1,
"pages": 1,
"per_page": 100,
"total": 2
}
}
user_info = {
"user": "test1",
"userName": "John Berner",
"userid": "1"
}
assert user_info in response['data']
Above doesn't raise AssertionError
because the user_info
is there in the response['data']
You can also use following if you have decoded the json response already -
assert {
"user": "test1",
"userName": "John Berner",
"userid": "1"
} in response['data']