def test_gateway(self, client):
        twilio = Twilio()
        client.assert_called_with('SID', 'TOKEN')

        for code in ['654321', '054321', '87654321', '07654321']:
            twilio.make_call(device=Mock(number=PhoneNumber.from_string('+123')), token=code)
            client.return_value.calls.create.assert_called_with(
                from_='+456', to='+123', method='GET', timeout=15,
                url='http://testserver/twilio/inbound/two_factor/%s/?locale=en-us' % code)

            twilio.send_sms(device=Mock(number=PhoneNumber.from_string('+123')), token=code)
            client.return_value.messages.create.assert_called_with(
                to='+123', body='Your authentication token is %s' % code, from_='+456')

            client.return_value.calls.create.reset_mock()
            with translation.override('en-gb'):
                twilio.make_call(device=Mock(number=PhoneNumber.from_string('+123')), token=code)
                client.return_value.calls.create.assert_called_with(
                    from_='+456', to='+123', method='GET', timeout=15,
                    url='http://testserver/twilio/inbound/two_factor/%s/?locale=en-gb' % code)

            client.return_value.calls.create.reset_mock()
            with translation.override('en-gb'):
                twilio.make_call(device=Mock(number=PhoneNumber.from_string('+123')), token=code)
                client.return_value.calls.create.assert_called_with(
                    from_='+456', to='+123', method='GET', timeout=15,
                    url='http://testserver/twilio/inbound/two_factor/%s/?locale=en-gb' % code)
    def test_gateway(self, client):
        twilio = Twilio()
        client.assert_called_with('SID', 'TOKEN')

        for code in ['654321', '054321', '87654321', '07654321']:
            twilio.make_call(device=Mock(number=PhoneNumber.from_string('+123')), token=code)
            client.return_value.calls.create.assert_called_with(
                from_='+456', to='+123', method='GET', timeout=15,
                url='http://testserver/twilio/inbound/two_factor/%s/?locale=en-us' % code)

            twilio.send_sms(device=Mock(number=PhoneNumber.from_string('+123')), token=code)
            client.return_value.messages.create.assert_called_with(
                to='+123', body='Your authentication token is %s' % code, from_='+456')

            client.return_value.calls.create.reset_mock()
            with translation.override('en-gb'):
                twilio.make_call(device=Mock(number=PhoneNumber.from_string('+123')), token=code)
                client.return_value.calls.create.assert_called_with(
                    from_='+456', to='+123', method='GET', timeout=15,
                    url='http://testserver/twilio/inbound/two_factor/%s/?locale=en-gb' % code)

            client.return_value.calls.create.reset_mock()
            with translation.override('en-gb'):
                twilio.make_call(device=Mock(number=PhoneNumber.from_string('+123')), token=code)
                client.return_value.calls.create.assert_called_with(
                    from_='+456', to='+123', method='GET', timeout=15,
                    url='http://testserver/twilio/inbound/two_factor/%s/?locale=en-gb' % code)
 def test_valid_numbers_are_valid(self):
     numbers = [PhoneNumber.from_string(number_string)
                for number_string in self.equal_number_strings]
     self.assertTrue(all([number.is_valid() for number in numbers]))
     numbers = [PhoneNumber.from_string(number_string, region=region)
                for region, number_string in self.local_numbers]
     self.assertTrue(all([number.is_valid() for number in numbers]))
Esempio n. 4
0
 def test_valid_numbers_are_valid(self):
     numbers = [PhoneNumber.from_string(number_string)
                for number_string in self.equal_number_strings]
     self.assertTrue(all(number.is_valid() for number in numbers))
     numbers = [PhoneNumber.from_string(number_string, region=region)
                for region, number_string in self.local_numbers]
     self.assertTrue(all(number.is_valid() for number in numbers))
Esempio n. 5
0
def seed_data(transactional_db):
    u1 = User.objects.create(username="******", first_name="Jenny")
    u1.profile.phone_number = PhoneNumber.from_string("+1 999 8675309")
    u1.profile.save()
    u2 = User.objects.create(username="******",
                             first_name="Taylor",
                             last_name="Swift")
    u2.profile.phone_number = PhoneNumber.from_string("+31 9921547733")
    u2.profile.save()
 def test_ordering(self):
     phone1 = PhoneNumber.from_string("+33600000000")
     phone2 = PhoneNumber.from_string("+33600000001")
     self.assertLess(phone1, phone2)
     # Ordering is total.
     self.assertGreater(phone2, phone1)
     self.assertLessEqual(phone1, phone1)
     self.assertGreaterEqual(phone1, phone1)
     self.assertEqual(phone1, phone1)
