I have this view that I want to test

def change_item(request):
    name_change = request.POST.get('name_change')
    cost_change = request.POST.get('cost_change')
    category_change = request.POST.get('category_change')
    product_id = request.POST.get('product_id')
    category_name = Category.objects.get(name = category_change)
    product = Product.objects.get(id__exact = product_id)
    product.name = name_change
    product.category = category_name
    product.price = cost_change
    product.save()
    return HttpResponse()

And I wrote a test for It,but it doesn't work (I want to test request)

from django.test import RequestFactory
from django.test import TestCase
from views import change_item
from models import Product
from django.utils import unittest


class TestChange_item(TestCase):
    def setUp(self):
        self.factory = RequestFactory()

    def change_item_test(self):
        # Create an instance of a GET request.
        request = self.factory.get('main/views')
        # Test my_view() as if it were deployed at /customer/details
        response = change_item(request)
        self.assertEqual(response.status_code, 200)

When I run it I get this in console

ERROR: change_item_test (src.main.tests.TestChange_item)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/volodia/work/shopping-helper/src/main/tests.py", line 19, in change_item_test
response = change_item(request)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/decorators.py", line 24, in _wrapped_view
if test_func(request.user):
AttributeError: 'WSGIRequest' object has no attribute 'user'

----------------------------------------------------------------------
Ran 1 test in 0.002s

FAILED (errors=1)

What can I do with it ? Or there is some different way of testing requests ?

有帮助吗?

解决方案

If you look at the documentation you will see that you need to manually add a user to the request. It doesn't do this for you automatically.

def change_item_test(self):
    request = self.factory.get('main/views')
    request.user = User.objects.create_user(username="bobalong")

Adding a user like this simulates making a logged in request. If this is NOT what you want then you should create an AnonymousUser instead. In general the error you were getting should provide you with everything you need to know. It is explicitly telling you that the test is failing because the request doesn't have a user. Adding a real user or adding a mock user object to the request is the answer.

Also, you seem to be testing a view that will only work with a POST request. It's going to fail because request.POST does not have the correct dictionary keys. You can create a POST request by doing

factory.post('main/views', {'name_change': 'some name'})`
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top