Ejemplo n.º 1
0
 def testShortNumbersValidAndCorrectCost(self):
     invalid_string_cases = []
     for regionCode in phonenumberutil.SUPPORTED_SHORT_REGIONS:
         exampleShortNumber = shortnumberinfo._example_short_number(
             regionCode)
         phoneNumber = phonenumberutil.parse(exampleShortNumber, regionCode)
         if not shortnumberinfo.is_valid_short_number_for_region(
                 phoneNumber, regionCode):
             invalid_string_case = "region_code: %s, national_number: %s" % (
                 regionCode, exampleShortNumber)
             invalid_string_cases.append(invalid_string_case)
             prnt("Failed validation from string %s" % invalid_string_case,
                  file=sys.stderr)
         if not shortnumberinfo.is_valid_short_number(phoneNumber):
             self.invalid_cases.append(phoneNumber)
             prnt("Failed validation for %s" % phoneNumber, file=sys.stderr)
         for cost in [
                 ShortNumberCost.TOLL_FREE, ShortNumberCost.STANDARD_RATE,
                 ShortNumberCost.PREMIUM_RATE, ShortNumberCost.UNKNOWN_COST
         ]:
             exampleShortNumber = shortnumberinfo._example_short_number_for_cost(
                 regionCode, cost)
             if exampleShortNumber != "":
                 phoneNumber = phonenumberutil.parse(
                     exampleShortNumber, regionCode)
                 if cost != shortnumberinfo.expected_cost_for_region(
                         phoneNumber, regionCode):
                     self.wrong_type_cases.append(phoneNumber)
                     prnt("Wrong cost for %s" % phoneNumber,
                          file=sys.stderr)
     self.assertEqual(0, len(invalid_string_cases))
     self.assertEqual(0, len(self.invalid_cases))
     self.assertEqual(0, len(self.wrong_type_cases))
 def testShortNumbersValidAndCorrectCost(self):
     invalid_string_cases = []
     for regionCode in phonenumberutil.SUPPORTED_SHORT_REGIONS:
         if regionCode == "PG":
             # The only short number for Papua New Guinea is 000, which
             # fails the test, since the national prefix is 0. This needs
             # to be fixed.
             continue
         exampleShortNumber = shortnumberinfo._example_short_number(regionCode)
         if not shortnumberinfo.is_valid_short_number(exampleShortNumber, regionCode):
             invalid_string_case = "region_code: %s, national_number: %s" % (regionCode, exampleShortNumber)
             invalid_string_cases.append(invalid_string_case)
             print >> sys.stderr, "Failed validation from string %s" % invalid_string_case
         phoneNumber = phonenumberutil.parse(exampleShortNumber, regionCode)
         if not shortnumberinfo.is_valid_short_number_object(phoneNumber):
             self.invalid_cases.append(phoneNumber)
             print >> sys.stderr, "Failed validation for %s" % phoneNumber
         for cost in [ShortNumberCost.TOLL_FREE, ShortNumberCost.STANDARD_RATE,
                      ShortNumberCost.PREMIUM_RATE, ShortNumberCost.UNKNOWN_COST]:
             exampleShortNumber = shortnumberinfo._example_short_number_for_cost(regionCode, cost)
             if exampleShortNumber != "":
                 phoneNumber = phonenumberutil.parse(exampleShortNumber, regionCode)
                 if cost != shortnumberinfo.expected_cost(phoneNumber):
                     self.wrong_type_cases.append(phoneNumber)
                     print >> sys.stderr, "Wrong cost for %s" % phoneNumber
     self.assertEqual(0, len(invalid_string_cases))
     self.assertEqual(0, len(self.invalid_cases))
     self.assertEqual(0, len(self.wrong_type_cases))
