def test_recaptchafield_validation_messages_error( messages, recaptcha_response, expected_error ): field = ReCaptchaField(error_messages=messages) assert len(field.validators) == 1 assert isinstance(field.validators[0], ReCaptchaValidator) field.validators[0]._get_recaptcha_response = mock.Mock( return_value=recaptcha_response ) with pytest.raises(serializers.ValidationError) as excinfo: field.run_validators("token") assert expected_error in str(excinfo.value)
class EventRegistrationSerializer(serializers.ModelSerializer): participants = EventParticipantSerializer(many=True) recaptcha = ReCaptchaField(error_messages={ "invalid-input-response": "reCAPTCHA token is invalid.", "idiot": "Don't try to hack (tum se na ho paayga", }) class Meta: model = EventRegistrationModel fields = ("participants", "college_name", "college_code", "faculty_name", "faculty_designation", "faculty_phn_no", "faculty_email", "event", "recaptcha", "faculty_gender") def create(self, validated_data): registration_data = { 'college_name': validated_data.get("college_name"), 'college_code': validated_data.get("college_code"), 'faculty_name': validated_data.get("faculty_name"), 'faculty_designation': validated_data.get("faculty_designation"), 'faculty_phn_no': validated_data.get("faculty_phn_no"), 'faculty_email': validated_data.get("faculty_email"), 'event': validated_data.get("event"), 'faculty_gender': validated_data.get("faculty_gender") } event = validated_data.get("event") dict_event = model_to_dict( event ) participants = validated_data.get("participants") if not participants or len(participants) == 0: raise serializers.ValidationError("No Paticpants provided.") if len(participants) > dict_event['maxp']: raise serializers.ValidationError("Paticpants exceeds provided limit") EventRegistrationModel.objects.do_registration(registration_data, participants, False) return validated_data
class ContactMessageSerializer(serializers.Serializer): recaptcha = ReCaptchaField() full_name = serializers.CharField(max_length=100) phone_number = serializers.CharField(max_length=50) email = serializers.EmailField(max_length=100) title = serializers.CharField(max_length=100) body = serializers.CharField(max_length=400)
class HelpRequestSerializer(serializers.Serializer): recaptcha = ReCaptchaField() first_name = serializers.CharField(max_length=50) last_name = serializers.CharField(max_length=50) position = serializers.CharField(max_length=50) hospital_name = serializers.CharField(max_length=250) locality_id = serializers.IntegerField(allow_null=False) phone_number = serializers.CharField(max_length=100) description = serializers.CharField(max_length=500)
class PetitionFormSerializers(ModelSerializer): recaptcha = ReCaptchaField() class Meta: model = PetitionForm fields = ( 'id', 'first_name', 'last_name', 'email', 'phone_number1', 'petition', 'recaptcha', )
class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ["id", "username", "email", "password", "recaptcha"] extra_kwargs = {"password": {"write_only": True}} recaptcha = ReCaptchaField() def save(self, **kwargs): del self.validated_data["recaptcha"] User.objects.create_user( **self.validated_data, **kwargs, )
class ActivFormSerializers(ModelSerializer): recaptcha = ReCaptchaField() class Meta: model = ActivForm fields = ( 'id', 'first_name', 'last_name', 'email', 'phone_number1', 'product_id', 'recaptcha', ) depth = 3
class UserCreateSerializer(serializers.ModelSerializer): password = serializers.CharField(style={"input_type": "password"}, write_only=True) recaptcha = ReCaptchaField() default_error_messages = { "cannot_create_user": settings.CONSTANTS.messages.CANNOT_CREATE_USER_ERROR } class Meta: model = User fields = tuple(User.REQUIRED_FIELDS) + ( settings.LOGIN_FIELD, User._meta.pk.name, "password", "recaptcha") def validate(self, attrs): user = User(**attrs) password = attrs.get("password") try: validate_password(password, user) except django_exceptions.ValidationError as e: serializer_error = serializers.as_serializer_error(e) raise serializers.ValidationError( {"password": serializer_error["non_field_errors"]}) return attrs def create(self, validated_data): try: user = self.perform_create(validated_data) except IntegrityError: self.fail("cannot_create_user") return user def perform_create(self, validated_data): with transaction.atomic(): user = User.objects.create_user(**validated_data) if settings.SEND_ACTIVATION_EMAIL: user.is_active = False user.save(update_fields=["is_active"]) return user
class RegisterUserSerializer(serializers.ModelSerializer): recaptcha = ReCaptchaField() password = PasswordField(write_only=True, validators=[validate_password], label=_("Password")) class Meta: model = User fields = ["email", "name", "nickname", "password", "recaptcha"] ref_name = None def create(self, validated_data): validated_data.pop("recaptcha") instance = super().create(validated_data) instance.send_welcome_email() return instance @staticmethod def validate_password(value): return make_password(value)
class MySerializer(serializers.Serializer): recaptcha = ReCaptchaField(write_only=True)
def test_recaptchafield_has_recaptcha_validator(): field = ReCaptchaField() assert len(field.validators) == 1 assert isinstance(field.validators[0], ReCaptchaValidator)
def test_recaptchafield_write_only(params, expected): field = ReCaptchaField(**params) assert field.write_only is expected
class ReCaptchaSerializer(serializers.Serializer): recaptcha = ReCaptchaField()
def test_recaptchafield_has_recaptcha_validator(): field = ReCaptchaField() nb_validators = len(field.validators) assert nb_validators > 0 assert isinstance(field.validators[nb_validators - 1], ReCaptchaValidator)