Python rest_framework.status.HTTP_201_CREATED Examples

The following are 30 code examples for showing how to use rest_framework.status.HTTP_201_CREATED(). 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: django-puppy-store   Author: realpython   File: views.py    License: MIT License 6 votes vote down vote up
def get_post_puppies(request):
    # get all puppies
    if request.method == 'GET':
        puppies = Puppy.objects.all()
        serializer = PuppySerializer(puppies, many=True)
        return Response(serializer.data)
    # insert a new record for a puppy
    if request.method == 'POST':
        data = {
            'name': request.data.get('name'),
            'age': int(request.data.get('age')),
            'breed': request.data.get('breed'),
            'color': request.data.get('color')
        }
        serializer = PuppySerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) 
Example 2
Project: resolwe   Author: genialis   File: test_data.py    License: Apache License 2.0 6 votes vote down vote up
def test_post(self):
        # logged-in user w/ perms
        collection_n = Data.objects.count()

        resp = self._post(self.data, self.user1)
        self.assertEqual(resp.status_code, status.HTTP_201_CREATED)
        self.assertEqual(Data.objects.count(), collection_n + 1)

        d = Data.objects.get(pk=resp.data["id"])
        self.assertTrue(now() - d.modified < timedelta(seconds=1))
        self.assertTrue(now() - d.created < timedelta(seconds=1))
        self.assertEqual(d.status, "OK")

        self.assertTrue(now() - d.started < timedelta(seconds=1))
        self.assertTrue(now() - d.finished < timedelta(seconds=1))
        self.assertEqual(d.contributor_id, self.user1.pk) 
Example 3
Project: resolwe   Author: genialis   File: test_relations.py    License: Apache License 2.0 6 votes vote down vote up
def test_create_only_entity(self):
        data = {
            "collection": {"id": self.collection.pk},
            "type": "group",
            "category": "clones",
            "partitions": [{"entity": self.entity_3.pk}, {"entity": self.entity_4.pk},],
        }

        resp = self._post(data, user=self.contributor)
        self.assertEqual(resp.status_code, status.HTTP_201_CREATED)

        self.assertEqual(Relation.objects.count(), 3)

        relation = Relation.objects.last()
        self.assertEqual(relation.collection, self.collection)
        self.assertEqual(relation.relationpartition_set.count(), 2)
        self.assertTrue(
            relation.relationpartition_set.filter(entity=self.entity_3.pk).exists()
        )
        self.assertTrue(
            relation.relationpartition_set.filter(entity=self.entity_4.pk).exists()
        ) 
Example 4
Project: django-rest-messaging   Author: raphaelgyory   File: views.py    License: ISC License 6 votes vote down vote up
def post_message(self, request, pk=None):
        """ Pk is the pk of the Thread to which the message belongs. """
        # we get the thread and check for permission
        thread = Thread.objects.get(id=pk)
        self.check_object_permissions(request, thread)
        # we get the body
        body = compat_get_request_data(self.request).get('body')
        # we create the message
        # Message.objects.save() could return an Exception
        try:
            message = Message(sender=request.rest_messaging_participant, thread=thread, body=body)
            message.save()
            serializer = SimpleMessageSerializer(message)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        except Exception:
            return Response(status=status.HTTP_412_PRECONDITION_FAILED) 
Example 5
Project: django-rest-messaging   Author: raphaelgyory   File: views.py    License: ISC License 6 votes vote down vote up
def check(self, request, *args, **kwargs):
        # we get the NotificationCheck instance corresponding to the user or we create it

        try:
            nc = NotificationCheck.objects.get(participant=request.rest_messaging_participant)
            if nc:
                nc.date_check = now()
                nc.save()
            status_code = status.HTTP_200_OK

        except Exception:
            nc = NotificationCheck.objects.create(participant=request.rest_messaging_participant, date_check=now())
            status_code = status.HTTP_201_CREATED

        serializer = self.get_serializer(nc)
        return Response(serializer.data, status=status_code) 