Esempio n. 7
0
 def test_eq_and_ne(self):
     number_1 = "+411111111"
     number_2 = "+412222222"
     one = PhoneNumber.from_string("+411111111")
     two = PhoneNumber.from_string("+412222222")
     self.assertNotEqual(one, two)
     self.assertNotEqual(one, number_2)
     self.assertNotEqual(number_2, one)
     self.assertEqual(one, number_1)
     self.assertEqual(number_1, one)
Esempio n. 8
0
 def test_eq_and_ne(self):
     number_1 = '+411111111'
     number_2 = '+412222222'
     one = PhoneNumber.from_string('+411111111')
     two = PhoneNumber.from_string('+412222222')
     self.assertNotEqual(one, two)
     self.assertNotEqual(one, number_2)
     self.assertNotEqual(number_2, one)
     self.assertEqual(one, number_1)
     self.assertEqual(number_1, one)
 def test_eq_and_ne(self):
     number_1 = "+411111111"
     number_2 = "+412222222"
     one = PhoneNumber.from_string("+411111111")
     two = PhoneNumber.from_string("+412222222")
     self.assertNotEqual(one, two)
     self.assertNotEqual(one, number_2)
     self.assertNotEqual(number_2, one)
     self.assertEqual(one, number_1)
     self.assertEqual(number_1, one)
    def test_gateway(self, logger):
        fake = Fake()

        for code in ['654321', '87654321']:
            fake.make_call(device=Mock(number=PhoneNumber.from_string('+123')), token=code)
            logger.info.assert_called_with(
                'Fake call to %s: "Your token is: %s"', '+123', code)

            fake.send_sms(device=Mock(number=PhoneNumber.from_string('+123')), token=code)
            logger.info.assert_called_with(
                'Fake SMS to %s: "Your token is: %s"', '+123', code)
 def test_ordering_with_invalid_value(self):
     phone1 = PhoneNumber.from_string("+33600000000")
     invalid = PhoneNumber.from_string("+1000000000")
     invalid_phonenumbers = phonenumbers.parse("+1000000000")
     for number in [invalid, invalid_phonenumbers]:
         with self.subTest(number):
             for p1, p2 in [[phone1, number], [number, phone1]]:
                 with self.subTest([p1, p2]):
                     with self.assertRaisesRegex(
                             ValueError, r"^Invalid phone number: "):
                         self.assertLess(p1, p2)
    def test_gateway(self, logger):
        fake = Fake()

        for code in ['654321', '87654321']:
            fake.make_call(device=Mock(number=PhoneNumber.from_string('+123')), token=code)
            logger.info.assert_called_with(
                'Fake call to %s: "Your token is: %s"', '+123', code)

            fake.send_sms(device=Mock(number=PhoneNumber.from_string('+123')), token=code)
            logger.info.assert_called_with(
                'Fake SMS to %s: "Your token is: %s"', '+123', code)
Esempio n. 13
0
    def handle(self, *args, **kwargs):
        print("Don't worry, it always takes this long.")

        for fd in FireDepartment.objects.all():
            # If the FD has a phone number, clean it up
            if fd.headquarters_phone and not fd.headquarters_phone.raw_input == "Invalid Input":
                try:
                    new_phone = PhoneNumber.from_string(
                        fd.headquarters_phone.raw_input)

                    if new_phone.is_valid():
                        fd.headquarters_phone = new_phone
                        valid.append(new_phone)
                    else:
                        invalid.append(new_phone)
                        fd.headquarters_phone = None

                except NumberParseException:
                    invalid.append(new_phone)
                    fd.headquarters_phone = None

            # If the FD has a fax number, clean it up
            if fd.headquarters_fax and not fd.headquarters_fax.raw_input == "Invalid Input":
                try:
                    new_fax = PhoneNumber.from_string(
                        fd.headquarters_fax.raw_input)

                    if new_fax.is_valid():
                        fd.headquarters_fax = new_fax
                        valid.append(new_fax)
                    else:
                        invalid.append(new_fax)
                        fd.headquarters_fax = None

                except NumberParseException:
                    invalid.append(new_fax)
                    fd.headquarters_fax = None

            # Save and continue to the next FD (if any)
            fd.save()

        print 'Valid Numbers: {}'.format(len(valid))
        print 'Invalid numbers: {}'.format(len(invalid))
        print 'Invald percent: {}'.format(
            len(invalid) / (len(valid) + len(invalid)))
        print 'Invalid numbers: ', map(str, invalid)

        print("Completed successfully!")
Esempio n. 14
0
def get_phone_number(raw_number, country):
    # Dealing with exceptions
    raw_number = re.sub(r'^\+00', '+', raw_number)
    raw_number = re.sub(r'^\+42 602 ', '+420 602 ', raw_number)
    raw_number = re.sub(r'(^\+01 |^00-1-|^00 1 )', '+1 ', raw_number)  # US
    raw_number = re.sub(r'^045 ', '+45 ', raw_number)  # DK
    raw_number = re.sub(r'(^80|^380\+|^\+38-|^38-)', '+380 ', raw_number)  # UA
    raw_number = re.sub(r'(^55|^00 55|^055)', '+55 ', raw_number) if country == 'BR' else raw_number
    raw_number = re.sub(r'^0041 ', '+41 ', raw_number)  # CH
    raw_number = re.sub(r'(^0086\-|^86)', '+86 ', raw_number)  # CN
    raw_number = re.sub(r'(^\+098 |^0)', '+98 ', raw_number) if country == 'IR' else raw_number
    raw_number = re.sub(r'^\+69 ', '+49 69 ', raw_number)
    raw_number = re.sub(r'^\+80 ', '+81 ', raw_number)
    raw_number = re.sub(r'^54\+011\+', '+54 011 ', raw_number)
    raw_number = re.sub(r'( \(eksterlande$| \(enlande\)$)', '', raw_number)
    raw_number = re.sub(r' \(nur en Japanio\)$', '', raw_number)
    raw_number = re.sub(r' \(p\.3257\)$', '', raw_number)
    raw_number = re.sub(r'\(20\-23h UTC\)', '', raw_number)
    raw_number = re.sub(r'\(0\)', '', raw_number)  # Remove (0)
    raw_number = re.sub(r'(\(|\))', '', raw_number)  # Remove parenthesis
    raw_number = re.sub(r'(\-|\.)', ' ', raw_number)  # Remove '-' and '.'
    raw_number = raw_number.lower().strip('ifmnty oi zs')
    if raw_number and len(raw_number) > 3:
        _country = [country] if country else []
        try:
            phone_number = PhoneNumber.from_string(raw_number, *_country)
            return phone_number.as_e164
        except NumberParseException as e:
            print('  Invalid phone number:', country, raw_number, ' Error', e)
    return ''
Esempio n. 15
0
def get_phone_info(request, raw_phone):
    try:
        phone = PhoneNumber.from_string(phone_number=raw_phone)
    except NumberParseException:
        raise Http404

    if not phone.is_valid():
        raise Http404

    code = int(raw_phone[1:4])
    number = int(raw_phone[4:])
    try:
        phone_info = PhoneNumbering.objects.get(
            code=code,
            start__lte=number,
            end__gte=number,
        )
    except PhoneNumbering.DoesNotExist:
        return Response(
            {
                'detail':
                f"Информация о номере телефона '{phone.as_e164}' "
                f"отсутствует."
            },
            status=https_status.HTTP_400_BAD_REQUEST)

    return Response({
        'operator': phone_info.operator_name,
        'region': phone_info.region_name,
    })
Esempio n. 16
0
def format_phonenumber(potential_number):
    try:
        number = PhoneNumber.from_string(potential_number)
        logger.debug("Got number in search for %s" % number)
        return str(number)
    except Exception as e:
        return potential_number
Esempio n. 17
0
def get_phone_number(raw_number, country):
    # Dealing with exceptions
    raw_number = re.sub(r'^\+00', '+', raw_number)
    raw_number = re.sub(r'^\+42 602 ', '+420 602 ', raw_number)
    raw_number = re.sub(r'(^\+01 |^00-1-|^00 1 )', '+1 ', raw_number)  # US
    raw_number = re.sub(r'^045 ', '+45 ', raw_number)  # DK
    raw_number = re.sub(r'(^80|^380\+|^\+38-|^38-)', '+380 ', raw_number)  # UA
    raw_number = re.sub(r'(^55|^00 55|^055)', '+55 ', raw_number) if country == 'BR' else raw_number
    raw_number = re.sub(r'^0041 ', '+41 ', raw_number)  # CH
    raw_number = re.sub(r'(^0086\-|^86)', '+86 ', raw_number)  # CN
    raw_number = re.sub(r'(^\+098 |^0)', '+98 ', raw_number) if country == 'IR' else raw_number
    raw_number = re.sub(r'^\+69 ', '+49 69 ', raw_number)
    raw_number = re.sub(r'^\+80 ', '+81 ', raw_number)
    raw_number = re.sub(r'^54\+011\+', '+54 011 ', raw_number)
    raw_number = re.sub(r'( \(eksterlande$| \(enlande\)$)', '', raw_number)
    raw_number = re.sub(r' \(nur en Japanio\)$', '', raw_number)
    raw_number = re.sub(r' \(p\.3257\)$', '', raw_number)
    raw_number = re.sub(r'\(20\-23h UTC\)', '', raw_number)
    raw_number = re.sub(r'\(0\)', '', raw_number)  # Remove (0)
    raw_number = re.sub(r'(\(|\))', '', raw_number)  # Remove parenthesis
    raw_number = re.sub(r'(\-|\.)', ' ', raw_number)  # Remove '-' and '.'
    raw_number = raw_number.lower().strip('ifmnty oi zs')
    if raw_number and len(raw_number) > 3:
        _country = [country] if country else []
        try:
            phone_number = PhoneNumber.from_string(raw_number, *_country)
            return phone_number.as_e164
        except NumberParseException as e:
            print('  Invalid phone number:', country, raw_number, ' Error', e)
    return ''
Esempio n. 18
0
def test_view_order_address_edit(admin_client, order_with_lines,
                                 address_other_country):

    order = order_with_lines
    new_address = address_other_country

    new_address.phone = PhoneNumber.from_string(
        region=new_address.country.code, phone_number="+33.600000000")

    address_data = new_address.as_data()
    address_data.pop("phone")

    address_data.update({"phone_0": "+33", "phone_1": "600000000"})

    url = reverse(
        "dashboard:address-edit",
        kwargs={
            "order_pk": order.pk,
            "address_type": "shipping"
        },
    )

    response = admin_client.post(url, address_data)
    assert response.status_code == 302

    order.refresh_from_db(fields=["shipping_address"])
    assert new_address.as_data() == order.shipping_address.as_data()
Esempio n. 19
0
def test_view_order_address_edit(admin_client, order_with_lines,
                                 address_other_country):

    order = order_with_lines
    new_address = address_other_country

    new_address.phone = PhoneNumber.from_string(
        region=new_address.country.code, phone_number='+33.600000000')

    address_data = new_address.as_data()
    address_data.pop('phone')

    address_data.update({'phone_0': '+33', 'phone_1': '600000000'})

    url = reverse('dashboard:address-edit',
                  kwargs={
                      'order_pk': order.pk,
                      'address_type': 'shipping'
                  })

    response = admin_client.post(url, address_data)
    assert response.status_code == 302

    order.refresh_from_db(fields=['shipping_address'])
    assert new_address.as_data() == order.shipping_address.as_data()
def test_basic_write(client_query):
    response = client_query(
        """
        mutation CreateUser {
            createUser(input: { username: "******", password: "******", phoneNumber: "+1 2125552368"}) {
                user {
                    username
                    profile {
                        phoneNumber
                    }
                }
                errors {
                    field
                    messages
                }
            }
        }
        """,
    )

    content = json.loads(response.content)
    assert "errors" not in content
    assert content["data"] == {
        "createUser": {
            "user": {"username": "******", "profile": {"phoneNumber": "(212) 555-2368"}},
            "errors": [],
        }
    }
    assert User.objects.count() == 3
    user = User.objects.last()
    assert user.username == "alice"
    assert user.profile.phone_number == PhoneNumber.from_string("2125552368")
