Search code examples
djangopostdjango-testing

Django test client post data


The problem has been solved thanks to Thaian, by adding a login to the beginning of the 'test_create' function, as you need to be logged in on this site to use the createview

I am currently writing a test for a createview and I am unable to post data to it.

The object being tested has the following model

class Role(models.Model):
    name = models.CharField(max_length=255)
    linked_tenant = models.ForeignKey(Tenant, blank=True, null=True)

And is used in the following (generic) view

class RolCreate(TenantRootedMixin, CreateView):
    model = RolTemplate
    form_class = RoleForm

    def get_form_kwargs(self):
        kwargs = super(RolCreate, self).get_form_kwargs()
        kwargs['linked_tenant'] = self.request.tenant
        return kwargs

    def form_valid(self, form):
        form.instance.linked_tenant = self.kwargs.get('tenant')
        return super(RolCreate, self).form_valid(form)

    def get_success_url(self, **kwargs):
        return reverse('rol_list', args=[self.request.tenant.slug])

And this is the test that I am using.

class RolCreate_tests(TestCase):

    def setUp(self):
        self.tenant = get_tenant()
        self.role = get_role(self.tenant)
        self.client = Client(HTTP_HOST='tc.tc:8000')
        self.user = get_user(self.tenant)

    def test_create(self):

        response = self.client.post(reverse('rolcreate'), {'name' : 'new_object'})
        self.assertEqual(response.status_code, 302)
        test_against = Role.objects.get(name='new_object')
        self.assertEqual(test_against, self.tenant)

The assertion that throws the error is the 'get' request at the end.

DoesNotExist: Role matching query does not exist.

So the object is not created, yet the test does validate the 302 view, meaning a post is being made. I do not understand why this test is failing to do what it should. Could someone here help me?

=====

After Thaians suggestions I got the following values:

(Pdb) print(self.client.post)
<bound method Client.post of <django.test.client.Client object at     0x10f20da50>>

Pdb) response
<HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/accounts/login/?next=/my/role/create/">
(Pdb) print(response)
Vary: Cookie
Content-Length: 0
Content-Type: text/html; charset=utf-8
Location: /accounts/login/?next=/my/role/create/

Solution

  • Did you print response and check what return maybe?

    Good idea is to run tests with PDB.

    def test_create(self):
    
            response = self.client.post(reverse('rolcreate'), {'name': 'new_object'})
            import pdb; pdb.set_trace()
            self.assertEqual(response.status_code, 302)
            test_against = Role.objects.get(name='new_object')
            self.assertEqual(test_against, self.tenant)
    

    add import pdb;pdb.set_trace() in your test and then check self.client.post().

    So please paste what response contain.