使用NestedSimpleRouter和AP​​ITestCase时找不到URL

时间:2019-02-19 09:20:33

标签: django django-rest-framework django-unittest drf-nested-routers

通过Postman和Swagger访问API时,我可以执行CRUD操作。但是,当我尝试通过TestCases访问URL时,显示未找到错误。

当我尝试在测试用例中访问嵌套路由的URL时,就会发生这种情况。在测试用例中正确的做法是什么。

urls.py

from django.conf.urls import include, url
from rest_framework_nested import routers

router = routers.SimpleRouter(trailing_slash=False)
router.register('company', CompanyViewSet, base_name='companies')
company_routers = routers.NestedSimpleRouter(router, r'company', 
                                        lookup='companyrate')
company_routers.register(r'rate', RateViewSet, base_name='disposal-rate')

urlpatterns = [
              url(r'^', include(router.urls)),
              url(r'^', include(company_routers.urls)),
              ]


test.py

from rest_framework.test import APITestCase
from users.models import User

class TestCompanyRates(APITestCase):

fixtures = ['user.json', 'company.json']

data = {
        "company": 1,
         "rate": 123
     }

def setUp(self):
     self.user = User.objects.get(email='coordinator@outlook.com')
     self.client.force_authenticate(user=self.user)

def test_rates(self):

    response = self.client.post('company/1/rate/', self.data)
    self.assertEqual(response.status_code, 201, "API 
                          should return 200 OK status")

我是APITestCases的新手。我正在使用Django 2.1,Python 3.6和drf-nested-routers 0.90.URL和错误在下面提到。这是我尝试将数据发布到URL时遇到的错误:

  

URL:localhost:8000 / company / 1 / rate和   错误:status_code = 404,未找到

0 个答案:

没有答案