Example 6
Project: longclaw   Author: JamesRamm   File: api.py    License: MIT License 6 votes vote down vote up
def create(self, request):
        """Create a new product request
        """

        variant_id = request.data.get("variant_id", None)
        if variant_id is not None:
            variant = ProductVariant.objects.get(id=variant_id)
            product_request = ProductRequest(variant=variant)
            product_request.save()
            serializer = self.serializer_class(product_request)
            response = Response(data=serializer.data, status=status.HTTP_201_CREATED)
        else:
            response = Response(
                {"message": "Missing 'variant_id'"},
                status=status.HTTP_400_BAD_REQUEST)

        return response 
Example 7
Project: django-channels-chat   Author: narrowfail   File: test_api.py    License: MIT License 6 votes vote down vote up
def test_read_message(self):
        self.login_user1()
        url = reverse('message-api-list')
        message = {'recipient': 'u2', 'body': 'hello'}
        response = self.client.post(url, message, format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.logout()
        # Change user
        self.login_user2()
        url = reverse('message-api-detail', kwargs={'pk': 1})
        response = self.client.get(url, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data['body'], 'hello')
        self.logout()
        # Change to another user (not in conversation)
        self.login_user3()
        response = self.client.get(url, format='json')
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
        self.logout() 
Example 8
Project: aws-workshop   Author: tryolabs   File: views.py    License: MIT License 6 votes vote down vote up
def post(self, request, username=None):
        follower = self.request.user.profile

        try:
            followee = Profile.objects.get(user__username=username)
        except Profile.DoesNotExist:
            raise NotFound('A profile with this username was not found.')

        if follower.pk is followee.pk:
            raise serializers.ValidationError('You can not follow yourself.')

        follower.follow(followee)

        serializer = self.serializer_class(followee, context={
            'request': request
        })

        return Response(serializer.data, status=status.HTTP_201_CREATED) 
Example 9
def test_revoke_refresh_token(self):
        self.client.credentials(
            HTTP_AUTHORIZATION='JWT ' + utils.jwt_encode_handler(
                utils.jwt_payload_handler(self.user)))
        response = self.client.post(self.revoke_url)
        self.assertEqual(
            response.status_code,
            status.HTTP_201_CREATED,
            (response.status_code, response.content)
        )
        new_rt = self.user.refresh_tokens.get()
        self.assertEqual(
            response.data,
            {'key': new_rt.key,
             'app': new_rt.app,
             'user': self.user.pk,
             'created': new_rt.created.isoformat()[:-6] + 'Z',
             })
        response = self.client.post(self.revoke_url)
        self.assertEqual(
            response.status_code,
            status.HTTP_404_NOT_FOUND,
            (response.status_code, response.content)
        ) 
Example 10
Project: desec-stack   Author: desec-io   File: test_donations.py    License: MIT License 6 votes vote down vote up
def test_create_donation(self):
        url = reverse('v1:donation')
        data = {
            'name': 'Komplizierter Vörnämü-ßßß 马大为',
            'iban': 'DE89370400440532013000',
            'bic': 'BYLADEM1SWU',
            'amount': 123.45,
            'message': 'hi there, thank you. Also, some random chars:  ™ • ½ ¼ ¾ ⅓ ⅔ † ‡ µ ¢ £ € « » ♤ ♧ ♥ ♢ ¿ ',
            'email': 'email@example.com',
        }
        response = self.client.post(url, data)
        self.assertTrue(mail.outbox)
        email_internal = str(mail.outbox[0].message())
        direct_debit = str(mail.outbox[0].attachments[0][1])
        self.assertStatus(response, status.HTTP_201_CREATED)
        self.assertEqual(len(mail.outbox), 2)
        self.assertEqual(response.data['iban'], data['iban'])
        self.assertTrue('Komplizierter Vornamu' in direct_debit)
        self.assertTrue(data['iban'] in email_internal) 
Example 11
Project: desec-stack   Author: desec-io   File: test_rrsets_bulk.py    License: MIT License 6 votes vote down vote up
def test_bulk_post_my_rr_sets(self):
        with self.assertPdnsRequests(self.requests_desec_rr_sets_update(name=self.my_empty_domain.name)):
            response = self.client.bulk_post_rr_sets(domain_name=self.my_empty_domain.name, payload=self.data)
            self.assertStatus(response, status.HTTP_201_CREATED)

        response = self.client.get_rr_sets(self.my_empty_domain.name)
        self.assertStatus(response, status.HTTP_200_OK)
        self.assertRRSetsCount(response.data, self.data)

        # Check subname requirement on bulk endpoint (and uniqueness at the same time)
        self.assertResponse(
            self.client.bulk_post_rr_sets(domain_name=self.my_empty_domain.name, payload=self.data_no_subname),
            status.HTTP_400_BAD_REQUEST,
            [
                {'subname': ['This field is required.']},
                {'non_field_errors': ['Another RRset with the same subdomain and type exists for this domain.']}
            ]
        ) 
Example 12
Project: desec-stack   Author: desec-io   File: test_domains.py    License: MIT License 6 votes vote down vote up
def test_create_domains(self):
        self.owner.limit_domains = 100
        self.owner.save()
        for name in [
            '0.8.0.0.0.1.c.a.2.4.6.0.c.e.e.d.4.4.0.1.a.0.1.0.8.f.4.0.1.0.a.2.ip6.arpa',
            'very.long.domain.name.' + self.random_domain_name(),
            self.random_domain_name(),
        ]:
            with self.assertPdnsRequests(self.requests_desec_domain_creation(name)):
                response = self.client.post(self.reverse('v1:domain-list'), {'name': name})
                self.assertStatus(response, status.HTTP_201_CREATED)
                self.assertTrue(all(field in response.data for field in
                                    ['created', 'published', 'name', 'keys', 'minimum_ttl', 'touched']))
                self.assertEqual(len(mail.outbox), 0)
                self.assertTrue(isinstance(response.data['keys'], list))

            with self.assertPdnsRequests(self.request_pdns_zone_retrieve_crypto_keys(name)):
                self.assertStatus(
                    self.client.get(self.reverse('v1:domain-detail', name=name), {'name': name}),
                    status.HTTP_200_OK
                )
                response = self.client.get_rr_sets(name, type='NS', subname='')
                self.assertStatus(response, status.HTTP_200_OK)
                self.assertContainsRRSets(response.data, [dict(subname='', records=settings.DEFAULT_NS, type='NS')]) 
Example 13
Project: desec-stack   Author: desec-io   File: test_domains.py    License: MIT License 6 votes vote down vote up
def test_create_domain_under_public_suffix_with_private_parent(self):
        name = 'amazonaws.com'
        with self.assertPdnsRequests(self.requests_desec_domain_creation(name)[:-1]), PDNSChangeTracker():
            Domain(owner=self.create_user(), name=name).save()
            self.assertTrue(Domain.objects.filter(name=name).exists())

        # If amazonaws.com is owned by another user, we cannot register test.s4.amazonaws.com
        name = 'test.s4.amazonaws.com'
        response = self.client.post(self.reverse('v1:domain-list'), {'name': name})
        self.assertStatus(response, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(response.data['name'][0].code, 'name_unavailable')

        # s3.amazonaws.com is a public suffix. Therefore, test.s3.amazonaws.com can be
        # registered even if the parent zone amazonaws.com is owned by another user
        name = 'test.s3.amazonaws.com'
        psl_cm = self.get_psl_context_manager('s3.amazonaws.com')
        with psl_cm, self.assertPdnsRequests(self.requests_desec_domain_creation(name)):
            response = self.client.post(self.reverse('v1:domain-list'), {'name': name})
            self.assertStatus(response, status.HTTP_201_CREATED) 
Example 14
def post(self, request, format=None):
        """
        curl -X POST -S \
          -H 'Accept: application/json' \
          -H 'Content-Type: multipart/form-data' \
          -H 'Authorization: Token {header_token_key}' \
          -F "selection={selection_code/url_code}" \
          -F "name={candidate name}" \
          -F "about={about}" \
          -F "photo=@/path/to/your_photo.jpg;type=image/jpg" \
          http://localhost:8000/api/v1/candidates
        """
        serializer = CandidateSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save(
                selection=Selection.objects.get(code=request.data.get('selection')),
                photo=request.data.get('photo')
            )
            return Response(data=serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) 
Example 15
Project: MPContribs   Author: materialsproject   File: views.py    License: MIT License 5 votes vote down vote up
def rest_submission(request):
    if request.method == "POST":
        serializer = QMCDBSetSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response([serializer.errors], status=status.HTTP_400_BAD_REQUEST)
    return HttpResponse(status=400) 
Example 16
Project: django-puppy-store   Author: realpython   File: test_views.py    License: MIT License 5 votes vote down vote up
def test_create_valid_puppy(self):
        response = client.post(
            reverse('get_post_puppies'),
            data=json.dumps(self.valid_payload),
            content_type='application/json'
        )
        self.assertEqual(response.status_code, status.HTTP_201_CREATED) 
Example 17
Project: controller   Author: deis   File: views.py    License: MIT License 5 votes vote down vote up
def create(self, request, **kwargs):
        appSettings = self.get_app().appsettings_set.latest()
        addresses = self.get_serializer().validate_whitelist(request.data.get('addresses'))
        addresses = list(set(appSettings.whitelist) | set(addresses))
        new_appsettings = appSettings.new(self.request.user, whitelist=addresses)
        return Response({"addresses": new_appsettings.whitelist}, status=status.HTTP_201_CREATED) 
Example 18
Project: controller   Author: deis   File: views.py    License: MIT License 5 votes vote down vote up
def attach(self, request, *args, **kwargs):
        try:
            if kwargs['domain'] is None and not request.data.get('domain'):
                raise DeisException("domain is a required field")
            elif request.data.get('domain'):
                kwargs['domain'] = request.data['domain']

            self.get_object().attach(*args, **kwargs)
        except Http404:
            raise

        return Response(status=status.HTTP_201_CREATED) 
Example 19
Project: controller   Author: deis   File: views.py    License: MIT License 5 votes vote down vote up
def rollback(self, request, **kwargs):
        """
        Create a new release as a copy of the state of the compiled slug and config vars of a
        previous release.
        """
        release = self.get_app().release_set.filter(failed=False).latest()
        new_release = release.rollback(request.user, request.data.get('version', None))
        response = {'version': new_release.version}
        return Response(response, status=status.HTTP_201_CREATED) 
Example 20
Project: controller   Author: deis   File: views.py    License: MIT License 5 votes vote down vote up
def create(self, request, **kwargs):
        app = self.get_object()
        if not permissions.IsOwnerOrAdmin.has_object_permission(permissions.IsOwnerOrAdmin(),
                                                                request, self, app):
            raise PermissionDenied()

        user = get_object_or_404(User, username=request.data['username'])
        assign_perm(self.perm, user, app)
        app.log("User {} was granted access to {}".format(user, app))
        return Response(status=status.HTTP_201_CREATED) 
Example 21
Project: controller   Author: deis   File: views.py    License: MIT License 5 votes vote down vote up
def create(self, request, **kwargs):
        user = get_object_or_404(User, username=request.data['username'])
        user.is_superuser = user.is_staff = True
        user.save(update_fields=['is_superuser', 'is_staff'])
        return Response(status=status.HTTP_201_CREATED) 
Example 22
Project: normandy   Author: mozilla   File: views.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def request_approval(self, request, pk=None):
        revision = self.get_object()

        if revision.approval_status is not None:
            return Response(
                {"error": "This revision already has an approval request."},
                status=status.HTTP_400_BAD_REQUEST,
            )

        approval_request = revision.request_approval(creator=request.user)

        return Response(
            ApprovalRequestSerializer(approval_request).data, status=status.HTTP_201_CREATED
        ) 
Example 23
Project: hummer   Author: wangtaoking1   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def create(self, request, *args, **kwargs):
        """
        Create project by only admin users.
        """
        self.check_admin_permission()

        project = Project.objects.filter(name=request.data.get('name', None))
        if project:
            raise ValidationError(detail="Already has an project called {}."
                .format(request.data['name']))

        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        response = Response(serializer.data, status=status.HTTP_201_CREATED,
            headers=headers)

        # Create the namespace
        try:
            kubeclient = KubeClient("http://{}:{}{}".format(settings.MASTER_IP,
                settings.K8S_PORT, settings.K8S_API_PATH))
            kubeclient.create_namespace(serializer.data['name'])
        except Exception as e:
            logger.error(e)

        logger.info("User {} create a new project {}.".format(
            request.user.username, serializer.data['name']))

        return response 
Example 24
Project: django-rest-registration   Author: apragacz   File: register.py    License: MIT License 5 votes vote down vote up
def register(request):
    '''
    Register new user.
    '''
    serializer_class = registration_settings.REGISTER_SERIALIZER_CLASS
    serializer = serializer_class(
        data=request.data,
        context={'request': request},
    )
    serializer.is_valid(raise_exception=True)

    kwargs = {}

    if registration_settings.REGISTER_VERIFICATION_ENABLED:
        verification_flag_field = get_user_setting('VERIFICATION_FLAG_FIELD')
        kwargs[verification_flag_field] = False
        email_field_name = get_user_email_field_name()
        if (email_field_name not in serializer.validated_data
                or not serializer.validated_data[email_field_name]):
            raise BadRequest(_("User without email cannot be verified"))

    with transaction.atomic():
        user = serializer.save(**kwargs)
        if registration_settings.REGISTER_VERIFICATION_ENABLED:
            send_register_verification_email_notification(request, user)

    signals.user_registered.send(sender=None, user=user, request=request)
    output_serializer_class = registration_settings.REGISTER_OUTPUT_SERIALIZER_CLASS  # noqa: E501
    output_serializer = output_serializer_class(
        instance=user,
        context={'request': request},
    )
    user_data = output_serializer.data
    return Response(user_data, status=status.HTTP_201_CREATED) 
Example 25
Project: django-rest-registration   Author: apragacz   File: api_views.py    License: MIT License 5 votes vote down vote up
def assert_response_status_is_created(response):
    assert_valid_response(
        response,
        expected_status_code=status.HTTP_201_CREATED,
    ) 
Example 26
Project: django-rest-registration   Author: apragacz   File: test_register.py    License: MIT License 5 votes vote down vote up
def test_register_ok(self):
        data = self._get_register_user_data(password='testpassword')
        request = self.create_post_request(data)
        with self.assert_one_mail_sent() as sent_emails, self.timer() as timer:
            response = self.view_func(request)
            self.assert_valid_response(response, status.HTTP_201_CREATED)
        user_id = response.data['id']
        # Check database state.
        user = self.user_class.objects.get(id=user_id)
        self.assertEqual(user.username, data['username'])
        self.assertTrue(user.check_password(data['password']))
        self.assertFalse(user.is_active)
        # Check verification e-mail.
        sent_email = sent_emails[0]
        self.assertEqual(sent_email.from_email, VERIFICATION_FROM_EMAIL)
        self.assertListEqual(sent_email.to, [data['email']])
        url = self.assert_one_url_line_in_text(sent_email.body)

        verification_data = self.assert_valid_verification_url(
            url,
            expected_path=REGISTER_VERIFICATION_URL,
            expected_fields={'signature', 'user_id', 'timestamp'},
        )
        url_user_id = int(verification_data['user_id'])
        self.assertEqual(url_user_id, user_id)
        url_sig_timestamp = int(verification_data['timestamp'])
        self.assertGreaterEqual(url_sig_timestamp, timer.start_time)
        self.assertLessEqual(url_sig_timestamp, timer.end_time)
        signer = RegisterSigner(verification_data)
        signer.verify() 
Example 27
Project: django-rest-registration   Author: apragacz   File: test_register.py    License: MIT License 5 votes vote down vote up
def test_register_with_username_as_verification_id_ok(self):
        # Using username is not recommended if it can change for a given user.
        data = self._get_register_user_data(password='testpassword')
        request = self.create_post_request(data)
        with self.assert_one_mail_sent() as sent_emails, self.timer() as timer:
            response = self.view_func(request)
            self.assert_valid_response(response, status.HTTP_201_CREATED)
        user_id = response.data['id']
        # Check database state.
        user = self.user_class.objects.get(id=user_id)
        self.assertEqual(user.username, data['username'])
        self.assertTrue(user.check_password(data['password']))
        self.assertFalse(user.is_active)
        # Check verification e-mail.
        sent_email = sent_emails[0]
        self.assertEqual(sent_email.from_email, VERIFICATION_FROM_EMAIL)
        self.assertListEqual(sent_email.to, [data['email']])
        url = self.assert_one_url_line_in_text(sent_email.body)

        verification_data = self.assert_valid_verification_url(
            url,
            expected_path=REGISTER_VERIFICATION_URL,
            expected_fields={'signature', 'user_id', 'timestamp'},
        )
        user_verification_id = verification_data['user_id']
        self.assertEqual(user_verification_id, user.username)
        url_sig_timestamp = int(verification_data['timestamp'])
        self.assertGreaterEqual(url_sig_timestamp, timer.start_time)
        self.assertLessEqual(url_sig_timestamp, timer.end_time)
        signer = RegisterSigner(verification_data)
        signer.verify() 
Example 28
Project: django-rest-registration   Author: apragacz   File: test_register.py    License: MIT License 5 votes vote down vote up
def test_register_with_custom_verification_url_ok(self):
        data = self._get_register_user_data(password='testpassword')
        request = self.create_post_request(data)
        with self.assert_one_mail_sent() as sent_emails, self.timer() as timer:
            response = self.view_func(request)
            self.assert_valid_response(response, status.HTTP_201_CREATED)
        user_id = response.data['id']
        # Check database state.
        user = self.user_class.objects.get(id=user_id)
        self.assertEqual(user.username, data['username'])
        self.assertTrue(user.check_password(data['password']))
        self.assertFalse(user.is_active)
        # Check verification e-mail.
        sent_email = sent_emails[0]
        self.assertEqual(sent_email.from_email, VERIFICATION_FROM_EMAIL)
        self.assertListEqual(sent_email.to, [data['email']])
        url = self.assert_one_url_line_in_text(sent_email.body)

        verification_data = self.assert_valid_verification_url(
            url,
            expected_path=REGISTER_VERIFICATION_URL,
            expected_fields=['user_id', 'signature', 'timestamp'],
            url_parser=parse_custom_verification_url,
        )
        url_user_id = int(verification_data['user_id'])
        self.assertEqual(url_user_id, user_id)
        url_sig_timestamp = int(verification_data['timestamp'])
        self.assertGreaterEqual(url_sig_timestamp, timer.start_time)
        self.assertLessEqual(url_sig_timestamp, timer.end_time)
        signer = RegisterSigner(verification_data)
        signer.verify() 
Example 29
Project: django-rest-registration   Author: apragacz   File: test_register.py    License: MIT License 5 votes vote down vote up
def test_register_no_password_confirm_ok(self):
        data = self._get_register_user_data(password='testpassword')
        data.pop('password_confirm')
        request = self.create_post_request(data)
        with self.assert_one_mail_sent() as sent_emails, self.timer() as timer:
            response = self.view_func(request)
            self.assert_valid_response(response, status.HTTP_201_CREATED)
        user_id = response.data['id']
        # Check database state.
        user = self.user_class.objects.get(id=user_id)
        self.assertEqual(user.username, data['username'])
        self.assertTrue(user.check_password(data['password']))
        self.assertFalse(user.is_active)
        # Check verification e-mail.
        sent_email = sent_emails[0]
        self.assertEqual(sent_email.from_email, VERIFICATION_FROM_EMAIL)
        self.assertListEqual(sent_email.to, [data['email']])
        url = self.assert_one_url_line_in_text(sent_email.body)

        verification_data = self.assert_valid_verification_url(
            url,
            expected_path=REGISTER_VERIFICATION_URL,
            expected_fields={'signature', 'user_id', 'timestamp'},
        )
        url_user_id = int(verification_data['user_id'])
        self.assertEqual(url_user_id, user_id)
        url_sig_timestamp = int(verification_data['timestamp'])
        self.assertGreaterEqual(url_sig_timestamp, timer.start_time)
        self.assertLessEqual(url_sig_timestamp, timer.end_time)
        signer = RegisterSigner(verification_data)
        signer.verify() 
Example 30
Project: django-rest-registration   Author: apragacz   File: test_register.py    License: MIT License 5 votes vote down vote up
def test_register_without_verification_ok(self):
        data = self._get_register_user_data(password='testpassword')
        request = self.create_post_request(data)
        with self.assert_no_mail_sent():
            response = self.view_func(request)
            self.assert_valid_response(response, status.HTTP_201_CREATED)
        user_id = response.data['id']
        user = self.user_class.objects.get(id=user_id)
        self.assertEqual(user.username, data['username'])
        self.assertTrue(user.check_password(data['password']))
        self.assertTrue(user.is_active)