Esempio n. 21
0
def test_clean_data():
    assert clean_data({
        "A": 1,
        "B": None,
        "C": 2.2,
        "D": b"foo\0bar",
        "E": "foo\0bar\nbaz",
        "F": "x" * MAX_FIELD_LEN * 2,
        "G": set(),
        "H": [],
        "I": {},
        "J": PhoneNumber.from_string("+16175551234"),
        "K": "Hagåtña",
    }) == {
        "A": 1,
        "B": None,
        "C": 2.2,
        "D": "foobar",
        "E": "foobar\nbaz",
        "F": "x" * MAX_FIELD_LEN,
        "G": "set()",
        "H": "[]",
        "I": "{}",
        "J": "(617) 555-1234",
        "K": "Hagatna",
    }
    def get_formatted_value(self, field_name, value, html=False):
        if field_name not in self.fields:
            return value

        if value is None:
            return "NA"

        field = self.fields[field_name]

        if isinstance(field, forms.DateTimeField):
            date = iso8601.parse_date(value)
            return localize(date.astimezone(get_current_timezone()))
        elif isinstance(field, PhoneNumberField):
            try:
                phone_number = PhoneNumber.from_string(value)
                return phone_number.as_international
            except NumberParseException:
                return value
        elif isinstance(field, forms.FileField):
            url = settings.FRONT_DOMAIN + settings.MEDIA_URL + value
            if html:
                return format_html('<a href="{}">Accéder au fichier</a>', url)
            else:
                return url

        return value
Esempio n. 23
0
 def clean_phone_number_raw(self):
     error_messages = {
         'non_int':
         ('Could not recognize phone number. Please only user numbers and these characters: '
          '-, (, ), +'),
         'general':
         ('Error saving phone number or format unrecognized. Please try again.'
          ),
     }
     input = self.cleaned_data['phone_number_raw']
     input = input.replace('-', '').replace('(',
                                            '').replace(')', '').replace(
                                                ' ', '').replace('+', '')
     try:
         input = int(input)
     except:
         raise ValidationError(error_messages['non_int'])
     try:
         ## Make sure this can be stored as PhoneNumber object
         phone = TruePhoneNumber(country_code=self.cleaned_data.get(
             'phone_number_country_code'),
                                 national_number=input)
         ## Make sure this can be stored as a django PhoneNumberField
         pnf_phone = PhoneNumber.from_string('+' + str(phone.country_code) +
                                             str(phone.national_number))
         if not pnf_phone.is_valid():
             raise ValidationError(error_messages['non_int'])
     except Exception as e:
         raise ValidationError(error_messages['general'])
     return pnf_phone
Esempio n. 24
0
    def telephone_link(self):
        phone_number = PhoneNumber.from_string(choice(self.telephones))

        return format_html(
            '<a href="tel:{international}">{national}</a>',
            international=phone_number.as_e164,
            national=phone_number.as_national,
        )
Esempio n. 25
0
    def get_username(self, email_or_phone):
        try:
            email_or_phone = PhoneNumber.from_string(
                phone_number=email_or_phone, region='RU').as_e164
            return email_or_phone

        except NumberParseException:
            return email_or_phone
Esempio n. 26
0
 def test_same_number_has_same_hash(self):
     numbers = [PhoneNumber.from_string(number_string)
                for number_string in self.equal_number_strings]
     numbers_set = set(numbers)
     self.assertEqual(len(numbers_set), 1)
     for number in numbers:
         self.assertIn(number, numbers_set)
     self.assertNotIn(self.test_number_1, numbers_set)
Esempio n. 27
0
 def test_same_number_has_same_hash(self):
     numbers = [PhoneNumber.from_string(number_string)
                for number_string in self.equal_number_strings]
     numbers_set = set(numbers)
     self.assertEqual(len(numbers_set), 1)
     for number in numbers:
         self.assertIn(number, numbers_set)
     self.assertNotIn(self.test_number_1, numbers_set)
Esempio n. 28
0
    def handle(self, *args, **kwargs):
        print ("Don't worry, it always takes this long.")

        for fd in FireDepartment.objects.all():
            # If the FD has a phone number, clean it up
            if fd.headquarters_phone and not fd.headquarters_phone.raw_input == "Invalid Input":
                try:
                    new_phone = PhoneNumber.from_string(fd.headquarters_phone.raw_input)

                    if new_phone.is_valid():
                        fd.headquarters_phone = new_phone
                        valid.append(new_phone)
                    else:
                        invalid.append(new_phone)
                        fd.headquarters_phone = None

                except NumberParseException:
                    invalid.append(new_phone)
                    fd.headquarters_phone = None

            # If the FD has a fax number, clean it up
            if fd.headquarters_fax and not fd.headquarters_fax.raw_input == "Invalid Input":
                try:
                    new_fax = PhoneNumber.from_string(fd.headquarters_fax.raw_input)

                    if new_fax.is_valid():
                        fd.headquarters_fax = new_fax
                        valid.append(new_fax)
                    else:
                        invalid.append(new_fax)
                        fd.headquarters_fax = None

                except NumberParseException:
                    invalid.append(new_fax)
                    fd.headquarters_fax = None

            # Save and continue to the next FD (if any)
            fd.save()

        print "Valid Numbers: {}".format(len(valid))
        print "Invalid numbers: {}".format(len(invalid))
        print "Invald percent: {}".format(len(invalid) / (len(valid) + len(invalid)))
        print "Invalid numbers: ", map(str, invalid)

        print ("Completed successfully!")