Ejemplo n.º 3
0
    def get_phone_number_object(self, data_string):
        """
        Takes the data_string and tries to parse a phone number out of it

        :param data_string: data that might be a phone number
        :type data_string: str
        :return: phone number data if it's a phone number
        :rtype: dict
        """
        try:
            check_region = (data_string[0] == "+")

            # First pass to see if it's a valid number
            num_obj = phonenumberutil.parse(
                data_string,
                _check_region=check_region
            )

            num_desc = geocoder.description_for_valid_number(
                num_obj, "en"
            ).strip()

        except NumberParseException:
            # If we can't parse it out, it's not a valid number
            return False

        # if we weren't able to check the region, and we didn't get a
        # description we want to modify the data and give it another go
        # with a country code added
        if not check_region and not num_desc:
            prefix = None
            if len(self.digits) == 11 and data_string[0] == "1":
                prefix = "+"
            elif len(self.digits) == 10 \
                    and (data_string[0].isdigit() or
                         data_string[0] in string.punctuation):
                prefix = "+1"

            if prefix:
                try:
                    # Second pass to see if we can get an actual
                    # geocode out of it using a hammer
                    second_pass = phonenumberutil.parse(prefix + data_string)
                    num_desc = geocoder.description_for_valid_number(
                        second_pass, "en"
                    ).strip()
                    if num_desc:
                        num_obj = second_pass
                        # confidence hit because we had to
                        # modify the data to get a result
                        self.confidence -= 5
                except (NumberParseException, Exception):
                    pass

        # Attempting to get a valid region
        num_region = phonenumberutil.region_code_for_number(num_obj)

        # This is the compiled phone number data that
        # we will use for the confidence decision
        return self.build_phone_number_dict(num_obj, num_desc, num_region)
 def testWhitespaceInNationalPrefixForParsing(self):
     # Python version extra test
     # AR metadata has whitespace in the RE for nationalPrefixForParsing
     number = phonenumberutil.parse("+540348215617137", "AR")
     self.assertTrue(phonenumberutil.is_valid_number(number))
     self.assertEqual(PhoneNumberType.MOBILE, phonenumberutil.number_type(number))
     number = phonenumberutil.parse("0344615614207", "AR")
     self.assertTrue(phonenumberutil.is_valid_number(number))
     self.assertEqual(PhoneNumberType.MOBILE, phonenumberutil.number_type(number))
 def testWhitespaceInNationalPrefixForParsing(self):
     # Python version extra test
     # AR metadata has whitespace in the RE for nationalPrefixForParsing
     number = phonenumberutil.parse("+540348215617137", "AR")
     self.assertTrue(phonenumberutil.is_valid_number(number))
     self.assertEqual(PhoneNumberType.MOBILE, phonenumberutil.number_type(number))
     number = phonenumberutil.parse("0344615614207", "AR")
     self.assertTrue(phonenumberutil.is_valid_number(number))
     self.assertEqual(PhoneNumberType.MOBILE, phonenumberutil.number_type(number))
Ejemplo n.º 6
0
    def get_phone_number_object(self, data_string):
        """Takes the data_string and tries to parse a phone number out of it"""

        try:
            check_region = (data_string[0] == "+")

            # First pass to see if it's a valid number
            num_obj = phonenumberutil.parse(
                data_string,
                _check_region=check_region
            )

            num_desc = geocoder.description_for_valid_number(
                num_obj, "en"
            ).strip()

        except NumberParseException:
            # If we can't parse it out, it's not a valid number
            return False

        # if we weren't able to check the region, and we didn't get a
        # description we want to modify the data and give it another go
        # with a country code added
        if not check_region and not num_desc:
            prefix = None
            if len(self.digits) == 11 and data_string[0] == "1":
                prefix = "+"
            elif len(self.digits) == 10 \
                    and (data_string[0].isdigit() or
                         data_string[0] in string.punctuation):
                prefix = "+1"

            if prefix:
                try:
                    # Second pass to see if we can get an actual
                    # geocode out of it using a hammer
                    second_pass = phonenumberutil.parse(prefix + data_string)
                    num_desc = geocoder.description_for_valid_number(
                        second_pass, "en"
                    ).strip()
                    if num_desc:
                        num_obj = second_pass
                        # confidence hit because we had to
                        # modify the data to get a result
                        self.confidence -= 5
                except (NumberParseException, Exception):
                    pass

        # Attempting to get a valid region
        num_region = phonenumberutil.region_code_for_number(num_obj)

        # This is the compiled phone number data that
        # we will use for the confidence decision
        return self.build_phone_number_dict(num_obj, num_desc, num_region)
Ejemplo n.º 7
0
 def testEmergency(self):
     wrongTypeCounter = 0
     for regionCode in phonenumberutil.SUPPORTED_SHORT_REGIONS:
         if regionCode == "PG":
             # The only short number for Papua New Guinea is 000, which
             # fails the test, since the national prefix is 0. This needs
             # to be fixed.
             continue
         metadata = PhoneMetadata.short_metadata_for_region(
             regionCode, None)
         desc = metadata.emergency
         if desc.example_number is not None:
             exampleNumber = desc.example_number
             if (not fullmatch(re.compile(desc.possible_number_pattern),
                               exampleNumber)
                     or not is_emergency_number(exampleNumber, regionCode)):
                 wrongTypeCounter += 1
                 print >> sys.stderr, "Emergency example number test failed for %s" % regionCode
             else:
                 emergencyNumber = phonenumberutil.parse(
                     exampleNumber, regionCode)
                 if shortnumberinfo.expected_cost(
                         emergencyNumber) != ShortNumberCost.TOLL_FREE:
                     # TODO: Reenable this when a method is available to get the expected cost for a
                     # particular region.
                     #wrongTypeCounter += 1
                     print >> sys.stderr, "Emergency example number not toll free for %s" % regionCode
     self.assertEqual(0, wrongTypeCounter)
 def testBlankMetadata(self):
     # Python version extra test
     # Some metadata is blank; check that we cope with this.
     # Example: MH (+692)
     number = phonenumberutil.parse("+6927654321", "US")
     self.assertEqual("Country Code: 692 National Number: 7654321",
                      str(number))
