def setUp(self):
        class NoteViewSet(viewsets.ModelViewSet):
            queryset = RouterTestModel.objects.all()

        self.router = SimpleRouter(trailing_slash=False)
        self.router.register(r'notes', NoteViewSet)
        self.urls = self.router.urls
    def setUp(self):
        class NoteViewSet(viewsets.ModelViewSet):
            queryset = RouterTestModel.objects.all()
            lookup_field = 'uuid'
            lookup_value_regex = '[0-9a-f]{32}'

        self.router = SimpleRouter()
        self.router.register(r'notes', NoteViewSet)
        self.urls = self.router.urls
    def test_basename_argument_no_warnings(self):
        router = SimpleRouter()

        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')
            router.register('mock', MockViewSet, basename='mock')

        assert len(w) == 0
        assert router.registry == [
            ('mock', MockViewSet, 'mock'),
        ]
    def test_exception_raised_when_action_applied_to_existing_route(self):
        class TestViewSet(viewsets.ModelViewSet):
            @action(methods=['post'], detail=True)
            def retrieve(self, request, *args, **kwargs):
                return Response({'hello': 'world'})

        self.router = SimpleRouter()
        self.router.register(r'test', TestViewSet, basename='test')

        with pytest.raises(ImproperlyConfigured):
            self.router.urls
    def test_base_name_and_basename_assertion(self):
        router = SimpleRouter()

        msg = "Do not provide both the `basename` and `base_name` arguments."
        with warnings.catch_warnings(record=True) as w, \
                self.assertRaisesMessage(AssertionError, msg):
            warnings.simplefilter('always')
            router.register('mock', MockViewSet, 'mock', base_name='mock')

        msg = "The `base_name` argument is pending deprecation in favor of `basename`."
        assert len(w) == 1
        assert str(w[0].message) == msg
    def test_base_name_argument_deprecation(self):
        router = SimpleRouter()

        with pytest.warns(RemovedInDRF311Warning) as w:
            warnings.simplefilter('always')
            router.register('mock', MockViewSet, base_name='mock')

        msg = "The `base_name` argument is pending deprecation in favor of `basename`."
        assert len(w) == 1
        assert str(w[0].message) == msg
        assert router.registry == [
            ('mock', MockViewSet, 'mock'),
        ]
class TestTrailingSlashRemoved(TestCase):
    def setUp(self):
        class NoteViewSet(viewsets.ModelViewSet):
            queryset = RouterTestModel.objects.all()

        self.router = SimpleRouter(trailing_slash=False)
        self.router.register(r'notes', NoteViewSet)
        self.urls = self.router.urls

    def test_urls_can_have_trailing_slash_removed(self):
        expected = ['^notes$', '^notes/(?P<pk>[^/.]+)$']
        for idx in range(len(expected)):
            assert expected[idx] == get_regex_pattern(self.urls[idx])
    def setUp(self):
        class TestViewSet(viewsets.ModelViewSet):
            permission_classes = []

            @action(methods=['post'],
                    detail=True,
                    permission_classes=[permissions.AllowAny])
            def custom(self, request, *args, **kwargs):
                return Response(
                    {'permission_classes': self.permission_classes})

        self.router = SimpleRouter()
        self.router.register(r'test', TestViewSet, basename='test')
        self.view = self.router.urls[-1].callback
class TestLookupValueRegex(TestCase):
    """
    Ensure the router honors lookup_value_regex when applied
    to the viewset.
    """
    def setUp(self):
        class NoteViewSet(viewsets.ModelViewSet):
            queryset = RouterTestModel.objects.all()
            lookup_field = 'uuid'
            lookup_value_regex = '[0-9a-f]{32}'

        self.router = SimpleRouter()
        self.router.register(r'notes', NoteViewSet)
        self.urls = self.router.urls

    def test_urls_limited_by_lookup_value_regex(self):
        expected = ['^notes/$', '^notes/(?P<uuid>[0-9a-f]{32})/$']
        for idx in range(len(expected)):
            assert expected[idx] == get_regex_pattern(self.urls[idx])
