Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing external URLs in Django

I'm currently having a hard time getting some of my Django tests to work. What I'm trying to do is test if a given URL (the REST API I want to consume) is up and running (returning status code 200) and later on if it's responding the expected values. However, all I get returned is a status code 404 (Page not found), even though the URL is definitely the right one. (Tried the exact string in my browser)

This is the code:

from django.test import TestCase


class RestTest(TestCase):
    def test_api_test_endpoint(self):
        response = self.client.get("http://ip.to.my.api:8181/test/")
        self.assertEqual(response.status_code, 200, "Status code not equals 200")

It always returns a 404 instead of a 200... Anyone knows what I do wrong here?

like image 964
0ctar Avatar asked Dec 05 '25 03:12

0ctar


1 Answers

self.client is not a real HTTP client; it's the Django test client, which simulates requests to your own app for the purposes of testing. It doesn't make HTTP requests, and it only accepts a path, not a full URL.

If you really needed to check that an external URL was up, you would need a proper HTTP client like requests. However this doesn't seem to be an appropriate thing to do in a test case, since it depends on an external API; if that API went down, suddenly your tests would fail, which seems odd. This could be something that you do in a monitoring job, but not in a test.

like image 159
Daniel Roseman Avatar answered Dec 07 '25 16:12

Daniel Roseman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!