mercredi 31 janvier 2018

Django Test Not Getting Model Object

I am just scratching the surface of testing in Django. Here is my testing code, inside tests.py:

class AdvertisingTests( TestCase ):

    def test_get_ad( self ):
        '''
        Test if the get ad feature is working, should always load an ad
        '''
        url = reverse('advertising:get_ad')
        response = self.client.get( url )
        self.assertEqual(response.status_code, 200)

This test is just a basic test of a view that should return an Ad. Here is the view code:

from .models import Ad, Impression

def get_ad(request):
    FirstAd = Ad.objects.first()

    # +1 impression
    Impression.objects.create(ad = FirstAd)

    import json
    data = { 'url': FirstAd.url, 'image_url': FirstAd.image.url, 'title': FirstAd.title, 'desc': FirstAd.desc }
    json_data = json.dumps( data )
    return HttpResponse(json_data, content_type='application/json')

I am working in a heroku local environment, so I run the tests like this: heroku local:run python manage.py test advertising

And this test fails, coming from the Impression.objects.create(ad = FirstAd) line:

ValueError: Cannot assign None: "Impression.ad" does not allow null values.

What that tells me is that the FirstAd object is null. OK so I wind up the local shell like this: heroku local:run python manage.py shell to double check. Replicating that code there are no errors:

In [2]: from advertising.models import Ad, Impression

In [3]: print Ad.objects.first()
Flamingo T-Shirt Corporation

In [4]: FirstAd = Ad.objects.first()

In [5]: Impression.objects.create(ad = FirstAd)
Out[5]: <Impression: Impression object>

In [6]: exit()

So I am a little bit stuck. It seems like the tester is accessing an empty database. Is this the correct and desired functionality of the testing suite?

THANKS!

Aucun commentaire:

Enregistrer un commentaire