Ejemplo n.º 9
0
    def test_build_phone_number_dict(self):

        numObj = phonenumberutil.parse("+1-979-549-5150")

        numDict = self.pp.build_phone_number_dict(numObj, "Angleton, TX", "US")

        self.assertEqual(numDict, self.testDict)
Ejemplo n.º 10
0
    def calculate_confidence(cls, data):
        """Calculates a confidence rating for this (possible) equation"""
        # We start with 100% confidence, and
        # then lower our confidence if needed.
        confidence = 100

        # lowering confidence if we have a phone number
        try:
            if len(data) <= 30 and len(data) >= 7:
                phonenumberutil.parse(data, _check_region=False)
                for _ in [c for c in data if c in string.punctuation]:
                    confidence -= 10
        except NumberParseException:
            pass

        return confidence
Ejemplo n.º 11
0
 def to_python(self, value):
     if isinstance(value, basestring) and value != '':
         try:
             value = format_number(parse(value,"US"),PhoneNumberFormat.INTERNATIONAL)
         except NumberParseException:
             pass
     return value
Ejemplo n.º 12
0
 def testGBLocalNumberLength(self):
     # Python version extra test.  Issue #172.
     numobj = phonenumberutil.parse("+4408001111", "GB")
     self.assertEqual(
         "+44 800 1111",
         phonenumberutil.format_number(
             numobj, phonenumberutil.PhoneNumberFormat.INTERNATIONAL))
Ejemplo n.º 13
0
    def testMatchWithSurroundingZipcodes(self):
        number = "415-666-7777"
        zipPreceding = "My address is CA 34215 - " + number + " is my number."
        expectedResult = phonenumberutil.parse(number, "US")

        matcher = PhoneNumberMatcher(zipPreceding, "US")
        if matcher.has_next():
            match = matcher.next()
        else:
            match = None
        self.assertTrue(match is not None,
                        msg="Did not find a number in '" + zipPreceding +
                        "'; expected " + number)
        self.assertEqual(expectedResult, match.number)
        self.assertEqual(number, match.raw_string)

        # Now repeat, but this time the phone number has spaces in it. It should still be found.
        number = "(415) 666 7777"

        zipFollowing = "My number is " + number + ". 34215 is my zip-code."
        matcher = PhoneNumberMatcher(zipFollowing, "US")
        if matcher.has_next():
            matchWithSpaces = matcher.next()
        else:
            matchWithSpaces = None
        self.assertTrue(matchWithSpaces is not None,
                        msg="Did not find a number in '" + zipFollowing +
                        "'; expected " + number)
        self.assertEqual(expectedResult, matchWithSpaces.number)
        self.assertEqual(number, matchWithSpaces.raw_string)
    def testMatchWithSurroundingZipcodes(self):
        number = "415-666-7777"
        zipPreceding = "My address is CA 34215. " + number + " is my number."
        expectedResult = phonenumberutil.parse(number, "US")

        matcher = PhoneNumberMatcher(zipPreceding, "US")
        if matcher.has_next():
            match = matcher.next()
        else:
            match = None
        self.assertTrue(match is not None,
                        msg="Did not find a number in '" + zipPreceding + "'; expected " + number)
        self.assertEquals(expectedResult, match.number)
        self.assertEquals(number, match.raw_string)

        # Now repeat, but this time the phone number has spaces in it. It should still be found.
        number = "(415) 666 7777"

        zipFollowing = "My number is " + number + ". 34215 is my zip-code."
        matcher = PhoneNumberMatcher(zipFollowing, "US")
        if matcher.has_next():
            matchWithSpaces = matcher.next()
        else:
            matchWithSpaces = None
        self.assertTrue(matchWithSpaces is not None,
                        msg="Did not find a number in '" + zipFollowing + "'; expected " + number)
        self.assertEquals(expectedResult, matchWithSpaces.number)
        self.assertEquals(number, matchWithSpaces.raw_string)
Ejemplo n.º 15
0
    def calculate_confidence(cls, data):
        """Calculates a confidence rating for this (possible) equation"""
        # We start with 100% confidence, and
        # then lower our confidence if needed.
        confidence = 100

        # lowering confidence if we have a phone number
        try:
            if len(data) <= 30 and len(data) >= 7:
                phonenumberutil.parse(data, _check_region=False)
                for _ in [c for c in data if c in string.punctuation]:
                    confidence -= 10
        except NumberParseException:
            pass

        return confidence
