【问题标题】:Failing functional test on GAE, Django, WebTest在 GAE、Django、WebTest 上的功能测试失败
【发布时间】:2013-09-19 03:05:03
【问题描述】:

我有一个 GAE/Django 项目,我正在尝试使用 WebTest 进行功能测试环境,项目布局如下:

/gaeroot
  /djangoroot
    wsgi.py
    urls.py
    ...
    /anapp
      urls.py
      ...
      /tests
        test_functional.py

wsgi.py(由GAE的django-admin.py django1.5版本生成):

import os

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoroot.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

test_functional.py:

import unittest
import webtest
from djangoroot.wsgi import application

class TestHomePage(unittest.TestCase):
    def setUp(self):
        self.testapp = webtest.TestApp(application)

    def test_get_method_ok(self):
        response = self.testapp.get('/path')
        self.assertEqual(response.status_int, 200, response)

失败的测试消息:

Traceback (most recent call last):
...
line 14, in test_get_method_ok
self.assertEqual(response.status_int, 200, response)
AssertionError: Response: 301 MOVED PERMANENTLY
Content-Type: text/html; charset=utf-8
Location: http://localhost:80/path/

为什么要将重定向代码扔到同一路径,我唯一能想到的是 django 的某些代码负责重定向,因为从目录树中可以看到我有一个两级 url 配置。

另一方面,为什么使用端口 80?当我在浏览器上测试它时,它显示了一个 8080 端口,它根本不应该使用端口,因为 WebTest 它应该根本不使用端口,因为它正在测试 WSGI 接口,对吧?

顶级 urls.py

from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
    url(r'^path/', include('djangoroot.anapp.urls')),
)

应用级 urls.py

from django.conf.urls import patterns, url
urlpatterns = patterns('djangoroot.anapp.views',
    url(r'^$', 'home', name='anapp_home'),
)

浏览器在相同的 url 上显示正确的页面,我从 google 的支持页面中获取了 WebTest 示例,所以问题应该是 GAE/Django 互操作。

提前致谢,如果您需要更多信息,请告诉我。

【问题讨论】:

    标签: django google-app-engine webtest


    【解决方案1】:

    问题似乎出在django.conf.urls.url 函数上,因为我测试了根urls.py 文件,它适用于根路径/,没有重定向,但它确实用根以外的路径重定向了我,我在 Django 源文件中找不到任何似乎正在重定向我的网址的东西。

    我在Webtest 文档中找到了替代方案:

    resp = self.testapp.get('/path')
    resp = resp.maybe_follow()
    

    使用maybe_follow 方法,您最终会得到最终页面。

    编辑

    终于在这一行发现了问题:

    response = self.testapp.get('/path')
    

    用这个替换它:

    response = self.testapp.get('/path/')
    

    看起来Django 将 url 重定向到末尾带有 / 的 propper 路径。

    【讨论】:

    • 啊哈!尾随'/'。谢谢!
    猜你喜欢
    • 2016-03-05
    • 1970-01-01
    • 2019-11-02
    • 2020-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多