How can we confirm sleeping time in Loop Operation at Pytest?

Question:

We’d like to confirm if the job was sure to wait during the loop operation as expected, in the Pytest.
We set the sleep time as 30 sec in 3 times loop — we expect and testify the total waiting time would be 90 sec in Pytest as below.

-- Loop.py
class Loop
    
    def LoopJob(self, job_id, date, subject, fromDate, toDate):

        for error_count in range(3):
            try:
                request_url = 'http://' + self.hostname + '/samplejob'
                headers = {'content-type': 'application/json'}
                response = requests.post(request_url, data=json.dumps(payload), timeout=self.timeout, headers=headers)

            if response is None:
                time.sleep(30)
            else:
                break

        if response is None or response.status_code != 202:
            error_message = "error message on parent method"
            raise CommunicationError(error_message)

        return response

I think we can testify about the loop times using "request_history" like below, but no idea about how to assert waiting time in pytest.

-- Pytest.py
def test_looptimes(monkeypatch, requests_mock):

monkeypatch.setenv('ENV_ID', 'Local')
headers = {'content-type': 'application/json'}
mock_response = [
    {'json': {'status': None}, 'status_code': None},
    {'json': {'status': None}, 'status_code': None},
    {'json': {'status': None}, 'status_code': None},
    {'json': {'status': None}, 'status_code': None}
]
requests_mock.post("http://localhost:8080/samplejob", headers=headers, json=mock_response)
...
history = requests_mock.request_history
assert len(history) == 3
assert history[0].url == 'http://localhost:8080/samplejob'
assert history[1].url == 'http://localhost:8080/samplejob'
assert history[2].url == 'http://localhost:8080/samplejob'

If you have any good idea or example, please let us know.
Thank you in advance.

Asked By: Sachiko

||

Answers:

You can mock the sleep method just like any other method, then you can assert the calls made to it.

For a simple example, if my module sleeping_beauty.py looks like this:

import time


def wait_for_my_hero():
    time.sleep(15)
    time.sleep(30)
    time.sleep(45)

The test would be (using pytest-mock):

from sleeping_beauty import wait_for_my_hero

from mock import call


def test_wait_for_my_hero(mocker):
    my_sleep_mock = mocker.patch("sleeping_beauty.time.sleep")
    wait_for_my_hero()

    assert 3 == my_sleep_mock.call_count
    my_sleep_mock.assert_has_calls(calls=[call(15), call(30), call(45)])

Another benefit of mocking the sleep method is that your tests would be much faster – it won’t take 90 seconds to complete, but rather a fraction of a second.

Answered By: Peter K
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.