S
S
Sergey Nizhny Novgorod2016-08-09 02:55:34
Django
Sergey Nizhny Novgorod, 2016-08-09 02:55:34

How to mock a model (queryset) in django?

Hello.
I use the standard library: django.test and unittest.mock, I want to check the following point:

class Dynamical_Pages(TestCase):
    def test_advertisement(self):
        response = self.client.get('/advertisement')
        self.assertEqual(response.status_code, 200)

Those. I check if this page is working or not.
When I try to run I get an error like:
File "C:\python35\lib\site-packages\django\db\models\query.py", line 387, in get
    self.model._meta.object_name
faceset.models.DoesNotExist: Banner matching query does not exist.

Those. swears that there is no data from the Banner model.
Tell me, please, how can the model get wet? So that the test stops swearing at him?
Banner Model
class Banner(models.Model):
    bancode = models.TextField()
    banlink = models.TextField()
    banimg = models.ImageField()

________________________________
As the guys suggested, I tried factory-boy:
from django.test import TestCase
from django.test import Client
import factory
from faceset.models import Banner

#factory_boy data

class BannerFactory(factory.Factory):
    class Meta:
        model = Banner

    bancode = 'test_code_for_deploy'
    banlink = 'test_link_for_deploy'
    banimg = ''

class Dynamic_pages(TestCase):

    def test_upmenu(self):
        Banner = BannerFactory.create()
        response = self.client.get('/upmenu')
        self.assertEqual(response.status_code, 200)

I get the same error, am I using it the wrong way? If you pass data to Banner.objects.create(...), then it works. How to use factorial?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
U
un1t, 2016-08-09
@Terras

It is necessary to create test objects before executing the get request in the test.

def test_advertisement(self):
        Banner.objects.create()
        response = self.client.get('/advertisement')
        self.assertEqual(response.status_code, 200)

It is better to immediately take factory-boy for this.

I
Ilya, 2016-08-09
@FireGM

Tests require a separate test database.
https://docs.djangoproject.com/en/1.10/topics/test...
https://docs.djangoproject.com/en/1.10/topics/test...

J
John, 2016-08-09
Doe

Add entries to the database from the setUp method manually. There is no data because the base is used by another, test

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question