1

I am trying to get data from a fake URL. In the process, the method some_method is called and that is where it fails because the url is not valid.

I am using Pytest. How can I achieve this?

Here's my code:

models.py

class AModel(models.Model):
    name = models.CharField(max_length=233, default='default')
    url = models.URLField(blank=True, null=True)


    def some_method(self, data):
        return requests.post(url=self.url, data=data)

tests.py

def test_amodel(self, mock):
    url = 'http://www.dummyurl.com/23'
    res = self.client.post(reverse(url))
    assert res.status_code == 200
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
twingo
  • 119
  • 1
  • 8
  • See https://stackoverflow.com/questions/15753390/how-can-i-mock-requests-and-the-response. – ozs Aug 25 '21 at 13:23
  • 1
    Does this answer your question? [How can I mock requests and the response?](https://stackoverflow.com/questions/15753390/how-can-i-mock-requests-and-the-response) – Gino Mempin Aug 26 '21 at 07:20

1 Answers1

0

I solved it by using requests_mock

@requests_mock.Mocker(kw='mock')
def test_something(self, **kwargs):
    kwargs['mock'].post('http://some/url/here/')
    response = self.client.post(reverse(url))
    assert response.status_code == 200
twingo
  • 119
  • 1
  • 8