Ejemplo n.º 16
0
 def test_null_field_returns_none(self):
     model = NullablePhoneNumber()
     self.assertEqual(model.phone_number, None)
     model.phone_number = self.test_number_1
     self.assertEqual(type(model.phone_number), PhoneNumber)
     model.phone_number = phonenumberutil.parse(
         self.test_number_1, keep_raw_input=True)
     self.assertEqual(type(model.phone_number), PhoneNumber)
 def assertMatchProperties(self, match, text, number, region):
     """Asserts that the expected match is non-null, and that the raw string
     and expected proto buffer are set appropriately."""
     expectedResult = phonenumberutil.parse(number, region)
     self.assertTrue(match is not None,
                     msg="Did not find a number in '" + text + "'; expected " + number)
     self.assertEqual(expectedResult, match.number)
     self.assertEqual(number, match.raw_string)
Ejemplo n.º 18
0
 def testBlankMetadata(self):
     # Python version extra test
     # Some metadata is blank; check that we cope with this.
     # Example: MH (+692)
     number = phonenumberutil.parse("+6921234567", "US")
     self.assertEquals(
         "Country Code: 692 National Number: 1234567 Leading Zero: False",
         str(number))
Ejemplo n.º 19
0
 def test_null_field_returns_none(self):
     model = models.NullablePhoneNumber()
     self.assertIsNone(model.phone_number)
     model.phone_number = self.test_number_1
     self.assertIsInstance(model.phone_number, PhoneNumber)
     model.phone_number = phonenumberutil.parse(self.test_number_1,
                                                keep_raw_input=True)
     self.assertIsInstance(model.phone_number, PhoneNumber)
 def test_null_field_returns_none(self):
     model = NullablePhoneNumber()
     self.assertEqual(model.phone_number, None)
     model.phone_number = '+49 176 96842671'
     self.assertEqual(type(model.phone_number), PhoneNumber)
     model.phone_number = phonenumberutil.parse(
         self.test_number_1, keep_raw_input=True)
     self.assertEqual(type(model.phone_number), PhoneNumber)
 def assertMatchProperties(self, match, text, number, region):
     """Asserts that the expected match is non-null, and that the raw string
     and expected proto buffer are set appropriately."""
     expectedResult = phonenumberutil.parse(number, region)
     self.assertTrue(match is not None,
                     msg="Did not find a number in '" + text + "'; expected " + number)
     self.assertEqual(expectedResult, match.number)
     self.assertEqual(number, match.raw_string)
 def test_can_assign_phonenumber(self):
     """
     Tests assignment phonenumberutil.PhoneNumber to field
     """
     opt_phone = OptionalPhoneNumber()
     opt_phone.phone_number = phonenumberutil.parse(
         self.test_number_1, keep_raw_input=True)
     self.assertEqual(type(opt_phone.phone_number), PhoneNumber)
     self.assertEqual(opt_phone.phone_number.as_e164, self.test_number_1)
Ejemplo n.º 23
0
 def test_null_field_returns_none(self):
     model = models.NullablePhoneNumber()
     self.assertIsNone(model.phone_number)
     model.phone_number = self.test_number_1
     self.assertIsInstance(model.phone_number, PhoneNumber)
     model.phone_number = phonenumberutil.parse(
         self.test_number_1, keep_raw_input=True
     )
     self.assertIsInstance(model.phone_number, PhoneNumber)
Ejemplo n.º 24
0
 def test_can_assign_phonenumber(self):
     """
     Tests assignment phonenumberutil.PhoneNumber to field
     """
     opt_phone = OptionalPhoneNumber()
     opt_phone.phone_number = phonenumberutil.parse(self.test_number_1,
                                                    keep_raw_input=True)
     self.assertEqual(type(opt_phone.phone_number), PhoneNumber)
     self.assertEqual(opt_phone.phone_number.as_e164, self.test_number_1)
    def testMaxMatches(self):
        # Set up text with 100 valid phone numbers.
        numbers = "My info: 415-666-7777," * 100

        # Matches all 100. Max only applies to failed cases.
        number = phonenumberutil.parse("+14156667777", None)
        expected = [number] * 100

        matcher = PhoneNumberMatcher(numbers, "US", Leniency.VALID, 10)
        actual = [x.number for x in matcher]

        self.assertEquals(expected, actual)
    def testMaxMatchesMixed(self):
        # Set up text with 100 valid numbers inside an invalid number.
        numbers = "My info: 415-666-7777 123 fake street" * 100

        # Only matches the first 10 despite there being 100 numbers due to max matches.
        number = phonenumberutil.parse("+14156667777", None)
        expected = [number] * 10

        matcher = PhoneNumberMatcher(numbers, "US", Leniency.VALID, 10)
        actual = [x.number for x in matcher]

        self.assertEqual(expected, actual)
