简体   繁体   English

具有request.user的Django测试功能

[英]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. 我正在尝试为Django模型中的自定义函数编写测试,并且遇到了一些问题。 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. 我正在使用pytest。

Code examples below: 下面的代码示例:

models.py - I want to test this function models.py-我要测试此功能

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 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 当我运行这些测试时,第一个测试有效,但是第二个测试显示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. 完整的回溯清楚地表明它正在测试中进入myitem.save() ,并且错误与将request.user传递到save()函数有关。

You are expecting request in model save method but it's not declared, your are not passing it even from myitem.save() , do following changes: 您期望模型save方法中的request ,但未声明该request ,即使从myitem.save()也没有传递该myitem.save() ,请执行以下更改:

in tests.py 在tests.py中

myitem.save(request=request)

in models.py 在models.py中

def save(self, *args, **kwargs):
    request = kwargs.pop('request')
    # other code

Keep in mind that save method will always requires request , probably not a good idea. 请记住, save方法将始终需要request ,可能不是一个好主意。 If you still want to stick with it then I would suggest pass user explicitly to model save method, as you are not doing anything else with the request : 如果您仍然想坚持使用它,那么我建议您将user显式传递给模型保存方法,因为您对request不做任何其他事情:

in tests.py 在tests.py中

myitem.save(user=request.user)

in models.py 在models.py中

def save(self, *args, **kwargs):
    user = kwargs.get('user')
    # other code

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM