Python rest_framework.status.HTTP_405_METHOD_NOT_ALLOWED Examples

The following are 30 code examples for showing how to use rest_framework.status.HTTP_405_METHOD_NOT_ALLOWED(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module rest_framework.status , or try the search function .

Example 1
Project: securethenews   Author: freedomofpress   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_forbidden_actions(self):
        """
        <api root>/sites/ should not permit POST, PUT or DELETE operations
        """
        url = urljoin(urlroot, 'sites/securethe.news/')
        response1 = self.client.post(
            url, json={'name': 'Insecure the News?',
                       'domain': 'insecurethe.news'})
        self.assertEqual(response1.status_code,
                         status.HTTP_405_METHOD_NOT_ALLOWED)

        response2 = self.client.delete(url)
        self.assertEqual(response2.status_code,
                         status.HTTP_405_METHOD_NOT_ALLOWED)

        url = urljoin(urlroot, 'sites/insecurethe.news/')
        response3 = self.client.put(
            url, json={'name': 'Insecure the News?',
                       'domain': 'insecurethe.news'})
        self.assertEqual(response3.status_code,
                         status.HTTP_405_METHOD_NOT_ALLOWED) 
Example 2
Project: tfrs   Author: bcgov   File: test_api_security_users.py    License: Apache License 2.0 6 votes vote down vote up
def test_delete(self):
        """Test that deleting users is not a semantically valid action"""

        url = "/api/users/{0!s}"

        all_users = self.users

        expected_results = defaultdict(lambda: {
            'status': [status.HTTP_405_METHOD_NOT_ALLOWED,
                       status.HTTP_403_FORBIDDEN],
            'reason': "Default response should be no access"})

        for user in all_users:
            with self.subTest(
                    user=user,
                    expected_statuses=expected_results[(user,)]['status'],
                    reason=expected_results[(user,)]['reason']):
                user_that_exists = DataCreationUtilities.create_test_user()
                response = self.clients[user].delete(
                    url.format(user_that_exists['id']))

                logging.debug(response)

                self.assertIn(
                    response.status_code, expected_results[(user,)]['status']) 
Example 3
Project: bennedetto   Author: arecker   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def membership(self, request, **kwargs):
        if request.method == 'POST':
            email = request.data.get('email', None)

            if not email:
                return Response('email required', status=400)

            if User.objects.filter(email=email).exists():
                return Response('user already has account', status=400)

            family = request.user.membership.family
            family.invite_user_to_family(email=email)

            return Response('user invited', status=201)

        elif request.method == 'GET':
            family = request.user.membership.family
            members = Membership.objects \
                                .select_related('user') \
                                .filter(family=family)
            data = MembershipSerializer(members, many=True).data
            return Response(data)

        else:
            return Response('Method not allowed', status=status.HTTP_405_METHOD_NOT_ALLOWED) 
Example 4
Project: django-project   Author: peragro   File: views.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def follow(self, request, pk, **kwargs):
        obj = self.queryset.get(id=int(pk))

        #follow, created = Follow.objects.get_or_create(request.user, obj)
        can_change_follow = True
        if hasattr(self, 'can_change_follow'):
            can_change_follow = self.can_change_follow(request.user, obj)

        if can_change_follow:
            if request.method == 'DELETE':
                if Follow.objects.is_following(request.user, obj):
                    fol = follow.utils.unfollow(request.user, obj)
                    signals.unfollow.send(FollowingModelViewSet, follower=request.user, followee=obj)
                return Response(status=status.HTTP_205_RESET_CONTENT)
            elif request.method == 'POST':
                if not Follow.objects.is_following(request.user, obj):
                    fol = follow.utils.follow(request.user, obj)
                    signals.follow.send(FollowingModelViewSet, follower=request.user, followee=obj)
                return Response(status=status.HTTP_201_CREATED)
        else:
            return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED) 