Ejemplo n.º 27
0
    def testMaxMatches(self):
        # Set up text with 100 valid phone numbers.
        numbers = "My info: 415-666-7777," * 100

        # Matches all 100. Max only applies to failed cases.
        number = phonenumberutil.parse("+14156667777", None)
        expected = [number] * 100

        matcher = PhoneNumberMatcher(numbers, "US", Leniency.VALID, 10)
        actual = [x.number for x in matcher]

        self.assertEqual(expected, actual)
Ejemplo n.º 28
0
    def testMaxMatchesMixed(self):
        # Set up text with 100 valid numbers inside an invalid number.
        numbers = "My info: 415-666-7777 123 fake street" * 100

        # Only matches the first 10 despite there being 100 numbers due to max matches.
        number = phonenumberutil.parse("+14156667777", None)
        expected = [number] * 10

        matcher = PhoneNumberMatcher(numbers, "US", Leniency.VALID, 10)
        actual = [x.number for x in matcher]

        self.assertEqual(expected, actual)
 def testSmsServiceShortNumbers(self):
     wrongTagCounter = 0
     for regionCode in shortnumberinfo.SUPPORTED_SHORT_REGIONS:
         metadata = PhoneMetadata.short_metadata_for_region(regionCode, None)
         desc = metadata.sms_services
         if desc is not None and desc.example_number is not None:
             exampleNumber = desc.example_number
             smsServiceNumber = phonenumberutil.parse(exampleNumber, regionCode)
             if (not shortnumberinfo.is_possible_short_number_for_region(smsServiceNumber, regionCode) or
                 not shortnumberinfo.is_sms_service_for_region(smsServiceNumber, regionCode)):
                 wrongTagCounter += 1
                 prnt("SMS service test failed for %s" % regionCode, file=sys.stderr)
     self.assertEqual(0, wrongTagCounter)
 def testCarrierSpecificShortNumbers(self):
     wrongTagCounter = 0
     for regionCode in shortnumberinfo.SUPPORTED_SHORT_REGIONS:
         metadata = PhoneMetadata.short_metadata_for_region(regionCode, None)
         desc = metadata.carrier_specific
         if desc is not None and desc.example_number is not None:
             exampleNumber = desc.example_number
             carrierSpecificNumber = phonenumberutil.parse(exampleNumber, regionCode)
             if (not shortnumberinfo.is_possible_short_number_for_region(carrierSpecificNumber, regionCode) or
                 not shortnumberinfo.is_carrier_specific_for_region(carrierSpecificNumber, regionCode)):
                 wrongTagCounter += 1
                 prnt("Carrier-specific test failed for %s" % regionCode, file=sys.stderr)
     self.assertEqual(0, wrongTagCounter)
 def testShortNumbersValidAndCorrectCost(self):
     invalid_string_cases = []
     for regionCode in phonenumberutil.SUPPORTED_SHORT_REGIONS:
         exampleShortNumber = shortnumberinfo._example_short_number(regionCode)
         phoneNumber = phonenumberutil.parse(exampleShortNumber, regionCode)
         if not shortnumberinfo.is_valid_short_number_for_region(phoneNumber, regionCode):
             invalid_string_case = "region_code: %s, national_number: %s" % (regionCode, exampleShortNumber)
             invalid_string_cases.append(invalid_string_case)
             prnt("Failed validation from string %s" % invalid_string_case, file=sys.stderr)
         if not shortnumberinfo.is_valid_short_number(phoneNumber):
             self.invalid_cases.append(phoneNumber)
             prnt("Failed validation for %s" % phoneNumber, file=sys.stderr)
         for cost in [ShortNumberCost.TOLL_FREE, ShortNumberCost.STANDARD_RATE,
                      ShortNumberCost.PREMIUM_RATE, ShortNumberCost.UNKNOWN_COST]:
             exampleShortNumber = shortnumberinfo._example_short_number_for_cost(regionCode, cost)
             if exampleShortNumber != "":
                 phoneNumber = phonenumberutil.parse(exampleShortNumber, regionCode)
                 if cost != shortnumberinfo.expected_cost_for_region(phoneNumber, regionCode):
                     self.wrong_type_cases.append(phoneNumber)
                     prnt("Wrong cost for %s" % phoneNumber, file=sys.stderr)
     self.assertEqual(0, len(invalid_string_cases))
     self.assertEqual(0, len(self.invalid_cases))
     self.assertEqual(0, len(self.wrong_type_cases))
 def testCarrierSpecificShortNumbers(self):
     wrongTagCounter = 0
     for regionCode in phonenumberutil.SUPPORTED_SHORT_REGIONS:
         # Test the carrier-specific tag.
         metadata = PhoneMetadata.short_metadata_for_region(regionCode, None)
         desc = metadata.carrier_specific
         if desc.example_number is not None:
             exampleNumber = desc.example_number
             carrierSpecificNumber = phonenumberutil.parse(exampleNumber, regionCode)
             if (not fullmatch(re.compile(desc.possible_number_pattern), exampleNumber) or
                 not shortnumberinfo.is_carrier_specific(carrierSpecificNumber)):
                 wrongTagCounter += 1
                 prnt("Carrier-specific test failed for %s" % regionCode, file=sys.stderr)
         # TODO: Test other tags here
     self.assertEqual(0, wrongTagCounter)
