Home | History | Annotate | Download | only in phonenumbers
      1 /*
      2  * Copyright (C) 2009 The Libphonenumber Authors
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  * http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package com.android.i18n.phonenumbers;
     18 
     19 import com.android.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberFormat;
     20 import com.android.i18n.phonenumbers.Phonemetadata.NumberFormat;
     21 import com.android.i18n.phonenumbers.Phonemetadata.PhoneMetadata;
     22 import com.android.i18n.phonenumbers.Phonemetadata.PhoneNumberDesc;
     23 import com.android.i18n.phonenumbers.Phonenumber.PhoneNumber;
     24 import com.android.i18n.phonenumbers.Phonenumber.PhoneNumber.CountryCodeSource;
     25 
     26 import java.util.ArrayList;
     27 import java.util.List;
     28 
     29 /**
     30  * Unit tests for PhoneNumberUtil.java
     31  *
     32  * Note that these tests use the test metadata, not the normal metadata file, so should not be used
     33  * for regression test purposes - these tests are illustrative only and test functionality.
     34  *
     35  * @author Shaopeng Jia
     36  * @author Lara Rennie
     37  */
     38 public class PhoneNumberUtilTest extends TestMetadataTestCase {
     39   // Set up some test numbers to re-use.
     40   private static final PhoneNumber ALPHA_NUMERIC_NUMBER =
     41       new PhoneNumber().setCountryCode(1).setNationalNumber(80074935247L);
     42   private static final PhoneNumber AR_MOBILE =
     43       new PhoneNumber().setCountryCode(54).setNationalNumber(91187654321L);
     44   private static final PhoneNumber AR_NUMBER =
     45       new PhoneNumber().setCountryCode(54).setNationalNumber(1187654321);
     46   private static final PhoneNumber AU_NUMBER =
     47       new PhoneNumber().setCountryCode(61).setNationalNumber(236618300L);
     48   private static final PhoneNumber BS_MOBILE =
     49       new PhoneNumber().setCountryCode(1).setNationalNumber(2423570000L);
     50   private static final PhoneNumber BS_NUMBER =
     51       new PhoneNumber().setCountryCode(1).setNationalNumber(2423651234L);
     52   // Note that this is the same as the example number for DE in the metadata.
     53   private static final PhoneNumber DE_NUMBER =
     54       new PhoneNumber().setCountryCode(49).setNationalNumber(30123456L);
     55   private static final PhoneNumber DE_SHORT_NUMBER =
     56       new PhoneNumber().setCountryCode(49).setNationalNumber(1234L);
     57   private static final PhoneNumber GB_MOBILE =
     58       new PhoneNumber().setCountryCode(44).setNationalNumber(7912345678L);
     59   private static final PhoneNumber GB_NUMBER =
     60       new PhoneNumber().setCountryCode(44).setNationalNumber(2070313000L);
     61   private static final PhoneNumber IT_MOBILE =
     62       new PhoneNumber().setCountryCode(39).setNationalNumber(345678901L);
     63   private static final PhoneNumber IT_NUMBER =
     64       new PhoneNumber().setCountryCode(39).setNationalNumber(236618300L).
     65       setItalianLeadingZero(true);
     66   private static final PhoneNumber JP_STAR_NUMBER =
     67       new PhoneNumber().setCountryCode(81).setNationalNumber(2345);
     68   // Numbers to test the formatting rules from Mexico.
     69   private static final PhoneNumber MX_MOBILE1 =
     70       new PhoneNumber().setCountryCode(52).setNationalNumber(12345678900L);
     71   private static final PhoneNumber MX_MOBILE2 =
     72       new PhoneNumber().setCountryCode(52).setNationalNumber(15512345678L);
     73   private static final PhoneNumber MX_NUMBER1 =
     74       new PhoneNumber().setCountryCode(52).setNationalNumber(3312345678L);
     75   private static final PhoneNumber MX_NUMBER2 =
     76       new PhoneNumber().setCountryCode(52).setNationalNumber(8211234567L);
     77   private static final PhoneNumber NZ_NUMBER =
     78       new PhoneNumber().setCountryCode(64).setNationalNumber(33316005L);
     79   private static final PhoneNumber SG_NUMBER =
     80       new PhoneNumber().setCountryCode(65).setNationalNumber(65218000L);
     81   // A too-long and hence invalid US number.
     82   private static final PhoneNumber US_LONG_NUMBER =
     83       new PhoneNumber().setCountryCode(1).setNationalNumber(65025300001L);
     84   private static final PhoneNumber US_NUMBER =
     85       new PhoneNumber().setCountryCode(1).setNationalNumber(6502530000L);
     86   private static final PhoneNumber US_PREMIUM =
     87       new PhoneNumber().setCountryCode(1).setNationalNumber(9002530000L);
     88   // Too short, but still possible US numbers.
     89   private static final PhoneNumber US_LOCAL_NUMBER =
     90       new PhoneNumber().setCountryCode(1).setNationalNumber(2530000L);
     91   private static final PhoneNumber US_SHORT_BY_ONE_NUMBER =
     92       new PhoneNumber().setCountryCode(1).setNationalNumber(650253000L);
     93   private static final PhoneNumber US_TOLLFREE =
     94       new PhoneNumber().setCountryCode(1).setNationalNumber(8002530000L);
     95   private static final PhoneNumber US_SPOOF =
     96       new PhoneNumber().setCountryCode(1).setNationalNumber(0L);
     97   private static final PhoneNumber US_SPOOF_WITH_RAW_INPUT =
     98       new PhoneNumber().setCountryCode(1).setNationalNumber(0L)
     99           .setRawInput("000-000-0000");
    100   private static final PhoneNumber INTERNATIONAL_TOLL_FREE =
    101       new PhoneNumber().setCountryCode(800).setNationalNumber(12345678L);
    102   private static final PhoneNumber INTERNATIONAL_TOLL_FREE_TOO_LONG =
    103       new PhoneNumber().setCountryCode(800).setNationalNumber(1234567890L);
    104 
    105   public void testGetSupportedRegions() {
    106     assertTrue(phoneUtil.getSupportedRegions().size() > 0);
    107   }
    108 
    109   public void testGetInstanceLoadUSMetadata() {
    110     PhoneMetadata metadata = phoneUtil.getMetadataForRegion(RegionCode.US);
    111     assertEquals("US", metadata.getId());
    112     assertEquals(1, metadata.getCountryCode());
    113     assertEquals("011", metadata.getInternationalPrefix());
    114     assertTrue(metadata.hasNationalPrefix());
    115     assertEquals(2, metadata.numberFormatSize());
    116     assertEquals("(\\d{3})(\\d{3})(\\d{4})",
    117                  metadata.getNumberFormat(1).getPattern());
    118     assertEquals("$1 $2 $3", metadata.getNumberFormat(1).getFormat());
    119     assertEquals("[13-689]\\d{9}|2[0-35-9]\\d{8}",
    120                  metadata.getGeneralDesc().getNationalNumberPattern());
    121     assertEquals("\\d{7}(?:\\d{3})?", metadata.getGeneralDesc().getPossibleNumberPattern());
    122     assertTrue(metadata.getGeneralDesc().exactlySameAs(metadata.getFixedLine()));
    123     assertEquals("\\d{10}", metadata.getTollFree().getPossibleNumberPattern());
    124     assertEquals("900\\d{7}", metadata.getPremiumRate().getNationalNumberPattern());
    125     // No shared-cost data is available, so it should be initialised to "NA".
    126     assertEquals("NA", metadata.getSharedCost().getNationalNumberPattern());
    127     assertEquals("NA", metadata.getSharedCost().getPossibleNumberPattern());
    128   }
    129 
    130   public void testGetInstanceLoadDEMetadata() {
    131     PhoneMetadata metadata = phoneUtil.getMetadataForRegion(RegionCode.DE);
    132     assertEquals("DE", metadata.getId());
    133     assertEquals(49, metadata.getCountryCode());
    134     assertEquals("00", metadata.getInternationalPrefix());
    135     assertEquals("0", metadata.getNationalPrefix());
    136     assertEquals(6, metadata.numberFormatSize());
    137     assertEquals(1, metadata.getNumberFormat(5).leadingDigitsPatternSize());
    138     assertEquals("900", metadata.getNumberFormat(5).getLeadingDigitsPattern(0));
    139     assertEquals("(\\d{3})(\\d{3,4})(\\d{4})",
    140                  metadata.getNumberFormat(5).getPattern());
    141     assertEquals("$1 $2 $3", metadata.getNumberFormat(5).getFormat());
    142     assertEquals("(?:[24-6]\\d{2}|3[03-9]\\d|[789](?:[1-9]\\d|0[2-9]))\\d{1,8}",
    143                  metadata.getFixedLine().getNationalNumberPattern());
    144     assertEquals("\\d{2,14}", metadata.getFixedLine().getPossibleNumberPattern());
    145     assertEquals("30123456", metadata.getFixedLine().getExampleNumber());
    146     assertEquals("\\d{10}", metadata.getTollFree().getPossibleNumberPattern());
    147     assertEquals("900([135]\\d{6}|9\\d{7})", metadata.getPremiumRate().getNationalNumberPattern());
    148   }
    149 
    150   public void testGetInstanceLoadARMetadata() {
    151     PhoneMetadata metadata = phoneUtil.getMetadataForRegion(RegionCode.AR);
    152     assertEquals("AR", metadata.getId());
    153     assertEquals(54, metadata.getCountryCode());
    154     assertEquals("00", metadata.getInternationalPrefix());
    155     assertEquals("0", metadata.getNationalPrefix());
    156     assertEquals("0(?:(11|343|3715)15)?", metadata.getNationalPrefixForParsing());
    157     assertEquals("9$1", metadata.getNationalPrefixTransformRule());
    158     assertEquals("$2 15 $3-$4", metadata.getNumberFormat(2).getFormat());
    159     assertEquals("(9)(\\d{4})(\\d{2})(\\d{4})",
    160                  metadata.getNumberFormat(3).getPattern());
    161     assertEquals("(9)(\\d{4})(\\d{2})(\\d{4})",
    162                  metadata.getIntlNumberFormat(3).getPattern());
    163     assertEquals("$1 $2 $3 $4", metadata.getIntlNumberFormat(3).getFormat());
    164   }
    165 
    166   public void testGetInstanceLoadInternationalTollFreeMetadata() {
    167     PhoneMetadata metadata = phoneUtil.getMetadataForNonGeographicalRegion(800);
    168     assertEquals("001", metadata.getId());
    169     assertEquals(800, metadata.getCountryCode());
    170     assertEquals("$1 $2", metadata.getNumberFormat(0).getFormat());
    171     assertEquals("(\\d{4})(\\d{4})", metadata.getNumberFormat(0).getPattern());
    172     assertEquals("12345678", metadata.getGeneralDesc().getExampleNumber());
    173     assertEquals("12345678", metadata.getTollFree().getExampleNumber());
    174   }
    175 
    176   public void testIsLeadingZeroPossible() {
    177     assertTrue(phoneUtil.isLeadingZeroPossible(39));  // Italy
    178     assertFalse(phoneUtil.isLeadingZeroPossible(1));  // USA
    179     assertFalse(phoneUtil.isLeadingZeroPossible(800));  // International toll free numbers
    180     assertFalse(phoneUtil.isLeadingZeroPossible(888));  // Not in metadata file, just default to
    181                                                         // false.
    182   }
    183 
    184   public void testGetLengthOfGeographicalAreaCode() {
    185     // Google MTV, which has area code "650".
    186     assertEquals(3, phoneUtil.getLengthOfGeographicalAreaCode(US_NUMBER));
    187 
    188     // A North America toll-free number, which has no area code.
    189     assertEquals(0, phoneUtil.getLengthOfGeographicalAreaCode(US_TOLLFREE));
    190 
    191     // Google London, which has area code "20".
    192     assertEquals(2, phoneUtil.getLengthOfGeographicalAreaCode(GB_NUMBER));
    193 
    194     // A UK mobile phone, which has no area code.
    195     assertEquals(0, phoneUtil.getLengthOfGeographicalAreaCode(GB_MOBILE));
    196 
    197     // Google Buenos Aires, which has area code "11".
    198     assertEquals(2, phoneUtil.getLengthOfGeographicalAreaCode(AR_NUMBER));
    199 
    200     // Google Sydney, which has area code "2".
    201     assertEquals(1, phoneUtil.getLengthOfGeographicalAreaCode(AU_NUMBER));
    202 
    203     // Google Singapore. Singapore has no area code and no national prefix.
    204     assertEquals(0, phoneUtil.getLengthOfGeographicalAreaCode(SG_NUMBER));
    205 
    206     // An invalid US number (1 digit shorter), which has no area code.
    207     assertEquals(0, phoneUtil.getLengthOfGeographicalAreaCode(US_SHORT_BY_ONE_NUMBER));
    208 
    209     // An international toll free number, which has no area code.
    210     assertEquals(0, phoneUtil.getLengthOfGeographicalAreaCode(INTERNATIONAL_TOLL_FREE));
    211   }
    212 
    213   public void testGetLengthOfNationalDestinationCode() {
    214     // Google MTV, which has national destination code (NDC) "650".
    215     assertEquals(3, phoneUtil.getLengthOfNationalDestinationCode(US_NUMBER));
    216 
    217     // A North America toll-free number, which has NDC "800".
    218     assertEquals(3, phoneUtil.getLengthOfNationalDestinationCode(US_TOLLFREE));
    219 
    220     // Google London, which has NDC "20".
    221     assertEquals(2, phoneUtil.getLengthOfNationalDestinationCode(GB_NUMBER));
    222 
    223     // A UK mobile phone, which has NDC "7912".
    224     assertEquals(4, phoneUtil.getLengthOfNationalDestinationCode(GB_MOBILE));
    225 
    226     // Google Buenos Aires, which has NDC "11".
    227     assertEquals(2, phoneUtil.getLengthOfNationalDestinationCode(AR_NUMBER));
    228 
    229     // An Argentinian mobile which has NDC "911".
    230     assertEquals(3, phoneUtil.getLengthOfNationalDestinationCode(AR_MOBILE));
    231 
    232     // Google Sydney, which has NDC "2".
    233     assertEquals(1, phoneUtil.getLengthOfNationalDestinationCode(AU_NUMBER));
    234 
    235     // Google Singapore, which has NDC "6521".
    236     assertEquals(4, phoneUtil.getLengthOfNationalDestinationCode(SG_NUMBER));
    237 
    238     // An invalid US number (1 digit shorter), which has no NDC.
    239     assertEquals(0, phoneUtil.getLengthOfNationalDestinationCode(US_SHORT_BY_ONE_NUMBER));
    240 
    241     // A number containing an invalid country calling code, which shouldn't have any NDC.
    242     PhoneNumber number = new PhoneNumber().setCountryCode(123).setNationalNumber(6502530000L);
    243     assertEquals(0, phoneUtil.getLengthOfNationalDestinationCode(number));
    244 
    245     // An international toll free number, which has NDC "1234".
    246     assertEquals(4, phoneUtil.getLengthOfNationalDestinationCode(INTERNATIONAL_TOLL_FREE));
    247   }
    248 
    249   public void testGetNationalSignificantNumber() {
    250     assertEquals("6502530000", phoneUtil.getNationalSignificantNumber(US_NUMBER));
    251 
    252     // An Italian mobile number.
    253     assertEquals("345678901", phoneUtil.getNationalSignificantNumber(IT_MOBILE));
    254 
    255     // An Italian fixed line number.
    256     assertEquals("0236618300", phoneUtil.getNationalSignificantNumber(IT_NUMBER));
    257 
    258     assertEquals("12345678", phoneUtil.getNationalSignificantNumber(INTERNATIONAL_TOLL_FREE));
    259   }
    260 
    261   public void testGetExampleNumber() {
    262     assertEquals(DE_NUMBER, phoneUtil.getExampleNumber(RegionCode.DE));
    263 
    264     assertEquals(DE_NUMBER,
    265                  phoneUtil.getExampleNumberForType(RegionCode.DE,
    266                                                    PhoneNumberUtil.PhoneNumberType.FIXED_LINE));
    267     assertEquals(null,
    268                  phoneUtil.getExampleNumberForType(RegionCode.DE,
    269                                                    PhoneNumberUtil.PhoneNumberType.MOBILE));
    270     // For the US, the example number is placed under general description, and hence should be used
    271     // for both fixed line and mobile, so neither of these should return null.
    272     assertNotNull(phoneUtil.getExampleNumberForType(RegionCode.US,
    273                                                     PhoneNumberUtil.PhoneNumberType.FIXED_LINE));
    274     assertNotNull(phoneUtil.getExampleNumberForType(RegionCode.US,
    275                                                     PhoneNumberUtil.PhoneNumberType.MOBILE));
    276     // CS is an invalid region, so we have no data for it.
    277     assertNull(phoneUtil.getExampleNumberForType(RegionCode.CS,
    278                                                  PhoneNumberUtil.PhoneNumberType.MOBILE));
    279     // RegionCode 001 is reserved for supporting non-geographical country calling code. We don't
    280     // support getting an example number for it with this method.
    281     assertEquals(null, phoneUtil.getExampleNumber(RegionCode.UN001));
    282   }
    283 
    284   public void testGetExampleNumberForNonGeoEntity() {
    285     assertEquals(INTERNATIONAL_TOLL_FREE, phoneUtil.getExampleNumberForNonGeoEntity(800));
    286   }
    287 
    288   public void testConvertAlphaCharactersInNumber() {
    289     String input = "1800-ABC-DEF";
    290     // Alpha chars are converted to digits; everything else is left untouched.
    291     String expectedOutput = "1800-222-333";
    292     assertEquals(expectedOutput, PhoneNumberUtil.convertAlphaCharactersInNumber(input));
    293   }
    294 
    295   public void testNormaliseRemovePunctuation() {
    296     String inputNumber = "034-56&+#234";
    297     String expectedOutput = "03456234";
    298     assertEquals("Conversion did not correctly remove punctuation",
    299                  expectedOutput,
    300                  PhoneNumberUtil.normalize(inputNumber));
    301   }
    302 
    303   public void testNormaliseReplaceAlphaCharacters() {
    304     String inputNumber = "034-I-am-HUNGRY";
    305     String expectedOutput = "034426486479";
    306     assertEquals("Conversion did not correctly replace alpha characters",
    307                  expectedOutput,
    308                  PhoneNumberUtil.normalize(inputNumber));
    309   }
    310 
    311   public void testNormaliseOtherDigits() {
    312     String inputNumber = "\uFF125\u0665";
    313     String expectedOutput = "255";
    314     assertEquals("Conversion did not correctly replace non-latin digits",
    315                  expectedOutput,
    316                  PhoneNumberUtil.normalize(inputNumber));
    317     // Eastern-Arabic digits.
    318     inputNumber = "\u06F52\u06F0";
    319     expectedOutput = "520";
    320     assertEquals("Conversion did not correctly replace non-latin digits",
    321                  expectedOutput,
    322                  PhoneNumberUtil.normalize(inputNumber));
    323   }
    324 
    325   public void testNormaliseStripAlphaCharacters() {
    326     String inputNumber = "034-56&+a#234";
    327     String expectedOutput = "03456234";
    328     assertEquals("Conversion did not correctly remove alpha character",
    329                  expectedOutput,
    330                  PhoneNumberUtil.normalizeDigitsOnly(inputNumber));
    331   }
    332 
    333   public void testFormatUSNumber() {
    334     assertEquals("650 253 0000", phoneUtil.format(US_NUMBER, PhoneNumberFormat.NATIONAL));
    335     assertEquals("+1 650 253 0000", phoneUtil.format(US_NUMBER, PhoneNumberFormat.INTERNATIONAL));
    336 
    337     assertEquals("800 253 0000", phoneUtil.format(US_TOLLFREE, PhoneNumberFormat.NATIONAL));
    338     assertEquals("+1 800 253 0000", phoneUtil.format(US_TOLLFREE, PhoneNumberFormat.INTERNATIONAL));
    339 
    340     assertEquals("900 253 0000", phoneUtil.format(US_PREMIUM, PhoneNumberFormat.NATIONAL));
    341     assertEquals("+1 900 253 0000", phoneUtil.format(US_PREMIUM, PhoneNumberFormat.INTERNATIONAL));
    342     assertEquals("tel:+1-900-253-0000", phoneUtil.format(US_PREMIUM, PhoneNumberFormat.RFC3966));
    343     // Numbers with all zeros in the national number part will be formatted by using the raw_input
    344     // if that is available no matter which format is specified.
    345     assertEquals("000-000-0000",
    346                  phoneUtil.format(US_SPOOF_WITH_RAW_INPUT, PhoneNumberFormat.NATIONAL));
    347     assertEquals("0", phoneUtil.format(US_SPOOF, PhoneNumberFormat.NATIONAL));
    348   }
    349 
    350   public void testFormatBSNumber() {
    351     assertEquals("242 365 1234", phoneUtil.format(BS_NUMBER, PhoneNumberFormat.NATIONAL));
    352     assertEquals("+1 242 365 1234", phoneUtil.format(BS_NUMBER, PhoneNumberFormat.INTERNATIONAL));
    353   }
    354 
    355   public void testFormatGBNumber() {
    356     assertEquals("(020) 7031 3000", phoneUtil.format(GB_NUMBER, PhoneNumberFormat.NATIONAL));
    357     assertEquals("+44 20 7031 3000", phoneUtil.format(GB_NUMBER, PhoneNumberFormat.INTERNATIONAL));
    358 
    359     assertEquals("(07912) 345 678", phoneUtil.format(GB_MOBILE, PhoneNumberFormat.NATIONAL));
    360     assertEquals("+44 7912 345 678", phoneUtil.format(GB_MOBILE, PhoneNumberFormat.INTERNATIONAL));
    361   }
    362 
    363   public void testFormatDENumber() {
    364     PhoneNumber deNumber = new PhoneNumber();
    365     deNumber.setCountryCode(49).setNationalNumber(301234L);
    366     assertEquals("030/1234", phoneUtil.format(deNumber, PhoneNumberFormat.NATIONAL));
    367     assertEquals("+49 30/1234", phoneUtil.format(deNumber, PhoneNumberFormat.INTERNATIONAL));
    368     assertEquals("tel:+49-30-1234", phoneUtil.format(deNumber, PhoneNumberFormat.RFC3966));
    369 
    370     deNumber.clear();
    371     deNumber.setCountryCode(49).setNationalNumber(291123L);
    372     assertEquals("0291 123", phoneUtil.format(deNumber, PhoneNumberFormat.NATIONAL));
    373     assertEquals("+49 291 123", phoneUtil.format(deNumber, PhoneNumberFormat.INTERNATIONAL));
    374 
    375     deNumber.clear();
    376     deNumber.setCountryCode(49).setNationalNumber(29112345678L);
    377     assertEquals("0291 12345678", phoneUtil.format(deNumber, PhoneNumberFormat.NATIONAL));
    378     assertEquals("+49 291 12345678", phoneUtil.format(deNumber, PhoneNumberFormat.INTERNATIONAL));
    379 
    380     deNumber.clear();
    381     deNumber.setCountryCode(49).setNationalNumber(912312345L);
    382     assertEquals("09123 12345", phoneUtil.format(deNumber, PhoneNumberFormat.NATIONAL));
    383     assertEquals("+49 9123 12345", phoneUtil.format(deNumber, PhoneNumberFormat.INTERNATIONAL));
    384     deNumber.clear();
    385     deNumber.setCountryCode(49).setNationalNumber(80212345L);
    386     assertEquals("08021 2345", phoneUtil.format(deNumber, PhoneNumberFormat.NATIONAL));
    387     assertEquals("+49 8021 2345", phoneUtil.format(deNumber, PhoneNumberFormat.INTERNATIONAL));
    388     // Note this number is correctly formatted without national prefix. Most of the numbers that
    389     // are treated as invalid numbers by the library are short numbers, and they are usually not
    390     // dialed with national prefix.
    391     assertEquals("1234", phoneUtil.format(DE_SHORT_NUMBER, PhoneNumberFormat.NATIONAL));
    392     assertEquals("+49 1234", phoneUtil.format(DE_SHORT_NUMBER, PhoneNumberFormat.INTERNATIONAL));
    393 
    394     deNumber.clear();
    395     deNumber.setCountryCode(49).setNationalNumber(41341234);
    396     assertEquals("04134 1234", phoneUtil.format(deNumber, PhoneNumberFormat.NATIONAL));
    397   }
    398 
    399   public void testFormatITNumber() {
    400     assertEquals("02 3661 8300", phoneUtil.format(IT_NUMBER, PhoneNumberFormat.NATIONAL));
    401     assertEquals("+39 02 3661 8300", phoneUtil.format(IT_NUMBER, PhoneNumberFormat.INTERNATIONAL));
    402     assertEquals("+390236618300", phoneUtil.format(IT_NUMBER, PhoneNumberFormat.E164));
    403 
    404     assertEquals("345 678 901", phoneUtil.format(IT_MOBILE, PhoneNumberFormat.NATIONAL));
    405     assertEquals("+39 345 678 901", phoneUtil.format(IT_MOBILE, PhoneNumberFormat.INTERNATIONAL));
    406     assertEquals("+39345678901", phoneUtil.format(IT_MOBILE, PhoneNumberFormat.E164));
    407   }
    408 
    409   public void testFormatAUNumber() {
    410     assertEquals("02 3661 8300", phoneUtil.format(AU_NUMBER, PhoneNumberFormat.NATIONAL));
    411     assertEquals("+61 2 3661 8300", phoneUtil.format(AU_NUMBER, PhoneNumberFormat.INTERNATIONAL));
    412     assertEquals("+61236618300", phoneUtil.format(AU_NUMBER, PhoneNumberFormat.E164));
    413 
    414     PhoneNumber auNumber = new PhoneNumber().setCountryCode(61).setNationalNumber(1800123456L);
    415     assertEquals("1800 123 456", phoneUtil.format(auNumber, PhoneNumberFormat.NATIONAL));
    416     assertEquals("+61 1800 123 456", phoneUtil.format(auNumber, PhoneNumberFormat.INTERNATIONAL));
    417     assertEquals("+611800123456", phoneUtil.format(auNumber, PhoneNumberFormat.E164));
    418   }
    419 
    420   public void testFormatARNumber() {
    421     assertEquals("011 8765-4321", phoneUtil.format(AR_NUMBER, PhoneNumberFormat.NATIONAL));
    422     assertEquals("+54 11 8765-4321", phoneUtil.format(AR_NUMBER, PhoneNumberFormat.INTERNATIONAL));
    423     assertEquals("+541187654321", phoneUtil.format(AR_NUMBER, PhoneNumberFormat.E164));
    424 
    425     assertEquals("011 15 8765-4321", phoneUtil.format(AR_MOBILE, PhoneNumberFormat.NATIONAL));
    426     assertEquals("+54 9 11 8765 4321", phoneUtil.format(AR_MOBILE,
    427                                                         PhoneNumberFormat.INTERNATIONAL));
    428     assertEquals("+5491187654321", phoneUtil.format(AR_MOBILE, PhoneNumberFormat.E164));
    429   }
    430 
    431   public void testFormatMXNumber() {
    432     assertEquals("045 234 567 8900", phoneUtil.format(MX_MOBILE1, PhoneNumberFormat.NATIONAL));
    433     assertEquals("+52 1 234 567 8900", phoneUtil.format(
    434         MX_MOBILE1, PhoneNumberFormat.INTERNATIONAL));
    435     assertEquals("+5212345678900", phoneUtil.format(MX_MOBILE1, PhoneNumberFormat.E164));
    436 
    437     assertEquals("045 55 1234 5678", phoneUtil.format(MX_MOBILE2, PhoneNumberFormat.NATIONAL));
    438     assertEquals("+52 1 55 1234 5678", phoneUtil.format(
    439         MX_MOBILE2, PhoneNumberFormat.INTERNATIONAL));
    440     assertEquals("+5215512345678", phoneUtil.format(MX_MOBILE2, PhoneNumberFormat.E164));
    441 
    442     assertEquals("01 33 1234 5678", phoneUtil.format(MX_NUMBER1, PhoneNumberFormat.NATIONAL));
    443     assertEquals("+52 33 1234 5678", phoneUtil.format(MX_NUMBER1, PhoneNumberFormat.INTERNATIONAL));
    444     assertEquals("+523312345678", phoneUtil.format(MX_NUMBER1, PhoneNumberFormat.E164));
    445 
    446     assertEquals("01 821 123 4567", phoneUtil.format(MX_NUMBER2, PhoneNumberFormat.NATIONAL));
    447     assertEquals("+52 821 123 4567", phoneUtil.format(MX_NUMBER2, PhoneNumberFormat.INTERNATIONAL));
    448     assertEquals("+528211234567", phoneUtil.format(MX_NUMBER2, PhoneNumberFormat.E164));
    449   }
    450 
    451   public void testFormatOutOfCountryCallingNumber() {
    452     assertEquals("00 1 900 253 0000",
    453                  phoneUtil.formatOutOfCountryCallingNumber(US_PREMIUM, RegionCode.DE));
    454 
    455     assertEquals("1 650 253 0000",
    456                  phoneUtil.formatOutOfCountryCallingNumber(US_NUMBER, RegionCode.BS));
    457 
    458     assertEquals("00 1 650 253 0000",
    459                  phoneUtil.formatOutOfCountryCallingNumber(US_NUMBER, RegionCode.PL));
    460 
    461     assertEquals("011 44 7912 345 678",
    462                  phoneUtil.formatOutOfCountryCallingNumber(GB_MOBILE, RegionCode.US));
    463 
    464     assertEquals("00 49 1234",
    465                  phoneUtil.formatOutOfCountryCallingNumber(DE_SHORT_NUMBER, RegionCode.GB));
    466     // Note this number is correctly formatted without national prefix. Most of the numbers that
    467     // are treated as invalid numbers by the library are short numbers, and they are usually not
    468     // dialed with national prefix.
    469     assertEquals("1234", phoneUtil.formatOutOfCountryCallingNumber(DE_SHORT_NUMBER, RegionCode.DE));
    470 
    471     assertEquals("011 39 02 3661 8300",
    472                  phoneUtil.formatOutOfCountryCallingNumber(IT_NUMBER, RegionCode.US));
    473     assertEquals("02 3661 8300",
    474                  phoneUtil.formatOutOfCountryCallingNumber(IT_NUMBER, RegionCode.IT));
    475     assertEquals("+39 02 3661 8300",
    476                  phoneUtil.formatOutOfCountryCallingNumber(IT_NUMBER, RegionCode.SG));
    477 
    478     assertEquals("6521 8000",
    479                  phoneUtil.formatOutOfCountryCallingNumber(SG_NUMBER, RegionCode.SG));
    480 
    481     assertEquals("011 54 9 11 8765 4321",
    482                  phoneUtil.formatOutOfCountryCallingNumber(AR_MOBILE, RegionCode.US));
    483     assertEquals("011 800 1234 5678",
    484                  phoneUtil.formatOutOfCountryCallingNumber(INTERNATIONAL_TOLL_FREE, RegionCode.US));
    485 
    486     PhoneNumber arNumberWithExtn = new PhoneNumber().mergeFrom(AR_MOBILE).setExtension("1234");
    487     assertEquals("011 54 9 11 8765 4321 ext. 1234",
    488                  phoneUtil.formatOutOfCountryCallingNumber(arNumberWithExtn, RegionCode.US));
    489     assertEquals("0011 54 9 11 8765 4321 ext. 1234",
    490                  phoneUtil.formatOutOfCountryCallingNumber(arNumberWithExtn, RegionCode.AU));
    491     assertEquals("011 15 8765-4321 ext. 1234",
    492                  phoneUtil.formatOutOfCountryCallingNumber(arNumberWithExtn, RegionCode.AR));
    493   }
    494 
    495   public void testFormatOutOfCountryWithInvalidRegion() {
    496     // AQ/Antarctica isn't a valid region code for phone number formatting,
    497     // so this falls back to intl formatting.
    498     assertEquals("+1 650 253 0000",
    499                  phoneUtil.formatOutOfCountryCallingNumber(US_NUMBER, RegionCode.AQ));
    500     // For region code 001, the out-of-country format always turns into the international format.
    501     assertEquals("+1 650 253 0000",
    502                  phoneUtil.formatOutOfCountryCallingNumber(US_NUMBER, RegionCode.UN001));
    503   }
    504 
    505   public void testFormatOutOfCountryWithPreferredIntlPrefix() {
    506     // This should use 0011, since that is the preferred international prefix (both 0011 and 0012
    507     // are accepted as possible international prefixes in our test metadta.)
    508     assertEquals("0011 39 02 3661 8300",
    509                  phoneUtil.formatOutOfCountryCallingNumber(IT_NUMBER, RegionCode.AU));
    510   }
    511 
    512   public void testFormatOutOfCountryKeepingAlphaChars() {
    513     PhoneNumber alphaNumericNumber = new PhoneNumber();
    514     alphaNumericNumber.setCountryCode(1).setNationalNumber(8007493524L)
    515         .setRawInput("1800 six-flag");
    516     assertEquals("0011 1 800 SIX-FLAG",
    517                  phoneUtil.formatOutOfCountryKeepingAlphaChars(alphaNumericNumber, RegionCode.AU));
    518 
    519     alphaNumericNumber.setRawInput("1-800-SIX-flag");
    520     assertEquals("0011 1 800-SIX-FLAG",
    521                  phoneUtil.formatOutOfCountryKeepingAlphaChars(alphaNumericNumber, RegionCode.AU));
    522 
    523     alphaNumericNumber.setRawInput("Call us from UK: 00 1 800 SIX-flag");
    524     assertEquals("0011 1 800 SIX-FLAG",
    525                  phoneUtil.formatOutOfCountryKeepingAlphaChars(alphaNumericNumber, RegionCode.AU));
    526 
    527     alphaNumericNumber.setRawInput("800 SIX-flag");
    528     assertEquals("0011 1 800 SIX-FLAG",
    529                  phoneUtil.formatOutOfCountryKeepingAlphaChars(alphaNumericNumber, RegionCode.AU));
    530 
    531     // Formatting from within the NANPA region.
    532     assertEquals("1 800 SIX-FLAG",
    533                  phoneUtil.formatOutOfCountryKeepingAlphaChars(alphaNumericNumber, RegionCode.US));
    534 
    535     assertEquals("1 800 SIX-FLAG",
    536                  phoneUtil.formatOutOfCountryKeepingAlphaChars(alphaNumericNumber, RegionCode.BS));
    537 
    538     // Testing that if the raw input doesn't exist, it is formatted using
    539     // formatOutOfCountryCallingNumber.
    540     alphaNumericNumber.clearRawInput();
    541     assertEquals("00 1 800 749 3524",
    542                  phoneUtil.formatOutOfCountryKeepingAlphaChars(alphaNumericNumber, RegionCode.DE));
    543 
    544     // Testing AU alpha number formatted from Australia.
    545     alphaNumericNumber.setCountryCode(61).setNationalNumber(827493524L)
    546         .setRawInput("+61 82749-FLAG");
    547     // This number should have the national prefix fixed.
    548     assertEquals("082749-FLAG",
    549                  phoneUtil.formatOutOfCountryKeepingAlphaChars(alphaNumericNumber, RegionCode.AU));
    550 
    551     alphaNumericNumber.setRawInput("082749-FLAG");
    552     assertEquals("082749-FLAG",
    553                  phoneUtil.formatOutOfCountryKeepingAlphaChars(alphaNumericNumber, RegionCode.AU));
    554 
    555     alphaNumericNumber.setNationalNumber(18007493524L).setRawInput("1-800-SIX-flag");
    556     // This number should not have the national prefix prefixed, in accordance with the override for
    557     // this specific formatting rule.
    558     assertEquals("1-800-SIX-FLAG",
    559                  phoneUtil.formatOutOfCountryKeepingAlphaChars(alphaNumericNumber, RegionCode.AU));
    560 
    561     // The metadata should not be permanently changed, since we copied it before modifying patterns.
    562     // Here we check this.
    563     alphaNumericNumber.setNationalNumber(1800749352L);
    564     assertEquals("1800 749 352",
    565                  phoneUtil.formatOutOfCountryCallingNumber(alphaNumericNumber, RegionCode.AU));
    566 
    567     // Testing a region with multiple international prefixes.
    568     assertEquals("+61 1-800-SIX-FLAG",
    569                  phoneUtil.formatOutOfCountryKeepingAlphaChars(alphaNumericNumber, RegionCode.SG));
    570     // Testing the case of calling from a non-supported region.
    571     assertEquals("+61 1-800-SIX-FLAG",
    572                  phoneUtil.formatOutOfCountryKeepingAlphaChars(alphaNumericNumber, RegionCode.AQ));
    573 
    574     // Testing the case with an invalid country calling code.
    575     alphaNumericNumber.setCountryCode(0).setNationalNumber(18007493524L)
    576         .setRawInput("1-800-SIX-flag");
    577     // Uses the raw input only.
    578     assertEquals("1-800-SIX-flag",
    579                  phoneUtil.formatOutOfCountryKeepingAlphaChars(alphaNumericNumber, RegionCode.DE));
    580 
    581     // Testing the case of an invalid alpha number.
    582     alphaNumericNumber.setCountryCode(1).setNationalNumber(80749L).setRawInput("180-SIX");
    583     // No country-code stripping can be done.
    584     assertEquals("00 1 180-SIX",
    585                  phoneUtil.formatOutOfCountryKeepingAlphaChars(alphaNumericNumber, RegionCode.DE));
    586 
    587     // Testing the case of calling from a non-supported region.
    588     alphaNumericNumber.setCountryCode(1).setNationalNumber(80749L).setRawInput("180-SIX");
    589     // No country-code stripping can be done since the number is invalid.
    590     assertEquals("+1 180-SIX",
    591                  phoneUtil.formatOutOfCountryKeepingAlphaChars(alphaNumericNumber, RegionCode.AQ));
    592   }
    593 
    594   public void testFormatWithCarrierCode() {
    595     // We only support this for AR in our test metadata, and only for mobile numbers starting with
    596     // certain values.
    597     PhoneNumber arMobile = new PhoneNumber().setCountryCode(54).setNationalNumber(92234654321L);
    598     assertEquals("02234 65-4321", phoneUtil.format(arMobile, PhoneNumberFormat.NATIONAL));
    599     // Here we force 14 as the carrier code.
    600     assertEquals("02234 14 65-4321",
    601                  phoneUtil.formatNationalNumberWithCarrierCode(arMobile, "14"));
    602     // Here we force the number to be shown with no carrier code.
    603     assertEquals("02234 65-4321",
    604                  phoneUtil.formatNationalNumberWithCarrierCode(arMobile, ""));
    605     // Here the international rule is used, so no carrier code should be present.
    606     assertEquals("+5492234654321", phoneUtil.format(arMobile, PhoneNumberFormat.E164));
    607     // We don't support this for the US so there should be no change.
    608     assertEquals("650 253 0000", phoneUtil.formatNationalNumberWithCarrierCode(US_NUMBER, "15"));
    609   }
    610 
    611   public void testFormatWithPreferredCarrierCode() {
    612     // We only support this for AR in our test metadata.
    613     PhoneNumber arNumber = new PhoneNumber();
    614     arNumber.setCountryCode(54).setNationalNumber(91234125678L);
    615     // Test formatting with no preferred carrier code stored in the number itself.
    616     assertEquals("01234 15 12-5678",
    617         phoneUtil.formatNationalNumberWithPreferredCarrierCode(arNumber, "15"));
    618     assertEquals("01234 12-5678",
    619         phoneUtil.formatNationalNumberWithPreferredCarrierCode(arNumber, ""));
    620     // Test formatting with preferred carrier code present.
    621     arNumber.setPreferredDomesticCarrierCode("19");
    622     assertEquals("01234 12-5678", phoneUtil.format(arNumber, PhoneNumberFormat.NATIONAL));
    623     assertEquals("01234 19 12-5678",
    624         phoneUtil.formatNationalNumberWithPreferredCarrierCode(arNumber, "15"));
    625     assertEquals("01234 19 12-5678",
    626         phoneUtil.formatNationalNumberWithPreferredCarrierCode(arNumber, ""));
    627     // When the preferred_domestic_carrier_code is present (even when it contains an empty string),
    628     // use it instead of the default carrier code passed in.
    629     arNumber.setPreferredDomesticCarrierCode("");
    630     assertEquals("01234 12-5678",
    631         phoneUtil.formatNationalNumberWithPreferredCarrierCode(arNumber, "15"));
    632     // We don't support this for the US so there should be no change.
    633     PhoneNumber usNumber = new PhoneNumber();
    634     usNumber.setCountryCode(1).setNationalNumber(4241231234L).setPreferredDomesticCarrierCode("99");
    635     assertEquals("424 123 1234", phoneUtil.format(usNumber, PhoneNumberFormat.NATIONAL));
    636     assertEquals("424 123 1234",
    637         phoneUtil.formatNationalNumberWithPreferredCarrierCode(usNumber, "15"));
    638   }
    639 
    640   public void testFormatNumberForMobileDialing() {
    641     // US toll free numbers are marked as noInternationalDialling in the test metadata for testing
    642     // purposes.
    643     assertEquals("800 253 0000",
    644         phoneUtil.formatNumberForMobileDialing(US_TOLLFREE, RegionCode.US,
    645                                                true /*  keep formatting */));
    646     assertEquals("", phoneUtil.formatNumberForMobileDialing(US_TOLLFREE, RegionCode.CN, true));
    647     assertEquals("+1 650 253 0000",
    648         phoneUtil.formatNumberForMobileDialing(US_NUMBER, RegionCode.US, true));
    649     PhoneNumber usNumberWithExtn = new PhoneNumber().mergeFrom(US_NUMBER).setExtension("1234");
    650     assertEquals("+1 650 253 0000",
    651         phoneUtil.formatNumberForMobileDialing(usNumberWithExtn, RegionCode.US, true));
    652 
    653     assertEquals("8002530000",
    654         phoneUtil.formatNumberForMobileDialing(US_TOLLFREE, RegionCode.US,
    655                                                false /* remove formatting */));
    656     assertEquals("", phoneUtil.formatNumberForMobileDialing(US_TOLLFREE, RegionCode.CN, false));
    657     assertEquals("+16502530000",
    658         phoneUtil.formatNumberForMobileDialing(US_NUMBER, RegionCode.US, false));
    659     assertEquals("+16502530000",
    660         phoneUtil.formatNumberForMobileDialing(usNumberWithExtn, RegionCode.US, false));
    661 
    662     // An invalid US number, which is one digit too long.
    663     assertEquals("+165025300001",
    664         phoneUtil.formatNumberForMobileDialing(US_LONG_NUMBER, RegionCode.US, false));
    665     assertEquals("+1 65025300001",
    666         phoneUtil.formatNumberForMobileDialing(US_LONG_NUMBER, RegionCode.US, true));
    667 
    668     // Star numbers. In real life they appear in Israel, but we have them in JP in our test
    669     // metadata.
    670     assertEquals("*2345",
    671         phoneUtil.formatNumberForMobileDialing(JP_STAR_NUMBER, RegionCode.JP, false));
    672     assertEquals("*2345",
    673         phoneUtil.formatNumberForMobileDialing(JP_STAR_NUMBER, RegionCode.JP, true));
    674 
    675     assertEquals("+80012345678",
    676         phoneUtil.formatNumberForMobileDialing(INTERNATIONAL_TOLL_FREE, RegionCode.JP, false));
    677     assertEquals("+800 1234 5678",
    678         phoneUtil.formatNumberForMobileDialing(INTERNATIONAL_TOLL_FREE, RegionCode.JP, true));
    679   }
    680 
    681   public void testFormatByPattern() {
    682     NumberFormat newNumFormat = new NumberFormat();
    683     newNumFormat.setPattern("(\\d{3})(\\d{3})(\\d{4})");
    684     newNumFormat.setFormat("($1) $2-$3");
    685     List<NumberFormat> newNumberFormats = new ArrayList<NumberFormat>();
    686     newNumberFormats.add(newNumFormat);
    687 
    688     assertEquals("(650) 253-0000", phoneUtil.formatByPattern(US_NUMBER, PhoneNumberFormat.NATIONAL,
    689                                                              newNumberFormats));
    690     assertEquals("+1 (650) 253-0000", phoneUtil.formatByPattern(US_NUMBER,
    691                                                                 PhoneNumberFormat.INTERNATIONAL,
    692                                                                 newNumberFormats));
    693     assertEquals("tel:+1-650-253-0000", phoneUtil.formatByPattern(US_NUMBER,
    694                                                                   PhoneNumberFormat.RFC3966,
    695                                                                   newNumberFormats));
    696 
    697     // $NP is set to '1' for the US. Here we check that for other NANPA countries the US rules are
    698     // followed.
    699     newNumFormat.setNationalPrefixFormattingRule("$NP ($FG)");
    700     newNumFormat.setFormat("$1 $2-$3");
    701     assertEquals("1 (242) 365-1234",
    702                  phoneUtil.formatByPattern(BS_NUMBER, PhoneNumberFormat.NATIONAL,
    703                                            newNumberFormats));
    704     assertEquals("+1 242 365-1234",
    705                  phoneUtil.formatByPattern(BS_NUMBER, PhoneNumberFormat.INTERNATIONAL,
    706                                            newNumberFormats));
    707 
    708     newNumFormat.setPattern("(\\d{2})(\\d{5})(\\d{3})");
    709     newNumFormat.setFormat("$1-$2 $3");
    710     newNumberFormats.set(0, newNumFormat);
    711 
    712     assertEquals("02-36618 300",
    713                  phoneUtil.formatByPattern(IT_NUMBER, PhoneNumberFormat.NATIONAL,
    714                                            newNumberFormats));
    715     assertEquals("+39 02-36618 300",
    716                  phoneUtil.formatByPattern(IT_NUMBER, PhoneNumberFormat.INTERNATIONAL,
    717                                            newNumberFormats));
    718 
    719     newNumFormat.setNationalPrefixFormattingRule("$NP$FG");
    720     newNumFormat.setPattern("(\\d{2})(\\d{4})(\\d{4})");
    721     newNumFormat.setFormat("$1 $2 $3");
    722     newNumberFormats.set(0, newNumFormat);
    723     assertEquals("020 7031 3000",
    724                  phoneUtil.formatByPattern(GB_NUMBER, PhoneNumberFormat.NATIONAL,
    725                                            newNumberFormats));
    726 
    727     newNumFormat.setNationalPrefixFormattingRule("($NP$FG)");
    728     assertEquals("(020) 7031 3000",
    729                  phoneUtil.formatByPattern(GB_NUMBER, PhoneNumberFormat.NATIONAL,
    730                                            newNumberFormats));
    731 
    732     newNumFormat.setNationalPrefixFormattingRule("");
    733     assertEquals("20 7031 3000",
    734                  phoneUtil.formatByPattern(GB_NUMBER, PhoneNumberFormat.NATIONAL,
    735                                            newNumberFormats));
    736 
    737     assertEquals("+44 20 7031 3000",
    738                  phoneUtil.formatByPattern(GB_NUMBER, PhoneNumberFormat.INTERNATIONAL,
    739                                            newNumberFormats));
    740   }
    741 
    742   public void testFormatE164Number() {
    743     assertEquals("+16502530000", phoneUtil.format(US_NUMBER, PhoneNumberFormat.E164));
    744     assertEquals("+4930123456", phoneUtil.format(DE_NUMBER, PhoneNumberFormat.E164));
    745     assertEquals("+80012345678", phoneUtil.format(INTERNATIONAL_TOLL_FREE, PhoneNumberFormat.E164));
    746   }
    747 
    748   public void testFormatNumberWithExtension() {
    749     PhoneNumber nzNumber = new PhoneNumber().mergeFrom(NZ_NUMBER).setExtension("1234");
    750     // Uses default extension prefix:
    751     assertEquals("03-331 6005 ext. 1234", phoneUtil.format(nzNumber, PhoneNumberFormat.NATIONAL));
    752     // Uses RFC 3966 syntax.
    753     assertEquals("tel:+64-3-331-6005;ext=1234",
    754         phoneUtil.format(nzNumber, PhoneNumberFormat.RFC3966));
    755     // Extension prefix overridden in the territory information for the US:
    756     PhoneNumber usNumberWithExtension = new PhoneNumber().mergeFrom(US_NUMBER).setExtension("4567");
    757     assertEquals("650 253 0000 extn. 4567", phoneUtil.format(usNumberWithExtension,
    758                                                              PhoneNumberFormat.NATIONAL));
    759   }
    760 
    761   public void testFormatInOriginalFormat() throws Exception {
    762     PhoneNumber number1 = phoneUtil.parseAndKeepRawInput("+442087654321", RegionCode.GB);
    763     assertEquals("+44 20 8765 4321", phoneUtil.formatInOriginalFormat(number1, RegionCode.GB));
    764 
    765     PhoneNumber number2 = phoneUtil.parseAndKeepRawInput("02087654321", RegionCode.GB);
    766     assertEquals("(020) 8765 4321", phoneUtil.formatInOriginalFormat(number2, RegionCode.GB));
    767 
    768     PhoneNumber number3 = phoneUtil.parseAndKeepRawInput("011442087654321", RegionCode.US);
    769     assertEquals("011 44 20 8765 4321", phoneUtil.formatInOriginalFormat(number3, RegionCode.US));
    770 
    771     PhoneNumber number4 = phoneUtil.parseAndKeepRawInput("442087654321", RegionCode.GB);
    772     assertEquals("44 20 8765 4321", phoneUtil.formatInOriginalFormat(number4, RegionCode.GB));
    773 
    774     PhoneNumber number5 = phoneUtil.parse("+442087654321", RegionCode.GB);
    775     assertEquals("(020) 8765 4321", phoneUtil.formatInOriginalFormat(number5, RegionCode.GB));
    776 
    777     // Invalid numbers that we have a formatting pattern for should be formatted properly. Note area
    778     // codes starting with 7 are intentionally excluded in the test metadata for testing purposes.
    779     PhoneNumber number6 = phoneUtil.parseAndKeepRawInput("7345678901", RegionCode.US);
    780     assertEquals("734 567 8901", phoneUtil.formatInOriginalFormat(number6, RegionCode.US));
    781 
    782     // US is not a leading zero country, and the presence of the leading zero leads us to format the
    783     // number using raw_input.
    784     PhoneNumber number7 = phoneUtil.parseAndKeepRawInput("0734567 8901", RegionCode.US);
    785     assertEquals("0734567 8901", phoneUtil.formatInOriginalFormat(number7, RegionCode.US));
    786 
    787     // This number is valid, but we don't have a formatting pattern for it. Fall back to the raw
    788     // input.
    789     PhoneNumber number8 = phoneUtil.parseAndKeepRawInput("02-4567-8900", RegionCode.KR);
    790     assertEquals("02-4567-8900", phoneUtil.formatInOriginalFormat(number8, RegionCode.KR));
    791 
    792     PhoneNumber number9 = phoneUtil.parseAndKeepRawInput("01180012345678", RegionCode.US);
    793     assertEquals("011 800 1234 5678", phoneUtil.formatInOriginalFormat(number9, RegionCode.US));
    794 
    795     PhoneNumber number10 = phoneUtil.parseAndKeepRawInput("+80012345678", RegionCode.KR);
    796     assertEquals("+800 1234 5678", phoneUtil.formatInOriginalFormat(number10, RegionCode.KR));
    797 
    798     // US local numbers are formatted correctly, as we have formatting patterns for them.
    799     PhoneNumber localNumberUS = phoneUtil.parseAndKeepRawInput("2530000", RegionCode.US);
    800     assertEquals("253 0000", phoneUtil.formatInOriginalFormat(localNumberUS, RegionCode.US));
    801 
    802     PhoneNumber numberWithNationalPrefixUS =
    803         phoneUtil.parseAndKeepRawInput("18003456789", RegionCode.US);
    804     assertEquals("1 800 345 6789",
    805         phoneUtil.formatInOriginalFormat(numberWithNationalPrefixUS, RegionCode.US));
    806 
    807     PhoneNumber numberWithoutNationalPrefixGB =
    808         phoneUtil.parseAndKeepRawInput("2087654321", RegionCode.GB);
    809     assertEquals("20 8765 4321",
    810         phoneUtil.formatInOriginalFormat(numberWithoutNationalPrefixGB, RegionCode.GB));
    811     // Make sure no metadata is modified as a result of the previous function call.
    812     assertEquals("(020) 8765 4321", phoneUtil.formatInOriginalFormat(number5, RegionCode.GB));
    813 
    814     PhoneNumber numberWithNationalPrefixMX =
    815         phoneUtil.parseAndKeepRawInput("013312345678", RegionCode.MX);
    816     assertEquals("01 33 1234 5678",
    817         phoneUtil.formatInOriginalFormat(numberWithNationalPrefixMX, RegionCode.MX));
    818 
    819     PhoneNumber numberWithoutNationalPrefixMX =
    820         phoneUtil.parseAndKeepRawInput("3312345678", RegionCode.MX);
    821     assertEquals("33 1234 5678",
    822         phoneUtil.formatInOriginalFormat(numberWithoutNationalPrefixMX, RegionCode.MX));
    823 
    824     PhoneNumber italianFixedLineNumber =
    825         phoneUtil.parseAndKeepRawInput("0212345678", RegionCode.IT);
    826     assertEquals("02 1234 5678",
    827         phoneUtil.formatInOriginalFormat(italianFixedLineNumber, RegionCode.IT));
    828 
    829     PhoneNumber numberWithNationalPrefixJP =
    830         phoneUtil.parseAndKeepRawInput("00777012", RegionCode.JP);
    831     assertEquals("0077-7012",
    832         phoneUtil.formatInOriginalFormat(numberWithNationalPrefixJP, RegionCode.JP));
    833 
    834     PhoneNumber numberWithoutNationalPrefixJP =
    835         phoneUtil.parseAndKeepRawInput("0777012", RegionCode.JP);
    836     assertEquals("0777012",
    837         phoneUtil.formatInOriginalFormat(numberWithoutNationalPrefixJP, RegionCode.JP));
    838 
    839     PhoneNumber numberWithCarrierCodeBR =
    840         phoneUtil.parseAndKeepRawInput("012 3121286979", RegionCode.BR);
    841     assertEquals("012 3121286979",
    842         phoneUtil.formatInOriginalFormat(numberWithCarrierCodeBR, RegionCode.BR));
    843 
    844     // The default national prefix used in this case is 045. When a number with national prefix 044
    845     // is entered, we return the raw input as we don't want to change the number entered.
    846     PhoneNumber numberWithNationalPrefixMX1 =
    847         phoneUtil.parseAndKeepRawInput("044(33)1234-5678", RegionCode.MX);
    848     assertEquals("044(33)1234-5678",
    849         phoneUtil.formatInOriginalFormat(numberWithNationalPrefixMX1, RegionCode.MX));
    850 
    851     PhoneNumber numberWithNationalPrefixMX2 =
    852         phoneUtil.parseAndKeepRawInput("045(33)1234-5678", RegionCode.MX);
    853     assertEquals("045 33 1234 5678",
    854         phoneUtil.formatInOriginalFormat(numberWithNationalPrefixMX2, RegionCode.MX));
    855 
    856     // The default international prefix used in this case is 0011. When a number with international
    857     // prefix 0012 is entered, we return the raw input as we don't want to change the number
    858     // entered.
    859     PhoneNumber outOfCountryNumberFromAU1 =
    860         phoneUtil.parseAndKeepRawInput("0012 16502530000", RegionCode.AU);
    861     assertEquals("0012 16502530000",
    862         phoneUtil.formatInOriginalFormat(outOfCountryNumberFromAU1, RegionCode.AU));
    863 
    864     PhoneNumber outOfCountryNumberFromAU2 =
    865         phoneUtil.parseAndKeepRawInput("0011 16502530000", RegionCode.AU);
    866     assertEquals("0011 1 650 253 0000",
    867         phoneUtil.formatInOriginalFormat(outOfCountryNumberFromAU2, RegionCode.AU));
    868   }
    869 
    870   public void testIsPremiumRate() {
    871     assertEquals(PhoneNumberUtil.PhoneNumberType.PREMIUM_RATE, phoneUtil.getNumberType(US_PREMIUM));
    872 
    873     PhoneNumber premiumRateNumber = new PhoneNumber();
    874     premiumRateNumber.setCountryCode(39).setNationalNumber(892123L);
    875     assertEquals(PhoneNumberUtil.PhoneNumberType.PREMIUM_RATE,
    876                  phoneUtil.getNumberType(premiumRateNumber));
    877 
    878     premiumRateNumber.clear();
    879     premiumRateNumber.setCountryCode(44).setNationalNumber(9187654321L);
    880     assertEquals(PhoneNumberUtil.PhoneNumberType.PREMIUM_RATE,
    881                  phoneUtil.getNumberType(premiumRateNumber));
    882 
    883     premiumRateNumber.clear();
    884     premiumRateNumber.setCountryCode(49).setNationalNumber(9001654321L);
    885     assertEquals(PhoneNumberUtil.PhoneNumberType.PREMIUM_RATE,
    886                  phoneUtil.getNumberType(premiumRateNumber));
    887 
    888     premiumRateNumber.clear();
    889     premiumRateNumber.setCountryCode(49).setNationalNumber(90091234567L);
    890     assertEquals(PhoneNumberUtil.PhoneNumberType.PREMIUM_RATE,
    891                  phoneUtil.getNumberType(premiumRateNumber));
    892   }
    893 
    894   public void testIsTollFree() {
    895     PhoneNumber tollFreeNumber = new PhoneNumber();
    896 
    897     tollFreeNumber.setCountryCode(1).setNationalNumber(8881234567L);
    898     assertEquals(PhoneNumberUtil.PhoneNumberType.TOLL_FREE,
    899                  phoneUtil.getNumberType(tollFreeNumber));
    900 
    901     tollFreeNumber.clear();
    902     tollFreeNumber.setCountryCode(39).setNationalNumber(803123L);
    903     assertEquals(PhoneNumberUtil.PhoneNumberType.TOLL_FREE,
    904                  phoneUtil.getNumberType(tollFreeNumber));
    905 
    906     tollFreeNumber.clear();
    907     tollFreeNumber.setCountryCode(44).setNationalNumber(8012345678L);
    908     assertEquals(PhoneNumberUtil.PhoneNumberType.TOLL_FREE,
    909                  phoneUtil.getNumberType(tollFreeNumber));
    910 
    911     tollFreeNumber.clear();
    912     tollFreeNumber.setCountryCode(49).setNationalNumber(8001234567L);
    913     assertEquals(PhoneNumberUtil.PhoneNumberType.TOLL_FREE,
    914                  phoneUtil.getNumberType(tollFreeNumber));
    915 
    916     assertEquals(PhoneNumberUtil.PhoneNumberType.TOLL_FREE,
    917                  phoneUtil.getNumberType(INTERNATIONAL_TOLL_FREE));
    918   }
    919 
    920   public void testIsMobile() {
    921     assertEquals(PhoneNumberUtil.PhoneNumberType.MOBILE, phoneUtil.getNumberType(BS_MOBILE));
    922     assertEquals(PhoneNumberUtil.PhoneNumberType.MOBILE, phoneUtil.getNumberType(GB_MOBILE));
    923     assertEquals(PhoneNumberUtil.PhoneNumberType.MOBILE, phoneUtil.getNumberType(IT_MOBILE));
    924     assertEquals(PhoneNumberUtil.PhoneNumberType.MOBILE, phoneUtil.getNumberType(AR_MOBILE));
    925 
    926     PhoneNumber mobileNumber = new PhoneNumber();
    927     mobileNumber.setCountryCode(49).setNationalNumber(15123456789L);
    928     assertEquals(PhoneNumberUtil.PhoneNumberType.MOBILE, phoneUtil.getNumberType(mobileNumber));
    929   }
    930 
    931   public void testIsFixedLine() {
    932     assertEquals(PhoneNumberUtil.PhoneNumberType.FIXED_LINE, phoneUtil.getNumberType(BS_NUMBER));
    933     assertEquals(PhoneNumberUtil.PhoneNumberType.FIXED_LINE, phoneUtil.getNumberType(IT_NUMBER));
    934     assertEquals(PhoneNumberUtil.PhoneNumberType.FIXED_LINE, phoneUtil.getNumberType(GB_NUMBER));
    935     assertEquals(PhoneNumberUtil.PhoneNumberType.FIXED_LINE, phoneUtil.getNumberType(DE_NUMBER));
    936   }
    937 
    938   public void testIsFixedLineAndMobile() {
    939     assertEquals(PhoneNumberUtil.PhoneNumberType.FIXED_LINE_OR_MOBILE,
    940                  phoneUtil.getNumberType(US_NUMBER));
    941 
    942     PhoneNumber fixedLineAndMobileNumber = new PhoneNumber().
    943         setCountryCode(54).setNationalNumber(1987654321L);
    944     assertEquals(PhoneNumberUtil.PhoneNumberType.FIXED_LINE_OR_MOBILE,
    945                  phoneUtil.getNumberType(fixedLineAndMobileNumber));
    946   }
    947 
    948   public void testIsSharedCost() {
    949     PhoneNumber gbNumber = new PhoneNumber();
    950     gbNumber.setCountryCode(44).setNationalNumber(8431231234L);
    951     assertEquals(PhoneNumberUtil.PhoneNumberType.SHARED_COST, phoneUtil.getNumberType(gbNumber));
    952   }
    953 
    954   public void testIsVoip() {
    955     PhoneNumber gbNumber = new PhoneNumber();
    956     gbNumber.setCountryCode(44).setNationalNumber(5631231234L);
    957     assertEquals(PhoneNumberUtil.PhoneNumberType.VOIP, phoneUtil.getNumberType(gbNumber));
    958   }
    959 
    960   public void testIsPersonalNumber() {
    961     PhoneNumber gbNumber = new PhoneNumber();
    962     gbNumber.setCountryCode(44).setNationalNumber(7031231234L);
    963     assertEquals(PhoneNumberUtil.PhoneNumberType.PERSONAL_NUMBER,
    964                  phoneUtil.getNumberType(gbNumber));
    965   }
    966 
    967   public void testIsUnknown() {
    968     // Invalid numbers should be of type UNKNOWN.
    969     assertEquals(PhoneNumberUtil.PhoneNumberType.UNKNOWN, phoneUtil.getNumberType(US_LOCAL_NUMBER));
    970   }
    971 
    972   public void testIsValidNumber() {
    973     assertTrue(phoneUtil.isValidNumber(US_NUMBER));
    974     assertTrue(phoneUtil.isValidNumber(IT_NUMBER));
    975     assertTrue(phoneUtil.isValidNumber(GB_MOBILE));
    976     assertTrue(phoneUtil.isValidNumber(INTERNATIONAL_TOLL_FREE));
    977 
    978     PhoneNumber nzNumber = new PhoneNumber().setCountryCode(64).setNationalNumber(21387835L);
    979     assertTrue(phoneUtil.isValidNumber(nzNumber));
    980   }
    981 
    982   public void testIsValidForRegion() {
    983     // This number is valid for the Bahamas, but is not a valid US number.
    984     assertTrue(phoneUtil.isValidNumber(BS_NUMBER));
    985     assertTrue(phoneUtil.isValidNumberForRegion(BS_NUMBER, RegionCode.BS));
    986     assertFalse(phoneUtil.isValidNumberForRegion(BS_NUMBER, RegionCode.US));
    987     PhoneNumber bsInvalidNumber =
    988         new PhoneNumber().setCountryCode(1).setNationalNumber(2421232345L);
    989     // This number is no longer valid.
    990     assertFalse(phoneUtil.isValidNumber(bsInvalidNumber));
    991 
    992     // La Mayotte and Reunion use 'leadingDigits' to differentiate them.
    993     PhoneNumber reNumber = new PhoneNumber();
    994     reNumber.setCountryCode(262).setNationalNumber(262123456L);
    995     assertTrue(phoneUtil.isValidNumber(reNumber));
    996     assertTrue(phoneUtil.isValidNumberForRegion(reNumber, RegionCode.RE));
    997     assertFalse(phoneUtil.isValidNumberForRegion(reNumber, RegionCode.YT));
    998     // Now change the number to be a number for La Mayotte.
    999     reNumber.setNationalNumber(269601234L);
   1000     assertTrue(phoneUtil.isValidNumberForRegion(reNumber, RegionCode.YT));
   1001     assertFalse(phoneUtil.isValidNumberForRegion(reNumber, RegionCode.RE));
   1002     // This number is no longer valid for La Reunion.
   1003     reNumber.setNationalNumber(269123456L);
   1004     assertFalse(phoneUtil.isValidNumberForRegion(reNumber, RegionCode.YT));
   1005     assertFalse(phoneUtil.isValidNumberForRegion(reNumber, RegionCode.RE));
   1006     assertFalse(phoneUtil.isValidNumber(reNumber));
   1007     // However, it should be recognised as from La Mayotte, since it is valid for this region.
   1008     assertEquals(RegionCode.YT, phoneUtil.getRegionCodeForNumber(reNumber));
   1009     // This number is valid in both places.
   1010     reNumber.setNationalNumber(800123456L);
   1011     assertTrue(phoneUtil.isValidNumberForRegion(reNumber, RegionCode.YT));
   1012     assertTrue(phoneUtil.isValidNumberForRegion(reNumber, RegionCode.RE));
   1013     assertTrue(phoneUtil.isValidNumberForRegion(INTERNATIONAL_TOLL_FREE, RegionCode.UN001));
   1014     assertFalse(phoneUtil.isValidNumberForRegion(INTERNATIONAL_TOLL_FREE, RegionCode.US));
   1015     assertFalse(phoneUtil.isValidNumberForRegion(INTERNATIONAL_TOLL_FREE, RegionCode.ZZ));
   1016 
   1017     PhoneNumber invalidNumber = new PhoneNumber();
   1018     // Invalid country calling codes.
   1019     invalidNumber.setCountryCode(3923).setNationalNumber(2366L);
   1020     assertFalse(phoneUtil.isValidNumberForRegion(invalidNumber, RegionCode.ZZ));
   1021     assertFalse(phoneUtil.isValidNumberForRegion(invalidNumber, RegionCode.UN001));
   1022     invalidNumber.setCountryCode(0);
   1023     assertFalse(phoneUtil.isValidNumberForRegion(invalidNumber, RegionCode.UN001));
   1024     assertFalse(phoneUtil.isValidNumberForRegion(invalidNumber, RegionCode.ZZ));
   1025   }
   1026 
   1027   public void testIsNotValidNumber() {
   1028     assertFalse(phoneUtil.isValidNumber(US_LOCAL_NUMBER));
   1029 
   1030     PhoneNumber invalidNumber = new PhoneNumber();
   1031     invalidNumber.setCountryCode(39).setNationalNumber(23661830000L).setItalianLeadingZero(true);
   1032     assertFalse(phoneUtil.isValidNumber(invalidNumber));
   1033 
   1034     invalidNumber.clear();
   1035     invalidNumber.setCountryCode(44).setNationalNumber(791234567L);
   1036     assertFalse(phoneUtil.isValidNumber(invalidNumber));
   1037 
   1038     invalidNumber.clear();
   1039     invalidNumber.setCountryCode(49).setNationalNumber(1234L);
   1040     assertFalse(phoneUtil.isValidNumber(invalidNumber));
   1041 
   1042     invalidNumber.clear();
   1043     invalidNumber.setCountryCode(64).setNationalNumber(3316005L);
   1044     assertFalse(phoneUtil.isValidNumber(invalidNumber));
   1045 
   1046     invalidNumber.clear();
   1047     // Invalid country calling codes.
   1048     invalidNumber.setCountryCode(3923).setNationalNumber(2366L);
   1049     assertFalse(phoneUtil.isValidNumber(invalidNumber));
   1050     invalidNumber.setCountryCode(0);
   1051     assertFalse(phoneUtil.isValidNumber(invalidNumber));
   1052 
   1053     assertFalse(phoneUtil.isValidNumber(INTERNATIONAL_TOLL_FREE_TOO_LONG));
   1054   }
   1055 
   1056   public void testGetRegionCodeForCountryCode() {
   1057     assertEquals(RegionCode.US, phoneUtil.getRegionCodeForCountryCode(1));
   1058     assertEquals(RegionCode.GB, phoneUtil.getRegionCodeForCountryCode(44));
   1059     assertEquals(RegionCode.DE, phoneUtil.getRegionCodeForCountryCode(49));
   1060     assertEquals(RegionCode.UN001, phoneUtil.getRegionCodeForCountryCode(800));
   1061   }
   1062 
   1063   public void testGetRegionCodeForNumber() {
   1064     assertEquals(RegionCode.BS, phoneUtil.getRegionCodeForNumber(BS_NUMBER));
   1065     assertEquals(RegionCode.US, phoneUtil.getRegionCodeForNumber(US_NUMBER));
   1066     assertEquals(RegionCode.GB, phoneUtil.getRegionCodeForNumber(GB_MOBILE));
   1067     assertEquals(RegionCode.UN001, phoneUtil.getRegionCodeForNumber(INTERNATIONAL_TOLL_FREE));
   1068   }
   1069 
   1070   public void testGetCountryCodeForRegion() {
   1071     assertEquals(1, phoneUtil.getCountryCodeForRegion(RegionCode.US));
   1072     assertEquals(64, phoneUtil.getCountryCodeForRegion(RegionCode.NZ));
   1073     assertEquals(0, phoneUtil.getCountryCodeForRegion(null));
   1074     assertEquals(0, phoneUtil.getCountryCodeForRegion(RegionCode.ZZ));
   1075     assertEquals(0, phoneUtil.getCountryCodeForRegion(RegionCode.UN001));
   1076     // CS is already deprecated so the library doesn't support it.
   1077     assertEquals(0, phoneUtil.getCountryCodeForRegion(RegionCode.CS));
   1078   }
   1079 
   1080   public void testGetNationalDiallingPrefixForRegion() {
   1081     assertEquals("1", phoneUtil.getNddPrefixForRegion(RegionCode.US, false));
   1082     // Test non-main country to see it gets the national dialling prefix for the main country with
   1083     // that country calling code.
   1084     assertEquals("1", phoneUtil.getNddPrefixForRegion(RegionCode.BS, false));
   1085     assertEquals("0", phoneUtil.getNddPrefixForRegion(RegionCode.NZ, false));
   1086     // Test case with non digit in the national prefix.
   1087     assertEquals("0~0", phoneUtil.getNddPrefixForRegion(RegionCode.AO, false));
   1088     assertEquals("00", phoneUtil.getNddPrefixForRegion(RegionCode.AO, true));
   1089     // Test cases with invalid regions.
   1090     assertEquals(null, phoneUtil.getNddPrefixForRegion(null, false));
   1091     assertEquals(null, phoneUtil.getNddPrefixForRegion(RegionCode.ZZ, false));
   1092     assertEquals(null, phoneUtil.getNddPrefixForRegion(RegionCode.UN001, false));
   1093     // CS is already deprecated so the library doesn't support it.
   1094     assertEquals(null, phoneUtil.getNddPrefixForRegion(RegionCode.CS, false));
   1095   }
   1096 
   1097   public void testIsNANPACountry() {
   1098     assertTrue(phoneUtil.isNANPACountry(RegionCode.US));
   1099     assertTrue(phoneUtil.isNANPACountry(RegionCode.BS));
   1100     assertFalse(phoneUtil.isNANPACountry(RegionCode.DE));
   1101     assertFalse(phoneUtil.isNANPACountry(RegionCode.ZZ));
   1102     assertFalse(phoneUtil.isNANPACountry(RegionCode.UN001));
   1103     assertFalse(phoneUtil.isNANPACountry(null));
   1104   }
   1105 
   1106   public void testIsPossibleNumber() {
   1107     assertTrue(phoneUtil.isPossibleNumber(US_NUMBER));
   1108     assertTrue(phoneUtil.isPossibleNumber(US_LOCAL_NUMBER));
   1109     assertTrue(phoneUtil.isPossibleNumber(GB_NUMBER));
   1110     assertTrue(phoneUtil.isPossibleNumber(INTERNATIONAL_TOLL_FREE));
   1111 
   1112     assertTrue(phoneUtil.isPossibleNumber("+1 650 253 0000", RegionCode.US));
   1113     assertTrue(phoneUtil.isPossibleNumber("+1 650 GOO OGLE", RegionCode.US));
   1114     assertTrue(phoneUtil.isPossibleNumber("(650) 253-0000", RegionCode.US));
   1115     assertTrue(phoneUtil.isPossibleNumber("253-0000", RegionCode.US));
   1116     assertTrue(phoneUtil.isPossibleNumber("+1 650 253 0000", RegionCode.GB));
   1117     assertTrue(phoneUtil.isPossibleNumber("+44 20 7031 3000", RegionCode.GB));
   1118     assertTrue(phoneUtil.isPossibleNumber("(020) 7031 3000", RegionCode.GB));
   1119     assertTrue(phoneUtil.isPossibleNumber("7031 3000", RegionCode.GB));
   1120     assertTrue(phoneUtil.isPossibleNumber("3331 6005", RegionCode.NZ));
   1121     assertTrue(phoneUtil.isPossibleNumber("+800 1234 5678", RegionCode.UN001));
   1122   }
   1123 
   1124   public void testIsPossibleNumberWithReason() {
   1125     // National numbers for country calling code +1 that are within 7 to 10 digits are possible.
   1126     assertEquals(PhoneNumberUtil.ValidationResult.IS_POSSIBLE,
   1127                  phoneUtil.isPossibleNumberWithReason(US_NUMBER));
   1128 
   1129     assertEquals(PhoneNumberUtil.ValidationResult.IS_POSSIBLE,
   1130                  phoneUtil.isPossibleNumberWithReason(US_LOCAL_NUMBER));
   1131 
   1132     assertEquals(PhoneNumberUtil.ValidationResult.TOO_LONG,
   1133                  phoneUtil.isPossibleNumberWithReason(US_LONG_NUMBER));
   1134 
   1135     PhoneNumber number = new PhoneNumber();
   1136     number.setCountryCode(0).setNationalNumber(2530000L);
   1137     assertEquals(PhoneNumberUtil.ValidationResult.INVALID_COUNTRY_CODE,
   1138                  phoneUtil.isPossibleNumberWithReason(number));
   1139 
   1140     number.clear();
   1141     number.setCountryCode(1).setNationalNumber(253000L);
   1142     assertEquals(PhoneNumberUtil.ValidationResult.TOO_SHORT,
   1143                  phoneUtil.isPossibleNumberWithReason(number));
   1144 
   1145     number.clear();
   1146     number.setCountryCode(65).setNationalNumber(1234567890L);
   1147     assertEquals(PhoneNumberUtil.ValidationResult.IS_POSSIBLE,
   1148                  phoneUtil.isPossibleNumberWithReason(number));
   1149 
   1150     assertEquals(PhoneNumberUtil.ValidationResult.TOO_LONG,
   1151                  phoneUtil.isPossibleNumberWithReason(INTERNATIONAL_TOLL_FREE_TOO_LONG));
   1152 
   1153     // Try with number that we don't have metadata for.
   1154     PhoneNumber adNumber = new PhoneNumber();
   1155     adNumber.setCountryCode(376).setNationalNumber(12345L);
   1156     assertEquals(PhoneNumberUtil.ValidationResult.IS_POSSIBLE,
   1157                  phoneUtil.isPossibleNumberWithReason(adNumber));
   1158     adNumber.setCountryCode(376).setNationalNumber(13L);
   1159     assertEquals(PhoneNumberUtil.ValidationResult.TOO_SHORT,
   1160                  phoneUtil.isPossibleNumberWithReason(adNumber));
   1161     adNumber.setCountryCode(376).setNationalNumber(12345678901234567L);
   1162     assertEquals(PhoneNumberUtil.ValidationResult.TOO_LONG,
   1163                  phoneUtil.isPossibleNumberWithReason(adNumber));
   1164   }
   1165 
   1166   public void testIsNotPossibleNumber() {
   1167     assertFalse(phoneUtil.isPossibleNumber(US_LONG_NUMBER));
   1168     assertFalse(phoneUtil.isPossibleNumber(INTERNATIONAL_TOLL_FREE_TOO_LONG));
   1169 
   1170     PhoneNumber number = new PhoneNumber();
   1171     number.setCountryCode(1).setNationalNumber(253000L);
   1172     assertFalse(phoneUtil.isPossibleNumber(number));
   1173 
   1174     number.clear();
   1175     number.setCountryCode(44).setNationalNumber(300L);
   1176     assertFalse(phoneUtil.isPossibleNumber(number));
   1177     assertFalse(phoneUtil.isPossibleNumber("+1 650 253 00000", RegionCode.US));
   1178     assertFalse(phoneUtil.isPossibleNumber("(650) 253-00000", RegionCode.US));
   1179     assertFalse(phoneUtil.isPossibleNumber("I want a Pizza", RegionCode.US));
   1180     assertFalse(phoneUtil.isPossibleNumber("253-000", RegionCode.US));
   1181     assertFalse(phoneUtil.isPossibleNumber("1 3000", RegionCode.GB));
   1182     assertFalse(phoneUtil.isPossibleNumber("+44 300", RegionCode.GB));
   1183     assertFalse(phoneUtil.isPossibleNumber("+800 1234 5678 9", RegionCode.UN001));
   1184   }
   1185 
   1186   public void testTruncateTooLongNumber() {
   1187     // GB number 080 1234 5678, but entered with 4 extra digits at the end.
   1188     PhoneNumber tooLongNumber = new PhoneNumber();
   1189     tooLongNumber.setCountryCode(44).setNationalNumber(80123456780123L);
   1190     PhoneNumber validNumber = new PhoneNumber();
   1191     validNumber.setCountryCode(44).setNationalNumber(8012345678L);
   1192     assertTrue(phoneUtil.truncateTooLongNumber(tooLongNumber));
   1193     assertEquals(validNumber, tooLongNumber);
   1194 
   1195     // IT number 022 3456 7890, but entered with 3 extra digits at the end.
   1196     tooLongNumber.clear();
   1197     tooLongNumber.setCountryCode(39).setNationalNumber(2234567890123L).setItalianLeadingZero(true);
   1198     validNumber.clear();
   1199     validNumber.setCountryCode(39).setNationalNumber(2234567890L).setItalianLeadingZero(true);
   1200     assertTrue(phoneUtil.truncateTooLongNumber(tooLongNumber));
   1201     assertEquals(validNumber, tooLongNumber);
   1202 
   1203     // US number 650-253-0000, but entered with one additional digit at the end.
   1204     tooLongNumber.clear();
   1205     tooLongNumber.mergeFrom(US_LONG_NUMBER);
   1206     assertTrue(phoneUtil.truncateTooLongNumber(tooLongNumber));
   1207     assertEquals(US_NUMBER, tooLongNumber);
   1208 
   1209     tooLongNumber.clear();
   1210     tooLongNumber.mergeFrom(INTERNATIONAL_TOLL_FREE_TOO_LONG);
   1211     assertTrue(phoneUtil.truncateTooLongNumber(tooLongNumber));
   1212     assertEquals(INTERNATIONAL_TOLL_FREE, tooLongNumber);
   1213 
   1214     // Tests what happens when a valid number is passed in.
   1215     PhoneNumber validNumberCopy = new PhoneNumber().mergeFrom(validNumber);
   1216     assertTrue(phoneUtil.truncateTooLongNumber(validNumber));
   1217     // Tests the number is not modified.
   1218     assertEquals(validNumberCopy, validNumber);
   1219 
   1220     // Tests what happens when a number with invalid prefix is passed in.
   1221     PhoneNumber numberWithInvalidPrefix = new PhoneNumber();
   1222     // The test metadata says US numbers cannot have prefix 240.
   1223     numberWithInvalidPrefix.setCountryCode(1).setNationalNumber(2401234567L);
   1224     PhoneNumber invalidNumberCopy = new PhoneNumber().mergeFrom(numberWithInvalidPrefix);
   1225     assertFalse(phoneUtil.truncateTooLongNumber(numberWithInvalidPrefix));
   1226     // Tests the number is not modified.
   1227     assertEquals(invalidNumberCopy, numberWithInvalidPrefix);
   1228 
   1229     // Tests what happens when a too short number is passed in.
   1230     PhoneNumber tooShortNumber = new PhoneNumber().setCountryCode(1).setNationalNumber(1234L);
   1231     PhoneNumber tooShortNumberCopy = new PhoneNumber().mergeFrom(tooShortNumber);
   1232     assertFalse(phoneUtil.truncateTooLongNumber(tooShortNumber));
   1233     // Tests the number is not modified.
   1234     assertEquals(tooShortNumberCopy, tooShortNumber);
   1235   }
   1236 
   1237   public void testIsViablePhoneNumber() {
   1238     // Only one or two digits before strange non-possible punctuation.
   1239     assertFalse(PhoneNumberUtil.isViablePhoneNumber("12. March"));
   1240     assertFalse(PhoneNumberUtil.isViablePhoneNumber("1+1+1"));
   1241     assertFalse(PhoneNumberUtil.isViablePhoneNumber("80+0"));
   1242     assertFalse(PhoneNumberUtil.isViablePhoneNumber("00"));
   1243     // Three digits is viable.
   1244     assertTrue(PhoneNumberUtil.isViablePhoneNumber("111"));
   1245     // Alpha numbers.
   1246     assertTrue(PhoneNumberUtil.isViablePhoneNumber("0800-4-pizza"));
   1247     assertTrue(PhoneNumberUtil.isViablePhoneNumber("0800-4-PIZZA"));
   1248   }
   1249 
   1250   public void testIsViablePhoneNumberNonAscii() {
   1251     // Only one or two digits before possible punctuation followed by more digits.
   1252     assertTrue(PhoneNumberUtil.isViablePhoneNumber("1\u300034"));
   1253     assertFalse(PhoneNumberUtil.isViablePhoneNumber("1\u30003+4"));
   1254     // Unicode variants of possible starting character and other allowed punctuation/digits.
   1255     assertTrue(PhoneNumberUtil.isViablePhoneNumber("\uFF081\uFF09\u30003456789"));
   1256     // Testing a leading + is okay.
   1257     assertTrue(PhoneNumberUtil.isViablePhoneNumber("+1\uFF09\u30003456789"));
   1258   }
   1259 
   1260   public void testExtractPossibleNumber() {
   1261     // Removes preceding funky punctuation and letters but leaves the rest untouched.
   1262     assertEquals("0800-345-600", PhoneNumberUtil.extractPossibleNumber("Tel:0800-345-600"));
   1263     assertEquals("0800 FOR PIZZA", PhoneNumberUtil.extractPossibleNumber("Tel:0800 FOR PIZZA"));
   1264     // Should not remove plus sign
   1265     assertEquals("+800-345-600", PhoneNumberUtil.extractPossibleNumber("Tel:+800-345-600"));
   1266     // Should recognise wide digits as possible start values.
   1267     assertEquals("\uFF10\uFF12\uFF13",
   1268                  PhoneNumberUtil.extractPossibleNumber("\uFF10\uFF12\uFF13"));
   1269     // Dashes are not possible start values and should be removed.
   1270     assertEquals("\uFF11\uFF12\uFF13",
   1271                  PhoneNumberUtil.extractPossibleNumber("Num-\uFF11\uFF12\uFF13"));
   1272     // If not possible number present, return empty string.
   1273     assertEquals("", PhoneNumberUtil.extractPossibleNumber("Num-...."));
   1274     // Leading brackets are stripped - these are not used when parsing.
   1275     assertEquals("650) 253-0000", PhoneNumberUtil.extractPossibleNumber("(650) 253-0000"));
   1276 
   1277     // Trailing non-alpha-numeric characters should be removed.
   1278     assertEquals("650) 253-0000", PhoneNumberUtil.extractPossibleNumber("(650) 253-0000..- .."));
   1279     assertEquals("650) 253-0000", PhoneNumberUtil.extractPossibleNumber("(650) 253-0000."));
   1280     // This case has a trailing RTL char.
   1281     assertEquals("650) 253-0000", PhoneNumberUtil.extractPossibleNumber("(650) 253-0000\u200F"));
   1282   }
   1283 
   1284   public void testMaybeStripNationalPrefix() {
   1285     PhoneMetadata metadata = new PhoneMetadata();
   1286     metadata.setNationalPrefixForParsing("34");
   1287     metadata.setGeneralDesc(new PhoneNumberDesc().setNationalNumberPattern("\\d{4,8}"));
   1288     StringBuilder numberToStrip = new StringBuilder("34356778");
   1289     String strippedNumber = "356778";
   1290     assertTrue(phoneUtil.maybeStripNationalPrefixAndCarrierCode(numberToStrip, metadata, null));
   1291     assertEquals("Should have had national prefix stripped.",
   1292                  strippedNumber, numberToStrip.toString());
   1293     // Retry stripping - now the number should not start with the national prefix, so no more
   1294     // stripping should occur.
   1295     assertFalse(phoneUtil.maybeStripNationalPrefixAndCarrierCode(numberToStrip, metadata, null));
   1296     assertEquals("Should have had no change - no national prefix present.",
   1297                  strippedNumber, numberToStrip.toString());
   1298     // Some countries have no national prefix. Repeat test with none specified.
   1299     metadata.setNationalPrefixForParsing("");
   1300     assertFalse(phoneUtil.maybeStripNationalPrefixAndCarrierCode(numberToStrip, metadata, null));
   1301     assertEquals("Should not strip anything with empty national prefix.",
   1302                  strippedNumber, numberToStrip.toString());
   1303     // If the resultant number doesn't match the national rule, it shouldn't be stripped.
   1304     metadata.setNationalPrefixForParsing("3");
   1305     numberToStrip = new StringBuilder("3123");
   1306     strippedNumber = "3123";
   1307     assertFalse(phoneUtil.maybeStripNationalPrefixAndCarrierCode(numberToStrip, metadata, null));
   1308     assertEquals("Should have had no change - after stripping, it wouldn't have matched " +
   1309                  "the national rule.",
   1310                  strippedNumber, numberToStrip.toString());
   1311     // Test extracting carrier selection code.
   1312     metadata.setNationalPrefixForParsing("0(81)?");
   1313     numberToStrip = new StringBuilder("08122123456");
   1314     strippedNumber = "22123456";
   1315     StringBuilder carrierCode = new StringBuilder();
   1316     assertTrue(phoneUtil.maybeStripNationalPrefixAndCarrierCode(
   1317         numberToStrip, metadata, carrierCode));
   1318     assertEquals("81", carrierCode.toString());
   1319     assertEquals("Should have had national prefix and carrier code stripped.",
   1320                  strippedNumber, numberToStrip.toString());
   1321     // If there was a transform rule, check it was applied.
   1322     metadata.setNationalPrefixTransformRule("5$15");
   1323     // Note that a capturing group is present here.
   1324     metadata.setNationalPrefixForParsing("0(\\d{2})");
   1325     numberToStrip = new StringBuilder("031123");
   1326     String transformedNumber = "5315123";
   1327     assertTrue(phoneUtil.maybeStripNationalPrefixAndCarrierCode(numberToStrip, metadata, null));
   1328     assertEquals("Should transform the 031 to a 5315.",
   1329                  transformedNumber, numberToStrip.toString());
   1330   }
   1331 
   1332   public void testMaybeStripInternationalPrefix() {
   1333     String internationalPrefix = "00[39]";
   1334     StringBuilder numberToStrip = new StringBuilder("0034567700-3898003");
   1335     // Note the dash is removed as part of the normalization.
   1336     StringBuilder strippedNumber = new StringBuilder("45677003898003");
   1337     assertEquals(CountryCodeSource.FROM_NUMBER_WITH_IDD,
   1338                  phoneUtil.maybeStripInternationalPrefixAndNormalize(numberToStrip,
   1339                                                                      internationalPrefix));
   1340     assertEquals("The number supplied was not stripped of its international prefix.",
   1341                  strippedNumber.toString(), numberToStrip.toString());
   1342     // Now the number no longer starts with an IDD prefix, so it should now report
   1343     // FROM_DEFAULT_COUNTRY.
   1344     assertEquals(CountryCodeSource.FROM_DEFAULT_COUNTRY,
   1345                  phoneUtil.maybeStripInternationalPrefixAndNormalize(numberToStrip,
   1346                                                                      internationalPrefix));
   1347 
   1348     numberToStrip = new StringBuilder("00945677003898003");
   1349     assertEquals(CountryCodeSource.FROM_NUMBER_WITH_IDD,
   1350                  phoneUtil.maybeStripInternationalPrefixAndNormalize(numberToStrip,
   1351                                                                      internationalPrefix));
   1352     assertEquals("The number supplied was not stripped of its international prefix.",
   1353                  strippedNumber.toString(), numberToStrip.toString());
   1354     // Test it works when the international prefix is broken up by spaces.
   1355     numberToStrip = new StringBuilder("00 9 45677003898003");
   1356     assertEquals(CountryCodeSource.FROM_NUMBER_WITH_IDD,
   1357                  phoneUtil.maybeStripInternationalPrefixAndNormalize(numberToStrip,
   1358                                                                      internationalPrefix));
   1359     assertEquals("The number supplied was not stripped of its international prefix.",
   1360                  strippedNumber.toString(), numberToStrip.toString());
   1361     // Now the number no longer starts with an IDD prefix, so it should now report
   1362     // FROM_DEFAULT_COUNTRY.
   1363     assertEquals(CountryCodeSource.FROM_DEFAULT_COUNTRY,
   1364                  phoneUtil.maybeStripInternationalPrefixAndNormalize(numberToStrip,
   1365                                                                      internationalPrefix));
   1366 
   1367     // Test the + symbol is also recognised and stripped.
   1368     numberToStrip = new StringBuilder("+45677003898003");
   1369     strippedNumber = new StringBuilder("45677003898003");
   1370     assertEquals(CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN,
   1371                  phoneUtil.maybeStripInternationalPrefixAndNormalize(numberToStrip,
   1372                                                                      internationalPrefix));
   1373     assertEquals("The number supplied was not stripped of the plus symbol.",
   1374                  strippedNumber.toString(), numberToStrip.toString());
   1375 
   1376     // If the number afterwards is a zero, we should not strip this - no country calling code begins
   1377     // with 0.
   1378     numberToStrip = new StringBuilder("0090112-3123");
   1379     strippedNumber = new StringBuilder("00901123123");
   1380     assertEquals(CountryCodeSource.FROM_DEFAULT_COUNTRY,
   1381                  phoneUtil.maybeStripInternationalPrefixAndNormalize(numberToStrip,
   1382                                                                      internationalPrefix));
   1383     assertEquals("The number supplied had a 0 after the match so shouldn't be stripped.",
   1384                  strippedNumber.toString(), numberToStrip.toString());
   1385     // Here the 0 is separated by a space from the IDD.
   1386     numberToStrip = new StringBuilder("009 0-112-3123");
   1387     assertEquals(CountryCodeSource.FROM_DEFAULT_COUNTRY,
   1388                  phoneUtil.maybeStripInternationalPrefixAndNormalize(numberToStrip,
   1389                                                                      internationalPrefix));
   1390   }
   1391 
   1392   public void testMaybeExtractCountryCode() {
   1393     PhoneNumber number = new PhoneNumber();
   1394     PhoneMetadata metadata = phoneUtil.getMetadataForRegion(RegionCode.US);
   1395     // Note that for the US, the IDD is 011.
   1396     try {
   1397       String phoneNumber = "011112-3456789";
   1398       String strippedNumber = "123456789";
   1399       int countryCallingCode = 1;
   1400       StringBuilder numberToFill = new StringBuilder();
   1401       assertEquals("Did not extract country calling code " + countryCallingCode + " correctly.",
   1402                    countryCallingCode,
   1403                    phoneUtil.maybeExtractCountryCode(phoneNumber, metadata, numberToFill, true,
   1404                                                      number));
   1405       assertEquals("Did not figure out CountryCodeSource correctly",
   1406                    CountryCodeSource.FROM_NUMBER_WITH_IDD, number.getCountryCodeSource());
   1407       // Should strip and normalize national significant number.
   1408       assertEquals("Did not strip off the country calling code correctly.",
   1409                    strippedNumber,
   1410                    numberToFill.toString());
   1411     } catch (NumberParseException e) {
   1412       fail("Should not have thrown an exception: " + e.toString());
   1413     }
   1414     number.clear();
   1415     try {
   1416       String phoneNumber = "+6423456789";
   1417       int countryCallingCode = 64;
   1418       StringBuilder numberToFill = new StringBuilder();
   1419       assertEquals("Did not extract country calling code " + countryCallingCode + " correctly.",
   1420                    countryCallingCode,
   1421                    phoneUtil.maybeExtractCountryCode(phoneNumber, metadata, numberToFill, true,
   1422                                                      number));
   1423       assertEquals("Did not figure out CountryCodeSource correctly",
   1424                    CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN, number.getCountryCodeSource());
   1425     } catch (NumberParseException e) {
   1426       fail("Should not have thrown an exception: " + e.toString());
   1427     }
   1428     number.clear();
   1429     try {
   1430       String phoneNumber = "+80012345678";
   1431       int countryCallingCode = 800;
   1432       StringBuilder numberToFill = new StringBuilder();
   1433       assertEquals("Did not extract country calling code " + countryCallingCode + " correctly.",
   1434                    countryCallingCode,
   1435                    phoneUtil.maybeExtractCountryCode(phoneNumber, metadata, numberToFill, true,
   1436                                                      number));
   1437       assertEquals("Did not figure out CountryCodeSource correctly",
   1438                    CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN, number.getCountryCodeSource());
   1439     } catch (NumberParseException e) {
   1440       fail("Should not have thrown an exception: " + e.toString());
   1441     }
   1442     number.clear();
   1443     try {
   1444       String phoneNumber = "2345-6789";
   1445       StringBuilder numberToFill = new StringBuilder();
   1446       assertEquals(
   1447           "Should not have extracted a country calling code - no international prefix present.",
   1448           0,
   1449           phoneUtil.maybeExtractCountryCode(phoneNumber, metadata, numberToFill, true, number));
   1450       assertEquals("Did not figure out CountryCodeSource correctly",
   1451                    CountryCodeSource.FROM_DEFAULT_COUNTRY, number.getCountryCodeSource());
   1452     } catch (NumberParseException e) {
   1453       fail("Should not have thrown an exception: " + e.toString());
   1454     }
   1455     number.clear();
   1456     try {
   1457       String phoneNumber = "0119991123456789";
   1458       StringBuilder numberToFill = new StringBuilder();
   1459       phoneUtil.maybeExtractCountryCode(phoneNumber, metadata, numberToFill, true, number);
   1460       fail("Should have thrown an exception, no valid country calling code present.");
   1461     } catch (NumberParseException e) {
   1462       // Expected.
   1463       assertEquals("Wrong error type stored in exception.",
   1464                    NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
   1465                    e.getErrorType());
   1466     }
   1467     number.clear();
   1468     try {
   1469       String phoneNumber = "(1 610) 619 4466";
   1470       int countryCallingCode = 1;
   1471       StringBuilder numberToFill = new StringBuilder();
   1472       assertEquals("Should have extracted the country calling code of the region passed in",
   1473                    countryCallingCode,
   1474                    phoneUtil.maybeExtractCountryCode(phoneNumber, metadata, numberToFill, true,
   1475                                                      number));
   1476       assertEquals("Did not figure out CountryCodeSource correctly",
   1477                    CountryCodeSource.FROM_NUMBER_WITHOUT_PLUS_SIGN,
   1478                    number.getCountryCodeSource());
   1479     } catch (NumberParseException e) {
   1480       fail("Should not have thrown an exception: " + e.toString());
   1481     }
   1482     number.clear();
   1483     try {
   1484       String phoneNumber = "(1 610) 619 4466";
   1485       int countryCallingCode = 1;
   1486       StringBuilder numberToFill = new StringBuilder();
   1487       assertEquals("Should have extracted the country calling code of the region passed in",
   1488                    countryCallingCode,
   1489                    phoneUtil.maybeExtractCountryCode(phoneNumber, metadata, numberToFill, false,
   1490                                                      number));
   1491       assertFalse("Should not contain CountryCodeSource.", number.hasCountryCodeSource());
   1492     } catch (NumberParseException e) {
   1493       fail("Should not have thrown an exception: " + e.toString());
   1494     }
   1495     number.clear();
   1496     try {
   1497       String phoneNumber = "(1 610) 619 446";
   1498       StringBuilder numberToFill = new StringBuilder();
   1499       assertEquals("Should not have extracted a country calling code - invalid number after " +
   1500                    "extraction of uncertain country calling code.",
   1501                    0,
   1502                    phoneUtil.maybeExtractCountryCode(phoneNumber, metadata, numberToFill, false,
   1503                                                      number));
   1504       assertFalse("Should not contain CountryCodeSource.", number.hasCountryCodeSource());
   1505     } catch (NumberParseException e) {
   1506       fail("Should not have thrown an exception: " + e.toString());
   1507     }
   1508     number.clear();
   1509     try {
   1510       String phoneNumber = "(1 610) 619";
   1511       StringBuilder numberToFill = new StringBuilder();
   1512       assertEquals("Should not have extracted a country calling code - too short number both " +
   1513                    "before and after extraction of uncertain country calling code.",
   1514                    0,
   1515                    phoneUtil.maybeExtractCountryCode(phoneNumber, metadata, numberToFill, true,
   1516                                                      number));
   1517       assertEquals("Did not figure out CountryCodeSource correctly",
   1518                    CountryCodeSource.FROM_DEFAULT_COUNTRY, number.getCountryCodeSource());
   1519     } catch (NumberParseException e) {
   1520       fail("Should not have thrown an exception: " + e.toString());
   1521     }
   1522   }
   1523 
   1524   public void testParseNationalNumber() throws Exception {
   1525     // National prefix attached.
   1526     assertEquals(NZ_NUMBER, phoneUtil.parse("033316005", RegionCode.NZ));
   1527     assertEquals(NZ_NUMBER, phoneUtil.parse("33316005", RegionCode.NZ));
   1528     // National prefix attached and some formatting present.
   1529     assertEquals(NZ_NUMBER, phoneUtil.parse("03-331 6005", RegionCode.NZ));
   1530     assertEquals(NZ_NUMBER, phoneUtil.parse("03 331 6005", RegionCode.NZ));
   1531 
   1532     // Testing international prefixes.
   1533     // Should strip country calling code.
   1534     assertEquals(NZ_NUMBER, phoneUtil.parse("0064 3 331 6005", RegionCode.NZ));
   1535     // Try again, but this time we have an international number with Region Code US. It should
   1536     // recognise the country calling code and parse accordingly.
   1537     assertEquals(NZ_NUMBER, phoneUtil.parse("01164 3 331 6005", RegionCode.US));
   1538     assertEquals(NZ_NUMBER, phoneUtil.parse("+64 3 331 6005", RegionCode.US));
   1539     // We should ignore the leading plus here, since it is not followed by a valid country code but
   1540     // instead is followed by the IDD for the US.
   1541     assertEquals(NZ_NUMBER, phoneUtil.parse("+01164 3 331 6005", RegionCode.US));
   1542     assertEquals(NZ_NUMBER, phoneUtil.parse("+0064 3 331 6005", RegionCode.NZ));
   1543     assertEquals(NZ_NUMBER, phoneUtil.parse("+ 00 64 3 331 6005", RegionCode.NZ));
   1544 
   1545     PhoneNumber nzNumber = new PhoneNumber();
   1546     nzNumber.setCountryCode(64).setNationalNumber(64123456L);
   1547     assertEquals(nzNumber, phoneUtil.parse("64(0)64123456", RegionCode.NZ));
   1548     // Check that using a "/" is fine in a phone number.
   1549     assertEquals(DE_NUMBER, phoneUtil.parse("301/23456", RegionCode.DE));
   1550 
   1551     PhoneNumber usNumber = new PhoneNumber();
   1552     // Check it doesn't use the '1' as a country calling code when parsing if the phone number was
   1553     // already possible.
   1554     usNumber.setCountryCode(1).setNationalNumber(1234567890L);
   1555     assertEquals(usNumber, phoneUtil.parse("123-456-7890", RegionCode.US));
   1556 
   1557     // Test star numbers. Although this is not strictly valid, we would like to make sure we can
   1558     // parse the output we produce when formatting the number.
   1559     assertEquals(JP_STAR_NUMBER, phoneUtil.parse("+81 *2345", RegionCode.JP));
   1560   }
   1561 
   1562   public void testParseNumberWithAlphaCharacters() throws Exception {
   1563     // Test case with alpha characters.
   1564     PhoneNumber tollfreeNumber = new PhoneNumber();
   1565     tollfreeNumber.setCountryCode(64).setNationalNumber(800332005L);
   1566     assertEquals(tollfreeNumber, phoneUtil.parse("0800 DDA 005", RegionCode.NZ));
   1567     PhoneNumber premiumNumber = new PhoneNumber();
   1568     premiumNumber.setCountryCode(64).setNationalNumber(9003326005L);
   1569     assertEquals(premiumNumber, phoneUtil.parse("0900 DDA 6005", RegionCode.NZ));
   1570     // Not enough alpha characters for them to be considered intentional, so they are stripped.
   1571     assertEquals(premiumNumber, phoneUtil.parse("0900 332 6005a", RegionCode.NZ));
   1572     assertEquals(premiumNumber, phoneUtil.parse("0900 332 600a5", RegionCode.NZ));
   1573     assertEquals(premiumNumber, phoneUtil.parse("0900 332 600A5", RegionCode.NZ));
   1574     assertEquals(premiumNumber, phoneUtil.parse("0900 a332 600A5", RegionCode.NZ));
   1575   }
   1576 
   1577   public void testParseMaliciousInput() throws Exception {
   1578     // Lots of leading + signs before the possible number.
   1579     StringBuilder maliciousNumber = new StringBuilder(6000);
   1580     for (int i = 0; i < 6000; i++) {
   1581       maliciousNumber.append('+');
   1582     }
   1583     maliciousNumber.append("12222-33-244 extensioB 343+");
   1584     try {
   1585       phoneUtil.parse(maliciousNumber.toString(), RegionCode.US);
   1586       fail("This should not parse without throwing an exception " + maliciousNumber);
   1587     } catch (NumberParseException e) {
   1588       // Expected this exception.
   1589       assertEquals("Wrong error type stored in exception.",
   1590                    NumberParseException.ErrorType.TOO_LONG,
   1591                    e.getErrorType());
   1592     }
   1593     StringBuilder maliciousNumberWithAlmostExt = new StringBuilder(6000);
   1594     for (int i = 0; i < 350; i++) {
   1595       maliciousNumberWithAlmostExt.append("200");
   1596     }
   1597     maliciousNumberWithAlmostExt.append(" extensiOB 345");
   1598     try {
   1599       phoneUtil.parse(maliciousNumberWithAlmostExt.toString(), RegionCode.US);
   1600       fail("This should not parse without throwing an exception " + maliciousNumberWithAlmostExt);
   1601     } catch (NumberParseException e) {
   1602       // Expected this exception.
   1603       assertEquals("Wrong error type stored in exception.",
   1604                    NumberParseException.ErrorType.TOO_LONG,
   1605                    e.getErrorType());
   1606     }
   1607   }
   1608 
   1609   public void testParseWithInternationalPrefixes() throws Exception {
   1610     assertEquals(US_NUMBER, phoneUtil.parse("+1 (650) 253-0000", RegionCode.NZ));
   1611     assertEquals(INTERNATIONAL_TOLL_FREE, phoneUtil.parse("011 800 1234 5678", RegionCode.US));
   1612     assertEquals(US_NUMBER, phoneUtil.parse("1-650-253-0000", RegionCode.US));
   1613     // Calling the US number from Singapore by using different service providers
   1614     // 1st test: calling using SingTel IDD service (IDD is 001)
   1615     assertEquals(US_NUMBER, phoneUtil.parse("0011-650-253-0000", RegionCode.SG));
   1616     // 2nd test: calling using StarHub IDD service (IDD is 008)
   1617     assertEquals(US_NUMBER, phoneUtil.parse("0081-650-253-0000", RegionCode.SG));
   1618     // 3rd test: calling using SingTel V019 service (IDD is 019)
   1619     assertEquals(US_NUMBER, phoneUtil.parse("0191-650-253-0000", RegionCode.SG));
   1620     // Calling the US number from Poland
   1621     assertEquals(US_NUMBER, phoneUtil.parse("0~01-650-253-0000", RegionCode.PL));
   1622     // Using "++" at the start.
   1623     assertEquals(US_NUMBER, phoneUtil.parse("++1 (650) 253-0000", RegionCode.PL));
   1624   }
   1625 
   1626   public void testParseNonAscii() throws Exception {
   1627     // Using a full-width plus sign.
   1628     assertEquals(US_NUMBER, phoneUtil.parse("\uFF0B1 (650) 253-0000", RegionCode.SG));
   1629     // The whole number, including punctuation, is here represented in full-width form.
   1630     assertEquals(US_NUMBER, phoneUtil.parse("\uFF0B\uFF11\u3000\uFF08\uFF16\uFF15\uFF10\uFF09" +
   1631                                             "\u3000\uFF12\uFF15\uFF13\uFF0D\uFF10\uFF10\uFF10" +
   1632                                             "\uFF10",
   1633                                             RegionCode.SG));
   1634     // Using U+30FC dash instead.
   1635     assertEquals(US_NUMBER, phoneUtil.parse("\uFF0B\uFF11\u3000\uFF08\uFF16\uFF15\uFF10\uFF09" +
   1636                                             "\u3000\uFF12\uFF15\uFF13\u30FC\uFF10\uFF10\uFF10" +
   1637                                             "\uFF10",
   1638                                             RegionCode.SG));
   1639 
   1640     // Using a very strange decimal digit range (Mongolian digits).
   1641     assertEquals(US_NUMBER, phoneUtil.parse("\u1811 \u1816\u1815\u1810 " +
   1642                                             "\u1812\u1815\u1813 \u1810\u1810\u1810\u1810",
   1643                                             RegionCode.US));
   1644   }
   1645 
   1646   public void testParseWithLeadingZero() throws Exception {
   1647     assertEquals(IT_NUMBER, phoneUtil.parse("+39 02-36618 300", RegionCode.NZ));
   1648     assertEquals(IT_NUMBER, phoneUtil.parse("02-36618 300", RegionCode.IT));
   1649 
   1650     assertEquals(IT_MOBILE, phoneUtil.parse("345 678 901", RegionCode.IT));
   1651   }
   1652 
   1653   public void testParseNationalNumberArgentina() throws Exception {
   1654     // Test parsing mobile numbers of Argentina.
   1655     PhoneNumber arNumber = new PhoneNumber();
   1656     arNumber.setCountryCode(54).setNationalNumber(93435551212L);
   1657     assertEquals(arNumber, phoneUtil.parse("+54 9 343 555 1212", RegionCode.AR));
   1658     assertEquals(arNumber, phoneUtil.parse("0343 15 555 1212", RegionCode.AR));
   1659 
   1660     arNumber.clear();
   1661     arNumber.setCountryCode(54).setNationalNumber(93715654320L);
   1662     assertEquals(arNumber, phoneUtil.parse("+54 9 3715 65 4320", RegionCode.AR));
   1663     assertEquals(arNumber, phoneUtil.parse("03715 15 65 4320", RegionCode.AR));
   1664     assertEquals(AR_MOBILE, phoneUtil.parse("911 876 54321", RegionCode.AR));
   1665 
   1666     // Test parsing fixed-line numbers of Argentina.
   1667     assertEquals(AR_NUMBER, phoneUtil.parse("+54 11 8765 4321", RegionCode.AR));
   1668     assertEquals(AR_NUMBER, phoneUtil.parse("011 8765 4321", RegionCode.AR));
   1669 
   1670     arNumber.clear();
   1671     arNumber.setCountryCode(54).setNationalNumber(3715654321L);
   1672     assertEquals(arNumber, phoneUtil.parse("+54 3715 65 4321", RegionCode.AR));
   1673     assertEquals(arNumber, phoneUtil.parse("03715 65 4321", RegionCode.AR));
   1674 
   1675     arNumber.clear();
   1676     arNumber.setCountryCode(54).setNationalNumber(2312340000L);
   1677     assertEquals(arNumber, phoneUtil.parse("+54 23 1234 0000", RegionCode.AR));
   1678     assertEquals(arNumber, phoneUtil.parse("023 1234 0000", RegionCode.AR));
   1679   }
   1680 
   1681   public void testParseWithXInNumber() throws Exception {
   1682     // Test that having an 'x' in the phone number at the start is ok and that it just gets removed.
   1683     assertEquals(AR_NUMBER, phoneUtil.parse("01187654321", RegionCode.AR));
   1684     assertEquals(AR_NUMBER, phoneUtil.parse("(0) 1187654321", RegionCode.AR));
   1685     assertEquals(AR_NUMBER, phoneUtil.parse("0 1187654321", RegionCode.AR));
   1686     assertEquals(AR_NUMBER, phoneUtil.parse("(0xx) 1187654321", RegionCode.AR));
   1687     PhoneNumber arFromUs = new PhoneNumber();
   1688     arFromUs.setCountryCode(54).setNationalNumber(81429712L);
   1689     // This test is intentionally constructed such that the number of digit after xx is larger than
   1690     // 7, so that the number won't be mistakenly treated as an extension, as we allow extensions up
   1691     // to 7 digits. This assumption is okay for now as all the countries where a carrier selection
   1692     // code is written in the form of xx have a national significant number of length larger than 7.
   1693     assertEquals(arFromUs, phoneUtil.parse("011xx5481429712", RegionCode.US));
   1694   }
   1695 
   1696   public void testParseNumbersMexico() throws Exception {
   1697     // Test parsing fixed-line numbers of Mexico.
   1698     PhoneNumber mxNumber = new PhoneNumber();
   1699     mxNumber.setCountryCode(52).setNationalNumber(4499780001L);
   1700     assertEquals(mxNumber, phoneUtil.parse("+52 (449)978-0001", RegionCode.MX));
   1701     assertEquals(mxNumber, phoneUtil.parse("01 (449)978-0001", RegionCode.MX));
   1702     assertEquals(mxNumber, phoneUtil.parse("(449)978-0001", RegionCode.MX));
   1703 
   1704     // Test parsing mobile numbers of Mexico.
   1705     mxNumber.clear();
   1706     mxNumber.setCountryCode(52).setNationalNumber(13312345678L);
   1707     assertEquals(mxNumber, phoneUtil.parse("+52 1 33 1234-5678", RegionCode.MX));
   1708     assertEquals(mxNumber, phoneUtil.parse("044 (33) 1234-5678", RegionCode.MX));
   1709     assertEquals(mxNumber, phoneUtil.parse("045 33 1234-5678", RegionCode.MX));
   1710   }
   1711 
   1712   public void testFailedParseOnInvalidNumbers() {
   1713     try {
   1714       String sentencePhoneNumber = "This is not a phone number";
   1715       phoneUtil.parse(sentencePhoneNumber, RegionCode.NZ);
   1716       fail("This should not parse without throwing an exception " + sentencePhoneNumber);
   1717     } catch (NumberParseException e) {
   1718       // Expected this exception.
   1719       assertEquals("Wrong error type stored in exception.",
   1720                    NumberParseException.ErrorType.NOT_A_NUMBER,
   1721                    e.getErrorType());
   1722     }
   1723     try {
   1724       String tooLongPhoneNumber = "01495 72553301873 810104";
   1725       phoneUtil.parse(tooLongPhoneNumber, RegionCode.GB);
   1726       fail("This should not parse without throwing an exception " + tooLongPhoneNumber);
   1727     } catch (NumberParseException e) {
   1728       // Expected this exception.
   1729       assertEquals("Wrong error type stored in exception.",
   1730                    NumberParseException.ErrorType.TOO_LONG,
   1731                    e.getErrorType());
   1732     }
   1733     try {
   1734       String plusMinusPhoneNumber = "+---";
   1735       phoneUtil.parse(plusMinusPhoneNumber, RegionCode.DE);
   1736       fail("This should not parse without throwing an exception " + plusMinusPhoneNumber);
   1737     } catch (NumberParseException e) {
   1738       // Expected this exception.
   1739       assertEquals("Wrong error type stored in exception.",
   1740                    NumberParseException.ErrorType.NOT_A_NUMBER,
   1741                    e.getErrorType());
   1742     }
   1743     try {
   1744       String plusStar = "+***";
   1745       phoneUtil.parse(plusStar, RegionCode.DE);
   1746       fail("This should not parse without throwing an exception " + plusStar);
   1747     } catch (NumberParseException e) {
   1748       // Expected this exception.
   1749       assertEquals("Wrong error type stored in exception.",
   1750                    NumberParseException.ErrorType.NOT_A_NUMBER,
   1751                    e.getErrorType());
   1752     }
   1753     try {
   1754       String plusStarPhoneNumber = "+*******91";
   1755       phoneUtil.parse(plusStarPhoneNumber, RegionCode.DE);
   1756       fail("This should not parse without throwing an exception " + plusStarPhoneNumber);
   1757     } catch (NumberParseException e) {
   1758       // Expected this exception.
   1759       assertEquals("Wrong error type stored in exception.",
   1760                    NumberParseException.ErrorType.NOT_A_NUMBER,
   1761                    e.getErrorType());
   1762     }
   1763     try {
   1764       String tooShortPhoneNumber = "+49 0";
   1765       phoneUtil.parse(tooShortPhoneNumber, RegionCode.DE);
   1766       fail("This should not parse without throwing an exception " + tooShortPhoneNumber);
   1767     } catch (NumberParseException e) {
   1768       // Expected this exception.
   1769       assertEquals("Wrong error type stored in exception.",
   1770                    NumberParseException.ErrorType.TOO_SHORT_NSN,
   1771                    e.getErrorType());
   1772     }
   1773     try {
   1774       String invalidCountryCode = "+210 3456 56789";
   1775       phoneUtil.parse(invalidCountryCode, RegionCode.NZ);
   1776       fail("This is not a recognised region code: should fail: " + invalidCountryCode);
   1777     } catch (NumberParseException e) {
   1778       // Expected this exception.
   1779       assertEquals("Wrong error type stored in exception.",
   1780                    NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
   1781                    e.getErrorType());
   1782     }
   1783     try {
   1784       String plusAndIddAndInvalidCountryCode = "+ 00 210 3 331 6005";
   1785       phoneUtil.parse(plusAndIddAndInvalidCountryCode, RegionCode.NZ);
   1786       fail("This should not parse without throwing an exception.");
   1787     } catch (NumberParseException e) {
   1788       // Expected this exception. 00 is a correct IDD, but 210 is not a valid country code.
   1789       assertEquals("Wrong error type stored in exception.",
   1790                    NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
   1791                    e.getErrorType());
   1792     }
   1793     try {
   1794       String someNumber = "123 456 7890";
   1795       phoneUtil.parse(someNumber, RegionCode.ZZ);
   1796       fail("'Unknown' region code not allowed: should fail.");
   1797     } catch (NumberParseException e) {
   1798       // Expected this exception.
   1799       assertEquals("Wrong error type stored in exception.",
   1800                    NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
   1801                    e.getErrorType());
   1802     }
   1803     try {
   1804       String someNumber = "123 456 7890";
   1805       phoneUtil.parse(someNumber, RegionCode.CS);
   1806       fail("Deprecated region code not allowed: should fail.");
   1807     } catch (NumberParseException e) {
   1808       // Expected this exception.
   1809       assertEquals("Wrong error type stored in exception.",
   1810                    NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
   1811                    e.getErrorType());
   1812     }
   1813     try {
   1814       String someNumber = "123 456 7890";
   1815       phoneUtil.parse(someNumber, null);
   1816       fail("Null region code not allowed: should fail.");
   1817     } catch (NumberParseException e) {
   1818       // Expected this exception.
   1819       assertEquals("Wrong error type stored in exception.",
   1820                    NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
   1821                    e.getErrorType());
   1822     }
   1823     try {
   1824       String someNumber = "0044------";
   1825       phoneUtil.parse(someNumber, RegionCode.GB);
   1826       fail("No number provided, only region code: should fail");
   1827     } catch (NumberParseException e) {
   1828       // Expected this exception.
   1829       assertEquals("Wrong error type stored in exception.",
   1830                    NumberParseException.ErrorType.TOO_SHORT_AFTER_IDD,
   1831                    e.getErrorType());
   1832     }
   1833     try {
   1834       String someNumber = "0044";
   1835       phoneUtil.parse(someNumber, RegionCode.GB);
   1836       fail("No number provided, only region code: should fail");
   1837     } catch (NumberParseException e) {
   1838       // Expected this exception.
   1839       assertEquals("Wrong error type stored in exception.",
   1840                    NumberParseException.ErrorType.TOO_SHORT_AFTER_IDD,
   1841                    e.getErrorType());
   1842     }
   1843     try {
   1844       String someNumber = "011";
   1845       phoneUtil.parse(someNumber, RegionCode.US);
   1846       fail("Only IDD provided - should fail.");
   1847     } catch (NumberParseException e) {
   1848       // Expected this exception.
   1849       assertEquals("Wrong error type stored in exception.",
   1850                    NumberParseException.ErrorType.TOO_SHORT_AFTER_IDD,
   1851                    e.getErrorType());
   1852     }
   1853     try {
   1854       String someNumber = "0119";
   1855       phoneUtil.parse(someNumber, RegionCode.US);
   1856       fail("Only IDD provided and then 9 - should fail.");
   1857     } catch (NumberParseException e) {
   1858       // Expected this exception.
   1859       assertEquals("Wrong error type stored in exception.",
   1860                    NumberParseException.ErrorType.TOO_SHORT_AFTER_IDD,
   1861                    e.getErrorType());
   1862     }
   1863     try {
   1864       String emptyNumber = "";
   1865       // Invalid region.
   1866       phoneUtil.parse(emptyNumber, RegionCode.ZZ);
   1867       fail("Empty string - should fail.");
   1868     } catch (NumberParseException e) {
   1869       // Expected this exception.
   1870       assertEquals("Wrong error type stored in exception.",
   1871                    NumberParseException.ErrorType.NOT_A_NUMBER,
   1872                    e.getErrorType());
   1873     }
   1874     try {
   1875       String nullNumber = null;
   1876       // Invalid region.
   1877       phoneUtil.parse(nullNumber, RegionCode.ZZ);
   1878       fail("Null string - should fail.");
   1879     } catch (NumberParseException e) {
   1880       // Expected this exception.
   1881       assertEquals("Wrong error type stored in exception.",
   1882                    NumberParseException.ErrorType.NOT_A_NUMBER,
   1883                    e.getErrorType());
   1884     } catch (NullPointerException e) {
   1885       fail("Null string - but should not throw a null pointer exception.");
   1886     }
   1887     try {
   1888       String nullNumber = null;
   1889       phoneUtil.parse(nullNumber, RegionCode.US);
   1890       fail("Null string - should fail.");
   1891     } catch (NumberParseException e) {
   1892       // Expected this exception.
   1893       assertEquals("Wrong error type stored in exception.",
   1894                    NumberParseException.ErrorType.NOT_A_NUMBER,
   1895                    e.getErrorType());
   1896     } catch (NullPointerException e) {
   1897       fail("Null string - but should not throw a null pointer exception.");
   1898     }
   1899   }
   1900 
   1901   public void testParseNumbersWithPlusWithNoRegion() throws Exception {
   1902     // RegionCode.ZZ is allowed only if the number starts with a '+' - then the country calling code
   1903     // can be calculated.
   1904     assertEquals(NZ_NUMBER, phoneUtil.parse("+64 3 331 6005", RegionCode.ZZ));
   1905     // Test with full-width plus.
   1906     assertEquals(NZ_NUMBER, phoneUtil.parse("\uFF0B64 3 331 6005", RegionCode.ZZ));
   1907     // Test with normal plus but leading characters that need to be stripped.
   1908     assertEquals(NZ_NUMBER, phoneUtil.parse("Tel: +64 3 331 6005", RegionCode.ZZ));
   1909     assertEquals(NZ_NUMBER, phoneUtil.parse("+64 3 331 6005", null));
   1910     assertEquals(INTERNATIONAL_TOLL_FREE, phoneUtil.parse("+800 1234 5678", null));
   1911 
   1912     // It is important that we set the carrier code to an empty string, since we used
   1913     // ParseAndKeepRawInput and no carrier code was found.
   1914     PhoneNumber nzNumberWithRawInput = new PhoneNumber().mergeFrom(NZ_NUMBER).
   1915         setRawInput("+64 3 331 6005").
   1916         setCountryCodeSource(CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN).
   1917         setPreferredDomesticCarrierCode("");
   1918     assertEquals(nzNumberWithRawInput, phoneUtil.parseAndKeepRawInput("+64 3 331 6005",
   1919                                                                       RegionCode.ZZ));
   1920     // Null is also allowed for the region code in these cases.
   1921     assertEquals(nzNumberWithRawInput, phoneUtil.parseAndKeepRawInput("+64 3 331 6005", null));
   1922   }
   1923 
   1924   public void testParseExtensions() throws Exception {
   1925     PhoneNumber nzNumber = new PhoneNumber();
   1926     nzNumber.setCountryCode(64).setNationalNumber(33316005L).setExtension("3456");
   1927     assertEquals(nzNumber, phoneUtil.parse("03 331 6005 ext 3456", RegionCode.NZ));
   1928     assertEquals(nzNumber, phoneUtil.parse("03-3316005x3456", RegionCode.NZ));
   1929     assertEquals(nzNumber, phoneUtil.parse("03-3316005 int.3456", RegionCode.NZ));
   1930     assertEquals(nzNumber, phoneUtil.parse("03 3316005 #3456", RegionCode.NZ));
   1931     // Test the following do not extract extensions:
   1932     assertEquals(ALPHA_NUMERIC_NUMBER, phoneUtil.parse("1800 six-flags", RegionCode.US));
   1933     assertEquals(ALPHA_NUMERIC_NUMBER, phoneUtil.parse("1800 SIX FLAGS", RegionCode.US));
   1934     assertEquals(ALPHA_NUMERIC_NUMBER, phoneUtil.parse("0~0 1800 7493 5247", RegionCode.PL));
   1935     assertEquals(ALPHA_NUMERIC_NUMBER, phoneUtil.parse("(1800) 7493.5247", RegionCode.US));
   1936     // Check that the last instance of an extension token is matched.
   1937     PhoneNumber extnNumber = new PhoneNumber().mergeFrom(ALPHA_NUMERIC_NUMBER).setExtension("1234");
   1938     assertEquals(extnNumber, phoneUtil.parse("0~0 1800 7493 5247 ~1234", RegionCode.PL));
   1939     // Verifying bug-fix where the last digit of a number was previously omitted if it was a 0 when
   1940     // extracting the extension. Also verifying a few different cases of extensions.
   1941     PhoneNumber ukNumber = new PhoneNumber();
   1942     ukNumber.setCountryCode(44).setNationalNumber(2034567890L).setExtension("456");
   1943     assertEquals(ukNumber, phoneUtil.parse("+44 2034567890x456", RegionCode.NZ));
   1944     assertEquals(ukNumber, phoneUtil.parse("+44 2034567890x456", RegionCode.GB));
   1945     assertEquals(ukNumber, phoneUtil.parse("+44 2034567890 x456", RegionCode.GB));
   1946     assertEquals(ukNumber, phoneUtil.parse("+44 2034567890 X456", RegionCode.GB));
   1947     assertEquals(ukNumber, phoneUtil.parse("+44 2034567890 X 456", RegionCode.GB));
   1948     assertEquals(ukNumber, phoneUtil.parse("+44 2034567890 X  456", RegionCode.GB));
   1949     assertEquals(ukNumber, phoneUtil.parse("+44 2034567890 x 456  ", RegionCode.GB));
   1950     assertEquals(ukNumber, phoneUtil.parse("+44 2034567890  X 456", RegionCode.GB));
   1951     assertEquals(ukNumber, phoneUtil.parse("+44-2034567890;ext=456", RegionCode.GB));
   1952     // Full-width extension, "extn" only.
   1953     assertEquals(ukNumber, phoneUtil.parse("+442034567890\uFF45\uFF58\uFF54\uFF4E456",
   1954                                            RegionCode.GB));
   1955     // "xtn" only.
   1956     assertEquals(ukNumber, phoneUtil.parse("+442034567890\uFF58\uFF54\uFF4E456",
   1957                                            RegionCode.GB));
   1958     // "xt" only.
   1959     assertEquals(ukNumber, phoneUtil.parse("+442034567890\uFF58\uFF54456",
   1960                                            RegionCode.GB));
   1961 
   1962     PhoneNumber usWithExtension = new PhoneNumber();
   1963     usWithExtension.setCountryCode(1).setNationalNumber(8009013355L).setExtension("7246433");
   1964     assertEquals(usWithExtension, phoneUtil.parse("(800) 901-3355 x 7246433", RegionCode.US));
   1965     assertEquals(usWithExtension, phoneUtil.parse("(800) 901-3355 , ext 7246433", RegionCode.US));
   1966     assertEquals(usWithExtension,
   1967                  phoneUtil.parse("(800) 901-3355 ,extension 7246433", RegionCode.US));
   1968     assertEquals(usWithExtension,
   1969                  phoneUtil.parse("(800) 901-3355 ,extensi\u00F3n 7246433", RegionCode.US));
   1970     // Repeat with the small letter o with acute accent created by combining characters.
   1971     assertEquals(usWithExtension,
   1972                  phoneUtil.parse("(800) 901-3355 ,extensio\u0301n 7246433", RegionCode.US));
   1973     assertEquals(usWithExtension, phoneUtil.parse("(800) 901-3355 , 7246433", RegionCode.US));
   1974     assertEquals(usWithExtension, phoneUtil.parse("(800) 901-3355 ext: 7246433", RegionCode.US));
   1975 
   1976     // Test that if a number has two extensions specified, we ignore the second.
   1977     PhoneNumber usWithTwoExtensionsNumber = new PhoneNumber();
   1978     usWithTwoExtensionsNumber.setCountryCode(1).setNationalNumber(2121231234L).setExtension("508");
   1979     assertEquals(usWithTwoExtensionsNumber, phoneUtil.parse("(212)123-1234 x508/x1234",
   1980                                                             RegionCode.US));
   1981     assertEquals(usWithTwoExtensionsNumber, phoneUtil.parse("(212)123-1234 x508/ x1234",
   1982                                                             RegionCode.US));
   1983     assertEquals(usWithTwoExtensionsNumber, phoneUtil.parse("(212)123-1234 x508\\x1234",
   1984                                                             RegionCode.US));
   1985 
   1986     // Test parsing numbers in the form (645) 123-1234-910# works, where the last 3 digits before
   1987     // the # are an extension.
   1988     usWithExtension.clear();
   1989     usWithExtension.setCountryCode(1).setNationalNumber(6451231234L).setExtension("910");
   1990     assertEquals(usWithExtension, phoneUtil.parse("+1 (645) 123 1234-910#", RegionCode.US));
   1991     // Retry with the same number in a slightly different format.
   1992     assertEquals(usWithExtension, phoneUtil.parse("+1 (645) 123 1234 ext. 910#", RegionCode.US));
   1993   }
   1994 
   1995   public void testParseAndKeepRaw() throws Exception {
   1996     PhoneNumber alphaNumericNumber = new PhoneNumber().mergeFrom(ALPHA_NUMERIC_NUMBER).
   1997         setRawInput("800 six-flags").
   1998         setCountryCodeSource(CountryCodeSource.FROM_DEFAULT_COUNTRY).
   1999         setPreferredDomesticCarrierCode("");
   2000     assertEquals(alphaNumericNumber,
   2001                  phoneUtil.parseAndKeepRawInput("800 six-flags", RegionCode.US));
   2002 
   2003     PhoneNumber shorterAlphaNumber = new PhoneNumber().
   2004         setCountryCode(1).setNationalNumber(8007493524L).
   2005         setRawInput("1800 six-flag").
   2006         setCountryCodeSource(CountryCodeSource.FROM_NUMBER_WITHOUT_PLUS_SIGN).
   2007         setPreferredDomesticCarrierCode("");
   2008     assertEquals(shorterAlphaNumber,
   2009                  phoneUtil.parseAndKeepRawInput("1800 six-flag", RegionCode.US));
   2010 
   2011     shorterAlphaNumber.setRawInput("+1800 six-flag").
   2012         setCountryCodeSource(CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN);
   2013     assertEquals(shorterAlphaNumber,
   2014                  phoneUtil.parseAndKeepRawInput("+1800 six-flag", RegionCode.NZ));
   2015 
   2016     shorterAlphaNumber.setRawInput("001800 six-flag").
   2017         setCountryCodeSource(CountryCodeSource.FROM_NUMBER_WITH_IDD);
   2018     assertEquals(shorterAlphaNumber,
   2019                  phoneUtil.parseAndKeepRawInput("001800 six-flag", RegionCode.NZ));
   2020 
   2021     // Invalid region code supplied.
   2022     try {
   2023       phoneUtil.parseAndKeepRawInput("123 456 7890", RegionCode.CS);
   2024       fail("Deprecated region code not allowed: should fail.");
   2025     } catch (NumberParseException e) {
   2026       // Expected this exception.
   2027       assertEquals("Wrong error type stored in exception.",
   2028                    NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
   2029                    e.getErrorType());
   2030     }
   2031 
   2032     PhoneNumber koreanNumber = new PhoneNumber();
   2033     koreanNumber.setCountryCode(82).setNationalNumber(22123456).setRawInput("08122123456").
   2034         setCountryCodeSource(CountryCodeSource.FROM_DEFAULT_COUNTRY).
   2035         setPreferredDomesticCarrierCode("81");
   2036     assertEquals(koreanNumber, phoneUtil.parseAndKeepRawInput("08122123456", RegionCode.KR));
   2037   }
   2038 
   2039   public void testCountryWithNoNumberDesc() {
   2040     // Andorra is a country where we don't have PhoneNumberDesc info in the metadata.
   2041     PhoneNumber adNumber = new PhoneNumber();
   2042     adNumber.setCountryCode(376).setNationalNumber(12345L);
   2043     assertEquals("+376 12345", phoneUtil.format(adNumber, PhoneNumberFormat.INTERNATIONAL));
   2044     assertEquals("+37612345", phoneUtil.format(adNumber, PhoneNumberFormat.E164));
   2045     assertEquals("12345", phoneUtil.format(adNumber, PhoneNumberFormat.NATIONAL));
   2046     assertEquals(PhoneNumberUtil.PhoneNumberType.UNKNOWN, phoneUtil.getNumberType(adNumber));
   2047     assertTrue(phoneUtil.isValidNumber(adNumber));
   2048 
   2049     // Test dialing a US number from within Andorra.
   2050     assertEquals("00 1 650 253 0000",
   2051                  phoneUtil.formatOutOfCountryCallingNumber(US_NUMBER, RegionCode.AD));
   2052   }
   2053 
   2054   public void testUnknownCountryCallingCodeForValidation() {
   2055     PhoneNumber invalidNumber = new PhoneNumber();
   2056     invalidNumber.setCountryCode(0).setNationalNumber(1234L);
   2057     assertFalse(phoneUtil.isValidNumber(invalidNumber));
   2058   }
   2059 
   2060   public void testIsNumberMatchMatches() throws Exception {
   2061     // Test simple matches where formatting is different, or leading zeroes, or country calling code
   2062     // has been specified.
   2063     assertEquals(PhoneNumberUtil.MatchType.EXACT_MATCH,
   2064                  phoneUtil.isNumberMatch("+64 3 331 6005", "+64 03 331 6005"));
   2065     assertEquals(PhoneNumberUtil.MatchType.EXACT_MATCH,
   2066                  phoneUtil.isNumberMatch("+800 1234 5678", "+80012345678"));
   2067     assertEquals(PhoneNumberUtil.MatchType.EXACT_MATCH,
   2068                  phoneUtil.isNumberMatch("+64 03 331-6005", "+64 03331 6005"));
   2069     assertEquals(PhoneNumberUtil.MatchType.EXACT_MATCH,
   2070                  phoneUtil.isNumberMatch("+643 331-6005", "+64033316005"));
   2071     assertEquals(PhoneNumberUtil.MatchType.EXACT_MATCH,
   2072                  phoneUtil.isNumberMatch("+643 331-6005", "+6433316005"));
   2073     assertEquals(PhoneNumberUtil.MatchType.EXACT_MATCH,
   2074                  phoneUtil.isNumberMatch("+64 3 331-6005", "+6433316005"));
   2075     // Test alpha numbers.
   2076     assertEquals(PhoneNumberUtil.MatchType.EXACT_MATCH,
   2077                  phoneUtil.isNumberMatch("+1800 siX-Flags", "+1 800 7493 5247"));
   2078     // Test numbers with extensions.
   2079     assertEquals(PhoneNumberUtil.MatchType.EXACT_MATCH,
   2080                  phoneUtil.isNumberMatch("+64 3 331-6005 extn 1234", "+6433316005#1234"));
   2081     // Test proto buffers.
   2082     assertEquals(PhoneNumberUtil.MatchType.EXACT_MATCH,
   2083                  phoneUtil.isNumberMatch(NZ_NUMBER, "+6403 331 6005"));
   2084 
   2085     PhoneNumber nzNumber = new PhoneNumber().mergeFrom(NZ_NUMBER).setExtension("3456");
   2086     assertEquals(PhoneNumberUtil.MatchType.EXACT_MATCH,
   2087                  phoneUtil.isNumberMatch(nzNumber, "+643 331 6005 ext 3456"));
   2088     // Check empty extensions are ignored.
   2089     nzNumber.setExtension("");
   2090     assertEquals(PhoneNumberUtil.MatchType.EXACT_MATCH,
   2091                  phoneUtil.isNumberMatch(nzNumber, "+6403 331 6005"));
   2092     // Check variant with two proto buffers.
   2093     assertEquals("Number " + nzNumber.toString() + " did not match " + NZ_NUMBER.toString(),
   2094                  PhoneNumberUtil.MatchType.EXACT_MATCH,
   2095                  phoneUtil.isNumberMatch(nzNumber, NZ_NUMBER));
   2096 
   2097     // Check raw_input, country_code_source and preferred_domestic_carrier_code are ignored.
   2098     PhoneNumber brNumberOne = new PhoneNumber();
   2099     PhoneNumber brNumberTwo = new PhoneNumber();
   2100     brNumberOne.setCountryCode(55).setNationalNumber(3121286979L)
   2101         .setCountryCodeSource(PhoneNumber.CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN)
   2102         .setPreferredDomesticCarrierCode("12").setRawInput("012 3121286979");
   2103     brNumberTwo.setCountryCode(55).setNationalNumber(3121286979L)
   2104         .setCountryCodeSource(PhoneNumber.CountryCodeSource.FROM_DEFAULT_COUNTRY)
   2105         .setPreferredDomesticCarrierCode("14").setRawInput("143121286979");
   2106     assertEquals(PhoneNumberUtil.MatchType.EXACT_MATCH,
   2107                  phoneUtil.isNumberMatch(brNumberOne, brNumberTwo));
   2108   }
   2109 
   2110   public void testIsNumberMatchNonMatches() throws Exception {
   2111     // Non-matches.
   2112     assertEquals(PhoneNumberUtil.MatchType.NO_MATCH,
   2113                  phoneUtil.isNumberMatch("03 331 6005", "03 331 6006"));
   2114     assertEquals(PhoneNumberUtil.MatchType.NO_MATCH,
   2115                  phoneUtil.isNumberMatch("+800 1234 5678", "+1 800 1234 5678"));
   2116     // Different country calling code, partial number match.
   2117     assertEquals(PhoneNumberUtil.MatchType.NO_MATCH,
   2118                  phoneUtil.isNumberMatch("+64 3 331-6005", "+16433316005"));
   2119     // Different country calling code, same number.
   2120     assertEquals(PhoneNumberUtil.MatchType.NO_MATCH,
   2121                  phoneUtil.isNumberMatch("+64 3 331-6005", "+6133316005"));
   2122     // Extension different, all else the same.
   2123     assertEquals(PhoneNumberUtil.MatchType.NO_MATCH,
   2124                  phoneUtil.isNumberMatch("+64 3 331-6005 extn 1234", "0116433316005#1235"));
   2125     // NSN matches, but extension is different - not the same number.
   2126     assertEquals(PhoneNumberUtil.MatchType.NO_MATCH,
   2127                  phoneUtil.isNumberMatch("+64 3 331-6005 ext.1235", "3 331 6005#1234"));
   2128 
   2129     // Invalid numbers that can't be parsed.
   2130     assertEquals(PhoneNumberUtil.MatchType.NOT_A_NUMBER,
   2131                  phoneUtil.isNumberMatch("43", "3 331 6043"));
   2132     assertEquals(PhoneNumberUtil.MatchType.NOT_A_NUMBER,
   2133                  phoneUtil.isNumberMatch("+43", "+64 3 331 6005"));
   2134     assertEquals(PhoneNumberUtil.MatchType.NOT_A_NUMBER,
   2135                  phoneUtil.isNumberMatch("+43", "64 3 331 6005"));
   2136     assertEquals(PhoneNumberUtil.MatchType.NOT_A_NUMBER,
   2137                  phoneUtil.isNumberMatch("Dog", "64 3 331 6005"));
   2138   }
   2139 
   2140   public void testIsNumberMatchNsnMatches() throws Exception {
   2141     // NSN matches.
   2142     assertEquals(PhoneNumberUtil.MatchType.NSN_MATCH,
   2143                  phoneUtil.isNumberMatch("+64 3 331-6005", "03 331 6005"));
   2144     assertEquals(PhoneNumberUtil.MatchType.NSN_MATCH,
   2145                  phoneUtil.isNumberMatch(NZ_NUMBER, "03 331 6005"));
   2146     // Here the second number possibly starts with the country calling code for New Zealand,
   2147     // although we are unsure.
   2148     PhoneNumber unchangedNzNumber = new PhoneNumber().mergeFrom(NZ_NUMBER);
   2149     assertEquals(PhoneNumberUtil.MatchType.NSN_MATCH,
   2150                  phoneUtil.isNumberMatch(unchangedNzNumber, "(64-3) 331 6005"));
   2151     // Check the phone number proto was not edited during the method call.
   2152     assertEquals(NZ_NUMBER, unchangedNzNumber);
   2153 
   2154     // Here, the 1 might be a national prefix, if we compare it to the US number, so the resultant
   2155     // match is an NSN match.
   2156     assertEquals(PhoneNumberUtil.MatchType.NSN_MATCH,
   2157                  phoneUtil.isNumberMatch(US_NUMBER, "1-650-253-0000"));
   2158     assertEquals(PhoneNumberUtil.MatchType.NSN_MATCH,
   2159                  phoneUtil.isNumberMatch(US_NUMBER, "6502530000"));
   2160     assertEquals(PhoneNumberUtil.MatchType.NSN_MATCH,
   2161                  phoneUtil.isNumberMatch("+1 650-253 0000", "1 650 253 0000"));
   2162     assertEquals(PhoneNumberUtil.MatchType.NSN_MATCH,
   2163                  phoneUtil.isNumberMatch("1 650-253 0000", "1 650 253 0000"));
   2164     assertEquals(PhoneNumberUtil.MatchType.NSN_MATCH,
   2165                  phoneUtil.isNumberMatch("1 650-253 0000", "+1 650 253 0000"));
   2166     // For this case, the match will be a short NSN match, because we cannot assume that the 1 might
   2167     // be a national prefix, so don't remove it when parsing.
   2168     PhoneNumber randomNumber = new PhoneNumber();
   2169     randomNumber.setCountryCode(41).setNationalNumber(6502530000L);
   2170     assertEquals(PhoneNumberUtil.MatchType.SHORT_NSN_MATCH,
   2171                  phoneUtil.isNumberMatch(randomNumber, "1-650-253-0000"));
   2172   }
   2173 
   2174   public void testIsNumberMatchShortNsnMatches() throws Exception {
   2175     // Short NSN matches with the country not specified for either one or both numbers.
   2176     assertEquals(PhoneNumberUtil.MatchType.SHORT_NSN_MATCH,
   2177                  phoneUtil.isNumberMatch("+64 3 331-6005", "331 6005"));
   2178     // We did not know that the "0" was a national prefix since neither number has a country code,
   2179     // so this is considered a SHORT_NSN_MATCH.
   2180     assertEquals(PhoneNumberUtil.MatchType.SHORT_NSN_MATCH,
   2181                  phoneUtil.isNumberMatch("3 331-6005", "03 331 6005"));
   2182     assertEquals(PhoneNumberUtil.MatchType.SHORT_NSN_MATCH,
   2183                  phoneUtil.isNumberMatch("3 331-6005", "331 6005"));
   2184     assertEquals(PhoneNumberUtil.MatchType.SHORT_NSN_MATCH,
   2185                  phoneUtil.isNumberMatch("3 331-6005", "+64 331 6005"));
   2186     // Short NSN match with the country specified.
   2187     assertEquals(PhoneNumberUtil.MatchType.SHORT_NSN_MATCH,
   2188                  phoneUtil.isNumberMatch("03 331-6005", "331 6005"));
   2189     assertEquals(PhoneNumberUtil.MatchType.SHORT_NSN_MATCH,
   2190                  phoneUtil.isNumberMatch("1 234 345 6789", "345 6789"));
   2191     assertEquals(PhoneNumberUtil.MatchType.SHORT_NSN_MATCH,
   2192                  phoneUtil.isNumberMatch("+1 (234) 345 6789", "345 6789"));
   2193     // NSN matches, country calling code omitted for one number, extension missing for one.
   2194     assertEquals(PhoneNumberUtil.MatchType.SHORT_NSN_MATCH,
   2195                  phoneUtil.isNumberMatch("+64 3 331-6005", "3 331 6005#1234"));
   2196     // One has Italian leading zero, one does not.
   2197     PhoneNumber italianNumberOne = new PhoneNumber();
   2198     italianNumberOne.setCountryCode(39).setNationalNumber(1234L).setItalianLeadingZero(true);
   2199     PhoneNumber italianNumberTwo = new PhoneNumber();
   2200     italianNumberTwo.setCountryCode(39).setNationalNumber(1234L);
   2201     assertEquals(PhoneNumberUtil.MatchType.SHORT_NSN_MATCH,
   2202                  phoneUtil.isNumberMatch(italianNumberOne, italianNumberTwo));
   2203     // One has an extension, the other has an extension of "".
   2204     italianNumberOne.setExtension("1234").clearItalianLeadingZero();
   2205     italianNumberTwo.setExtension("");
   2206     assertEquals(PhoneNumberUtil.MatchType.SHORT_NSN_MATCH,
   2207                  phoneUtil.isNumberMatch(italianNumberOne, italianNumberTwo));
   2208   }
   2209 
   2210   public void testCanBeInternationallyDialled() throws Exception {
   2211     // We have no-international-dialling rules for the US in our test metadata that say that
   2212     // toll-free numbers cannot be dialled internationally.
   2213     assertFalse(phoneUtil.canBeInternationallyDialled(US_TOLLFREE));
   2214 
   2215     // Normal US numbers can be internationally dialled.
   2216     assertTrue(phoneUtil.canBeInternationallyDialled(US_NUMBER));
   2217 
   2218     // Invalid number.
   2219     assertTrue(phoneUtil.canBeInternationallyDialled(US_LOCAL_NUMBER));
   2220 
   2221     // We have no data for NZ - should return true.
   2222     assertTrue(phoneUtil.canBeInternationallyDialled(NZ_NUMBER));
   2223     assertTrue(phoneUtil.canBeInternationallyDialled(INTERNATIONAL_TOLL_FREE));
   2224   }
   2225 
   2226   public void testIsAlphaNumber() throws Exception {
   2227     assertTrue(phoneUtil.isAlphaNumber("1800 six-flags"));
   2228     assertTrue(phoneUtil.isAlphaNumber("1800 six-flags ext. 1234"));
   2229     assertTrue(phoneUtil.isAlphaNumber("+800 six-flags"));
   2230     assertFalse(phoneUtil.isAlphaNumber("1800 123-1234"));
   2231     assertFalse(phoneUtil.isAlphaNumber("1800 123-1234 extension: 1234"));
   2232     assertFalse(phoneUtil.isAlphaNumber("+800 1234-1234"));
   2233   }
   2234 }
   2235