jeudi 30 novembre 2017

Django testing function with request.user

I'm trying to write a test for a custom function in my Django model and having some issues. The function works correctly tested manually so this is a test code issue. I have read all the related questions on this but they have not solved my problem. I am using pytest. Code examples below:

models.py - I want to test this function

def save(self, *args, **kwargs):
    if self.in_progress:
        MyModel.objects.filter(user=request.user, flag=True).update(flag=False)
    super(MyModel, self).save(*args, **kwargs)

tests.py

class MyTest(TestCase):

    def setUp(self):
        self.factory = RequestFactory()
        self.user = UserFactory.create()

    def test_that_works(self):
        request = self.factory.get('/mypage/')
        request.user = self.user
        response = my_view(request)
        self.assertEqual(response.status_code, 200)

    def test_that_doesnt_work(self):
        request = self.factory.get('/')
        request.user = self.user
        myitem = MyModelFactory.create()
        myitem.flag = True
        myitem.save()
        assert myitem.flag is True

When I run these tests, the first test works, but the second says NameError: global name 'request' is not defined

The full traceback makes it clear that it is getting to myitem.save() in the test and the error is something to do with passing the request.user into the save() function.

Can anyone help please?

Aucun commentaire:

Enregistrer un commentaire