I have a model like this:
class Car(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4)
create_date = models.DateTimeField('date added', auto_now_add=True)
modify_date = models.DateTimeField('date modified', auto_now=True)
...
def last_tracked_location(self):
...
try:
url = 'myurl'
return requests.get(
url,
).json()['location'])
except:
return False
This method get's called later for the admin's panel. It requests something from an api and then returns either this or false.
In testing mode the other api doesn't exist so the request delays all the tests till it timeouts and then returns False
.
Is there a way to override this? I checked the docs but could only find out to override the settings.
Another idea I had was to test inside the method if it's being called in testing mode and then just never go into this try block. But I don't think this is a clean way.
UPDATE
I am calling the tests like so:
python3 manage.py test --settings=app.settings_test
You can write your tests so that they mock the response of the API. The unittest mock module is a good starting point and part of the Python standard library since Python 3.3.
I don't have access to your full code but here is an example to get you started:
from unittest import mock
from django.test import TestCase
from .models import Car
@mock.patch('yourapp.models.Car.last_tracked_location')
class CarTestCase(TestCase):
def test_get_last_tracked_location(self, mock_last_tracked_location):
mock_last_tracked_location.return_value = {'location': 'Paris'}
car = Car.objects.create()
response = car.last_tracked_location()
assert response['location'] == 'Paris'