我正在为django app中的观点编写测试。以前它们位于我的观点所在的目录中。他们工作正常。但后来我在django应用程序中将它们移动到文件夹名tests
中。没有导入错误,但我收到NoReverseMatch
错误。我的目录结构如下。
Project
settings.py
urls.py
|my_app
|tests
|tests.py
|__init__.py
|migrations
|__init__.py
|views.py
|models.py
|urls.py
我的代码如下
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
import django
django.setup()
from rest_framework.reverse import reverse
from rest_framework import status
from rest_framework.test import APITestCase
class MyTests(APITestCase):
def test_01(self):
url = reverse('login')
data = {'username': 'username', 'password': 'StrongPassword'}
response = self.client.post(url, data)
self.assertEqual(response.data, my_expected_output)
我得到的错误是
NoReverseMatch: Reverse for 'login' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
有谁能告诉我我做错了什么 我的my_app / urls.py文件就是这样的
from rest_framework import routers
from my_app import views as app_views
from django.conf.urls import url, patterns, include
router = routers.DefaultRouter()
urlpatterns = [
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^login/$', app_views.login_view, name='login'),
url(r'^docs/', include('rest_framework_swagger.urls')),
url(r'^provider/$',
app_views.EntityViewSet.as_view({'get': 'list'}), name="provider-list"),
url(r'^provider/(?P<pk>\d+)/$',
app_views.EntityViewSet.as_view({'get': 'retrieve'}), name="provider-detail"),
]
urlpatterns += router.urls
我的主要urls.py是这样的。此文件与我的settings.py文件处于同一级别。我已经更新了我的目录结构。
urlpatterns = patterns(
'',
url(r'^app/', include('app.urls')),
)
答案 0 :(得分:1)
我能够通过将url放在我的测试用例中来解决我的错误
class MyTests(APITestCase):
urls = 'my_app.urls'
def test_01(self):
url = reverse('login')
data = {'username': 'username', 'password': 'StrongPassword'}
response = self.client.post(url, data)
self.assertEqual(response.data, my_expected_output)