python - Django 测试用例错误 'WSGIRequest' 对象没有属性 'session'

标签 python django django-sessions django-wsgi django-tests

我正在尝试为我的 Django 应用程序编写一些测试,但它抛出了一个错误:

File "/Users/croberts/.virtualenvs/litem/lib/python3.4/site-packages/django/contrib/auth/__init__.py", line 101, in login
    if SESSION_KEY in request.session:
AttributeError: 'WSGIRequest' object has no attribute 'session'

这是我尝试运行的代码:

class SimpleTest(TestCase):
    def setUp(self):
        self.request_factory = RequestFactory()

    def test_signup(self):
        request = self.request_factory.post("/signup/", {
            "email": "email@email.com", 
            "password": "password", 
            "password-confirm": "password", 
            "firm": "big law firm"})
        response = signup_user(request)
        user = User.objects.get(email="email@email.com")
        self.assertEqual(user.username, "email@email.com")
        self.assertEqual(user.firm, "big law firm")
        self.assertEqual(response.status_code, 302) #if it's successful it redirects.

这是我的中间件:

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

和我安装的应用:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'patents',
]

最佳答案

尝试使用测试客户端而不是请求工厂。这也具有测试您的 URL 配置的优势。

class SimpleTest(TestCase):
    def test_signup(self):
        response = self.client.post("/signup/", {
            "email": "email@email.com", 
            "password": "password", 
            "password-confirm": "password", 
            "firm": "big law firm"})
        user = User.objects.get(email="email@email.com")
        self.assertEqual(user.username, "email@email.com")
        self.assertEqual(user.firm, "big law firm")
        self.assertEqual(response.status_code, 302) #if it's successful it redirects.

关于python - Django 测试用例错误 'WSGIRequest' 对象没有属性 'session',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35659676/

相关文章:

python - 进程的异步生成 : design question - Celery or Twisted

python - 基于 Django 文件的 session - 文件名太长

python - key 错误 : Django Losing Session Data Between CBV Redirects

python - 具有异步任务和redis的django中的线程安全

python - Pandas 将字符串写入 csv 而不是数组

python - 从 datetime64[ns, UTC], Python 中提取年月日

python - Python 企业平台、设计建议

python - Scrapy明文错误

python - Django 别名将错误的 url 重定向到正确的 url

django - session 作为 Django REST 中的持久存储?