Django UrlResolver,在运行时添加 url 进行测试
我想做一些测试,但我还不太熟悉 URLResolver
,但我想快速解决这个问题。
在 TestCase
中,我想向解析器添加一个 URL,以便我可以使用 Client.get('/url/')
并将其与urls.py
。
I'm looking to do some tests and I'm not really familiar with the URLResolver
quite yet but I'd like to solve this issue quickly.
In a TestCase
, I'd like to add a URL to the resolver so that I can then use Client.get('/url/')
and keep it separate from urls.py
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
自 Django 1.8 使用
django.test.TestCase.urls
已弃用。您可以使用 django.test.utils.override_settings 代替:override_settings 可以应用于整个类或特定方法。
Since Django 1.8 using of
django.test.TestCase.urls
is deprecated. You can usedjango.test.utils.override_settings
instead:override_settings
can be applied either to a whole class or to a particular method.https://docs.djangoproject.com/en/2.1 /topics/testing/tools/#urlconf-configuration
在您的测试中:
这将使用
myapp/test_urls.py
作为ROOT_URLCONF
。https://docs.djangoproject.com/en/2.1/topics/testing/tools/#urlconf-configuration
In your test:
This will use
myapp/test_urls.py
as theROOT_URLCONF
.我知道不久前有人问过这个问题,但我想我会再次回答它以提供更完整和最新的内容。
您有两种选择来解决此问题,一种是提供您自己的 url 文件,如 SystemParadox 的答案所建议的:
另一种是猴子修补您的 url。这不是处理重写 URL 的推荐方法,但您可能会遇到仍然需要它的情况。要对单个测试用例执行此操作而不影响其余测试用例,您应该在
setUp()
方法中执行此操作,然后在tearDown()
方法中进行清理。请注意,如果省略
urls
类属性,这将不起作用。这是因为如果您将测试与其他测试用例一起运行,则 URL 将被缓存,并且您的猴子修补将不会生效。I know this was asked a while ago, but I thought I'd answer it again to offer something more complete and up-to-date.
You have two options to solve this, one is to provide your own urls file, as suggested by SystemParadox's answer:
The other is to monkey patch your urls. This is NOT the recommended way to deal with overriding urls but you might get into a situation where you still need it. To do this for a single test case without affecting the rest you should do it in your
setUp()
method and then cleanup in yourtearDown()
method.Please note that this will not work if you omit the
urls
class attribute. This is because the urls will otherwise be cached and your monkey patching will not take effect if you run your test together with other test cases.根据上面的答案无法让它运行。即使使用
override_settings
也不行。找到了一个适合我的解决方案。我的用例是编写一些集成测试,我想在其中测试需要应用程序中的 url 的 put/post 方法。
这里的主要线索是使用
django.urls
的set_urlconf
函数,而不是在类中覆盖它或使用override_settings.
Couldn't get it running with the answers above. Not even with the
override_settings
.Found a solution which works for me. My usecase was to write some integration tests where I want to test put/post methods where I needed the urls from my app.
The main clue here is to use the
set_urlconf
function ofdjango.urls
instead of overwriting it in the class or usingoverride_settings
.