Answer the question
In order to leave comments, you need to log in
How to check JSON key value through pytest?
Good day!
There is a specific get request that in response sends JSON with the value of exchange rates
Example of a response to a request:
{
"bankId": XXX,
"currency": "USD",
"toCurrency": "RUB",
"sellRate": 75.0,
"buyRate": 70.0,
"lastUpdated": "2021-04-03T20:55:19.4096176"
},
{
"bankId": XXX,
"currency": "EUR",
"toCurrency": "RUB",
"sellRate": 80.0,
"buyRate": 79.0,
"lastUpdated": "2021-04-03T20:55:19.4096176"
}
]
def test_bank_id(self, response, agent_id): - agent_id передается из parametrize
assert response.json()[0]['bankId'] == agent_id
def test_currency_code_EUR(self, response):
assert response.json()[1]['currency'] == 'EUR'
def test_toCurrency_code_RUB(self, response):
assert response.json()[0]['toCurrency'] == 'RUB'
def test_currency_code_USD(self, response):
> assert response.json()[X]['currency'] == 'USD'
E IndexError: list index out of range
Answer the question
In order to leave comments, you need to log in
Firstly, it is not clear why to take out field checks in separate test functions. The checks must be in the same test where the request is made.
Secondly, if the json structure is a list of objects, then these objects do not need to be accessed by a specific index.
As a result, your test can be written something like this:
def test_check_usd_rub_pair(self, agent_id):
response = rest_client.get("http//:...")
has_expected_pair = False
for obj in response.json():
assert obj.get('bankId') == agent_id
if obj.get('currency') == 'USD' and obj.get('toCurrency') == 'RUB':
has_expected_pair = True
assert has_expected_pair, "Ответ не содержит валютную пару USD-RUB"
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question