Example 5
Project: kpi   Author: kobotoolbox   File: test_api_submissions.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_cannot_create_submission(self):
        v_uid = self.asset.latest_deployed_version.uid
        submission = {
            "q1": "a5",
            "q2": "a6",
        }
        # Owner
        response = self.client.post(self.submission_url, data=submission)
        self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)

        # Shared
        self._share_with_another_user()
        self._log_in_as_another_user()
        response = self.client.post(self.submission_url, data=submission)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

        # Anonymous
        self.client.logout()
        response = self.client.post(self.submission_url, data=submission)
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) 
Example 6
Project: GenericCDSS   Author: bioinformatics-ua   File: testUserViewSet.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_active_user(self):
        '''
        Try to activate a user, where only staff is allowed
        '''
        response = self.client.post('/api/account/register/', self.userData, format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)             # Check if response is created
        user = User.objects.get(username=self.userName)

        #Unauthenticated
        response = self.client.post('/api/account/activateUser/', { "email":user.email}, format='json')
        #self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)        # Check if response is not authorized

        #Normal user authenticated
        self.client.force_authenticate(self.simpleUser)
        response = self.client.post('/api/account/activateUser/', {"email": user.email}, format='json')
        #self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)        # Check if response is not authorized
        self.client.logout()

        #Staff authenticated
        self.client.force_authenticate(self.admin)
        response = self.client.post('/api/account/activateUser/', {"email": user.email}, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)                  # Check if response is ok

        response = self.client.post('/api/account/activateUser/', {"email": user.email}, format='json')
        #self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)  # Check if response is method is not allowed 
Example 7
Project: product-database   Author: hoelsner   File: test_productdb_api_views.py    License: MIT License 6 votes vote down vote up
def test_add_access_with_permission(self):
        test_user = "user"
        u = User.objects.create_user(test_user, "", test_user)
        p = Permission.objects.get(codename="add_vendor")
        assert p is not None
        u.user_permissions.add(p)
        u.save()
        assert u.has_perm("productdb.add_vendor")

        client = APIClient()
        client.login(username=test_user, password=test_user)
        response = client.post(REST_VENDOR_LIST, data={"name": "Awesome Vendor"})

        assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED, "API endpoint is always read only"
        assert response.json() == {'detail': 'Method "POST" not allowed.'}
        assert Vendor.objects.count() == 3, "no additional vendor is created" 
Example 8
Project: product-database   Author: hoelsner   File: test_productdb_api_views.py    License: MIT License 6 votes vote down vote up
def test_change_access_with_permission(self):
        # create a user with permissions
        test_user = "user"
        u = User.objects.create_user(test_user, "", test_user)
        p = Permission.objects.get(codename="change_vendor")
        assert p is not None
        u.user_permissions.add(p)
        u.save()
        assert u.has_perm("productdb.change_vendor")

        client = APIClient()
        client.login(username=test_user, password=test_user)
        response = client.put(REST_VENDOR_DETAIL % 1, data={"name": "renamed vendor"})

        assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED, "API endpoint is always read only"
        assert response.json() == {'detail': 'Method "PUT" not allowed.'} 
Example 9
Project: product-database   Author: hoelsner   File: test_productdb_api_views.py    License: MIT License 6 votes vote down vote up
def test_delete_access_with_permission(self):
        test_user = "user"
        u = User.objects.create_user(test_user, "", test_user)
        p = Permission.objects.get(codename="delete_vendor")
        assert p is not None
        u.user_permissions.add(p)
        u.save()
        assert u.has_perm("productdb.delete_vendor")

        client = APIClient()
        client.login(username=test_user, password=test_user)
        response = client.delete(REST_VENDOR_DETAIL % 1)

        assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED, "API endpoint is always read only"
        assert response.json() == {'detail': 'Method "DELETE" not allowed.'}
        assert Vendor.objects.count() == 3, "no vendor was deleted" 
Example 10
Project: product-database   Author: hoelsner   File: test_productdb_api_views.py    License: MIT License 6 votes vote down vote up
def test_add_access_with_permission(self):
        test_user = "user"
        u = User.objects.create_user(test_user, "", test_user)
        p = Permission.objects.get(codename="add_productmigrationoption")
        assert p is not None
        u.user_permissions.add(p)
        u.save()
        assert u.has_perm("productdb.add_productmigrationoption")

        client = APIClient()
        client.login(username=test_user, password=test_user)
        response = client.post(REST_PRODUCTMIGRATIONOPTION_LIST,
                               data={"replacement_id": "Awesome Product Migration Option"})

        assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED, "API endpoint is always read only"
        assert response.json() == {'detail': 'Method "POST" not allowed.'}
        assert ProductMigrationOption.objects.count() == 0, "no additional product migration option is created" 
