4

我有这个要测试的观点

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()

我为它写了一个测试,但它不起作用(我想测试请求)

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)

当我运行它时,我在控制台中得到它

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)

我能用它做什么?或者有一些不同的测试请求的方式?

4

1 回答 1

6

如果您查看文档,您会发现您需要手动将用户添加到请求中。它不会自动为您执行此操作。

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

像这样添加用户模拟了发出登录请求。如果这不是您想要的,那么您应该创建一个AnonymousUser。一般来说,你得到的错误应该为你提供你需要知道的一切。它明确告诉您测试失败,因为请求没有user. 添加真实用户或向请求添加模拟用户对象就是答案。

此外,您似乎正在测试仅适用于 POST 请求的视图。它会失败,因为 request.POST 没有正确的字典键。您可以通过执行创建 POST 请求

factory.post('main/views', {'name_change': 'some name'})`
于 2013-10-19T10:54:59.000 回答