class TestActionKeywordArgs(TestCase):
    """
    Ensure keyword arguments passed in the `@action` decorator
    are properly handled.  Refs #940.
    """
    def setUp(self):
        class TestViewSet(viewsets.ModelViewSet):
            permission_classes = []

            @action(methods=['post'],
                    detail=True,
                    permission_classes=[permissions.AllowAny])
            def custom(self, request, *args, **kwargs):
                return Response(
                    {'permission_classes': self.permission_classes})

        self.router = SimpleRouter()
        self.router.register(r'test', TestViewSet, basename='test')
        self.view = self.router.urls[-1].callback

    def test_action_kwargs(self):
        request = factory.post('/test/0/custom/')
        response = self.view(request)
        assert response.data == {'permission_classes': [permissions.AllowAny]}
class TestDynamicListAndDetailRouter(TestCase):
    def setUp(self):
        self.router = SimpleRouter()

    def _test_list_and_detail_route_decorators(self, viewset):
        routes = self.router.get_routes(viewset)
        decorator_routes = [
            r for r in routes
            if not (r.name.endswith('-list') or r.name.endswith('-detail'))
        ]

        MethodNamesMap = namedtuple('MethodNamesMap', 'method_name url_path')
        # Make sure all these endpoints exist and none have been clobbered
        for i, endpoint in enumerate([
                MethodNamesMap('list_custom_route_get', 'list_custom-route'),
                MethodNamesMap('list_route_get', 'list_route_get'),
                MethodNamesMap('list_route_post', 'list_route_post'),
                MethodNamesMap('detail_custom_route_get',
                               'detail_custom-route'),
                MethodNamesMap('detail_route_get', 'detail_route_get'),
                MethodNamesMap('detail_route_post', 'detail_route_post')
        ]):
            route = decorator_routes[i]
            # check url listing
            method_name = endpoint.method_name
            url_path = endpoint.url_path

            if method_name.startswith('list_'):
                assert route.url == '^{{prefix}}/{0}{{trailing_slash}}$'.format(
                    url_path)
            else:
                assert route.url == '^{{prefix}}/{{lookup}}/{0}{{trailing_slash}}$'.format(
                    url_path)
            # check method to function mapping
            if method_name.endswith('_post'):
                method_map = 'post'
            else:
                method_map = 'get'
            assert route.mapping[method_map] == method_name

    def test_list_and_detail_route_decorators(self):
        self._test_list_and_detail_route_decorators(
            DynamicListAndDetailViewSet)

    def test_inherited_list_and_detail_route_decorators(self):
        self._test_list_and_detail_route_decorators(
            SubDynamicListAndDetailViewSet)
class TestSimpleRouter(URLPatternsTestCase, TestCase):
    router = SimpleRouter()
    router.register('basics', BasicViewSet, basename='basic')

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

    def setUp(self):
        self.router = SimpleRouter()

    def test_action_routes(self):
        # Get action routes (first two are list/detail)
        routes = self.router.get_routes(BasicViewSet)[2:]

        assert routes[0].url == '^{prefix}/{lookup}/action1{trailing_slash}$'
        assert routes[0].mapping == {
            'post': 'action1',
        }

        assert routes[1].url == '^{prefix}/{lookup}/action2{trailing_slash}$'
        assert routes[1].mapping == {
            'post': 'action2',
            'delete': 'action2',
        }

        assert routes[2].url == '^{prefix}/{lookup}/action3{trailing_slash}$'
        assert routes[2].mapping == {
            'post': 'action3',
            'delete': 'action3_delete',
        }

    def test_multiple_action_handlers(self):
        # Standard action
        response = self.client.post(reverse('basic-action3', args=[1]))
        assert response.data == {'post': '1'}

        # Additional handler registered with MethodMapper
        response = self.client.delete(reverse('basic-action3', args=[1]))
        assert response.data == {'delete': '1'}

    def test_register_after_accessing_urls(self):
        self.router.register(r'notes', NoteViewSet)
        assert len(self.router.urls) == 2  # list and detail
        self.router.register(r'notes_bis', NoteViewSet)
        assert len(self.router.urls) == 4