Esempio n. 29
0
 def save(self, *args, **kwargs):
     """Ensure validations are run and updated/created preserved."""
     self.full_clean(exclude=None)
     self.latitude, self.longitude = self.extract_lat_long_via_address()
     self.can_receive_blood_from = self.get_allowed_blood_groups(
         self.blood_group)
     self.phone_number = PhoneNumber.from_string(phone_number=self.phone,
                                                 region='KE').as_e164
     super(BDSGUser, self).save(*args, **kwargs)
Esempio n. 30
0
    def set_right_phone(self, phone_number):
        phone = PhoneNumber.from_string(phone_number)
        self.cleaned_data[self.PHONE_NUMBER_FIELD] = phone

        if hasattr(self, 'instance'):
            setattr(self.instance, self.PHONE_NUMBER_FIELD, phone)

        # is_valid will run again
        self._errors.pop(self.PHONE_NUMBER_FIELD, None)
Esempio n. 31
0
def to_python(value):
    if value in validators.EMPTY_VALUES:  # None or ''
        phone_number = None
    elif value and isinstance(value, basestring):
        try:
            phone_number = PhoneNumber.from_string(phone_number=value)
        except NumberParseException, e:
            # the string provided is not a valid PhoneNumber.
            phone_number = PhoneNumber(raw_input=value)
Esempio n. 32
0
def to_python(value):
    if value in validators.EMPTY_VALUES:  # None or ''
        phone_number = None
    elif value and isinstance(value, basestring):
        try:
            phone_number = PhoneNumber.from_string(phone_number=value)
        except NumberParseException, e:
            # the string provided is not a valid PhoneNumber.
            phone_number = PhoneNumber(raw_input=value)
Esempio n. 33
0
    def clean_phone_number_field(self, field_name):
        number = self.cleaned_data.get(field_name)

        # Empty
        if number in validators.EMPTY_VALUES:
            return ''

        # Check for an international phone format
        # 检查国际电话格式
        try:
            phone_number = PhoneNumber.from_string(number)
        except phonenumbers.NumberParseException:

            if not self.region_code:
                # There is no shipping country, not a valid international number
                # 没有运输国家/地区,不是有效的国际号码
                self.add_error(
                    field_name,
                    _('This is not a valid international phone format.'))
                return number

            # The PhoneNumber class does not allow specifying
            # the region. So we drop down to the underlying phonenumbers
            # library, which luckily allows parsing into a PhoneNumber
            # instance.
            # PhoneNumber类不允许指定区域。 所以我们下载到底层的phonenumbers库,幸运的是
            # 允许解析为PhoneNumber实例。
            try:
                phone_number = PhoneNumber.from_string(number,
                                                       region=self.region_code)
                if not phone_number.is_valid():
                    self.add_error(
                        field_name,
                        _('This is not a valid local phone format for %s.')
                        % self.country)
            except phonenumbers.NumberParseException:
                # Not a valid local or international phone number
                # 不是有效的本地或国际电话号码
                self.add_error(
                    field_name,
                    _('This is not a valid local or international phone format.'))
                return number

        return phone_number
Esempio n. 34
0
 def scramble_phone(self, phone):
     if not phone.number.is_valid():
         phone.number = PhoneNumber.from_string(
             self.faker.numerify('% %## ## ##'), region=phone.country.code)
         return True
     phone.number.national_number = 0
     while not phone.number.is_valid():
         phone.number.national_number = self.faker.random_int(
             10000, 99999999990)
     return True