Example 11
Project: product-database   Author: hoelsner   File: test_productdb_api_views.py    License: MIT License 6 votes vote down vote up
def test_delete_access_with_permission(self):
        test_user = "user"
        u = User.objects.create_user(test_user, "", test_user)
        p = Permission.objects.get(codename="delete_productmigrationoption")
        assert p is not None
        u.user_permissions.add(p)
        u.save()
        assert u.has_perm("productdb.delete_productmigrationoption")

        models.ProductMigrationOption.objects.create(
            product=models.Product.objects.create(product_id="test pid"),
            migration_source=models.ProductMigrationSource.objects.create(name="test")
        )
        client = APIClient()
        client.login(username=test_user, password=test_user)
        response = client.delete(REST_PRODUCTMIGRATIONOPTION_DETAIL % 1)

        assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED, "API endpoint is always read only"
        assert response.json() == {'detail': 'Method "DELETE" not allowed.'}
        assert ProductMigrationOption.objects.count() == 1, "no product migration option was deleted" 
Example 12
Project: product-database   Author: hoelsner   File: test_productdb_api_views.py    License: MIT License 6 votes vote down vote up
def test_add_access_with_permission(self):
        test_user = "user"
        u = User.objects.create_user(test_user, "", test_user)
        p = Permission.objects.get(codename="add_productmigrationsource")
        assert p is not None
        u.user_permissions.add(p)
        u.save()
        assert u.has_perm("productdb.add_productmigrationsource")

        client = APIClient()
        client.login(username=test_user, password=test_user)
        response = client.post(REST_PRODUCTMIGRATIONSOURCE_LIST, data={"name": "Awesome Product Migration Source"})

        assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED, "API endpoint is always read only"
        assert response.json() == {'detail': 'Method "POST" not allowed.'}
        assert ProductMigrationSource.objects.count() == 0, "no additional vendor is created" 
Example 13
Project: product-database   Author: hoelsner   File: test_productdb_api_views.py    License: MIT License 6 votes vote down vote up
def test_change_access_with_permission(self):
        # create a user with permissions
        test_user = "user"
        u = User.objects.create_user(test_user, "", test_user)
        p = Permission.objects.get(codename="change_productmigrationsource")
        assert p is not None
        u.user_permissions.add(p)
        u.save()
        assert u.has_perm("productdb.change_productmigrationsource")

        models.ProductMigrationSource.objects.create(name="foo")
        client = APIClient()
        client.login(username=test_user, password=test_user)
        response = client.put(REST_PRODUCTMIGRATIONSOURCE_DETAIL % 1, data={"name": "renamed product migration source"})

        assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED, "API endpoint is always read only"
        assert response.json() == {'detail': 'Method "PUT" not allowed.'} 
Example 14
Project: product-database   Author: hoelsner   File: test_productdb_api_views.py    License: MIT License 6 votes vote down vote up
def test_delete_access_with_permission(self):
        test_user = "user"
        u = User.objects.create_user(test_user, "", test_user)
        p = Permission.objects.get(codename="delete_productmigrationsource")
        assert p is not None
        u.user_permissions.add(p)
        u.save()
        assert u.has_perm("productdb.delete_productmigrationsource")

        models.ProductMigrationSource.objects.create(name="source")
        client = APIClient()
        client.login(username=test_user, password=test_user)
        response = client.delete(REST_PRODUCTMIGRATIONSOURCE_DETAIL % 1)

        assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED, "API endpoint is always read only"
        assert response.json() == {'detail': 'Method "DELETE" not allowed.'}
        assert ProductMigrationSource.objects.count() == 1, "no product migration source was deleted" 