class BrowsableAPIRendererTests(URLPatternsTestCase):
    class ExampleViewSet(ViewSet):
        def list(self, request):
            return Response()

        @action(detail=False, name="Extra list action")
        def list_action(self, request):
            raise NotImplementedError

    router = SimpleRouter()
    router.register('examples', ExampleViewSet, basename='example')
    urlpatterns = [url(r'^api/', include(router.urls))]

    def setUp(self):
        self.renderer = BrowsableAPIRenderer()

    def test_get_description_returns_empty_string_for_401_and_403_statuses(
            self):
        assert self.renderer.get_description({}, status_code=401) == ''
        assert self.renderer.get_description({}, status_code=403) == ''

    def test_get_filter_form_returns_none_if_data_is_not_list_instance(self):
        class DummyView(object):
            get_queryset = None
            filter_backends = None

        result = self.renderer.get_filter_form(data='not list',
                                               view=DummyView(),
                                               request={})
        assert result is None

    def test_extra_actions_dropdown(self):
        resp = self.client.get('/api/examples/', HTTP_ACCEPT='text/html')
        assert 'id="extra-actions-menu"' in resp.content.decode('utf-8')
        assert '/api/examples/list_action/' in resp.content.decode('utf-8')
        assert '>Extra list action<' in resp.content.decode('utf-8')
 def setUp(self):
     self.router = SimpleRouter()
        raise NotImplementedError

    @action(detail=True)
    def detail_action(self, request, *args, **kwargs):
        raise NotImplementedError

    @action(detail=True, name='Custom Name')
    def named_action(self, request, *args, **kwargs):
        raise NotImplementedError

    @action(detail=True, suffix='Custom Suffix')
    def suffixed_action(self, request, *args, **kwargs):
        raise NotImplementedError


router = SimpleRouter()
router.register(r'resources', ResourceViewSet)
urlpatterns = [
    url(r'^$', Root.as_view()),
    url(r'^resource/$', ResourceRoot.as_view()),
    url(r'^resource/customname$', CustomNameResourceInstance.as_view()),
    url(r'^resource/(?P<key>[0-9]+)$', ResourceInstance.as_view()),
    url(r'^resource/(?P<key>[0-9]+)/$', NestedResourceRoot.as_view()),
    url(r'^resource/(?P<key>[0-9]+)/(?P<other>[A-Za-z]+)$',
        NestedResourceInstance.as_view()),
]
urlpatterns += router.urls


@override_settings(ROOT_URLCONF='tests.test_utils')
class BreadcrumbTests(TestCase):
        return Response()

    @action(detail=True)
    def unnamed_action(self, request, *args, **kwargs):
        raise NotImplementedError

    @action(detail=True, name='Custom Name')
    def named_action(self, request, *args, **kwargs):
        raise NotImplementedError

    @action(detail=True, suffix='Custom Suffix')
    def suffixed_action(self, request, *args, **kwargs):
        raise NotImplementedError


router = SimpleRouter()
router.register(r'actions', ActionViewSet)
router.register(r'actions-alt', ActionViewSet, basename='actions-alt')
router.register(r'names', ActionNamesViewSet, basename='names')

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


class InitializeViewSetsTestCase(TestCase):
    def test_initialize_view_set_with_actions(self):
        request = factory.get('/', '', content_type='application/json')
        my_view = BasicViewSet.as_view(actions={
            'get': 'list',
        })

class RegexUrlPathViewSet(viewsets.ViewSet):
    @action(detail=False, url_path='list/(?P<kwarg>[0-9]{4})')
    def regex_url_path_list(self, request, *args, **kwargs):
        kwarg = self.kwargs.get('kwarg', '')
        return Response({'kwarg': kwarg})

    @action(detail=True, url_path='detail/(?P<kwarg>[0-9]{4})')
    def regex_url_path_detail(self, request, *args, **kwargs):
        pk = self.kwargs.get('pk', '')
        kwarg = self.kwargs.get('kwarg', '')
        return Response({'pk': pk, 'kwarg': kwarg})


notes_router = SimpleRouter()
notes_router.register(r'notes', NoteViewSet)

kwarged_notes_router = SimpleRouter()
kwarged_notes_router.register(r'notes', KWargedNoteViewSet)

namespaced_router = DefaultRouter()
namespaced_router.register(r'example', MockViewSet, basename='example')

empty_prefix_router = SimpleRouter()
empty_prefix_router.register(r'', EmptyPrefixViewSet, basename='empty_prefix')

regex_url_path_router = SimpleRouter()
regex_url_path_router.register(r'', RegexUrlPathViewSet, basename='regex')