Esempio n. 35
0
    def _get_formatted_value(self,
                             field,
                             value,
                             html=True,
                             na_placeholder=None):
        """Récupère la valeur du champ pour les humains

        :param field:
        :param value:
        :param html:
        :param na_placeholder: la valeur à présenter pour les champs vides
        :return:
        """

        if value is None:
            if na_placeholder is not None:
                return na_placeholder
            elif html:
                return self.NA_HTML_PLACEHOLDER
            return self.NA_TEXT_PLACEHOLDER

        field_type = field.get("type")

        if field_type in ["choice", "autocomplete_choice"
                          ] and "choices" in field:
            return self._get_choice_label(field, value, html)
        elif field_type == "multiple_choice" and "choices" in field:
            if isinstance(value, list):
                return [self._get_choice_label(field, v, html) for v in value]
            else:
                return value
        elif field_type == "person":
            try:
                UUID(value)
                return Person.objects.filter(id=value).first() or value
            except ValueError:
                return value
        elif field_type == "datetime":
            date = iso8601.parse_date(value)
            return localize(date.astimezone(get_current_timezone()))
        elif field_type == "phone_number":
            try:
                phone_number = PhoneNumber.from_string(value)
                return phone_number.as_international
            except NumberParseException:
                return value
        elif field_type == "file":
            if html:
                return format_html('<a href="{}">Accéder au fichier</a>',
                                   value)
            else:
                return value

        return value
Esempio n. 36
0
    def validate(self, data):
        number = data.get('number').strip('+\/[]*&^%$#@').replace(
            '-', '').replace(' ', '').replace('(', '').replace(')', '')
        try:
            num = PhoneNumber.from_string(number)
        except Exception as e:
            raise serializers.ValidationError(e)

        if not num.is_valid():
            raise serializers.ValidationError('Invalid phone number')
        return number
 def test_phonenumber_default_format(self):
     phone = PhoneNumber.from_string("+33612345678")
     # E164 by default.
     self.assertEqual(str(phone), "+33612345678")
     with override_settings(PHONENUMBER_DEFAULT_FORMAT="E164"):
         self.assertEqual(str(phone), "+33612345678")
     with override_settings(PHONENUMBER_DEFAULT_FORMAT="INTERNATIONAL"):
         self.assertEqual(str(phone), "+33 6 12 34 56 78")
     with override_settings(PHONENUMBER_DEFAULT_FORMAT="NATIONAL"):
         self.assertEqual(str(phone), "06 12 34 56 78")
     with override_settings(PHONENUMBER_DEFAULT_FORMAT="RFC3966"):
         self.assertEqual(str(phone), "tel:+33-6-12-34-56-78")
Esempio n. 38
0
def clean_phone_for_country(phone, country):
    error = _("The phone number entered is not valid.")
    error_code = "invalid_phone_number"
    if phone:
        try:
            phone = PhoneNumber.from_string(phone, country)
        except NumberParseException:
            raise forms.ValidationError(error, code=error_code)
        else:
            if not is_possible_number(phone):
                raise forms.ValidationError(error, code=error_code)
    return phone
 def test_ordering_contains_None(self):
     phone1 = PhoneNumber.from_string("+33600000000")
     msg = "'<' not supported between instances of 'PhoneNumber' and 'NoneType'"
     for assertion in [
             self.assertLess,
             self.assertLessEqual,
             self.assertGreater,
             self.assertGreaterEqual,
     ]:
         with self.subTest(assertion):
             with self.assertRaisesMessage(TypeError, msg):
                 assertion(phone1, None)
Esempio n. 40
0
    def get_users_list(self, phone):
        if not phone:
            return []

        try:
            ph = PhoneNumber.from_string(phone)
        except NumberParseException:
            return []

        coachs = Coach.objects.filter(phone_number=ph)
        managers = Manager.objects.filter(phone_number=ph)
        return [x.user for x in chain(coachs, managers)]
Esempio n. 41
0
    def clean_phone_number_field(self, field_name):
        number = self.cleaned_data.get(field_name)

        # Empty
        if number in validators.EMPTY_VALUES:
            return ''

        # Check for an international phone format
        try:
            phone_number = PhoneNumber.from_string(number)
        except phonenumbers.NumberParseException:

            if not self.region_code:
                # There is no shipping country, not a valid international number
                self.add_error(
                    field_name,
                    _(u'This is not a valid international phone format.'))
                return number

            # The PhoneNumber class does not allow specifying
            # the region. So we drop down to the underlying phonenumbers
            # library, which luckily allows parsing into a PhoneNumber
            # instance.
            try:
                phone_number = PhoneNumber.from_string(number,
                                                       region=self.region_code)
                if not phone_number.is_valid():
                    self.add_error(
                        field_name,
                        _(u'This is not a valid local phone format for %s.')
                        % self.country)
            except phonenumbers.NumberParseException:
                # Not a valid local or international phone number
                self.add_error(
                    field_name,
                    _(u'This is not a valid local or international phone format.'))
                return number

        return phone_number