Example 15
Project: product-database   Author: hoelsner   File: test_productdb_api_views.py    License: MIT License 6 votes vote down vote up
def test_add_access_with_permission(self):
        """add action through API for Product List not supported"""
        self.create_test_data()
        test_user = "user"
        test_product_list_id = "Test Product List"

        u = User.objects.create_user(test_user, "", test_user)
        p = Permission.objects.get(codename="add_productlist")
        assert p is not None
        u.user_permissions.add(p)
        u.save()
        assert u.has_perm("productdb.add_productlist")

        client = APIClient()
        client.login(username=test_user, password=test_user)

        # create with name
        response = client.post(REST_PRODUCTLIST_LIST, data={"name": test_product_list_id})

        assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED
        assert response.json() == {'detail': 'Method "POST" not allowed.'}
        assert ProductList.objects.count() == 0, "no product list was created" 
Example 16
Project: product-database   Author: hoelsner   File: test_productdb_api_views.py    License: MIT License 6 votes vote down vote up
def test_delete_access_with_permission(self):
        id = self.create_test_product_list()

        test_user = "user"
        u = User.objects.create_user(test_user, "", test_user)
        p = Permission.objects.get(codename="delete_productlist")
        assert p is not None
        u.user_permissions.add(p)
        u.save()
        assert u.has_perm("productdb.delete_productlist")

        client = APIClient()
        client.login(username=test_user, password=test_user)
        response = client.delete(REST_PRODUCTLIST_DETAIL % id)

        assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED, "API endpoint is always read only"
        assert response.json() == {'detail': 'Method "DELETE" not allowed.'}
        assert ProductList.objects.count() == 1, "no product list was deleted" 
Example 17
Project: rematch   Author: nirizr   File: test_models.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_model_creation(admin_api_client, admin_user, model_name):
  model_data = setup_model(model_name, admin_user)

  response = admin_api_client.post('/collab/{}/'.format(model_name),
                                   data=model_data,
                                   HTTP_ACCEPT='application/json')

  # Manually handle matches, where API does not allow creation or
  # modification of objects, as they're read only
  if model_name == "matches":
    assert_response(response, status.HTTP_405_METHOD_NOT_ALLOWED)
    return

  assert_response(response, status.HTTP_201_CREATED)
  projects_created = [response.data]

  response = admin_api_client.get('/collab/{}/'.format(model_name),
                                  HTTP_ACCEPT="application/json")
  assert_response(response, status.HTTP_200_OK, projects_created) 
Example 18
Project: DjangoRestMultipleModels   Author: MattBroach   File: test_object_view.py    License: MIT License 5 votes vote down vote up
def test_post(self):
        """
        POST requests should throw a 405 Error
        """
        view = BasicObjectView.as_view()

        data = {'fake': 'data'}
        request = factory.post('/', data, format='json')

        with self.assertNumQueries(0):
            response = view(request).render()

        self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
        self.assertEqual(response.data, {"detail": 'Method "POST" not allowed.'}) 
Example 19
Project: DjangoRestMultipleModels   Author: MattBroach   File: test_object_view.py    License: MIT License 5 votes vote down vote up
def test_put(self):
        """
        PUT requests should throw a 405 Error
        """
        view = BasicObjectView.as_view()

        data = {'fake': 'data'}
        request = factory.put('/', data, format='json')

        with self.assertNumQueries(0):
            response = view(request).render()

        self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
        self.assertEqual(response.data, {"detail": 'Method "PUT" not allowed.'}) 
Example 20
Project: DjangoRestMultipleModels   Author: MattBroach   File: test_object_view.py    License: MIT License 5 votes vote down vote up
def test_delete(self):
        """
        DELETE requests should throw a 405 Error
        """
        view = BasicObjectView.as_view()

        request = factory.delete('/')

        with self.assertNumQueries(0):
            response = view(request).render()

        self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
        self.assertEqual(response.data, {"detail": 'Method "DELETE" not allowed.'}) 
Example 21
Project: DjangoRestMultipleModels   Author: MattBroach   File: test_flat_view.py    License: MIT License 5 votes vote down vote up
def test_post(self):
        """
        POST requests should throw a 405 Error
        """
        view = BasicFlatView.as_view()

        data = {'fake': 'data'}
        request = factory.post('/', data, format='json')

        with self.assertNumQueries(0):
            response = view(request).render()

        self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
        self.assertEqual(response.data, {"detail": 'Method "POST" not allowed.'}) 
