代码之家  ›  专栏  ›  技术社区  ›  ncopiy

在testclass中未在此服务器上找到Django请求的URL

  •  1
  • ncopiy  · 技术社区  · 7 年前

    我的测试类如下:

    from django.test import TestCase, Client
    
    class TestGetSomething(TestCase):
        def test_get_first_url(self):
            path = "some/long/path"
            client = Client()
            response = client.get(path=path)
            self.assertEqual(response.status_code, 200)
    

    但是 assertEquals 引发异常, 404 != 200 .
    当我写的时候 print(response.__dict__) 我注意到请求,字段:

    '_closable_objects': [<WSGIRequest: GET 'somelong/path'>]
    'request': {'PATH_INFO': 'some/long/path', 'REQUEST_METHOD': 'GET', 'SERVER_PORT': '80', 'wsgi.url_scheme': 'http', 'QUERY_STRING': ''}
    'templates': [<django.template.base.Template object at 0x7f4b33ac17f0>], 'context': [{'True': True, 'False': False, 'None': None}, {'request_path': '/somelong/path/', 'exception': 'Resolver404'}]  
    

    如您所见,路径的一部分没有“some”和“long”之间的斜线。
    当我尝试手动(使用浏览器)按URL获取页面时,一切正常
    在我的django应用程序中,除了model和modeladmin之外,我什么都不使用。甚至urls.py都是清晰的。
    所有人现在我该怎么修?
    如果需要,我会添加任何附加代码。

    1 回复  |  直到 7 年前
        1
  •  2
  •   willeM_ Van Onsem    7 年前

    / localhost:8000/some/long/path path example.com example.com/

    class TestGetSomething(TestCase):
    
        def test_get_first_url(self):
            # start with a slash
            path = "/some/long/path"
            client = Client()
            response = client.get(path=path)
            self.assertEqual(response.status_code, 200)