Esempio n. 42
0
    def clean_phone_number(self):
        number = self.cleaned_data['phone_number']

        # empty
        if number in validators.EMPTY_VALUES:
            return ''

        # Check for an international phone format
        try:
            phone_number = PhoneNumber.from_string(number)
        except phonenumbers.NumberParseException:
            # Try hinting with the shipping country if we can determine one
            country = self.get_country()
            region_code = self.get_region_code(country) if country else None

            if not region_code:
                # There is no shipping country, not a valid international
                # number
                raise ValidationError(
                    _(u'This is not a valid international phone format.'))

            # The PhoneNumber class does not allow specifying
            # the region. So we drop down to the underlying phonenumbers
            # library, which luckily allows parsing into a PhoneNumber
            # instance
            try:
                phone_number = PhoneNumber.from_string(number, region=region_code)
                if not phone_number.is_valid():
                    raise ValidationError(
                        _(u'This is not a valid local phone format for %s.')
                        % country)
            except phonenumbers.NumberParseException:
                # Not a valid local or international phone number
                raise ValidationError(
                    _(u'This is not a valid local or international phone'
                      u' format.'))

        return phone_number
    def test_fallback_widget_switches_between_national_and_international(self):
        region, number_string = self.local_numbers[0]
        number = PhoneNumber.from_string(number_string, region=region)
        gb_widget = PhoneNumberInternationalFallbackWidget(region="GB")
        de_widget = PhoneNumberInternationalFallbackWidget(region="DE")
        self.assertHTMLEqual(
            gb_widget.render("number", number),
            '<input name="number" type="text" value="01606 75178" />',
        )
        self.assertHTMLEqual(
            de_widget.render("number", number),
            '<input name="number" type="text" value="+44 1606 75178" />',
        )

        # If there's been a validation error, the value should be included verbatim
        self.assertHTMLEqual(
            gb_widget.render("number", "error"),
            '<input name="number" type="text" value="error" />',
        )
Esempio n. 44
0
        def update_records(self, uploaded_file, file_type):
            transactions = []
            for transaction in csv.DictReader(uploaded_file, delimiter=","):

                # sent transactions
                if file_type == Transaction.TYPES.sent:
                    try:
                        date = time.strptime(transaction["Date"], "%d/%m/%Y %H:%M:%S")
                        date = datetime(*date[:6])
                        transactions.append(
                            Transaction(
                                code=transaction["Code"],
                                date=date,
                                recipient=transaction["Recipient"],
                                amount=float(transaction["Amount"].replace(",", "")),
                                type=file_type,
                                phonenumber=PhoneNumber.from_string(transaction["No."], "KE"),
                            )
                        )
                    except NumberParseException:
                        pass

                # received transactions
                if file_type == Transaction.TYPES.received:
                    try:
                        date = time.strptime(transaction["Date"], "%d/%m/%Y %H:%M:%S")
                        date = datetime(*date[:6])
                        transactions.append(
                            Transaction(
                                code=transaction['\xef\xbb\xbf"Code"'],
                                date=date,
                                sent_by=transaction["Sent By"],
                                amount=float(transaction["Amount"].replace(",", "")),
                                type=file_type,
                            )
                        )
                    except NumberParseException:
                        pass

            Transaction.objects.bulk_create(transactions)
Esempio n. 45
0
def test_view_order_address_edit(admin_client, order_with_lines, address_other_country):

    order = order_with_lines
    new_address = address_other_country

    new_address.phone = PhoneNumber.from_string(
        region=new_address.country.code, phone_number="+33.600000000"
    )

    address_data = new_address.as_data()
    address_data.pop("phone")

    address_data.update({"phone_0": "+33", "phone_1": "600000000"})

    url = reverse(
        "dashboard:address-edit",
        kwargs={"order_pk": order.pk, "address_type": "shipping"},
    )

    response = admin_client.post(url, address_data)
    assert response.status_code == 302

    order.refresh_from_db(fields=["shipping_address"])
    assert new_address.as_data() == order.shipping_address.as_data()
 def test_invalid_numbers_are_invalid(self):
     numbers = [
         PhoneNumber.from_string(number_string)
         for number_string in self.invalid_numbers
     ]
     self.assertTrue(all(not number.is_valid() for number in numbers))
Esempio n. 47
0
 def to_internal_value(self, data):
     try:
         return PhoneNumber.from_string(data)
     except:
         raise ValidationError(_("Enter a valid phone number"))