Ejemplo n.º 33
0
 def test_can_assign_phonenumber(self):
     """
     Tests assignment phonenumberutil.PhoneNumber to field
     """
     opt_phone = OptionalPhoneNumber()
     opt_phone.phone_number = phonenumberutil.parse(
         self.test_number_1, keep_raw_input=True)
     self.assertEqual(type(opt_phone.phone_number), PhoneNumber)
     self.assertEqual(opt_phone.phone_number.as_e164, self.test_number_1)
     opt_phone.full_clean()
     opt_phone.save()
     self.assertEqual(type(opt_phone.phone_number), PhoneNumber)
     self.assertEqual(opt_phone.phone_number.as_e164, self.test_number_1)
     opt_phone_db = OptionalPhoneNumber.objects.get(id=opt_phone.id)
     self.assertEqual(type(opt_phone_db.phone_number), PhoneNumber)
     self.assertEqual(opt_phone_db.phone_number.as_e164, self.test_number_1)
Ejemplo n.º 34
0
 def test_can_assign_phonenumber(self):
     """
     Tests assignment phonenumberutil.PhoneNumber to field
     """
     opt_phone = OptionalPhoneNumber()
     opt_phone.phone_number = phonenumberutil.parse(
         self.test_number_1, keep_raw_input=True)
     self.assertEqual(type(opt_phone.phone_number), PhoneNumber)
     self.assertEqual(opt_phone.phone_number.as_e164, self.test_number_1)
     opt_phone.full_clean()
     opt_phone.save()
     self.assertEqual(type(opt_phone.phone_number), PhoneNumber)
     self.assertEqual(opt_phone.phone_number.as_e164, self.test_number_1)
     opt_phone_db = OptionalPhoneNumber.objects.get(id=opt_phone.id)
     self.assertEqual(type(opt_phone_db.phone_number), PhoneNumber)
     self.assertEqual(opt_phone_db.phone_number.as_e164, self.test_number_1)
 def testEmergency(self):
     wrongTypeCounter = 0
     for regionCode in shortnumberinfo.SUPPORTED_SHORT_REGIONS:
         metadata = PhoneMetadata.short_metadata_for_region(regionCode, None)
         desc = metadata.emergency
         if desc is not None and desc.example_number is not None:
             exampleNumber = desc.example_number
             phoneNumber = phonenumberutil.parse(exampleNumber, regionCode)
             if (not is_possible_short_number_for_region(phoneNumber, regionCode) or
                 not is_emergency_number(exampleNumber, regionCode)):
                 wrongTypeCounter += 1
                 prnt("Emergency example number test failed for %s" % regionCode, file=sys.stderr)
             elif shortnumberinfo.expected_cost_for_region(phoneNumber, regionCode) != ShortNumberCost.TOLL_FREE:
                 wrongTypeCounter += 1
                 prnt("Emergency example number not toll free for %s" % regionCode, file=sys.stderr)
     self.assertEqual(0, wrongTypeCounter)
    def testCanBeInternationallyDialled(self):
        for regionCode in phonenumberutil.SUPPORTED_REGIONS:
            exampleNumber = None
            metadata = PhoneMetadata.region_metadata.get(regionCode, None)
            desc = None
            if metadata is not None:
                desc = metadata.no_international_dialling
            try:
                if desc.example_number is not None:
                    exampleNumber = phonenumberutil.parse(desc.example_number, regionCode)

            except NumberParseException, e:
                print >> sys.stderr, "Failed parse: %s" % e

            if (exampleNumber is not None and
                phonenumberutil._can_be_internationally_dialled(exampleNumber)):
                self.wrong_type_cases.append(exampleNumber)