Example 22
Project: DjangoRestMultipleModels   Author: MattBroach   File: test_flat_view.py    License: MIT License 5 votes vote down vote up
def test_put(self):
        """
        PUT requests should throw a 405 Error
        """
        view = BasicFlatView.as_view()

        data = {'fake': 'data'}
        request = factory.put('/', data, format='json')

        with self.assertNumQueries(0):
            response = view(request).render()

        self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
        self.assertEqual(response.data, {"detail": 'Method "PUT" not allowed.'}) 
Example 23
Project: resolwe   Author: genialis   File: test_tool.py    License: Apache License 2.0 5 votes vote down vote up
def test_patch(self):
        resp = self._patch(1, {"name": "Hacked process"}, self.admin)
        self.assertEqual(resp.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) 
Example 24
Project: resolwe   Author: genialis   File: test_tool.py    License: Apache License 2.0 5 votes vote down vote up
def test_delete(self):
        resp = self._delete(1, self.admin)
        self.assertEqual(resp.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) 
Example 25
Project: desec-stack   Author: desec-io   File: test_user_management.py    License: MIT License 5 votes vote down vote up
def test_view_account_read_only(self):
        # Should this test ever be removed (to allow writeable fields), make sure to
        # add new tests for each read-only field individually (such as limit_domains)!
        for method in [self.client.patch, self.client.put, self.client.post, self.client.delete]:
            response = method(
                reverse('v1:account'),
                {'limit_domains': 99},
                HTTP_AUTHORIZATION='Token {}'.format(self.token)
            )
            self.assertResponse(response, status.HTTP_405_METHOD_NOT_ALLOWED) 
Example 26
Project: desec-stack   Author: desec-io   File: test_donations.py    License: MIT License 5 votes vote down vote up
def test_unauthorized_access(self):
        for method in [self.client.get, self.client.put, self.client.delete]:
            response = method(reverse('v1:donation'))
            self.assertStatus(response, status.HTTP_405_METHOD_NOT_ALLOWED) 
Example 27
Project: desec-stack   Author: desec-io   File: test_rrsets_bulk.py    License: MIT License 5 votes vote down vote up
def test_bulk_delete_rrsets(self):
        self.assertStatus(
            self.client.delete(
                self.reverse('v1:rrsets', name=self.my_empty_domain.name),
                data=None,
            ),
            status.HTTP_405_METHOD_NOT_ALLOWED,
        ) 
Example 28
Project: desec-stack   Author: desec-io   File: test_domains.py    License: MIT License 5 votes vote down vote up
def test_update_domain(self):
        url = self.reverse('v1:domain-detail', name=self.my_domain.name)
        with self.assertPdnsRequests(self.request_pdns_zone_retrieve_crypto_keys(name=self.my_domain.name)):
            response = self.client.get(url)
            self.assertStatus(response, status.HTTP_200_OK)

        for method in [self.client.patch, self.client.put]:
            response = method(url, response.data, format='json')
            self.assertStatus(response, status.HTTP_405_METHOD_NOT_ALLOWED) 
Example 29
Project: koku   Author: project-koku   File: tests_views.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_post_cost_model_metrics_maps_source_filter(self):
        """Test that a POST call does not work for the Metrics Map."""
        url = reverse("metrics")
        client = APIClient()

        params = {"source_type": Provider.PROVIDER_OCP}
        url = url + "?" + urlencode(params, quote_via=quote_plus)
        response = client.post(url, **self.headers)
        self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) 
Example 30
Project: koku   Author: project-koku   File: tests_views.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_delete_cost_model_metrics_maps_source_filter(self):
        """Test that DELETE call does not work for the Metrics Map."""
        url = reverse("metrics")
        client = APIClient()

        params = {"source_type": Provider.PROVIDER_OCP}
        url = url + "?" + urlencode(params, quote_via=quote_plus)
        response = client.delete(url, **self.headers)
        self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)