D
D
Dmitry2021-04-04 00:50:50
Python
Dmitry, 2021-04-04 00:50:50

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"
  }
]

and to write a correct test, you need to check the currency and toCurrency values ​​for these currency pairs, I could do the correctness of getting 1 pair of currencies and bankId, but it's not clear how to get the assert of the second pair

A piece of code that passes the test
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'


For USD-RUB, an error like
def test_currency_code_USD(self, response):
>       assert response.json()[X]['currency'] == 'USD'
E       IndexError: list index out of range


At the same time, as you can see from the answer, the USD-RUB pair comes first in JSON, i.e. according to my version, lines 1 and 0 should be USD and RUB, respectively.

Question - how to check the second part of the answer?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
taktik, 2021-04-04
@Foxitovsky

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"

I also recommend attaching some json validator to your tests. Validating fields is important

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question