Ejemplo n.º 37
0
    def testCanBeInternationallyDialled(self):
        for regionCode in phonenumberutil.SUPPORTED_REGIONS:
            exampleNumber = None
            metadata = PhoneMetadata.region_metadata.get(regionCode, None)
            desc = None
            if metadata is not None:
                desc = metadata.no_international_dialling
            try:
                if desc.example_number is not None:
                    exampleNumber = phonenumberutil.parse(desc.example_number, regionCode)

            except NumberParseException, e:
                print >> sys.stderr, "Failed parse: %s" % e

            if (exampleNumber is not None and
                phonenumberutil._can_be_internationally_dialled(exampleNumber)):
                self.wrong_type_cases.append(exampleNumber)
 def testCarrierSpecificShortNumbers(self):
     wrongTagCounter = 0
     for regionCode in phonenumberutil.SUPPORTED_SHORT_REGIONS:
         # Test the carrier-specific tag.
         metadata = PhoneMetadata.short_metadata_for_region(
             regionCode, None)
         desc = metadata.carrier_specific
         if desc.example_number is not None:
             exampleNumber = desc.example_number
             carrierSpecificNumber = phonenumberutil.parse(
                 exampleNumber, regionCode)
             if (not fullmatch(re.compile(desc.possible_number_pattern),
                               exampleNumber)
                     or not shortnumberinfo.is_carrier_specific(
                         carrierSpecificNumber)):
                 wrongTagCounter += 1
                 prnt("Carrier-specific test failed for %s" % regionCode,
                      file=sys.stderr)
         # TODO: Test other tags here
     self.assertEqual(0, wrongTagCounter)
    def testCanBeInternationallyDialled(self):
        for regionCode in phonenumberutil.SUPPORTED_REGIONS:
            exampleNumber = None
            metadata = PhoneMetadata.metadata_for_region(regionCode, None)
            desc = None
            if metadata is not None:
                desc = metadata.no_international_dialling
            try:
                if desc is not None and desc.example_number is not None:
                    exampleNumber = phonenumberutil.parse(desc.example_number, regionCode)

            except NumberParseException:
                _, e, _ = sys.exc_info()
                prnt("Failed parse: %s" % e, file=sys.stderr)

            if (exampleNumber is not None and
                phonenumberutil.can_be_internationally_dialled(exampleNumber)):
                self.wrong_type_cases.append(exampleNumber)
                prnt("Number %s should not be internationally diallable" % exampleNumber, file=sys.stderr)
        self.assertEqual(0, len(self.wrong_type_cases))
    def testCanBeInternationallyDialled(self):
        for regionCode in phonenumberutil.SUPPORTED_REGIONS:
            exampleNumber = None
            metadata = PhoneMetadata.metadata_for_region(regionCode, None)
            desc = None
            if metadata is not None:
                desc = metadata.no_international_dialling
            try:
                if desc.example_number is not None:
                    exampleNumber = phonenumberutil.parse(desc.example_number, regionCode)

            except NumberParseException:
                _, e, _ = sys.exc_info()
                prnt("Failed parse: %s" % e, file=sys.stderr)

            if (exampleNumber is not None and
                phonenumberutil._can_be_internationally_dialled(exampleNumber)):
                self.wrong_type_cases.append(exampleNumber)
                prnt("Number %s should not be internationally diallable" % exampleNumber, file=sys.stderr)
        self.assertEqual(0, len(self.wrong_type_cases))
 def testBlankMetadata(self):
     # Python version extra test
     # Some metadata is blank; check that we cope with this.
     # Example: MH (+692)
     number = phonenumberutil.parse("+6921234567", "US")
     self.assertEquals("Country Code: 692 National Number: 1234567 Leading Zero: False", str(number))
Ejemplo n.º 42
0
def format_us_phone_number(value):
    phone = parse(value, 'US')
    formatted = format_number(phone, PhoneNumberFormat.E164)
    if phone.extension:
        formatted += 'x%s' % phone.extension
    return formatted
Ejemplo n.º 43
0
 def value_to_string(self, obj):
     value = self._get_val_from_obj(obj)
     try:
         return format_number(parse(value,"US"),PhoneNumberFormat.INTERNATIONAL)
     except NumberParseException:
         return value
 def doTestFindInContext(self, number, defaultCountry):
     """Tests numbers found by PhoneNumberMatcher in various textual contexts"""
     self.findPossibleInContext(number, defaultCountry)
     parsed = phonenumberutil.parse(number, defaultCountry)
     if phonenumberutil.is_valid_number(parsed):
         self.findValidInContext(number, defaultCountry)
Ejemplo n.º 45
0
def test_phonenumber():
    p = phonenumberutil.parse(p_loc, 'TW')
    i = phonenumberutil.parse(p_int, 'TW')
    print phonenumberutil.is_number_match(p, i)
    assert_equal(phonenumberutil.MatchType.EXACT_MATCH, phonenumberutil.is_number_match(p, i))
 def testBlankMetadata(self):
     # Python version extra test
     # Some metadata is blank; check that we cope with this.
     # Example: MH (+692)
     number = phonenumberutil.parse("+6927654321", "US")
     self.assertEqual("Country Code: 692 National Number: 7654321", str(number))
Ejemplo n.º 47
0
 def doTestFindInContext(self, number, defaultCountry):
     """Tests numbers found by PhoneNumberMatcher in various textual contexts"""
     self.findPossibleInContext(number, defaultCountry)
     parsed = phonenumberutil.parse(number, defaultCountry)
     if phonenumberutil.is_valid_number(parsed):
         self.findValidInContext(number, defaultCountry)
Ejemplo n.º 48
0
        logging.debug('Parsing config files...')
        config = ConfigParser.RawConfigParser()
        config.read(args['--config'])
        api_key = config.get('Password', 'api_key')
        api_secret = config.get('Password', 'api_secret')
    except Exception, e:
        logging.error(traceback.format_exc())
        exit(e)

    msg = args['MESSAGE']
    f_num = args['FROM_NUM']
    t_num = args['TO_NUM']
    country = args['--country']
    if t_num[0] == '+':
        logging.debug('Senderid use E164 form, e.g. +886123456...')
        from_num = phonenumberutil.format_number(phonenumberutil.parse(f_num, country) \
                , phonenumberutil.PhoneNumberFormat.E164).lstrip('+')
    logging.debug('Senderid use national form, e.g. 09123456...')
    from_num = ''.join(phonenumberutil.format_number(phonenumberutil.parse(f_num, country) \
             , phonenumberutil.PhoneNumberFormat.NATIONAL).split())
    to_num = phonenumberutil.format_number(phonenumberutil.parse(t_num, country) \
            , phonenumberutil.PhoneNumberFormat.E164)

    sms = NexmoMessage({
            'reqtype': 'json',
            'type': 'unicode',
            'api_secret': api_secret,
            'api_key': api_key,
            'from': from_num,
            'to': to_num,
            'text': msg
Ejemplo n.º 49
0
def format_us_phone_number(value):
    phone = parse(value, 'US')
    formatted = format_number(phone, PhoneNumberFormat.E164)
    if phone.extension:
        formatted += 'x%s' % phone.extension
    return formatted
def _clean_phone_for_rows(dataframe, phonenum_field, newField, region_string, region_field, use_orig_on_error, category):
    """
    Called by main function to iterate through phone number elements and clean them one by one.
    Assumes region values have already been validated as supported region abbreviations.
    :param dataframe:
    :param phonenum_field:
    :param newField:
    :param region_string:
    :param region_field:
    :param use_orig_on_error:
    :param category:
    :return:
    """

    if not dataframe[phonenum_field].index.is_unique:
        raise IndexError('indexes/keys in dataframe must be unique per row for this function to work correctly!')

    NULL_VALUES = IGNORED_VALUES   # null values that will be ignored

    # looping through elements because phone num library doesn't allow bulk validation
    for idx, value in dataframe[phonenum_field].iteritems():
        # for trivial null cases, don't attempt to parse phonenum and just continue to next value
        if value in NULL_VALUES:
            # in the future, might want to add some logic here to update the other field. For now, don't do anything
            pass
        else:
            # set region to appropriate specified string, or string specified in a specific column-row
            if category == 'both_string_and_field':
                if dataframe[region_field][idx] not in NULL_VALUES:
                    region = str(dataframe[region_field][idx])
                else:
                    region = region_string
            elif category == 'only_region_field':
                if dataframe[region_field][idx] not in NULL_VALUES:
                    region = str(dataframe[region_field][idx])
                else:
                    region = None
            else:
                region = region_string

            # validate/format phone number, or nullify value as NaN
            try:
                # parse will raise an exception if value doesn't seem to be a phone number, so need to use a try block
                phonenum = phonenumberutil.parse(str(value), region=region, keep_raw_input=False,
                                              numobj=None, _check_region=True)

                # update with validated, formatted phone number, or nullify as NaN
                if phonenumberutil.is_valid_number_for_region(phonenum, region):
                    _update_element(dataframe=dataframe, phonenum_field=phonenum_field, newField=newField,
                                    index=idx, replacement_value=phonenum.national_number)
                else:
                    _update_element(dataframe=dataframe, phonenum_field=phonenum_field, newField=newField,
                                    index=idx, replacement_value=np.nan)
            except:
                # update value as NaN or paste original value
                if use_orig_on_error:
                    _update_element(dataframe=dataframe, phonenum_field=phonenum_field, newField=newField,
                                    index=idx, replacement_value=dataframe[phonenum_field][idx])
                else:
                    _update_element(dataframe=dataframe, phonenum_field=phonenum_field, newField=newField,
                                    index=idx, replacement_value=np.nan)