• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.google.i18n.phonenumbers;
18 
19 import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberFormat;
20 import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberType;
21 import com.google.i18n.phonenumbers.PhoneNumberUtil.ValidationResult;
22 import com.google.i18n.phonenumbers.Phonemetadata.NumberFormat;
23 import com.google.i18n.phonenumbers.Phonemetadata.PhoneMetadata;
24 import com.google.i18n.phonenumbers.Phonemetadata.PhoneNumberDesc;
25 import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
26 import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber.CountryCodeSource;
27 
28 import java.util.ArrayList;
29 import java.util.List;
30 import java.util.Set;
31 
32 /**
33  * Unit tests for PhoneNumberUtil.java
34  *
35  * Note that these tests use the test metadata, not the normal metadata file, so should not be used
36  * for regression test purposes - these tests are illustrative only and test functionality.
37  *
38  * @author Shaopeng Jia
39  */
40 public class PhoneNumberUtilTest extends TestMetadataTestCase {
41   // Set up some test numbers to re-use.
42   // TODO: Rewrite this as static functions that return new numbers each time to avoid
43   // any risk of accidental changes to mutable static state affecting many tests.
44   private static final PhoneNumber ALPHA_NUMERIC_NUMBER =
45       new PhoneNumber().setCountryCode(1).setNationalNumber(80074935247L);
46   private static final PhoneNumber AE_UAN =
47       new PhoneNumber().setCountryCode(971).setNationalNumber(600123456L);
48   private static final PhoneNumber AR_MOBILE =
49       new PhoneNumber().setCountryCode(54).setNationalNumber(91187654321L);
50   private static final PhoneNumber AR_NUMBER =
51       new PhoneNumber().setCountryCode(54).setNationalNumber(1187654321);
52   private static final PhoneNumber AU_NUMBER =
53       new PhoneNumber().setCountryCode(61).setNationalNumber(236618300L);
54   private static final PhoneNumber BS_MOBILE =
55       new PhoneNumber().setCountryCode(1).setNationalNumber(2423570000L);
56   private static final PhoneNumber BS_NUMBER =
57       new PhoneNumber().setCountryCode(1).setNationalNumber(2423651234L);
58   // Note that this is the same as the example number for DE in the metadata.
59   private static final PhoneNumber DE_NUMBER =
60       new PhoneNumber().setCountryCode(49).setNationalNumber(30123456L);
61   private static final PhoneNumber DE_SHORT_NUMBER =
62       new PhoneNumber().setCountryCode(49).setNationalNumber(1234L);
63   private static final PhoneNumber GB_MOBILE =
64       new PhoneNumber().setCountryCode(44).setNationalNumber(7912345678L);
65   private static final PhoneNumber GB_NUMBER =
66       new PhoneNumber().setCountryCode(44).setNationalNumber(2070313000L);
67   private static final PhoneNumber IT_MOBILE =
68       new PhoneNumber().setCountryCode(39).setNationalNumber(345678901L);
69   private static final PhoneNumber IT_NUMBER =
70       new PhoneNumber().setCountryCode(39).setNationalNumber(236618300L).
71       setItalianLeadingZero(true);
72   private static final PhoneNumber JP_STAR_NUMBER =
73       new PhoneNumber().setCountryCode(81).setNationalNumber(2345);
74   // Numbers to test the formatting rules from Mexico.
75   private static final PhoneNumber MX_MOBILE1 =
76       new PhoneNumber().setCountryCode(52).setNationalNumber(12345678900L);
77   private static final PhoneNumber MX_MOBILE2 =
78       new PhoneNumber().setCountryCode(52).setNationalNumber(15512345678L);
79   private static final PhoneNumber MX_NUMBER1 =
80       new PhoneNumber().setCountryCode(52).setNationalNumber(3312345678L);
81   private static final PhoneNumber MX_NUMBER2 =
82       new PhoneNumber().setCountryCode(52).setNationalNumber(8211234567L);
83   private static final PhoneNumber NZ_NUMBER =
84       new PhoneNumber().setCountryCode(64).setNationalNumber(33316005L);
85   private static final PhoneNumber SG_NUMBER =
86       new PhoneNumber().setCountryCode(65).setNationalNumber(65218000L);
87   // A too-long and hence invalid US number.
88   private static final PhoneNumber US_LONG_NUMBER =
89       new PhoneNumber().setCountryCode(1).setNationalNumber(65025300001L);
90   private static final PhoneNumber US_NUMBER =
91       new PhoneNumber().setCountryCode(1).setNationalNumber(6502530000L);
92   private static final PhoneNumber US_PREMIUM =
93       new PhoneNumber().setCountryCode(1).setNationalNumber(9002530000L);
94   // Too short, but still possible US numbers.
95   private static final PhoneNumber US_LOCAL_NUMBER =
96       new PhoneNumber().setCountryCode(1).setNationalNumber(2530000L);
97   private static final PhoneNumber US_SHORT_BY_ONE_NUMBER =
98       new PhoneNumber().setCountryCode(1).setNationalNumber(650253000L);
99   private static final PhoneNumber US_TOLLFREE =
100       new PhoneNumber().setCountryCode(1).setNationalNumber(8002530000L);
101   private static final PhoneNumber US_SPOOF =
102       new PhoneNumber().setCountryCode(1).setNationalNumber(0L);
103   private static final PhoneNumber US_SPOOF_WITH_RAW_INPUT =
104       new PhoneNumber().setCountryCode(1).setNationalNumber(0L)
105           .setRawInput("000-000-0000");
106   private static final PhoneNumber UZ_FIXED_LINE =
107       new PhoneNumber().setCountryCode(998).setNationalNumber(612201234L);
108   private static final PhoneNumber UZ_MOBILE =
109       new PhoneNumber().setCountryCode(998).setNationalNumber(950123456L);
110   private static final PhoneNumber INTERNATIONAL_TOLL_FREE =
111       new PhoneNumber().setCountryCode(800).setNationalNumber(12345678L);
112   // We set this to be the same length as numbers for the other non-geographical country prefix that
113   // we have in our test metadata. However, this is not considered valid because they differ in
114   // their country calling code.
115   private static final PhoneNumber INTERNATIONAL_TOLL_FREE_TOO_LONG =
116       new PhoneNumber().setCountryCode(800).setNationalNumber(123456789L);
117   private static final PhoneNumber UNIVERSAL_PREMIUM_RATE =
118       new PhoneNumber().setCountryCode(979).setNationalNumber(123456789L);
119   private static final PhoneNumber UNKNOWN_COUNTRY_CODE_NO_RAW_INPUT =
120       new PhoneNumber().setCountryCode(2).setNationalNumber(12345L);
121 
testGetSupportedRegions()122   public void testGetSupportedRegions() {
123     assertTrue(phoneUtil.getSupportedRegions().size() > 0);
124   }
125 
testGetSupportedGlobalNetworkCallingCodes()126   public void testGetSupportedGlobalNetworkCallingCodes() {
127     Set<Integer> globalNetworkCallingCodes =
128         phoneUtil.getSupportedGlobalNetworkCallingCodes();
129     assertTrue(globalNetworkCallingCodes.size() > 0);
130     for (int callingCode : globalNetworkCallingCodes) {
131       assertTrue(callingCode > 0);
132       assertEquals(RegionCode.UN001, phoneUtil.getRegionCodeForCountryCode(callingCode));
133     }
134   }
135 
testGetSupportedCallingCodes()136   public void testGetSupportedCallingCodes() {
137     Set<Integer> callingCodes = phoneUtil.getSupportedCallingCodes();
138     assertTrue(callingCodes.size() > 0);
139     for (int callingCode : callingCodes) {
140       assertTrue(callingCode > 0);
141       assertTrue(phoneUtil.getRegionCodeForCountryCode(callingCode) != RegionCode.ZZ);
142     }
143     // There should be more than just the global network calling codes in this set.
144     assertTrue(callingCodes.size() > phoneUtil.getSupportedGlobalNetworkCallingCodes().size());
145     // But they should be included. Testing one of them.
146     assertTrue(callingCodes.contains(979));
147   }
148 
testGetInstanceLoadBadMetadata()149   public void testGetInstanceLoadBadMetadata() {
150     assertNull(phoneUtil.getMetadataForRegion("No Such Region"));
151     assertNull(phoneUtil.getMetadataForNonGeographicalRegion(-1));
152   }
153 
testGetSupportedTypesForRegion()154   public void testGetSupportedTypesForRegion() {
155     assertTrue(phoneUtil.getSupportedTypesForRegion(RegionCode.BR)
156         .contains(PhoneNumberType.FIXED_LINE));
157     // Our test data has no mobile numbers for Brazil.
158     assertFalse(phoneUtil.getSupportedTypesForRegion(RegionCode.BR)
159         .contains(PhoneNumberType.MOBILE));
160     // UNKNOWN should never be returned.
161     assertFalse(phoneUtil.getSupportedTypesForRegion(RegionCode.BR)
162         .contains(PhoneNumberType.UNKNOWN));
163     // In the US, many numbers are classified as FIXED_LINE_OR_MOBILE; but we don't want to expose
164     // this as a supported type, instead we say FIXED_LINE and MOBILE are both present.
165     assertTrue(phoneUtil.getSupportedTypesForRegion(RegionCode.US)
166         .contains(PhoneNumberType.FIXED_LINE));
167     assertTrue(phoneUtil.getSupportedTypesForRegion(RegionCode.US)
168         .contains(PhoneNumberType.MOBILE));
169     assertFalse(phoneUtil.getSupportedTypesForRegion(RegionCode.US)
170         .contains(PhoneNumberType.FIXED_LINE_OR_MOBILE));
171 
172     // Test the invalid region code.
173     assertEquals(0, phoneUtil.getSupportedTypesForRegion(RegionCode.ZZ).size());
174   }
175 
testGetSupportedTypesForNonGeoEntity()176   public void testGetSupportedTypesForNonGeoEntity() {
177     // No data exists for 999 at all, no types should be returned.
178     assertEquals(0, phoneUtil.getSupportedTypesForNonGeoEntity(999).size());
179 
180     Set<PhoneNumberType> typesFor979 = phoneUtil.getSupportedTypesForNonGeoEntity(979);
181     assertTrue(typesFor979.contains(PhoneNumberType.PREMIUM_RATE));
182     assertFalse(typesFor979.contains(PhoneNumberType.MOBILE));
183     assertFalse(typesFor979.contains(PhoneNumberType.UNKNOWN));
184   }
185 
testGetInstanceLoadUSMetadata()186   public void testGetInstanceLoadUSMetadata() {
187     PhoneMetadata metadata = phoneUtil.getMetadataForRegion(RegionCode.US);
188     assertEquals("US", metadata.getId());
189     assertEquals(1, metadata.getCountryCode());
190     assertEquals("011", metadata.getInternationalPrefix());
191     assertTrue(metadata.hasNationalPrefix());
192     assertEquals(2, metadata.numberFormatSize());
193     assertEquals("(\\d{3})(\\d{3})(\\d{4})",
194                  metadata.getNumberFormat(1).getPattern());
195     assertEquals("$1 $2 $3", metadata.getNumberFormat(1).getFormat());
196     assertEquals("[13-689]\\d{9}|2[0-35-9]\\d{8}",
197                  metadata.getGeneralDesc().getNationalNumberPattern());
198     assertEquals("[13-689]\\d{9}|2[0-35-9]\\d{8}",
199                  metadata.getFixedLine().getNationalNumberPattern());
200     assertEquals(1, metadata.getGeneralDesc().getPossibleLengthCount());
201     assertEquals(10, metadata.getGeneralDesc().getPossibleLength(0));
202     // Possible lengths are the same as the general description, so aren't stored separately in the
203     // toll free element as well.
204     assertEquals(0, metadata.getTollFree().getPossibleLengthCount());
205     assertEquals("900\\d{7}", metadata.getPremiumRate().getNationalNumberPattern());
206     // No shared-cost data is available, so its national number data should not be set.
207     assertFalse(metadata.getSharedCost().hasNationalNumberPattern());
208   }
209 
testGetInstanceLoadDEMetadata()210   public void testGetInstanceLoadDEMetadata() {
211     PhoneMetadata metadata = phoneUtil.getMetadataForRegion(RegionCode.DE);
212     assertEquals("DE", metadata.getId());
213     assertEquals(49, metadata.getCountryCode());
214     assertEquals("00", metadata.getInternationalPrefix());
215     assertEquals("0", metadata.getNationalPrefix());
216     assertEquals(6, metadata.numberFormatSize());
217     assertEquals(1, metadata.getNumberFormat(5).leadingDigitsPatternSize());
218     assertEquals("900", metadata.getNumberFormat(5).getLeadingDigitsPattern(0));
219     assertEquals("(\\d{3})(\\d{3,4})(\\d{4})",
220                  metadata.getNumberFormat(5).getPattern());
221     assertEquals("$1 $2 $3", metadata.getNumberFormat(5).getFormat());
222     assertEquals(2, metadata.getGeneralDesc().getPossibleLengthLocalOnlyCount());
223     assertEquals(8, metadata.getGeneralDesc().getPossibleLengthCount());
224     // Nothing is present for fixed-line, since it is the same as the general desc, so for
225     // efficiency reasons we don't store an extra value.
226     assertEquals(0, metadata.getFixedLine().getPossibleLengthCount());
227     assertEquals(2, metadata.getMobile().getPossibleLengthCount());
228     assertEquals("(?:[24-6]\\d{2}|3[03-9]\\d|[789](?:0[2-9]|[1-9]\\d))\\d{1,8}",
229                  metadata.getFixedLine().getNationalNumberPattern());
230     assertEquals("30123456", metadata.getFixedLine().getExampleNumber());
231     assertEquals(10, metadata.getTollFree().getPossibleLength(0));
232     assertEquals("900([135]\\d{6}|9\\d{7})", metadata.getPremiumRate().getNationalNumberPattern());
233   }
234 
testGetInstanceLoadARMetadata()235   public void testGetInstanceLoadARMetadata() {
236     PhoneMetadata metadata = phoneUtil.getMetadataForRegion(RegionCode.AR);
237     assertEquals("AR", metadata.getId());
238     assertEquals(54, metadata.getCountryCode());
239     assertEquals("00", metadata.getInternationalPrefix());
240     assertEquals("0", metadata.getNationalPrefix());
241     assertEquals("0(?:(11|343|3715)15)?", metadata.getNationalPrefixForParsing());
242     assertEquals("9$1", metadata.getNationalPrefixTransformRule());
243     assertEquals("$2 15 $3-$4", metadata.getNumberFormat(2).getFormat());
244     assertEquals("(\\d)(\\d{4})(\\d{2})(\\d{4})",
245                  metadata.getNumberFormat(3).getPattern());
246     assertEquals("(\\d)(\\d{4})(\\d{2})(\\d{4})",
247                  metadata.getIntlNumberFormat(3).getPattern());
248     assertEquals("$1 $2 $3 $4", metadata.getIntlNumberFormat(3).getFormat());
249   }
250 
testGetInstanceLoadInternationalTollFreeMetadata()251   public void testGetInstanceLoadInternationalTollFreeMetadata() {
252     PhoneMetadata metadata = phoneUtil.getMetadataForNonGeographicalRegion(800);
253     assertEquals("001", metadata.getId());
254     assertEquals(800, metadata.getCountryCode());
255     assertEquals("$1 $2", metadata.getNumberFormat(0).getFormat());
256     assertEquals("(\\d{4})(\\d{4})", metadata.getNumberFormat(0).getPattern());
257     assertEquals(0, metadata.getGeneralDesc().getPossibleLengthLocalOnlyCount());
258     assertEquals(1, metadata.getGeneralDesc().getPossibleLengthCount());
259     assertEquals("12345678", metadata.getTollFree().getExampleNumber());
260   }
261 
testIsNumberGeographical()262   public void testIsNumberGeographical() {
263     assertFalse(phoneUtil.isNumberGeographical(BS_MOBILE));  // Bahamas, mobile phone number.
264     assertTrue(phoneUtil.isNumberGeographical(AU_NUMBER));  // Australian fixed line number.
265     assertFalse(phoneUtil.isNumberGeographical(INTERNATIONAL_TOLL_FREE));  // International toll
266                                                                            // free number.
267     // We test that mobile phone numbers in relevant regions are indeed considered geographical.
268     assertTrue(phoneUtil.isNumberGeographical(AR_MOBILE));  // Argentina, mobile phone number.
269     assertTrue(phoneUtil.isNumberGeographical(MX_MOBILE1));  // Mexico, mobile phone number.
270     assertTrue(phoneUtil.isNumberGeographical(MX_MOBILE2));  // Mexico, another mobile phone number.
271   }
272 
testGetLengthOfGeographicalAreaCode()273   public void testGetLengthOfGeographicalAreaCode() {
274     // Google MTV, which has area code "650".
275     assertEquals(3, phoneUtil.getLengthOfGeographicalAreaCode(US_NUMBER));
276 
277     // A North America toll-free number, which has no area code.
278     assertEquals(0, phoneUtil.getLengthOfGeographicalAreaCode(US_TOLLFREE));
279 
280     // Google London, which has area code "20".
281     assertEquals(2, phoneUtil.getLengthOfGeographicalAreaCode(GB_NUMBER));
282 
283     // A mobile number in the UK does not have an area code (by default, mobile numbers do not,
284     // unless they have been added to our list of exceptions).
285     assertEquals(0, phoneUtil.getLengthOfGeographicalAreaCode(GB_MOBILE));
286 
287     // Google Buenos Aires, which has area code "11".
288     assertEquals(2, phoneUtil.getLengthOfGeographicalAreaCode(AR_NUMBER));
289 
290     // A mobile number in Argentina also has an area code.
291     assertEquals(3, phoneUtil.getLengthOfGeographicalAreaCode(AR_MOBILE));
292 
293     // Google Sydney, which has area code "2".
294     assertEquals(1, phoneUtil.getLengthOfGeographicalAreaCode(AU_NUMBER));
295 
296     // Italian numbers - there is no national prefix, but it still has an area code.
297     assertEquals(2, phoneUtil.getLengthOfGeographicalAreaCode(IT_NUMBER));
298 
299     // Google Singapore. Singapore has no area code and no national prefix.
300     assertEquals(0, phoneUtil.getLengthOfGeographicalAreaCode(SG_NUMBER));
301 
302     // An invalid US number (1 digit shorter), which has no area code.
303     assertEquals(0, phoneUtil.getLengthOfGeographicalAreaCode(US_SHORT_BY_ONE_NUMBER));
304 
305     // An international toll free number, which has no area code.
306     assertEquals(0, phoneUtil.getLengthOfGeographicalAreaCode(INTERNATIONAL_TOLL_FREE));
307 
308     // A mobile number from China is geographical, but does not have an area code.
309     PhoneNumber cnMobile = new PhoneNumber().setCountryCode(86).setNationalNumber(18912341234L);
310     assertEquals(0, phoneUtil.getLengthOfGeographicalAreaCode(cnMobile));
311   }
312 
testGetLengthOfNationalDestinationCode()313   public void testGetLengthOfNationalDestinationCode() {
314     // Google MTV, which has national destination code (NDC) "650".
315     assertEquals(3, phoneUtil.getLengthOfNationalDestinationCode(US_NUMBER));
316 
317     // A North America toll-free number, which has NDC "800".
318     assertEquals(3, phoneUtil.getLengthOfNationalDestinationCode(US_TOLLFREE));
319 
320     // Google London, which has NDC "20".
321     assertEquals(2, phoneUtil.getLengthOfNationalDestinationCode(GB_NUMBER));
322 
323     // A UK mobile phone, which has NDC "7912".
324     assertEquals(4, phoneUtil.getLengthOfNationalDestinationCode(GB_MOBILE));
325 
326     // Google Buenos Aires, which has NDC "11".
327     assertEquals(2, phoneUtil.getLengthOfNationalDestinationCode(AR_NUMBER));
328 
329     // An Argentinian mobile which has NDC "911".
330     assertEquals(3, phoneUtil.getLengthOfNationalDestinationCode(AR_MOBILE));
331 
332     // Google Sydney, which has NDC "2".
333     assertEquals(1, phoneUtil.getLengthOfNationalDestinationCode(AU_NUMBER));
334 
335     // Google Singapore, which has NDC "6521".
336     assertEquals(4, phoneUtil.getLengthOfNationalDestinationCode(SG_NUMBER));
337 
338     // An invalid US number (1 digit shorter), which has no NDC.
339     assertEquals(0, phoneUtil.getLengthOfNationalDestinationCode(US_SHORT_BY_ONE_NUMBER));
340 
341     // A number containing an invalid country calling code, which shouldn't have any NDC.
342     PhoneNumber number = new PhoneNumber().setCountryCode(123).setNationalNumber(6502530000L);
343     assertEquals(0, phoneUtil.getLengthOfNationalDestinationCode(number));
344 
345     // An international toll free number, which has NDC "1234".
346     assertEquals(4, phoneUtil.getLengthOfNationalDestinationCode(INTERNATIONAL_TOLL_FREE));
347 
348     // A mobile number from China is geographical, but does not have an area code: however it still
349     // can be considered to have a national destination code.
350     PhoneNumber cnMobile = new PhoneNumber().setCountryCode(86).setNationalNumber(18912341234L);
351     assertEquals(3, phoneUtil.getLengthOfNationalDestinationCode(cnMobile));
352   }
353 
testGetCountryMobileToken()354   public void testGetCountryMobileToken() {
355     assertEquals("9", PhoneNumberUtil.getCountryMobileToken(phoneUtil.getCountryCodeForRegion(
356         RegionCode.AR)));
357 
358     // Country calling code for Sweden, which has no mobile token.
359     assertEquals("", PhoneNumberUtil.getCountryMobileToken(phoneUtil.getCountryCodeForRegion(
360         RegionCode.SE)));
361   }
362 
testGetNationalSignificantNumber()363   public void testGetNationalSignificantNumber() {
364     assertEquals("6502530000", phoneUtil.getNationalSignificantNumber(US_NUMBER));
365 
366     // An Italian mobile number.
367     assertEquals("345678901", phoneUtil.getNationalSignificantNumber(IT_MOBILE));
368 
369     // An Italian fixed line number.
370     assertEquals("0236618300", phoneUtil.getNationalSignificantNumber(IT_NUMBER));
371 
372     assertEquals("12345678", phoneUtil.getNationalSignificantNumber(INTERNATIONAL_TOLL_FREE));
373   }
374 
testGetNationalSignificantNumber_ManyLeadingZeros()375   public void testGetNationalSignificantNumber_ManyLeadingZeros() {
376     PhoneNumber number = new PhoneNumber();
377     number.setCountryCode(1);
378     number.setNationalNumber(650);
379     number.setItalianLeadingZero(true);
380     number.setNumberOfLeadingZeros(2);
381     assertEquals("00650", phoneUtil.getNationalSignificantNumber(number));
382 
383     // Set a bad value; we shouldn't crash, we shouldn't output any leading zeros at all.
384     number.setNumberOfLeadingZeros(-3);
385     assertEquals("650", phoneUtil.getNationalSignificantNumber(number));
386   }
387 
testGetExampleNumber()388   public void testGetExampleNumber() {
389     assertEquals(DE_NUMBER, phoneUtil.getExampleNumber(RegionCode.DE));
390 
391     assertEquals(
392         DE_NUMBER, phoneUtil.getExampleNumberForType(RegionCode.DE, PhoneNumberType.FIXED_LINE));
393     // Should return the same response if asked for FIXED_LINE_OR_MOBILE too.
394     assertEquals(DE_NUMBER,
395         phoneUtil.getExampleNumberForType(RegionCode.DE, PhoneNumberType.FIXED_LINE_OR_MOBILE));
396     assertNotNull(phoneUtil.getExampleNumberForType(RegionCode.US, PhoneNumberType.FIXED_LINE));
397     assertNotNull(phoneUtil.getExampleNumberForType(RegionCode.US, PhoneNumberType.MOBILE));
398 
399     // We have data for the US, but no data for VOICEMAIL, so return null.
400     assertNull(phoneUtil.getExampleNumberForType(RegionCode.US, PhoneNumberType.VOICEMAIL));
401     // CS is an invalid region, so we have no data for it.
402     assertNull(phoneUtil.getExampleNumberForType(RegionCode.CS, PhoneNumberType.MOBILE));
403     // RegionCode 001 is reserved for supporting non-geographical country calling code. We don't
404     // support getting an example number for it with this method.
405     assertNull(phoneUtil.getExampleNumber(RegionCode.UN001));
406   }
407 
testGetInvalidExampleNumber()408   public void testGetInvalidExampleNumber() {
409     // RegionCode 001 is reserved for supporting non-geographical country calling codes. We don't
410     // support getting an invalid example number for it with getInvalidExampleNumber.
411     assertNull(phoneUtil.getInvalidExampleNumber(RegionCode.UN001));
412     assertNull(phoneUtil.getInvalidExampleNumber(RegionCode.CS));
413     PhoneNumber usInvalidNumber = phoneUtil.getInvalidExampleNumber(RegionCode.US);
414     assertEquals(1, usInvalidNumber.getCountryCode());
415     assertFalse(usInvalidNumber.getNationalNumber() == 0);
416   }
417 
testGetExampleNumberForNonGeoEntity()418   public void testGetExampleNumberForNonGeoEntity() {
419     assertEquals(INTERNATIONAL_TOLL_FREE, phoneUtil.getExampleNumberForNonGeoEntity(800));
420     assertEquals(UNIVERSAL_PREMIUM_RATE, phoneUtil.getExampleNumberForNonGeoEntity(979));
421   }
422 
testGetExampleNumberWithoutRegion()423   public void testGetExampleNumberWithoutRegion() {
424     // In our test metadata we don't cover all types: in our real metadata, we do.
425     assertNotNull(phoneUtil.getExampleNumberForType(PhoneNumberType.FIXED_LINE));
426     assertNotNull(phoneUtil.getExampleNumberForType(PhoneNumberType.MOBILE));
427     assertNotNull(phoneUtil.getExampleNumberForType(PhoneNumberType.PREMIUM_RATE));
428   }
429 
testConvertAlphaCharactersInNumber()430   public void testConvertAlphaCharactersInNumber() {
431     String input = "1800-ABC-DEF";
432     // Alpha chars are converted to digits; everything else is left untouched.
433     String expectedOutput = "1800-222-333";
434     assertEquals(expectedOutput, PhoneNumberUtil.convertAlphaCharactersInNumber(input));
435   }
436 
testNormaliseRemovePunctuation()437   public void testNormaliseRemovePunctuation() {
438     StringBuilder inputNumber = new StringBuilder("034-56&+#2\u00AD34");
439     String expectedOutput = "03456234";
440     assertEquals("Conversion did not correctly remove punctuation",
441                  expectedOutput, PhoneNumberUtil.normalize(inputNumber).toString());
442   }
443 
testNormaliseReplaceAlphaCharacters()444   public void testNormaliseReplaceAlphaCharacters() {
445     StringBuilder inputNumber = new StringBuilder("034-I-am-HUNGRY");
446     String expectedOutput = "034426486479";
447     assertEquals("Conversion did not correctly replace alpha characters",
448                  expectedOutput, PhoneNumberUtil.normalize(inputNumber).toString());
449   }
450 
testNormaliseOtherDigits()451   public void testNormaliseOtherDigits() {
452     StringBuilder inputNumber = new StringBuilder("\uFF125\u0665");
453     String expectedOutput = "255";
454     assertEquals("Conversion did not correctly replace non-latin digits",
455                  expectedOutput, PhoneNumberUtil.normalize(inputNumber).toString());
456     // Eastern-Arabic digits.
457     inputNumber = new StringBuilder("\u06F52\u06F0");
458     expectedOutput = "520";
459     assertEquals("Conversion did not correctly replace non-latin digits",
460                  expectedOutput, PhoneNumberUtil.normalize(inputNumber).toString());
461   }
462 
testNormaliseStripAlphaCharacters()463   public void testNormaliseStripAlphaCharacters() {
464     String inputNumber = "034-56&+a#234";
465     String expectedOutput = "03456234";
466     assertEquals("Conversion did not correctly remove alpha character",
467                  expectedOutput,
468                  PhoneNumberUtil.normalizeDigitsOnly(inputNumber));
469   }
470 
testNormaliseStripNonDiallableCharacters()471   public void testNormaliseStripNonDiallableCharacters() {
472     String inputNumber = "03*4-56&+1a#234";
473     String expectedOutput = "03*456+1#234";
474     assertEquals("Conversion did not correctly remove non-diallable characters",
475                  expectedOutput,
476                  PhoneNumberUtil.normalizeDiallableCharsOnly(inputNumber));
477   }
478 
testFormatUSNumber()479   public void testFormatUSNumber() {
480     assertEquals("650 253 0000", phoneUtil.format(US_NUMBER, PhoneNumberFormat.NATIONAL));
481     assertEquals("+1 650 253 0000", phoneUtil.format(US_NUMBER, PhoneNumberFormat.INTERNATIONAL));
482 
483     assertEquals("800 253 0000", phoneUtil.format(US_TOLLFREE, PhoneNumberFormat.NATIONAL));
484     assertEquals("+1 800 253 0000", phoneUtil.format(US_TOLLFREE, PhoneNumberFormat.INTERNATIONAL));
485 
486     assertEquals("900 253 0000", phoneUtil.format(US_PREMIUM, PhoneNumberFormat.NATIONAL));
487     assertEquals("+1 900 253 0000", phoneUtil.format(US_PREMIUM, PhoneNumberFormat.INTERNATIONAL));
488     assertEquals("tel:+1-900-253-0000", phoneUtil.format(US_PREMIUM, PhoneNumberFormat.RFC3966));
489     // Numbers with all zeros in the national number part will be formatted by using the raw_input
490     // if that is available no matter which format is specified.
491     assertEquals("000-000-0000",
492                  phoneUtil.format(US_SPOOF_WITH_RAW_INPUT, PhoneNumberFormat.NATIONAL));
493     assertEquals("0", phoneUtil.format(US_SPOOF, PhoneNumberFormat.NATIONAL));
494   }
495 
testFormatBSNumber()496   public void testFormatBSNumber() {
497     assertEquals("242 365 1234", phoneUtil.format(BS_NUMBER, PhoneNumberFormat.NATIONAL));
498     assertEquals("+1 242 365 1234", phoneUtil.format(BS_NUMBER, PhoneNumberFormat.INTERNATIONAL));
499   }
500 
testFormatGBNumber()501   public void testFormatGBNumber() {
502     assertEquals("(020) 7031 3000", phoneUtil.format(GB_NUMBER, PhoneNumberFormat.NATIONAL));
503     assertEquals("+44 20 7031 3000", phoneUtil.format(GB_NUMBER, PhoneNumberFormat.INTERNATIONAL));
504 
505     assertEquals("(07912) 345 678", phoneUtil.format(GB_MOBILE, PhoneNumberFormat.NATIONAL));
506     assertEquals("+44 7912 345 678", phoneUtil.format(GB_MOBILE, PhoneNumberFormat.INTERNATIONAL));
507   }
508 
testFormatDENumber()509   public void testFormatDENumber() {
510     PhoneNumber deNumber = new PhoneNumber();
511     deNumber.setCountryCode(49).setNationalNumber(301234L);
512     assertEquals("030/1234", phoneUtil.format(deNumber, PhoneNumberFormat.NATIONAL));
513     assertEquals("+49 30/1234", phoneUtil.format(deNumber, PhoneNumberFormat.INTERNATIONAL));
514     assertEquals("tel:+49-30-1234", phoneUtil.format(deNumber, PhoneNumberFormat.RFC3966));
515 
516     deNumber.clear();
517     deNumber.setCountryCode(49).setNationalNumber(291123L);
518     assertEquals("0291 123", phoneUtil.format(deNumber, PhoneNumberFormat.NATIONAL));
519     assertEquals("+49 291 123", phoneUtil.format(deNumber, PhoneNumberFormat.INTERNATIONAL));
520 
521     deNumber.clear();
522     deNumber.setCountryCode(49).setNationalNumber(29112345678L);
523     assertEquals("0291 12345678", phoneUtil.format(deNumber, PhoneNumberFormat.NATIONAL));
524     assertEquals("+49 291 12345678", phoneUtil.format(deNumber, PhoneNumberFormat.INTERNATIONAL));
525 
526     deNumber.clear();
527     deNumber.setCountryCode(49).setNationalNumber(912312345L);
528     assertEquals("09123 12345", phoneUtil.format(deNumber, PhoneNumberFormat.NATIONAL));
529     assertEquals("+49 9123 12345", phoneUtil.format(deNumber, PhoneNumberFormat.INTERNATIONAL));
530     deNumber.clear();
531     deNumber.setCountryCode(49).setNationalNumber(80212345L);
532     assertEquals("08021 2345", phoneUtil.format(deNumber, PhoneNumberFormat.NATIONAL));
533     assertEquals("+49 8021 2345", phoneUtil.format(deNumber, PhoneNumberFormat.INTERNATIONAL));
534     // Note this number is correctly formatted without national prefix. Most of the numbers that
535     // are treated as invalid numbers by the library are short numbers, and they are usually not
536     // dialed with national prefix.
537     assertEquals("1234", phoneUtil.format(DE_SHORT_NUMBER, PhoneNumberFormat.NATIONAL));
538     assertEquals("+49 1234", phoneUtil.format(DE_SHORT_NUMBER, PhoneNumberFormat.INTERNATIONAL));
539 
540     deNumber.clear();
541     deNumber.setCountryCode(49).setNationalNumber(41341234);
542     assertEquals("04134 1234", phoneUtil.format(deNumber, PhoneNumberFormat.NATIONAL));
543   }
544 
testFormatITNumber()545   public void testFormatITNumber() {
546     assertEquals("02 3661 8300", phoneUtil.format(IT_NUMBER, PhoneNumberFormat.NATIONAL));
547     assertEquals("+39 02 3661 8300", phoneUtil.format(IT_NUMBER, PhoneNumberFormat.INTERNATIONAL));
548     assertEquals("+390236618300", phoneUtil.format(IT_NUMBER, PhoneNumberFormat.E164));
549 
550     assertEquals("345 678 901", phoneUtil.format(IT_MOBILE, PhoneNumberFormat.NATIONAL));
551     assertEquals("+39 345 678 901", phoneUtil.format(IT_MOBILE, PhoneNumberFormat.INTERNATIONAL));
552     assertEquals("+39345678901", phoneUtil.format(IT_MOBILE, PhoneNumberFormat.E164));
553   }
554 
testFormatAUNumber()555   public void testFormatAUNumber() {
556     assertEquals("02 3661 8300", phoneUtil.format(AU_NUMBER, PhoneNumberFormat.NATIONAL));
557     assertEquals("+61 2 3661 8300", phoneUtil.format(AU_NUMBER, PhoneNumberFormat.INTERNATIONAL));
558     assertEquals("+61236618300", phoneUtil.format(AU_NUMBER, PhoneNumberFormat.E164));
559 
560     PhoneNumber auNumber = new PhoneNumber().setCountryCode(61).setNationalNumber(1800123456L);
561     assertEquals("1800 123 456", phoneUtil.format(auNumber, PhoneNumberFormat.NATIONAL));
562     assertEquals("+61 1800 123 456", phoneUtil.format(auNumber, PhoneNumberFormat.INTERNATIONAL));
563     assertEquals("+611800123456", phoneUtil.format(auNumber, PhoneNumberFormat.E164));
564   }
565 
testFormatARNumber()566   public void testFormatARNumber() {
567     assertEquals("011 8765-4321", phoneUtil.format(AR_NUMBER, PhoneNumberFormat.NATIONAL));
568     assertEquals("+54 11 8765-4321", phoneUtil.format(AR_NUMBER, PhoneNumberFormat.INTERNATIONAL));
569     assertEquals("+541187654321", phoneUtil.format(AR_NUMBER, PhoneNumberFormat.E164));
570 
571     assertEquals("011 15 8765-4321", phoneUtil.format(AR_MOBILE, PhoneNumberFormat.NATIONAL));
572     assertEquals("+54 9 11 8765 4321", phoneUtil.format(AR_MOBILE,
573                                                         PhoneNumberFormat.INTERNATIONAL));
574     assertEquals("+5491187654321", phoneUtil.format(AR_MOBILE, PhoneNumberFormat.E164));
575   }
576 
testFormatMXNumber()577   public void testFormatMXNumber() {
578     assertEquals("045 234 567 8900", phoneUtil.format(MX_MOBILE1, PhoneNumberFormat.NATIONAL));
579     assertEquals("+52 1 234 567 8900", phoneUtil.format(
580         MX_MOBILE1, PhoneNumberFormat.INTERNATIONAL));
581     assertEquals("+5212345678900", phoneUtil.format(MX_MOBILE1, PhoneNumberFormat.E164));
582 
583     assertEquals("045 55 1234 5678", phoneUtil.format(MX_MOBILE2, PhoneNumberFormat.NATIONAL));
584     assertEquals("+52 1 55 1234 5678", phoneUtil.format(
585         MX_MOBILE2, PhoneNumberFormat.INTERNATIONAL));
586     assertEquals("+5215512345678", phoneUtil.format(MX_MOBILE2, PhoneNumberFormat.E164));
587 
588     assertEquals("01 33 1234 5678", phoneUtil.format(MX_NUMBER1, PhoneNumberFormat.NATIONAL));
589     assertEquals("+52 33 1234 5678", phoneUtil.format(MX_NUMBER1, PhoneNumberFormat.INTERNATIONAL));
590     assertEquals("+523312345678", phoneUtil.format(MX_NUMBER1, PhoneNumberFormat.E164));
591 
592     assertEquals("01 821 123 4567", phoneUtil.format(MX_NUMBER2, PhoneNumberFormat.NATIONAL));
593     assertEquals("+52 821 123 4567", phoneUtil.format(MX_NUMBER2, PhoneNumberFormat.INTERNATIONAL));
594     assertEquals("+528211234567", phoneUtil.format(MX_NUMBER2, PhoneNumberFormat.E164));
595   }
596 
testFormatOutOfCountryCallingNumber()597   public void testFormatOutOfCountryCallingNumber() {
598     assertEquals("00 1 900 253 0000",
599                  phoneUtil.formatOutOfCountryCallingNumber(US_PREMIUM, RegionCode.DE));
600 
601     assertEquals("1 650 253 0000",
602                  phoneUtil.formatOutOfCountryCallingNumber(US_NUMBER, RegionCode.BS));
603 
604     assertEquals("00 1 650 253 0000",
605                  phoneUtil.formatOutOfCountryCallingNumber(US_NUMBER, RegionCode.PL));
606 
607     assertEquals("011 44 7912 345 678",
608                  phoneUtil.formatOutOfCountryCallingNumber(GB_MOBILE, RegionCode.US));
609 
610     assertEquals("00 49 1234",
611                  phoneUtil.formatOutOfCountryCallingNumber(DE_SHORT_NUMBER, RegionCode.GB));
612     // Note this number is correctly formatted without national prefix. Most of the numbers that
613     // are treated as invalid numbers by the library are short numbers, and they are usually not
614     // dialed with national prefix.
615     assertEquals("1234", phoneUtil.formatOutOfCountryCallingNumber(DE_SHORT_NUMBER, RegionCode.DE));
616 
617     assertEquals("011 39 02 3661 8300",
618                  phoneUtil.formatOutOfCountryCallingNumber(IT_NUMBER, RegionCode.US));
619     assertEquals("02 3661 8300",
620                  phoneUtil.formatOutOfCountryCallingNumber(IT_NUMBER, RegionCode.IT));
621     assertEquals("+39 02 3661 8300",
622                  phoneUtil.formatOutOfCountryCallingNumber(IT_NUMBER, RegionCode.SG));
623 
624     assertEquals("6521 8000",
625                  phoneUtil.formatOutOfCountryCallingNumber(SG_NUMBER, RegionCode.SG));
626 
627     assertEquals("011 54 9 11 8765 4321",
628                  phoneUtil.formatOutOfCountryCallingNumber(AR_MOBILE, RegionCode.US));
629     assertEquals("011 800 1234 5678",
630                  phoneUtil.formatOutOfCountryCallingNumber(INTERNATIONAL_TOLL_FREE, RegionCode.US));
631 
632     PhoneNumber arNumberWithExtn = new PhoneNumber().mergeFrom(AR_MOBILE).setExtension("1234");
633     assertEquals("011 54 9 11 8765 4321 ext. 1234",
634                  phoneUtil.formatOutOfCountryCallingNumber(arNumberWithExtn, RegionCode.US));
635     assertEquals("0011 54 9 11 8765 4321 ext. 1234",
636                  phoneUtil.formatOutOfCountryCallingNumber(arNumberWithExtn, RegionCode.AU));
637     assertEquals("011 15 8765-4321 ext. 1234",
638                  phoneUtil.formatOutOfCountryCallingNumber(arNumberWithExtn, RegionCode.AR));
639   }
640 
testFormatOutOfCountryWithInvalidRegion()641   public void testFormatOutOfCountryWithInvalidRegion() {
642     // AQ/Antarctica isn't a valid region code for phone number formatting,
643     // so this falls back to intl formatting.
644     assertEquals("+1 650 253 0000",
645                  phoneUtil.formatOutOfCountryCallingNumber(US_NUMBER, RegionCode.AQ));
646     // For region code 001, the out-of-country format always turns into the international format.
647     assertEquals("+1 650 253 0000",
648                  phoneUtil.formatOutOfCountryCallingNumber(US_NUMBER, RegionCode.UN001));
649   }
650 
testFormatOutOfCountryWithPreferredIntlPrefix()651   public void testFormatOutOfCountryWithPreferredIntlPrefix() {
652     // This should use 0011, since that is the preferred international prefix (both 0011 and 0012
653     // are accepted as possible international prefixes in our test metadta.)
654     assertEquals("0011 39 02 3661 8300",
655                  phoneUtil.formatOutOfCountryCallingNumber(IT_NUMBER, RegionCode.AU));
656   }
657 
testFormatOutOfCountryKeepingAlphaChars()658   public void testFormatOutOfCountryKeepingAlphaChars() {
659     PhoneNumber alphaNumericNumber = new PhoneNumber();
660     alphaNumericNumber.setCountryCode(1).setNationalNumber(8007493524L)
661         .setRawInput("1800 six-flag");
662     assertEquals("0011 1 800 SIX-FLAG",
663                  phoneUtil.formatOutOfCountryKeepingAlphaChars(alphaNumericNumber, RegionCode.AU));
664 
665     alphaNumericNumber.setRawInput("1-800-SIX-flag");
666     assertEquals("0011 1 800-SIX-FLAG",
667                  phoneUtil.formatOutOfCountryKeepingAlphaChars(alphaNumericNumber, RegionCode.AU));
668 
669     alphaNumericNumber.setRawInput("Call us from UK: 00 1 800 SIX-flag");
670     assertEquals("0011 1 800 SIX-FLAG",
671                  phoneUtil.formatOutOfCountryKeepingAlphaChars(alphaNumericNumber, RegionCode.AU));
672 
673     alphaNumericNumber.setRawInput("800 SIX-flag");
674     assertEquals("0011 1 800 SIX-FLAG",
675                  phoneUtil.formatOutOfCountryKeepingAlphaChars(alphaNumericNumber, RegionCode.AU));
676 
677     // Formatting from within the NANPA region.
678     assertEquals("1 800 SIX-FLAG",
679                  phoneUtil.formatOutOfCountryKeepingAlphaChars(alphaNumericNumber, RegionCode.US));
680 
681     assertEquals("1 800 SIX-FLAG",
682                  phoneUtil.formatOutOfCountryKeepingAlphaChars(alphaNumericNumber, RegionCode.BS));
683 
684     // Testing that if the raw input doesn't exist, it is formatted using
685     // formatOutOfCountryCallingNumber.
686     alphaNumericNumber.clearRawInput();
687     assertEquals("00 1 800 749 3524",
688                  phoneUtil.formatOutOfCountryKeepingAlphaChars(alphaNumericNumber, RegionCode.DE));
689 
690     // Testing AU alpha number formatted from Australia.
691     alphaNumericNumber.setCountryCode(61).setNationalNumber(827493524L)
692         .setRawInput("+61 82749-FLAG");
693     // This number should have the national prefix fixed.
694     assertEquals("082749-FLAG",
695                  phoneUtil.formatOutOfCountryKeepingAlphaChars(alphaNumericNumber, RegionCode.AU));
696 
697     alphaNumericNumber.setRawInput("082749-FLAG");
698     assertEquals("082749-FLAG",
699                  phoneUtil.formatOutOfCountryKeepingAlphaChars(alphaNumericNumber, RegionCode.AU));
700 
701     alphaNumericNumber.setNationalNumber(18007493524L).setRawInput("1-800-SIX-flag");
702     // This number should not have the national prefix prefixed, in accordance with the override for
703     // this specific formatting rule.
704     assertEquals("1-800-SIX-FLAG",
705                  phoneUtil.formatOutOfCountryKeepingAlphaChars(alphaNumericNumber, RegionCode.AU));
706 
707     // The metadata should not be permanently changed, since we copied it before modifying patterns.
708     // Here we check this.
709     alphaNumericNumber.setNationalNumber(1800749352L);
710     assertEquals("1800 749 352",
711                  phoneUtil.formatOutOfCountryCallingNumber(alphaNumericNumber, RegionCode.AU));
712 
713     // Testing a region with multiple international prefixes.
714     assertEquals("+61 1-800-SIX-FLAG",
715                  phoneUtil.formatOutOfCountryKeepingAlphaChars(alphaNumericNumber, RegionCode.SG));
716     // Testing the case of calling from a non-supported region.
717     assertEquals("+61 1-800-SIX-FLAG",
718                  phoneUtil.formatOutOfCountryKeepingAlphaChars(alphaNumericNumber, RegionCode.AQ));
719 
720     // Testing the case with an invalid country calling code.
721     alphaNumericNumber.setCountryCode(0).setNationalNumber(18007493524L)
722         .setRawInput("1-800-SIX-flag");
723     // Uses the raw input only.
724     assertEquals("1-800-SIX-flag",
725                  phoneUtil.formatOutOfCountryKeepingAlphaChars(alphaNumericNumber, RegionCode.DE));
726 
727     // Testing the case of an invalid alpha number.
728     alphaNumericNumber.setCountryCode(1).setNationalNumber(80749L).setRawInput("180-SIX");
729     // No country-code stripping can be done.
730     assertEquals("00 1 180-SIX",
731                  phoneUtil.formatOutOfCountryKeepingAlphaChars(alphaNumericNumber, RegionCode.DE));
732 
733     // Testing the case of calling from a non-supported region.
734     alphaNumericNumber.setCountryCode(1).setNationalNumber(80749L).setRawInput("180-SIX");
735     // No country-code stripping can be done since the number is invalid.
736     assertEquals("+1 180-SIX",
737                  phoneUtil.formatOutOfCountryKeepingAlphaChars(alphaNumericNumber, RegionCode.AQ));
738   }
739 
testFormatWithCarrierCode()740   public void testFormatWithCarrierCode() {
741     // We only support this for AR in our test metadata, and only for mobile numbers starting with
742     // certain values.
743     PhoneNumber arMobile = new PhoneNumber().setCountryCode(54).setNationalNumber(92234654321L);
744     assertEquals("02234 65-4321", phoneUtil.format(arMobile, PhoneNumberFormat.NATIONAL));
745     // Here we force 14 as the carrier code.
746     assertEquals("02234 14 65-4321",
747                  phoneUtil.formatNationalNumberWithCarrierCode(arMobile, "14"));
748     // Here we force the number to be shown with no carrier code.
749     assertEquals("02234 65-4321",
750                  phoneUtil.formatNationalNumberWithCarrierCode(arMobile, ""));
751     // Here the international rule is used, so no carrier code should be present.
752     assertEquals("+5492234654321", phoneUtil.format(arMobile, PhoneNumberFormat.E164));
753     // We don't support this for the US so there should be no change.
754     assertEquals("650 253 0000", phoneUtil.formatNationalNumberWithCarrierCode(US_NUMBER, "15"));
755 
756     // Invalid country code should just get the NSN.
757     assertEquals("12345",
758         phoneUtil.formatNationalNumberWithCarrierCode(UNKNOWN_COUNTRY_CODE_NO_RAW_INPUT, "89"));
759   }
760 
testFormatWithPreferredCarrierCode()761   public void testFormatWithPreferredCarrierCode() {
762     // We only support this for AR in our test metadata.
763     PhoneNumber arNumber = new PhoneNumber();
764     arNumber.setCountryCode(54).setNationalNumber(91234125678L);
765     // Test formatting with no preferred carrier code stored in the number itself.
766     assertEquals("01234 15 12-5678",
767         phoneUtil.formatNationalNumberWithPreferredCarrierCode(arNumber, "15"));
768     assertEquals("01234 12-5678",
769         phoneUtil.formatNationalNumberWithPreferredCarrierCode(arNumber, ""));
770     // Test formatting with preferred carrier code present.
771     arNumber.setPreferredDomesticCarrierCode("19");
772     assertEquals("01234 12-5678", phoneUtil.format(arNumber, PhoneNumberFormat.NATIONAL));
773     assertEquals("01234 19 12-5678",
774         phoneUtil.formatNationalNumberWithPreferredCarrierCode(arNumber, "15"));
775     assertEquals("01234 19 12-5678",
776         phoneUtil.formatNationalNumberWithPreferredCarrierCode(arNumber, ""));
777     // When the preferred_domestic_carrier_code is present (even when it is just a space), use it
778     // instead of the default carrier code passed in.
779     arNumber.setPreferredDomesticCarrierCode(" ");
780     assertEquals("01234   12-5678",
781         phoneUtil.formatNationalNumberWithPreferredCarrierCode(arNumber, "15"));
782     // When the preferred_domestic_carrier_code is present but empty, treat it as unset and use
783     // instead the default carrier code passed in.
784     arNumber.setPreferredDomesticCarrierCode("");
785     assertEquals("01234 15 12-5678",
786         phoneUtil.formatNationalNumberWithPreferredCarrierCode(arNumber, "15"));
787     // We don't support this for the US so there should be no change.
788     PhoneNumber usNumber = new PhoneNumber();
789     usNumber.setCountryCode(1).setNationalNumber(4241231234L).setPreferredDomesticCarrierCode("99");
790     assertEquals("424 123 1234", phoneUtil.format(usNumber, PhoneNumberFormat.NATIONAL));
791     assertEquals("424 123 1234",
792         phoneUtil.formatNationalNumberWithPreferredCarrierCode(usNumber, "15"));
793   }
794 
testFormatNumberForMobileDialing()795   public void testFormatNumberForMobileDialing() {
796     // Numbers are normally dialed in national format in-country, and international format from
797     // outside the country.
798     assertEquals("030123456",
799         phoneUtil.formatNumberForMobileDialing(DE_NUMBER, RegionCode.DE, false));
800     assertEquals("+4930123456",
801         phoneUtil.formatNumberForMobileDialing(DE_NUMBER, RegionCode.CH, false));
802     PhoneNumber deNumberWithExtn = new PhoneNumber().mergeFrom(DE_NUMBER).setExtension("1234");
803     assertEquals("030123456",
804         phoneUtil.formatNumberForMobileDialing(deNumberWithExtn, RegionCode.DE, false));
805     assertEquals("+4930123456",
806         phoneUtil.formatNumberForMobileDialing(deNumberWithExtn, RegionCode.CH, false));
807 
808     // US toll free numbers are marked as noInternationalDialling in the test metadata for testing
809     // purposes. For such numbers, we expect nothing to be returned when the region code is not the
810     // same one.
811     assertEquals("800 253 0000",
812         phoneUtil.formatNumberForMobileDialing(US_TOLLFREE, RegionCode.US,
813                                                true /*  keep formatting */));
814     assertEquals("", phoneUtil.formatNumberForMobileDialing(US_TOLLFREE, RegionCode.CN, true));
815     assertEquals("+1 650 253 0000",
816         phoneUtil.formatNumberForMobileDialing(US_NUMBER, RegionCode.US, true));
817     PhoneNumber usNumberWithExtn = new PhoneNumber().mergeFrom(US_NUMBER).setExtension("1234");
818     assertEquals("+1 650 253 0000",
819         phoneUtil.formatNumberForMobileDialing(usNumberWithExtn, RegionCode.US, true));
820 
821     assertEquals("8002530000",
822         phoneUtil.formatNumberForMobileDialing(US_TOLLFREE, RegionCode.US,
823                                                false /* remove formatting */));
824     assertEquals("", phoneUtil.formatNumberForMobileDialing(US_TOLLFREE, RegionCode.CN, false));
825     assertEquals("+16502530000",
826         phoneUtil.formatNumberForMobileDialing(US_NUMBER, RegionCode.US, false));
827     assertEquals("+16502530000",
828         phoneUtil.formatNumberForMobileDialing(usNumberWithExtn, RegionCode.US, false));
829 
830     // An invalid US number, which is one digit too long.
831     assertEquals("+165025300001",
832         phoneUtil.formatNumberForMobileDialing(US_LONG_NUMBER, RegionCode.US, false));
833     assertEquals("+1 65025300001",
834         phoneUtil.formatNumberForMobileDialing(US_LONG_NUMBER, RegionCode.US, true));
835 
836     // Star numbers. In real life they appear in Israel, but we have them in JP in our test
837     // metadata.
838     assertEquals("*2345",
839         phoneUtil.formatNumberForMobileDialing(JP_STAR_NUMBER, RegionCode.JP, false));
840     assertEquals("*2345",
841         phoneUtil.formatNumberForMobileDialing(JP_STAR_NUMBER, RegionCode.JP, true));
842 
843     assertEquals("+80012345678",
844         phoneUtil.formatNumberForMobileDialing(INTERNATIONAL_TOLL_FREE, RegionCode.JP, false));
845     assertEquals("+800 1234 5678",
846         phoneUtil.formatNumberForMobileDialing(INTERNATIONAL_TOLL_FREE, RegionCode.JP, true));
847 
848     // UAE numbers beginning with 600 (classified as UAN) need to be dialled without +971 locally.
849     assertEquals("+971600123456",
850         phoneUtil.formatNumberForMobileDialing(AE_UAN, RegionCode.JP, false));
851     assertEquals("600123456",
852         phoneUtil.formatNumberForMobileDialing(AE_UAN, RegionCode.AE, false));
853 
854     assertEquals("+523312345678",
855         phoneUtil.formatNumberForMobileDialing(MX_NUMBER1, RegionCode.MX, false));
856     assertEquals("+523312345678",
857         phoneUtil.formatNumberForMobileDialing(MX_NUMBER1, RegionCode.US, false));
858 
859     // Test whether Uzbek phone numbers are returned in international format even when dialled from
860     // same region or other regions.
861     assertEquals("+998612201234",
862         phoneUtil.formatNumberForMobileDialing(UZ_FIXED_LINE, RegionCode.UZ, false));
863     assertEquals("+998950123456",
864         phoneUtil.formatNumberForMobileDialing(UZ_MOBILE, RegionCode.UZ, false));
865     assertEquals("+998950123456",
866         phoneUtil.formatNumberForMobileDialing(UZ_MOBILE, RegionCode.US, false));
867 
868     // Non-geographical numbers should always be dialed in international format.
869     assertEquals("+80012345678",
870         phoneUtil.formatNumberForMobileDialing(INTERNATIONAL_TOLL_FREE, RegionCode.US, false));
871     assertEquals("+80012345678",
872         phoneUtil.formatNumberForMobileDialing(INTERNATIONAL_TOLL_FREE, RegionCode.UN001, false));
873 
874     // Test that a short number is formatted correctly for mobile dialing within the region,
875     // and is not diallable from outside the region.
876     PhoneNumber deShortNumber = new PhoneNumber().setCountryCode(49).setNationalNumber(123L);
877     assertEquals("123", phoneUtil.formatNumberForMobileDialing(deShortNumber, RegionCode.DE,
878         false));
879     assertEquals("", phoneUtil.formatNumberForMobileDialing(deShortNumber, RegionCode.IT, false));
880 
881     // Test the special logic for NANPA countries, for which regular length phone numbers are always
882     // output in international format, but short numbers are in national format.
883     assertEquals("+16502530000", phoneUtil.formatNumberForMobileDialing(US_NUMBER,
884         RegionCode.US, false));
885     assertEquals("+16502530000", phoneUtil.formatNumberForMobileDialing(US_NUMBER,
886         RegionCode.CA, false));
887     assertEquals("+16502530000", phoneUtil.formatNumberForMobileDialing(US_NUMBER,
888         RegionCode.BR, false));
889     PhoneNumber usShortNumber = new PhoneNumber().setCountryCode(1).setNationalNumber(911L);
890     assertEquals("911", phoneUtil.formatNumberForMobileDialing(usShortNumber, RegionCode.US,
891         false));
892     assertEquals("", phoneUtil.formatNumberForMobileDialing(usShortNumber, RegionCode.CA, false));
893     assertEquals("", phoneUtil.formatNumberForMobileDialing(usShortNumber, RegionCode.BR, false));
894 
895     // Test that the Australian emergency number 000 is formatted correctly.
896     PhoneNumber auNumber = new PhoneNumber().setCountryCode(61).setNationalNumber(0L)
897         .setItalianLeadingZero(true).setNumberOfLeadingZeros(2);
898     assertEquals("000", phoneUtil.formatNumberForMobileDialing(auNumber, RegionCode.AU, false));
899     assertEquals("", phoneUtil.formatNumberForMobileDialing(auNumber, RegionCode.NZ, false));
900   }
901 
testFormatByPattern()902   public void testFormatByPattern() {
903     NumberFormat newNumFormat = new NumberFormat();
904     newNumFormat.setPattern("(\\d{3})(\\d{3})(\\d{4})");
905     newNumFormat.setFormat("($1) $2-$3");
906     List<NumberFormat> newNumberFormats = new ArrayList<NumberFormat>();
907     newNumberFormats.add(newNumFormat);
908 
909     assertEquals("(650) 253-0000", phoneUtil.formatByPattern(US_NUMBER, PhoneNumberFormat.NATIONAL,
910                                                              newNumberFormats));
911     assertEquals("+1 (650) 253-0000", phoneUtil.formatByPattern(US_NUMBER,
912                                                                 PhoneNumberFormat.INTERNATIONAL,
913                                                                 newNumberFormats));
914     assertEquals("tel:+1-650-253-0000", phoneUtil.formatByPattern(US_NUMBER,
915                                                                   PhoneNumberFormat.RFC3966,
916                                                                   newNumberFormats));
917 
918     // $NP is set to '1' for the US. Here we check that for other NANPA countries the US rules are
919     // followed.
920     newNumFormat.setNationalPrefixFormattingRule("$NP ($FG)");
921     newNumFormat.setFormat("$1 $2-$3");
922     assertEquals("1 (242) 365-1234",
923                  phoneUtil.formatByPattern(BS_NUMBER, PhoneNumberFormat.NATIONAL,
924                                            newNumberFormats));
925     assertEquals("+1 242 365-1234",
926                  phoneUtil.formatByPattern(BS_NUMBER, PhoneNumberFormat.INTERNATIONAL,
927                                            newNumberFormats));
928 
929     newNumFormat.setPattern("(\\d{2})(\\d{5})(\\d{3})");
930     newNumFormat.setFormat("$1-$2 $3");
931     newNumberFormats.set(0, newNumFormat);
932 
933     assertEquals("02-36618 300",
934                  phoneUtil.formatByPattern(IT_NUMBER, PhoneNumberFormat.NATIONAL,
935                                            newNumberFormats));
936     assertEquals("+39 02-36618 300",
937                  phoneUtil.formatByPattern(IT_NUMBER, PhoneNumberFormat.INTERNATIONAL,
938                                            newNumberFormats));
939 
940     newNumFormat.setNationalPrefixFormattingRule("$NP$FG");
941     newNumFormat.setPattern("(\\d{2})(\\d{4})(\\d{4})");
942     newNumFormat.setFormat("$1 $2 $3");
943     newNumberFormats.set(0, newNumFormat);
944     assertEquals("020 7031 3000",
945                  phoneUtil.formatByPattern(GB_NUMBER, PhoneNumberFormat.NATIONAL,
946                                            newNumberFormats));
947 
948     newNumFormat.setNationalPrefixFormattingRule("($NP$FG)");
949     assertEquals("(020) 7031 3000",
950                  phoneUtil.formatByPattern(GB_NUMBER, PhoneNumberFormat.NATIONAL,
951                                            newNumberFormats));
952 
953     newNumFormat.setNationalPrefixFormattingRule("");
954     assertEquals("20 7031 3000",
955                  phoneUtil.formatByPattern(GB_NUMBER, PhoneNumberFormat.NATIONAL,
956                                            newNumberFormats));
957 
958     assertEquals("+44 20 7031 3000",
959                  phoneUtil.formatByPattern(GB_NUMBER, PhoneNumberFormat.INTERNATIONAL,
960                                            newNumberFormats));
961   }
962 
testFormatE164Number()963   public void testFormatE164Number() {
964     assertEquals("+16502530000", phoneUtil.format(US_NUMBER, PhoneNumberFormat.E164));
965     assertEquals("+4930123456", phoneUtil.format(DE_NUMBER, PhoneNumberFormat.E164));
966     assertEquals("+80012345678", phoneUtil.format(INTERNATIONAL_TOLL_FREE, PhoneNumberFormat.E164));
967   }
968 
testFormatNumberWithExtension()969   public void testFormatNumberWithExtension() {
970     PhoneNumber nzNumber = new PhoneNumber().mergeFrom(NZ_NUMBER).setExtension("1234");
971     // Uses default extension prefix:
972     assertEquals("03-331 6005 ext. 1234", phoneUtil.format(nzNumber, PhoneNumberFormat.NATIONAL));
973     // Uses RFC 3966 syntax.
974     assertEquals("tel:+64-3-331-6005;ext=1234",
975         phoneUtil.format(nzNumber, PhoneNumberFormat.RFC3966));
976     // Extension prefix overridden in the territory information for the US:
977     PhoneNumber usNumberWithExtension = new PhoneNumber().mergeFrom(US_NUMBER).setExtension("4567");
978     assertEquals("650 253 0000 extn. 4567", phoneUtil.format(usNumberWithExtension,
979                                                              PhoneNumberFormat.NATIONAL));
980   }
981 
testFormatInOriginalFormat()982   public void testFormatInOriginalFormat() throws Exception {
983     PhoneNumber number1 = phoneUtil.parseAndKeepRawInput("+442087654321", RegionCode.GB);
984     assertEquals("+44 20 8765 4321", phoneUtil.formatInOriginalFormat(number1, RegionCode.GB));
985 
986     PhoneNumber number2 = phoneUtil.parseAndKeepRawInput("02087654321", RegionCode.GB);
987     assertEquals("(020) 8765 4321", phoneUtil.formatInOriginalFormat(number2, RegionCode.GB));
988 
989     PhoneNumber number3 = phoneUtil.parseAndKeepRawInput("011442087654321", RegionCode.US);
990     assertEquals("011 44 20 8765 4321", phoneUtil.formatInOriginalFormat(number3, RegionCode.US));
991 
992     PhoneNumber number4 = phoneUtil.parseAndKeepRawInput("442087654321", RegionCode.GB);
993     assertEquals("44 20 8765 4321", phoneUtil.formatInOriginalFormat(number4, RegionCode.GB));
994 
995     PhoneNumber number5 = phoneUtil.parse("+442087654321", RegionCode.GB);
996     assertEquals("(020) 8765 4321", phoneUtil.formatInOriginalFormat(number5, RegionCode.GB));
997 
998     // Invalid numbers that we have a formatting pattern for should be formatted properly. Note area
999     // codes starting with 7 are intentionally excluded in the test metadata for testing purposes.
1000     PhoneNumber number6 = phoneUtil.parseAndKeepRawInput("7345678901", RegionCode.US);
1001     assertEquals("734 567 8901", phoneUtil.formatInOriginalFormat(number6, RegionCode.US));
1002 
1003     // US is not a leading zero country, and the presence of the leading zero leads us to format the
1004     // number using raw_input.
1005     PhoneNumber number7 = phoneUtil.parseAndKeepRawInput("0734567 8901", RegionCode.US);
1006     assertEquals("0734567 8901", phoneUtil.formatInOriginalFormat(number7, RegionCode.US));
1007 
1008     // This number is valid, but we don't have a formatting pattern for it. Fall back to the raw
1009     // input.
1010     PhoneNumber number8 = phoneUtil.parseAndKeepRawInput("02-4567-8900", RegionCode.KR);
1011     assertEquals("02-4567-8900", phoneUtil.formatInOriginalFormat(number8, RegionCode.KR));
1012 
1013     PhoneNumber number9 = phoneUtil.parseAndKeepRawInput("01180012345678", RegionCode.US);
1014     assertEquals("011 800 1234 5678", phoneUtil.formatInOriginalFormat(number9, RegionCode.US));
1015 
1016     PhoneNumber number10 = phoneUtil.parseAndKeepRawInput("+80012345678", RegionCode.KR);
1017     assertEquals("+800 1234 5678", phoneUtil.formatInOriginalFormat(number10, RegionCode.KR));
1018 
1019     // US local numbers are formatted correctly, as we have formatting patterns for them.
1020     PhoneNumber localNumberUS = phoneUtil.parseAndKeepRawInput("2530000", RegionCode.US);
1021     assertEquals("253 0000", phoneUtil.formatInOriginalFormat(localNumberUS, RegionCode.US));
1022 
1023     PhoneNumber numberWithNationalPrefixUS =
1024         phoneUtil.parseAndKeepRawInput("18003456789", RegionCode.US);
1025     assertEquals("1 800 345 6789",
1026         phoneUtil.formatInOriginalFormat(numberWithNationalPrefixUS, RegionCode.US));
1027 
1028     PhoneNumber numberWithoutNationalPrefixGB =
1029         phoneUtil.parseAndKeepRawInput("2087654321", RegionCode.GB);
1030     assertEquals("20 8765 4321",
1031         phoneUtil.formatInOriginalFormat(numberWithoutNationalPrefixGB, RegionCode.GB));
1032     // Make sure no metadata is modified as a result of the previous function call.
1033     assertEquals("(020) 8765 4321", phoneUtil.formatInOriginalFormat(number5, RegionCode.GB));
1034 
1035     PhoneNumber numberWithNationalPrefixMX =
1036         phoneUtil.parseAndKeepRawInput("013312345678", RegionCode.MX);
1037     assertEquals("01 33 1234 5678",
1038         phoneUtil.formatInOriginalFormat(numberWithNationalPrefixMX, RegionCode.MX));
1039 
1040     PhoneNumber numberWithoutNationalPrefixMX =
1041         phoneUtil.parseAndKeepRawInput("3312345678", RegionCode.MX);
1042     assertEquals("33 1234 5678",
1043         phoneUtil.formatInOriginalFormat(numberWithoutNationalPrefixMX, RegionCode.MX));
1044 
1045     PhoneNumber italianFixedLineNumber =
1046         phoneUtil.parseAndKeepRawInput("0212345678", RegionCode.IT);
1047     assertEquals("02 1234 5678",
1048         phoneUtil.formatInOriginalFormat(italianFixedLineNumber, RegionCode.IT));
1049 
1050     PhoneNumber numberWithNationalPrefixJP =
1051         phoneUtil.parseAndKeepRawInput("00777012", RegionCode.JP);
1052     assertEquals("0077-7012",
1053         phoneUtil.formatInOriginalFormat(numberWithNationalPrefixJP, RegionCode.JP));
1054 
1055     PhoneNumber numberWithoutNationalPrefixJP =
1056         phoneUtil.parseAndKeepRawInput("0777012", RegionCode.JP);
1057     assertEquals("0777012",
1058         phoneUtil.formatInOriginalFormat(numberWithoutNationalPrefixJP, RegionCode.JP));
1059 
1060     PhoneNumber numberWithCarrierCodeBR =
1061         phoneUtil.parseAndKeepRawInput("012 3121286979", RegionCode.BR);
1062     assertEquals("012 3121286979",
1063         phoneUtil.formatInOriginalFormat(numberWithCarrierCodeBR, RegionCode.BR));
1064 
1065     // The default national prefix used in this case is 045. When a number with national prefix 044
1066     // is entered, we return the raw input as we don't want to change the number entered.
1067     PhoneNumber numberWithNationalPrefixMX1 =
1068         phoneUtil.parseAndKeepRawInput("044(33)1234-5678", RegionCode.MX);
1069     assertEquals("044(33)1234-5678",
1070         phoneUtil.formatInOriginalFormat(numberWithNationalPrefixMX1, RegionCode.MX));
1071 
1072     PhoneNumber numberWithNationalPrefixMX2 =
1073         phoneUtil.parseAndKeepRawInput("045(33)1234-5678", RegionCode.MX);
1074     assertEquals("045 33 1234 5678",
1075         phoneUtil.formatInOriginalFormat(numberWithNationalPrefixMX2, RegionCode.MX));
1076 
1077     // The default international prefix used in this case is 0011. When a number with international
1078     // prefix 0012 is entered, we return the raw input as we don't want to change the number
1079     // entered.
1080     PhoneNumber outOfCountryNumberFromAU1 =
1081         phoneUtil.parseAndKeepRawInput("0012 16502530000", RegionCode.AU);
1082     assertEquals("0012 16502530000",
1083         phoneUtil.formatInOriginalFormat(outOfCountryNumberFromAU1, RegionCode.AU));
1084 
1085     PhoneNumber outOfCountryNumberFromAU2 =
1086         phoneUtil.parseAndKeepRawInput("0011 16502530000", RegionCode.AU);
1087     assertEquals("0011 1 650 253 0000",
1088         phoneUtil.formatInOriginalFormat(outOfCountryNumberFromAU2, RegionCode.AU));
1089 
1090     // Test the star sign is not removed from or added to the original input by this method.
1091     PhoneNumber starNumber = phoneUtil.parseAndKeepRawInput("*1234", RegionCode.JP);
1092     assertEquals("*1234", phoneUtil.formatInOriginalFormat(starNumber, RegionCode.JP));
1093     PhoneNumber numberWithoutStar = phoneUtil.parseAndKeepRawInput("1234", RegionCode.JP);
1094     assertEquals("1234", phoneUtil.formatInOriginalFormat(numberWithoutStar, RegionCode.JP));
1095 
1096     // Test an invalid national number without raw input is just formatted as the national number.
1097     assertEquals("650253000",
1098         phoneUtil.formatInOriginalFormat(US_SHORT_BY_ONE_NUMBER, RegionCode.US));
1099   }
1100 
testIsPremiumRate()1101   public void testIsPremiumRate() {
1102     assertEquals(PhoneNumberType.PREMIUM_RATE, phoneUtil.getNumberType(US_PREMIUM));
1103 
1104     PhoneNumber premiumRateNumber = new PhoneNumber();
1105     premiumRateNumber.setCountryCode(39).setNationalNumber(892123L);
1106     assertEquals(PhoneNumberType.PREMIUM_RATE, phoneUtil.getNumberType(premiumRateNumber));
1107 
1108     premiumRateNumber.clear();
1109     premiumRateNumber.setCountryCode(44).setNationalNumber(9187654321L);
1110     assertEquals(PhoneNumberType.PREMIUM_RATE, phoneUtil.getNumberType(premiumRateNumber));
1111 
1112     premiumRateNumber.clear();
1113     premiumRateNumber.setCountryCode(49).setNationalNumber(9001654321L);
1114     assertEquals(PhoneNumberType.PREMIUM_RATE, phoneUtil.getNumberType(premiumRateNumber));
1115 
1116     premiumRateNumber.clear();
1117     premiumRateNumber.setCountryCode(49).setNationalNumber(90091234567L);
1118     assertEquals(PhoneNumberType.PREMIUM_RATE, phoneUtil.getNumberType(premiumRateNumber));
1119 
1120     assertEquals(PhoneNumberType.PREMIUM_RATE, phoneUtil.getNumberType(UNIVERSAL_PREMIUM_RATE));
1121   }
1122 
testIsTollFree()1123   public void testIsTollFree() {
1124     PhoneNumber tollFreeNumber = new PhoneNumber();
1125 
1126     tollFreeNumber.setCountryCode(1).setNationalNumber(8881234567L);
1127     assertEquals(PhoneNumberType.TOLL_FREE, phoneUtil.getNumberType(tollFreeNumber));
1128 
1129     tollFreeNumber.clear();
1130     tollFreeNumber.setCountryCode(39).setNationalNumber(803123L);
1131     assertEquals(PhoneNumberType.TOLL_FREE, phoneUtil.getNumberType(tollFreeNumber));
1132 
1133     tollFreeNumber.clear();
1134     tollFreeNumber.setCountryCode(44).setNationalNumber(8012345678L);
1135     assertEquals(PhoneNumberType.TOLL_FREE, phoneUtil.getNumberType(tollFreeNumber));
1136 
1137     tollFreeNumber.clear();
1138     tollFreeNumber.setCountryCode(49).setNationalNumber(8001234567L);
1139     assertEquals(PhoneNumberType.TOLL_FREE, phoneUtil.getNumberType(tollFreeNumber));
1140 
1141     assertEquals(PhoneNumberType.TOLL_FREE, phoneUtil.getNumberType(INTERNATIONAL_TOLL_FREE));
1142   }
1143 
testIsMobile()1144   public void testIsMobile() {
1145     assertEquals(PhoneNumberType.MOBILE, phoneUtil.getNumberType(BS_MOBILE));
1146     assertEquals(PhoneNumberType.MOBILE, phoneUtil.getNumberType(GB_MOBILE));
1147     assertEquals(PhoneNumberType.MOBILE, phoneUtil.getNumberType(IT_MOBILE));
1148     assertEquals(PhoneNumberType.MOBILE, phoneUtil.getNumberType(AR_MOBILE));
1149 
1150     PhoneNumber mobileNumber = new PhoneNumber();
1151     mobileNumber.setCountryCode(49).setNationalNumber(15123456789L);
1152     assertEquals(PhoneNumberType.MOBILE, phoneUtil.getNumberType(mobileNumber));
1153   }
1154 
testIsFixedLine()1155   public void testIsFixedLine() {
1156     assertEquals(PhoneNumberType.FIXED_LINE, phoneUtil.getNumberType(BS_NUMBER));
1157     assertEquals(PhoneNumberType.FIXED_LINE, phoneUtil.getNumberType(IT_NUMBER));
1158     assertEquals(PhoneNumberType.FIXED_LINE, phoneUtil.getNumberType(GB_NUMBER));
1159     assertEquals(PhoneNumberType.FIXED_LINE, phoneUtil.getNumberType(DE_NUMBER));
1160   }
1161 
testIsFixedLineAndMobile()1162   public void testIsFixedLineAndMobile() {
1163     assertEquals(PhoneNumberType.FIXED_LINE_OR_MOBILE, phoneUtil.getNumberType(US_NUMBER));
1164 
1165     PhoneNumber fixedLineAndMobileNumber = new PhoneNumber().
1166         setCountryCode(54).setNationalNumber(1987654321L);
1167     assertEquals(
1168         PhoneNumberType.FIXED_LINE_OR_MOBILE, phoneUtil.getNumberType(fixedLineAndMobileNumber));
1169   }
1170 
testIsSharedCost()1171   public void testIsSharedCost() {
1172     PhoneNumber gbNumber = new PhoneNumber();
1173     gbNumber.setCountryCode(44).setNationalNumber(8431231234L);
1174     assertEquals(PhoneNumberType.SHARED_COST, phoneUtil.getNumberType(gbNumber));
1175   }
1176 
testIsVoip()1177   public void testIsVoip() {
1178     PhoneNumber gbNumber = new PhoneNumber();
1179     gbNumber.setCountryCode(44).setNationalNumber(5631231234L);
1180     assertEquals(PhoneNumberType.VOIP, phoneUtil.getNumberType(gbNumber));
1181   }
1182 
testIsPersonalNumber()1183   public void testIsPersonalNumber() {
1184     PhoneNumber gbNumber = new PhoneNumber();
1185     gbNumber.setCountryCode(44).setNationalNumber(7031231234L);
1186     assertEquals(PhoneNumberType.PERSONAL_NUMBER, phoneUtil.getNumberType(gbNumber));
1187   }
1188 
testIsUnknown()1189   public void testIsUnknown() {
1190     // Invalid numbers should be of type UNKNOWN.
1191     assertEquals(PhoneNumberType.UNKNOWN, phoneUtil.getNumberType(US_LOCAL_NUMBER));
1192   }
1193 
testIsValidNumber()1194   public void testIsValidNumber() {
1195     assertTrue(phoneUtil.isValidNumber(US_NUMBER));
1196     assertTrue(phoneUtil.isValidNumber(IT_NUMBER));
1197     assertTrue(phoneUtil.isValidNumber(GB_MOBILE));
1198     assertTrue(phoneUtil.isValidNumber(INTERNATIONAL_TOLL_FREE));
1199     assertTrue(phoneUtil.isValidNumber(UNIVERSAL_PREMIUM_RATE));
1200 
1201     PhoneNumber nzNumber = new PhoneNumber().setCountryCode(64).setNationalNumber(21387835L);
1202     assertTrue(phoneUtil.isValidNumber(nzNumber));
1203   }
1204 
testIsValidForRegion()1205   public void testIsValidForRegion() {
1206     // This number is valid for the Bahamas, but is not a valid US number.
1207     assertTrue(phoneUtil.isValidNumber(BS_NUMBER));
1208     assertTrue(phoneUtil.isValidNumberForRegion(BS_NUMBER, RegionCode.BS));
1209     assertFalse(phoneUtil.isValidNumberForRegion(BS_NUMBER, RegionCode.US));
1210     PhoneNumber bsInvalidNumber =
1211         new PhoneNumber().setCountryCode(1).setNationalNumber(2421232345L);
1212     // This number is no longer valid.
1213     assertFalse(phoneUtil.isValidNumber(bsInvalidNumber));
1214 
1215     // La Mayotte and Reunion use 'leadingDigits' to differentiate them.
1216     PhoneNumber reNumber = new PhoneNumber();
1217     reNumber.setCountryCode(262).setNationalNumber(262123456L);
1218     assertTrue(phoneUtil.isValidNumber(reNumber));
1219     assertTrue(phoneUtil.isValidNumberForRegion(reNumber, RegionCode.RE));
1220     assertFalse(phoneUtil.isValidNumberForRegion(reNumber, RegionCode.YT));
1221     // Now change the number to be a number for La Mayotte.
1222     reNumber.setNationalNumber(269601234L);
1223     assertTrue(phoneUtil.isValidNumberForRegion(reNumber, RegionCode.YT));
1224     assertFalse(phoneUtil.isValidNumberForRegion(reNumber, RegionCode.RE));
1225     // This number is no longer valid for La Reunion.
1226     reNumber.setNationalNumber(269123456L);
1227     assertFalse(phoneUtil.isValidNumberForRegion(reNumber, RegionCode.YT));
1228     assertFalse(phoneUtil.isValidNumberForRegion(reNumber, RegionCode.RE));
1229     assertFalse(phoneUtil.isValidNumber(reNumber));
1230     // However, it should be recognised as from La Mayotte, since it is valid for this region.
1231     assertEquals(RegionCode.YT, phoneUtil.getRegionCodeForNumber(reNumber));
1232     // This number is valid in both places.
1233     reNumber.setNationalNumber(800123456L);
1234     assertTrue(phoneUtil.isValidNumberForRegion(reNumber, RegionCode.YT));
1235     assertTrue(phoneUtil.isValidNumberForRegion(reNumber, RegionCode.RE));
1236     assertTrue(phoneUtil.isValidNumberForRegion(INTERNATIONAL_TOLL_FREE, RegionCode.UN001));
1237     assertFalse(phoneUtil.isValidNumberForRegion(INTERNATIONAL_TOLL_FREE, RegionCode.US));
1238     assertFalse(phoneUtil.isValidNumberForRegion(INTERNATIONAL_TOLL_FREE, RegionCode.ZZ));
1239 
1240     PhoneNumber invalidNumber = new PhoneNumber();
1241     // Invalid country calling codes.
1242     invalidNumber.setCountryCode(3923).setNationalNumber(2366L);
1243     assertFalse(phoneUtil.isValidNumberForRegion(invalidNumber, RegionCode.ZZ));
1244     assertFalse(phoneUtil.isValidNumberForRegion(invalidNumber, RegionCode.UN001));
1245     invalidNumber.setCountryCode(0);
1246     assertFalse(phoneUtil.isValidNumberForRegion(invalidNumber, RegionCode.UN001));
1247     assertFalse(phoneUtil.isValidNumberForRegion(invalidNumber, RegionCode.ZZ));
1248   }
1249 
testIsNotValidNumber()1250   public void testIsNotValidNumber() {
1251     assertFalse(phoneUtil.isValidNumber(US_LOCAL_NUMBER));
1252 
1253     PhoneNumber invalidNumber = new PhoneNumber();
1254     invalidNumber.setCountryCode(39).setNationalNumber(23661830000L).setItalianLeadingZero(true);
1255     assertFalse(phoneUtil.isValidNumber(invalidNumber));
1256 
1257     invalidNumber.clear();
1258     invalidNumber.setCountryCode(44).setNationalNumber(791234567L);
1259     assertFalse(phoneUtil.isValidNumber(invalidNumber));
1260 
1261     invalidNumber.clear();
1262     invalidNumber.setCountryCode(49).setNationalNumber(1234L);
1263     assertFalse(phoneUtil.isValidNumber(invalidNumber));
1264 
1265     invalidNumber.clear();
1266     invalidNumber.setCountryCode(64).setNationalNumber(3316005L);
1267     assertFalse(phoneUtil.isValidNumber(invalidNumber));
1268 
1269     invalidNumber.clear();
1270     // Invalid country calling codes.
1271     invalidNumber.setCountryCode(3923).setNationalNumber(2366L);
1272     assertFalse(phoneUtil.isValidNumber(invalidNumber));
1273     invalidNumber.setCountryCode(0);
1274     assertFalse(phoneUtil.isValidNumber(invalidNumber));
1275 
1276     assertFalse(phoneUtil.isValidNumber(INTERNATIONAL_TOLL_FREE_TOO_LONG));
1277   }
1278 
testGetRegionCodeForCountryCode()1279   public void testGetRegionCodeForCountryCode() {
1280     assertEquals(RegionCode.US, phoneUtil.getRegionCodeForCountryCode(1));
1281     assertEquals(RegionCode.GB, phoneUtil.getRegionCodeForCountryCode(44));
1282     assertEquals(RegionCode.DE, phoneUtil.getRegionCodeForCountryCode(49));
1283     assertEquals(RegionCode.UN001, phoneUtil.getRegionCodeForCountryCode(800));
1284     assertEquals(RegionCode.UN001, phoneUtil.getRegionCodeForCountryCode(979));
1285   }
1286 
testGetRegionCodeForNumber()1287   public void testGetRegionCodeForNumber() {
1288     assertEquals(RegionCode.BS, phoneUtil.getRegionCodeForNumber(BS_NUMBER));
1289     assertEquals(RegionCode.US, phoneUtil.getRegionCodeForNumber(US_NUMBER));
1290     assertEquals(RegionCode.GB, phoneUtil.getRegionCodeForNumber(GB_MOBILE));
1291     assertEquals(RegionCode.UN001, phoneUtil.getRegionCodeForNumber(INTERNATIONAL_TOLL_FREE));
1292     assertEquals(RegionCode.UN001, phoneUtil.getRegionCodeForNumber(UNIVERSAL_PREMIUM_RATE));
1293   }
1294 
testGetRegionCodesForCountryCode()1295   public void testGetRegionCodesForCountryCode() {
1296     List<String> regionCodesForNANPA = phoneUtil.getRegionCodesForCountryCode(1);
1297     assertTrue(regionCodesForNANPA.contains(RegionCode.US));
1298     assertTrue(regionCodesForNANPA.contains(RegionCode.BS));
1299     assertTrue(phoneUtil.getRegionCodesForCountryCode(44).contains(RegionCode.GB));
1300     assertTrue(phoneUtil.getRegionCodesForCountryCode(49).contains(RegionCode.DE));
1301     assertTrue(phoneUtil.getRegionCodesForCountryCode(800).contains(RegionCode.UN001));
1302     // Test with invalid country calling code.
1303     assertTrue(phoneUtil.getRegionCodesForCountryCode(-1).isEmpty());
1304   }
1305 
testGetCountryCodeForRegion()1306   public void testGetCountryCodeForRegion() {
1307     assertEquals(1, phoneUtil.getCountryCodeForRegion(RegionCode.US));
1308     assertEquals(64, phoneUtil.getCountryCodeForRegion(RegionCode.NZ));
1309     assertEquals(0, phoneUtil.getCountryCodeForRegion(null));
1310     assertEquals(0, phoneUtil.getCountryCodeForRegion(RegionCode.ZZ));
1311     assertEquals(0, phoneUtil.getCountryCodeForRegion(RegionCode.UN001));
1312     // CS is already deprecated so the library doesn't support it.
1313     assertEquals(0, phoneUtil.getCountryCodeForRegion(RegionCode.CS));
1314   }
1315 
testGetNationalDiallingPrefixForRegion()1316   public void testGetNationalDiallingPrefixForRegion() {
1317     assertEquals("1", phoneUtil.getNddPrefixForRegion(RegionCode.US, false));
1318     // Test non-main country to see it gets the national dialling prefix for the main country with
1319     // that country calling code.
1320     assertEquals("1", phoneUtil.getNddPrefixForRegion(RegionCode.BS, false));
1321     assertEquals("0", phoneUtil.getNddPrefixForRegion(RegionCode.NZ, false));
1322     // Test case with non digit in the national prefix.
1323     assertEquals("0~0", phoneUtil.getNddPrefixForRegion(RegionCode.AO, false));
1324     assertEquals("00", phoneUtil.getNddPrefixForRegion(RegionCode.AO, true));
1325     // Test cases with invalid regions.
1326     assertEquals(null, phoneUtil.getNddPrefixForRegion(null, false));
1327     assertEquals(null, phoneUtil.getNddPrefixForRegion(RegionCode.ZZ, false));
1328     assertEquals(null, phoneUtil.getNddPrefixForRegion(RegionCode.UN001, false));
1329     // CS is already deprecated so the library doesn't support it.
1330     assertEquals(null, phoneUtil.getNddPrefixForRegion(RegionCode.CS, false));
1331   }
1332 
testIsNANPACountry()1333   public void testIsNANPACountry() {
1334     assertTrue(phoneUtil.isNANPACountry(RegionCode.US));
1335     assertTrue(phoneUtil.isNANPACountry(RegionCode.BS));
1336     assertFalse(phoneUtil.isNANPACountry(RegionCode.DE));
1337     assertFalse(phoneUtil.isNANPACountry(RegionCode.ZZ));
1338     assertFalse(phoneUtil.isNANPACountry(RegionCode.UN001));
1339     assertFalse(phoneUtil.isNANPACountry(null));
1340   }
1341 
testIsPossibleNumber()1342   public void testIsPossibleNumber() {
1343     assertTrue(phoneUtil.isPossibleNumber(US_NUMBER));
1344     assertTrue(phoneUtil.isPossibleNumber(US_LOCAL_NUMBER));
1345     assertTrue(phoneUtil.isPossibleNumber(GB_NUMBER));
1346     assertTrue(phoneUtil.isPossibleNumber(INTERNATIONAL_TOLL_FREE));
1347 
1348     assertTrue(phoneUtil.isPossibleNumber("+1 650 253 0000", RegionCode.US));
1349     assertTrue(phoneUtil.isPossibleNumber("+1 650 GOO OGLE", RegionCode.US));
1350     assertTrue(phoneUtil.isPossibleNumber("(650) 253-0000", RegionCode.US));
1351     assertTrue(phoneUtil.isPossibleNumber("253-0000", RegionCode.US));
1352     assertTrue(phoneUtil.isPossibleNumber("+1 650 253 0000", RegionCode.GB));
1353     assertTrue(phoneUtil.isPossibleNumber("+44 20 7031 3000", RegionCode.GB));
1354     assertTrue(phoneUtil.isPossibleNumber("(020) 7031 300", RegionCode.GB));
1355     assertTrue(phoneUtil.isPossibleNumber("7031 3000", RegionCode.GB));
1356     assertTrue(phoneUtil.isPossibleNumber("3331 6005", RegionCode.NZ));
1357     assertTrue(phoneUtil.isPossibleNumber("+800 1234 5678", RegionCode.UN001));
1358   }
1359 
testIsPossibleNumberForType_DifferentTypeLengths()1360   public void testIsPossibleNumberForType_DifferentTypeLengths() {
1361     // We use Argentinian numbers since they have different possible lengths for different types.
1362     PhoneNumber number = new PhoneNumber();
1363     number.setCountryCode(54).setNationalNumber(12345L);
1364     // Too short for any Argentinian number, including fixed-line.
1365     assertFalse(phoneUtil.isPossibleNumberForType(number, PhoneNumberType.FIXED_LINE));
1366     assertFalse(phoneUtil.isPossibleNumberForType(number, PhoneNumberType.UNKNOWN));
1367 
1368     // 6-digit numbers are okay for fixed-line.
1369     number.setNationalNumber(123456L);
1370     assertTrue(phoneUtil.isPossibleNumberForType(number, PhoneNumberType.UNKNOWN));
1371     assertTrue(phoneUtil.isPossibleNumberForType(number, PhoneNumberType.FIXED_LINE));
1372     // But too short for mobile.
1373     assertFalse(phoneUtil.isPossibleNumberForType(number, PhoneNumberType.MOBILE));
1374     // And too short for toll-free.
1375     assertFalse(phoneUtil.isPossibleNumberForType(number, PhoneNumberType.TOLL_FREE));
1376 
1377     // The same applies to 9-digit numbers.
1378     number.setNationalNumber(123456789L);
1379     assertTrue(phoneUtil.isPossibleNumberForType(number, PhoneNumberType.UNKNOWN));
1380     assertTrue(phoneUtil.isPossibleNumberForType(number, PhoneNumberType.FIXED_LINE));
1381     assertFalse(phoneUtil.isPossibleNumberForType(number, PhoneNumberType.MOBILE));
1382     assertFalse(phoneUtil.isPossibleNumberForType(number, PhoneNumberType.TOLL_FREE));
1383 
1384     // 10-digit numbers are universally possible.
1385     number.setNationalNumber(1234567890L);
1386     assertTrue(phoneUtil.isPossibleNumberForType(number, PhoneNumberType.UNKNOWN));
1387     assertTrue(phoneUtil.isPossibleNumberForType(number, PhoneNumberType.FIXED_LINE));
1388     assertTrue(phoneUtil.isPossibleNumberForType(number, PhoneNumberType.MOBILE));
1389     assertTrue(phoneUtil.isPossibleNumberForType(number, PhoneNumberType.TOLL_FREE));
1390 
1391     // 11-digit numbers are only possible for mobile numbers. Note we don't require the leading 9,
1392     // which all mobile numbers start with, and would be required for a valid mobile number.
1393     number.setNationalNumber(12345678901L);
1394     assertTrue(phoneUtil.isPossibleNumberForType(number, PhoneNumberType.UNKNOWN));
1395     assertFalse(phoneUtil.isPossibleNumberForType(number, PhoneNumberType.FIXED_LINE));
1396     assertTrue(phoneUtil.isPossibleNumberForType(number, PhoneNumberType.MOBILE));
1397     assertFalse(phoneUtil.isPossibleNumberForType(number, PhoneNumberType.TOLL_FREE));
1398   }
1399 
testIsPossibleNumberForType_LocalOnly()1400   public void testIsPossibleNumberForType_LocalOnly() {
1401     PhoneNumber number = new PhoneNumber();
1402     // Here we test a number length which matches a local-only length.
1403     number.setCountryCode(49).setNationalNumber(12L);
1404     assertTrue(phoneUtil.isPossibleNumberForType(number, PhoneNumberType.UNKNOWN));
1405     assertTrue(phoneUtil.isPossibleNumberForType(number, PhoneNumberType.FIXED_LINE));
1406     // Mobile numbers must be 10 or 11 digits, and there are no local-only lengths.
1407     assertFalse(phoneUtil.isPossibleNumberForType(number, PhoneNumberType.MOBILE));
1408   }
1409 
testIsPossibleNumberForType_DataMissingForSizeReasons()1410   public void testIsPossibleNumberForType_DataMissingForSizeReasons() {
1411     PhoneNumber number = new PhoneNumber();
1412     // Here we test something where the possible lengths match the possible lengths of the country
1413     // as a whole, and hence aren't present in the binary for size reasons - this should still work.
1414     // Local-only number.
1415     number.setCountryCode(55).setNationalNumber(12345678L);
1416     assertTrue(phoneUtil.isPossibleNumberForType(number, PhoneNumberType.UNKNOWN));
1417     assertTrue(phoneUtil.isPossibleNumberForType(number, PhoneNumberType.FIXED_LINE));
1418 
1419     number.setNationalNumber(1234567890L);
1420     assertTrue(phoneUtil.isPossibleNumberForType(number, PhoneNumberType.UNKNOWN));
1421     assertTrue(phoneUtil.isPossibleNumberForType(number, PhoneNumberType.FIXED_LINE));
1422   }
1423 
testIsPossibleNumberForType_NumberTypeNotSupportedForRegion()1424   public void testIsPossibleNumberForType_NumberTypeNotSupportedForRegion() {
1425     PhoneNumber number = new PhoneNumber();
1426     // There are *no* mobile numbers for this region at all, so we return false.
1427     number.setCountryCode(55).setNationalNumber(12345678L);
1428     assertFalse(phoneUtil.isPossibleNumberForType(number, PhoneNumberType.MOBILE));
1429     // This matches a fixed-line length though.
1430     assertTrue(phoneUtil.isPossibleNumberForType(number, PhoneNumberType.FIXED_LINE));
1431     assertTrue(phoneUtil.isPossibleNumberForType(number, PhoneNumberType.FIXED_LINE_OR_MOBILE));
1432 
1433     // There are *no* fixed-line OR mobile numbers for this country calling code at all, so we
1434     // return false for these.
1435     number.setCountryCode(979).setNationalNumber(123456789L);
1436     assertFalse(phoneUtil.isPossibleNumberForType(number, PhoneNumberType.MOBILE));
1437     assertFalse(phoneUtil.isPossibleNumberForType(number, PhoneNumberType.FIXED_LINE));
1438     assertFalse(phoneUtil.isPossibleNumberForType(number, PhoneNumberType.FIXED_LINE_OR_MOBILE));
1439     assertTrue(phoneUtil.isPossibleNumberForType(number, PhoneNumberType.PREMIUM_RATE));
1440   }
1441 
testIsPossibleNumberWithReason()1442   public void testIsPossibleNumberWithReason() {
1443     // National numbers for country calling code +1 that are within 7 to 10 digits are possible.
1444     assertEquals(ValidationResult.IS_POSSIBLE, phoneUtil.isPossibleNumberWithReason(US_NUMBER));
1445 
1446     assertEquals(ValidationResult.IS_POSSIBLE_LOCAL_ONLY,
1447         phoneUtil.isPossibleNumberWithReason(US_LOCAL_NUMBER));
1448 
1449     assertEquals(ValidationResult.TOO_LONG, phoneUtil.isPossibleNumberWithReason(US_LONG_NUMBER));
1450 
1451     PhoneNumber number = new PhoneNumber();
1452     number.setCountryCode(0).setNationalNumber(2530000L);
1453     assertEquals(
1454         ValidationResult.INVALID_COUNTRY_CODE, phoneUtil.isPossibleNumberWithReason(number));
1455 
1456     number.clear();
1457     number.setCountryCode(1).setNationalNumber(253000L);
1458     assertEquals(ValidationResult.TOO_SHORT, phoneUtil.isPossibleNumberWithReason(number));
1459 
1460     number.clear();
1461     number.setCountryCode(65).setNationalNumber(1234567890L);
1462     assertEquals(ValidationResult.IS_POSSIBLE, phoneUtil.isPossibleNumberWithReason(number));
1463 
1464     assertEquals(
1465         ValidationResult.TOO_LONG,
1466         phoneUtil.isPossibleNumberWithReason(INTERNATIONAL_TOLL_FREE_TOO_LONG));
1467   }
1468 
testIsPossibleNumberForTypeWithReason_DifferentTypeLengths()1469   public void testIsPossibleNumberForTypeWithReason_DifferentTypeLengths() {
1470     // We use Argentinian numbers since they have different possible lengths for different types.
1471     PhoneNumber number = new PhoneNumber();
1472     number.setCountryCode(54).setNationalNumber(12345L);
1473     // Too short for any Argentinian number.
1474     assertEquals(
1475         ValidationResult.TOO_SHORT,
1476         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.UNKNOWN));
1477     assertEquals(
1478         ValidationResult.TOO_SHORT,
1479         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.FIXED_LINE));
1480 
1481     // 6-digit numbers are okay for fixed-line.
1482     number.setNationalNumber(123456L);
1483     assertEquals(
1484         ValidationResult.IS_POSSIBLE,
1485         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.UNKNOWN));
1486     assertEquals(
1487         ValidationResult.IS_POSSIBLE,
1488         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.FIXED_LINE));
1489     // But too short for mobile.
1490     assertEquals(
1491         ValidationResult.TOO_SHORT,
1492         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.MOBILE));
1493     // And too short for toll-free.
1494     assertEquals(
1495         ValidationResult.TOO_SHORT,
1496         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.TOLL_FREE));
1497 
1498     // The same applies to 9-digit numbers.
1499     number.setNationalNumber(123456789L);
1500     assertEquals(
1501         ValidationResult.IS_POSSIBLE,
1502         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.UNKNOWN));
1503     assertEquals(
1504         ValidationResult.IS_POSSIBLE,
1505         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.FIXED_LINE));
1506     assertEquals(
1507         ValidationResult.TOO_SHORT,
1508         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.MOBILE));
1509     assertEquals(
1510         ValidationResult.TOO_SHORT,
1511         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.TOLL_FREE));
1512 
1513     // 10-digit numbers are universally possible.
1514     number.setNationalNumber(1234567890L);
1515     assertEquals(
1516         ValidationResult.IS_POSSIBLE,
1517         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.UNKNOWN));
1518     assertEquals(
1519         ValidationResult.IS_POSSIBLE,
1520         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.FIXED_LINE));
1521     assertEquals(
1522         ValidationResult.IS_POSSIBLE,
1523         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.MOBILE));
1524     assertEquals(
1525         ValidationResult.IS_POSSIBLE,
1526         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.TOLL_FREE));
1527 
1528     // 11-digit numbers are only possible for mobile numbers. Note we don't require the leading 9,
1529     // which all mobile numbers start with, and would be required for a valid mobile number.
1530     number.setNationalNumber(12345678901L);
1531     assertEquals(
1532         ValidationResult.IS_POSSIBLE,
1533         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.UNKNOWN));
1534     assertEquals(
1535         ValidationResult.TOO_LONG,
1536         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.FIXED_LINE));
1537     assertEquals(
1538         ValidationResult.IS_POSSIBLE,
1539         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.MOBILE));
1540     assertEquals(
1541         ValidationResult.TOO_LONG,
1542         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.TOLL_FREE));
1543   }
1544 
testIsPossibleNumberForTypeWithReason_LocalOnly()1545   public void testIsPossibleNumberForTypeWithReason_LocalOnly() {
1546     PhoneNumber number = new PhoneNumber();
1547     // Here we test a number length which matches a local-only length.
1548     number.setCountryCode(49).setNationalNumber(12L);
1549     assertEquals(
1550         ValidationResult.IS_POSSIBLE_LOCAL_ONLY,
1551         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.UNKNOWN));
1552     assertEquals(
1553         ValidationResult.IS_POSSIBLE_LOCAL_ONLY,
1554         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.FIXED_LINE));
1555     // Mobile numbers must be 10 or 11 digits, and there are no local-only lengths.
1556     assertEquals(
1557         ValidationResult.TOO_SHORT,
1558         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.MOBILE));
1559   }
1560 
testIsPossibleNumberForTypeWithReason_DataMissingForSizeReasons()1561   public void testIsPossibleNumberForTypeWithReason_DataMissingForSizeReasons() {
1562     PhoneNumber number = new PhoneNumber();
1563     // Here we test something where the possible lengths match the possible lengths of the country
1564     // as a whole, and hence aren't present in the binary for size reasons - this should still work.
1565     // Local-only number.
1566     number.setCountryCode(55).setNationalNumber(12345678L);
1567     assertEquals(
1568         ValidationResult.IS_POSSIBLE_LOCAL_ONLY,
1569         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.UNKNOWN));
1570     assertEquals(
1571         ValidationResult.IS_POSSIBLE_LOCAL_ONLY,
1572         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.FIXED_LINE));
1573 
1574     // Normal-length number.
1575     number.setNationalNumber(1234567890L);
1576     assertEquals(
1577         ValidationResult.IS_POSSIBLE,
1578         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.UNKNOWN));
1579     assertEquals(
1580         ValidationResult.IS_POSSIBLE,
1581         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.FIXED_LINE));
1582   }
1583 
testIsPossibleNumberForTypeWithReason_NumberTypeNotSupportedForRegion()1584   public void testIsPossibleNumberForTypeWithReason_NumberTypeNotSupportedForRegion() {
1585     PhoneNumber number = new PhoneNumber();
1586     // There are *no* mobile numbers for this region at all, so we return INVALID_LENGTH.
1587     number.setCountryCode(55).setNationalNumber(12345678L);
1588     assertEquals(
1589         ValidationResult.INVALID_LENGTH,
1590         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.MOBILE));
1591     // This matches a fixed-line length though.
1592     assertEquals(
1593         ValidationResult.IS_POSSIBLE_LOCAL_ONLY,
1594         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.FIXED_LINE_OR_MOBILE));
1595     // This is too short for fixed-line, and no mobile numbers exist.
1596     number.setCountryCode(55).setNationalNumber(1234567L);
1597     assertEquals(
1598         ValidationResult.INVALID_LENGTH,
1599         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.MOBILE));
1600     assertEquals(
1601         ValidationResult.TOO_SHORT,
1602         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.FIXED_LINE_OR_MOBILE));
1603     assertEquals(
1604         ValidationResult.TOO_SHORT,
1605         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.FIXED_LINE));
1606 
1607     // This is too short for mobile, and no fixed-line numbers exist.
1608     number.setCountryCode(882).setNationalNumber(1234567L);
1609     assertEquals(
1610         ValidationResult.TOO_SHORT,
1611         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.MOBILE));
1612     assertEquals(
1613         ValidationResult.TOO_SHORT,
1614         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.FIXED_LINE_OR_MOBILE));
1615     assertEquals(
1616         ValidationResult.INVALID_LENGTH,
1617         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.FIXED_LINE));
1618 
1619     // There are *no* fixed-line OR mobile numbers for this country calling code at all, so we
1620     // return INVALID_LENGTH.
1621     number.setCountryCode(979).setNationalNumber(123456789L);
1622     assertEquals(
1623         ValidationResult.INVALID_LENGTH,
1624         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.MOBILE));
1625     assertEquals(
1626         ValidationResult.INVALID_LENGTH,
1627         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.FIXED_LINE));
1628     assertEquals(
1629         ValidationResult.INVALID_LENGTH,
1630         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.FIXED_LINE_OR_MOBILE));
1631     assertEquals(
1632         ValidationResult.IS_POSSIBLE,
1633         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.PREMIUM_RATE));
1634   }
1635 
testIsPossibleNumberForTypeWithReason_FixedLineOrMobile()1636   public void testIsPossibleNumberForTypeWithReason_FixedLineOrMobile() {
1637     PhoneNumber number = new PhoneNumber();
1638     // For FIXED_LINE_OR_MOBILE, a number should be considered valid if it matches the possible
1639     // lengths for mobile *or* fixed-line numbers.
1640     number.setCountryCode(290).setNationalNumber(1234L);
1641     assertEquals(
1642         ValidationResult.TOO_SHORT,
1643         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.FIXED_LINE));
1644     assertEquals(
1645         ValidationResult.IS_POSSIBLE,
1646         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.MOBILE));
1647     assertEquals(
1648         ValidationResult.IS_POSSIBLE,
1649         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.FIXED_LINE_OR_MOBILE));
1650 
1651     number.setNationalNumber(12345L);
1652     assertEquals(
1653         ValidationResult.TOO_SHORT,
1654         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.FIXED_LINE));
1655     assertEquals(
1656         ValidationResult.TOO_LONG,
1657         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.MOBILE));
1658     assertEquals(
1659         ValidationResult.INVALID_LENGTH,
1660         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.FIXED_LINE_OR_MOBILE));
1661 
1662     number.setNationalNumber(123456L);
1663     assertEquals(
1664         ValidationResult.IS_POSSIBLE,
1665         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.FIXED_LINE));
1666     assertEquals(
1667         ValidationResult.TOO_LONG,
1668         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.MOBILE));
1669     assertEquals(
1670         ValidationResult.IS_POSSIBLE,
1671         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.FIXED_LINE_OR_MOBILE));
1672 
1673     number.setNationalNumber(1234567L);
1674     assertEquals(
1675         ValidationResult.TOO_LONG,
1676         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.FIXED_LINE));
1677     assertEquals(
1678         ValidationResult.TOO_LONG,
1679         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.MOBILE));
1680     assertEquals(
1681         ValidationResult.TOO_LONG,
1682         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.FIXED_LINE_OR_MOBILE));
1683 
1684     // 8-digit numbers are possible for toll-free and premium-rate numbers only.
1685     number.setNationalNumber(12345678L);
1686     assertEquals(
1687         ValidationResult.IS_POSSIBLE,
1688         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.TOLL_FREE));
1689     assertEquals(
1690         ValidationResult.TOO_LONG,
1691         phoneUtil.isPossibleNumberForTypeWithReason(number, PhoneNumberType.FIXED_LINE_OR_MOBILE));
1692   }
1693 
testIsNotPossibleNumber()1694   public void testIsNotPossibleNumber() {
1695     assertFalse(phoneUtil.isPossibleNumber(US_LONG_NUMBER));
1696     assertFalse(phoneUtil.isPossibleNumber(INTERNATIONAL_TOLL_FREE_TOO_LONG));
1697 
1698     PhoneNumber number = new PhoneNumber();
1699     number.setCountryCode(1).setNationalNumber(253000L);
1700     assertFalse(phoneUtil.isPossibleNumber(number));
1701 
1702     number.clear();
1703     number.setCountryCode(44).setNationalNumber(300L);
1704     assertFalse(phoneUtil.isPossibleNumber(number));
1705     assertFalse(phoneUtil.isPossibleNumber("+1 650 253 00000", RegionCode.US));
1706     assertFalse(phoneUtil.isPossibleNumber("(650) 253-00000", RegionCode.US));
1707     assertFalse(phoneUtil.isPossibleNumber("I want a Pizza", RegionCode.US));
1708     assertFalse(phoneUtil.isPossibleNumber("253-000", RegionCode.US));
1709     assertFalse(phoneUtil.isPossibleNumber("1 3000", RegionCode.GB));
1710     assertFalse(phoneUtil.isPossibleNumber("+44 300", RegionCode.GB));
1711     assertFalse(phoneUtil.isPossibleNumber("+800 1234 5678 9", RegionCode.UN001));
1712   }
1713 
testTruncateTooLongNumber()1714   public void testTruncateTooLongNumber() {
1715     // GB number 080 1234 5678, but entered with 4 extra digits at the end.
1716     PhoneNumber tooLongNumber = new PhoneNumber();
1717     tooLongNumber.setCountryCode(44).setNationalNumber(80123456780123L);
1718     PhoneNumber validNumber = new PhoneNumber();
1719     validNumber.setCountryCode(44).setNationalNumber(8012345678L);
1720     assertTrue(phoneUtil.truncateTooLongNumber(tooLongNumber));
1721     assertEquals(validNumber, tooLongNumber);
1722 
1723     // IT number 022 3456 7890, but entered with 3 extra digits at the end.
1724     tooLongNumber.clear();
1725     tooLongNumber.setCountryCode(39).setNationalNumber(2234567890123L).setItalianLeadingZero(true);
1726     validNumber.clear();
1727     validNumber.setCountryCode(39).setNationalNumber(2234567890L).setItalianLeadingZero(true);
1728     assertTrue(phoneUtil.truncateTooLongNumber(tooLongNumber));
1729     assertEquals(validNumber, tooLongNumber);
1730 
1731     // US number 650-253-0000, but entered with one additional digit at the end.
1732     tooLongNumber.clear();
1733     tooLongNumber.mergeFrom(US_LONG_NUMBER);
1734     assertTrue(phoneUtil.truncateTooLongNumber(tooLongNumber));
1735     assertEquals(US_NUMBER, tooLongNumber);
1736 
1737     tooLongNumber.clear();
1738     tooLongNumber.mergeFrom(INTERNATIONAL_TOLL_FREE_TOO_LONG);
1739     assertTrue(phoneUtil.truncateTooLongNumber(tooLongNumber));
1740     assertEquals(INTERNATIONAL_TOLL_FREE, tooLongNumber);
1741 
1742     // Tests what happens when a valid number is passed in.
1743     PhoneNumber validNumberCopy = new PhoneNumber().mergeFrom(validNumber);
1744     assertTrue(phoneUtil.truncateTooLongNumber(validNumber));
1745     // Tests the number is not modified.
1746     assertEquals(validNumberCopy, validNumber);
1747 
1748     // Tests what happens when a number with invalid prefix is passed in.
1749     PhoneNumber numberWithInvalidPrefix = new PhoneNumber();
1750     // The test metadata says US numbers cannot have prefix 240.
1751     numberWithInvalidPrefix.setCountryCode(1).setNationalNumber(2401234567L);
1752     PhoneNumber invalidNumberCopy = new PhoneNumber().mergeFrom(numberWithInvalidPrefix);
1753     assertFalse(phoneUtil.truncateTooLongNumber(numberWithInvalidPrefix));
1754     // Tests the number is not modified.
1755     assertEquals(invalidNumberCopy, numberWithInvalidPrefix);
1756 
1757     // Tests what happens when a too short number is passed in.
1758     PhoneNumber tooShortNumber = new PhoneNumber().setCountryCode(1).setNationalNumber(1234L);
1759     PhoneNumber tooShortNumberCopy = new PhoneNumber().mergeFrom(tooShortNumber);
1760     assertFalse(phoneUtil.truncateTooLongNumber(tooShortNumber));
1761     // Tests the number is not modified.
1762     assertEquals(tooShortNumberCopy, tooShortNumber);
1763   }
1764 
testIsViablePhoneNumber()1765   public void testIsViablePhoneNumber() {
1766     assertFalse(PhoneNumberUtil.isViablePhoneNumber("1"));
1767     // Only one or two digits before strange non-possible punctuation.
1768     assertFalse(PhoneNumberUtil.isViablePhoneNumber("1+1+1"));
1769     assertFalse(PhoneNumberUtil.isViablePhoneNumber("80+0"));
1770     // Two digits is viable.
1771     assertTrue(PhoneNumberUtil.isViablePhoneNumber("00"));
1772     assertTrue(PhoneNumberUtil.isViablePhoneNumber("111"));
1773     // Alpha numbers.
1774     assertTrue(PhoneNumberUtil.isViablePhoneNumber("0800-4-pizza"));
1775     assertTrue(PhoneNumberUtil.isViablePhoneNumber("0800-4-PIZZA"));
1776     // We need at least three digits before any alpha characters.
1777     assertFalse(PhoneNumberUtil.isViablePhoneNumber("08-PIZZA"));
1778     assertFalse(PhoneNumberUtil.isViablePhoneNumber("8-PIZZA"));
1779     assertFalse(PhoneNumberUtil.isViablePhoneNumber("12. March"));
1780   }
1781 
testIsViablePhoneNumberNonAscii()1782   public void testIsViablePhoneNumberNonAscii() {
1783     // Only one or two digits before possible punctuation followed by more digits.
1784     assertTrue(PhoneNumberUtil.isViablePhoneNumber("1\u300034"));
1785     assertFalse(PhoneNumberUtil.isViablePhoneNumber("1\u30003+4"));
1786     // Unicode variants of possible starting character and other allowed punctuation/digits.
1787     assertTrue(PhoneNumberUtil.isViablePhoneNumber("\uFF081\uFF09\u30003456789"));
1788     // Testing a leading + is okay.
1789     assertTrue(PhoneNumberUtil.isViablePhoneNumber("+1\uFF09\u30003456789"));
1790   }
1791 
testExtractPossibleNumber()1792   public void testExtractPossibleNumber() {
1793     // Removes preceding funky punctuation and letters but leaves the rest untouched.
1794     assertEquals("0800-345-600", PhoneNumberUtil.extractPossibleNumber("Tel:0800-345-600").toString());
1795     assertEquals("0800 FOR PIZZA", PhoneNumberUtil.extractPossibleNumber("Tel:0800 FOR PIZZA").toString());
1796     // Should not remove plus sign
1797     assertEquals("+800-345-600", PhoneNumberUtil.extractPossibleNumber("Tel:+800-345-600").toString());
1798     // Should recognise wide digits as possible start values.
1799     assertEquals("\uFF10\uFF12\uFF13",
1800                  PhoneNumberUtil.extractPossibleNumber("\uFF10\uFF12\uFF13").toString());
1801     // Dashes are not possible start values and should be removed.
1802     assertEquals("\uFF11\uFF12\uFF13",
1803                  PhoneNumberUtil.extractPossibleNumber("Num-\uFF11\uFF12\uFF13").toString());
1804     // If not possible number present, return empty string.
1805     assertEquals("", PhoneNumberUtil.extractPossibleNumber("Num-....").toString());
1806     // Leading brackets are stripped - these are not used when parsing.
1807     assertEquals("650) 253-0000", PhoneNumberUtil.extractPossibleNumber("(650) 253-0000").toString());
1808 
1809     // Trailing non-alpha-numeric characters should be removed.
1810     assertEquals("650) 253-0000", PhoneNumberUtil.extractPossibleNumber("(650) 253-0000..- ..").toString());
1811     assertEquals("650) 253-0000", PhoneNumberUtil.extractPossibleNumber("(650) 253-0000.").toString());
1812     // This case has a trailing RTL char.
1813     assertEquals("650) 253-0000", PhoneNumberUtil.extractPossibleNumber("(650) 253-0000\u200F").toString());
1814   }
1815 
testMaybeStripNationalPrefix()1816   public void testMaybeStripNationalPrefix() {
1817     PhoneMetadata metadata = new PhoneMetadata();
1818     metadata.setNationalPrefixForParsing("34");
1819     metadata.setGeneralDesc(new PhoneNumberDesc().setNationalNumberPattern("\\d{4,8}"));
1820     StringBuilder numberToStrip = new StringBuilder("34356778");
1821     String strippedNumber = "356778";
1822     assertTrue(phoneUtil.maybeStripNationalPrefixAndCarrierCode(numberToStrip, metadata, null));
1823     assertEquals("Should have had national prefix stripped.",
1824                  strippedNumber, numberToStrip.toString());
1825     // Retry stripping - now the number should not start with the national prefix, so no more
1826     // stripping should occur.
1827     assertFalse(phoneUtil.maybeStripNationalPrefixAndCarrierCode(numberToStrip, metadata, null));
1828     assertEquals("Should have had no change - no national prefix present.",
1829                  strippedNumber, numberToStrip.toString());
1830     // Some countries have no national prefix. Repeat test with none specified.
1831     metadata.setNationalPrefixForParsing("");
1832     assertFalse(phoneUtil.maybeStripNationalPrefixAndCarrierCode(numberToStrip, metadata, null));
1833     assertEquals("Should not strip anything with empty national prefix.",
1834                  strippedNumber, numberToStrip.toString());
1835     // If the resultant number doesn't match the national rule, it shouldn't be stripped.
1836     metadata.setNationalPrefixForParsing("3");
1837     numberToStrip = new StringBuilder("3123");
1838     strippedNumber = "3123";
1839     assertFalse(phoneUtil.maybeStripNationalPrefixAndCarrierCode(numberToStrip, metadata, null));
1840     assertEquals("Should have had no change - after stripping, it wouldn't have matched "
1841         + "the national rule.",
1842         strippedNumber, numberToStrip.toString());
1843     // Test extracting carrier selection code.
1844     metadata.setNationalPrefixForParsing("0(81)?");
1845     numberToStrip = new StringBuilder("08122123456");
1846     strippedNumber = "22123456";
1847     StringBuilder carrierCode = new StringBuilder();
1848     assertTrue(phoneUtil.maybeStripNationalPrefixAndCarrierCode(
1849         numberToStrip, metadata, carrierCode));
1850     assertEquals("81", carrierCode.toString());
1851     assertEquals("Should have had national prefix and carrier code stripped.",
1852                  strippedNumber, numberToStrip.toString());
1853     // If there was a transform rule, check it was applied.
1854     metadata.setNationalPrefixTransformRule("5$15");
1855     // Note that a capturing group is present here.
1856     metadata.setNationalPrefixForParsing("0(\\d{2})");
1857     numberToStrip = new StringBuilder("031123");
1858     String transformedNumber = "5315123";
1859     assertTrue(phoneUtil.maybeStripNationalPrefixAndCarrierCode(numberToStrip, metadata, null));
1860     assertEquals("Should transform the 031 to a 5315.",
1861                  transformedNumber, numberToStrip.toString());
1862   }
1863 
testMaybeStripInternationalPrefix()1864   public void testMaybeStripInternationalPrefix() {
1865     String internationalPrefix = "00[39]";
1866     StringBuilder numberToStrip = new StringBuilder("0034567700-3898003");
1867     // Note the dash is removed as part of the normalization.
1868     StringBuilder strippedNumber = new StringBuilder("45677003898003");
1869     assertEquals(CountryCodeSource.FROM_NUMBER_WITH_IDD,
1870                  phoneUtil.maybeStripInternationalPrefixAndNormalize(numberToStrip,
1871                                                                      internationalPrefix));
1872     assertEquals("The number supplied was not stripped of its international prefix.",
1873                  strippedNumber.toString(), numberToStrip.toString());
1874     // Now the number no longer starts with an IDD prefix, so it should now report
1875     // FROM_DEFAULT_COUNTRY.
1876     assertEquals(CountryCodeSource.FROM_DEFAULT_COUNTRY,
1877                  phoneUtil.maybeStripInternationalPrefixAndNormalize(numberToStrip,
1878                                                                      internationalPrefix));
1879 
1880     numberToStrip = new StringBuilder("00945677003898003");
1881     assertEquals(CountryCodeSource.FROM_NUMBER_WITH_IDD,
1882                  phoneUtil.maybeStripInternationalPrefixAndNormalize(numberToStrip,
1883                                                                      internationalPrefix));
1884     assertEquals("The number supplied was not stripped of its international prefix.",
1885                  strippedNumber.toString(), numberToStrip.toString());
1886     // Test it works when the international prefix is broken up by spaces.
1887     numberToStrip = new StringBuilder("00 9 45677003898003");
1888     assertEquals(CountryCodeSource.FROM_NUMBER_WITH_IDD,
1889                  phoneUtil.maybeStripInternationalPrefixAndNormalize(numberToStrip,
1890                                                                      internationalPrefix));
1891     assertEquals("The number supplied was not stripped of its international prefix.",
1892                  strippedNumber.toString(), numberToStrip.toString());
1893     // Now the number no longer starts with an IDD prefix, so it should now report
1894     // FROM_DEFAULT_COUNTRY.
1895     assertEquals(CountryCodeSource.FROM_DEFAULT_COUNTRY,
1896                  phoneUtil.maybeStripInternationalPrefixAndNormalize(numberToStrip,
1897                                                                      internationalPrefix));
1898 
1899     // Test the + symbol is also recognised and stripped.
1900     numberToStrip = new StringBuilder("+45677003898003");
1901     strippedNumber = new StringBuilder("45677003898003");
1902     assertEquals(CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN,
1903                  phoneUtil.maybeStripInternationalPrefixAndNormalize(numberToStrip,
1904                                                                      internationalPrefix));
1905     assertEquals("The number supplied was not stripped of the plus symbol.",
1906                  strippedNumber.toString(), numberToStrip.toString());
1907 
1908     // If the number afterwards is a zero, we should not strip this - no country calling code begins
1909     // with 0.
1910     numberToStrip = new StringBuilder("0090112-3123");
1911     strippedNumber = new StringBuilder("00901123123");
1912     assertEquals(CountryCodeSource.FROM_DEFAULT_COUNTRY,
1913                  phoneUtil.maybeStripInternationalPrefixAndNormalize(numberToStrip,
1914                                                                      internationalPrefix));
1915     assertEquals("The number supplied had a 0 after the match so shouldn't be stripped.",
1916                  strippedNumber.toString(), numberToStrip.toString());
1917     // Here the 0 is separated by a space from the IDD.
1918     numberToStrip = new StringBuilder("009 0-112-3123");
1919     assertEquals(CountryCodeSource.FROM_DEFAULT_COUNTRY,
1920                  phoneUtil.maybeStripInternationalPrefixAndNormalize(numberToStrip,
1921                                                                      internationalPrefix));
1922   }
1923 
testMaybeExtractCountryCode()1924   public void testMaybeExtractCountryCode() {
1925     PhoneNumber number = new PhoneNumber();
1926     PhoneMetadata metadata = phoneUtil.getMetadataForRegion(RegionCode.US);
1927     // Note that for the US, the IDD is 011.
1928     try {
1929       String phoneNumber = "011112-3456789";
1930       String strippedNumber = "123456789";
1931       int countryCallingCode = 1;
1932       StringBuilder numberToFill = new StringBuilder();
1933       assertEquals("Did not extract country calling code " + countryCallingCode + " correctly.",
1934                    countryCallingCode,
1935                    phoneUtil.maybeExtractCountryCode(phoneNumber, metadata, numberToFill, true,
1936                                                      number));
1937       assertEquals("Did not figure out CountryCodeSource correctly",
1938                    CountryCodeSource.FROM_NUMBER_WITH_IDD, number.getCountryCodeSource());
1939       // Should strip and normalize national significant number.
1940       assertEquals("Did not strip off the country calling code correctly.",
1941                    strippedNumber,
1942                    numberToFill.toString());
1943     } catch (NumberParseException e) {
1944       fail("Should not have thrown an exception: " + e.toString());
1945     }
1946     number.clear();
1947     try {
1948       String phoneNumber = "+6423456789";
1949       int countryCallingCode = 64;
1950       StringBuilder numberToFill = new StringBuilder();
1951       assertEquals("Did not extract country calling code " + countryCallingCode + " correctly.",
1952                    countryCallingCode,
1953                    phoneUtil.maybeExtractCountryCode(phoneNumber, metadata, numberToFill, true,
1954                                                      number));
1955       assertEquals("Did not figure out CountryCodeSource correctly",
1956                    CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN, number.getCountryCodeSource());
1957     } catch (NumberParseException e) {
1958       fail("Should not have thrown an exception: " + e.toString());
1959     }
1960     number.clear();
1961     try {
1962       String phoneNumber = "+80012345678";
1963       int countryCallingCode = 800;
1964       StringBuilder numberToFill = new StringBuilder();
1965       assertEquals("Did not extract country calling code " + countryCallingCode + " correctly.",
1966                    countryCallingCode,
1967                    phoneUtil.maybeExtractCountryCode(phoneNumber, metadata, numberToFill, true,
1968                                                      number));
1969       assertEquals("Did not figure out CountryCodeSource correctly",
1970                    CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN, number.getCountryCodeSource());
1971     } catch (NumberParseException e) {
1972       fail("Should not have thrown an exception: " + e.toString());
1973     }
1974     number.clear();
1975     try {
1976       String phoneNumber = "2345-6789";
1977       StringBuilder numberToFill = new StringBuilder();
1978       assertEquals(
1979           "Should not have extracted a country calling code - no international prefix present.",
1980           0,
1981           phoneUtil.maybeExtractCountryCode(phoneNumber, metadata, numberToFill, true, number));
1982       assertEquals("Did not figure out CountryCodeSource correctly",
1983                    CountryCodeSource.FROM_DEFAULT_COUNTRY, number.getCountryCodeSource());
1984     } catch (NumberParseException e) {
1985       fail("Should not have thrown an exception: " + e.toString());
1986     }
1987     number.clear();
1988     try {
1989       String phoneNumber = "0119991123456789";
1990       StringBuilder numberToFill = new StringBuilder();
1991       phoneUtil.maybeExtractCountryCode(phoneNumber, metadata, numberToFill, true, number);
1992       fail("Should have thrown an exception, no valid country calling code present.");
1993     } catch (NumberParseException e) {
1994       // Expected.
1995       assertEquals("Wrong error type stored in exception.",
1996                    NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
1997                    e.getErrorType());
1998     }
1999     number.clear();
2000     try {
2001       String phoneNumber = "(1 610) 619 4466";
2002       int countryCallingCode = 1;
2003       StringBuilder numberToFill = new StringBuilder();
2004       assertEquals("Should have extracted the country calling code of the region passed in",
2005                    countryCallingCode,
2006                    phoneUtil.maybeExtractCountryCode(phoneNumber, metadata, numberToFill, true,
2007                                                      number));
2008       assertEquals("Did not figure out CountryCodeSource correctly",
2009                    CountryCodeSource.FROM_NUMBER_WITHOUT_PLUS_SIGN,
2010                    number.getCountryCodeSource());
2011     } catch (NumberParseException e) {
2012       fail("Should not have thrown an exception: " + e.toString());
2013     }
2014     number.clear();
2015     try {
2016       String phoneNumber = "(1 610) 619 4466";
2017       int countryCallingCode = 1;
2018       StringBuilder numberToFill = new StringBuilder();
2019       assertEquals("Should have extracted the country calling code of the region passed in",
2020                    countryCallingCode,
2021                    phoneUtil.maybeExtractCountryCode(phoneNumber, metadata, numberToFill, false,
2022                                                      number));
2023       assertFalse("Should not contain CountryCodeSource.", number.hasCountryCodeSource());
2024     } catch (NumberParseException e) {
2025       fail("Should not have thrown an exception: " + e.toString());
2026     }
2027     number.clear();
2028     try {
2029       String phoneNumber = "(1 610) 619 446";
2030       StringBuilder numberToFill = new StringBuilder();
2031       assertEquals("Should not have extracted a country calling code - invalid number after "
2032           + "extraction of uncertain country calling code.",
2033           0,
2034           phoneUtil.maybeExtractCountryCode(phoneNumber, metadata, numberToFill, false, number));
2035       assertFalse("Should not contain CountryCodeSource.", number.hasCountryCodeSource());
2036     } catch (NumberParseException e) {
2037       fail("Should not have thrown an exception: " + e.toString());
2038     }
2039     number.clear();
2040     try {
2041       String phoneNumber = "(1 610) 619";
2042       StringBuilder numberToFill = new StringBuilder();
2043       assertEquals("Should not have extracted a country calling code - too short number both "
2044           + "before and after extraction of uncertain country calling code.",
2045           0,
2046           phoneUtil.maybeExtractCountryCode(phoneNumber, metadata, numberToFill, true, number));
2047       assertEquals("Did not figure out CountryCodeSource correctly",
2048                    CountryCodeSource.FROM_DEFAULT_COUNTRY, number.getCountryCodeSource());
2049     } catch (NumberParseException e) {
2050       fail("Should not have thrown an exception: " + e.toString());
2051     }
2052   }
2053 
testParseNationalNumber()2054   public void testParseNationalNumber() throws Exception {
2055     // National prefix attached.
2056     assertEquals(NZ_NUMBER, phoneUtil.parse("033316005", RegionCode.NZ));
2057     // Some fields are not filled in by parse, but only by parseAndKeepRawInput.
2058     assertFalse(NZ_NUMBER.hasCountryCodeSource());
2059     assertEquals(CountryCodeSource.UNSPECIFIED, NZ_NUMBER.getCountryCodeSource());
2060 
2061     assertEquals(NZ_NUMBER, phoneUtil.parse("33316005", RegionCode.NZ));
2062     // National prefix attached and some formatting present.
2063     assertEquals(NZ_NUMBER, phoneUtil.parse("03-331 6005", RegionCode.NZ));
2064     assertEquals(NZ_NUMBER, phoneUtil.parse("03 331 6005", RegionCode.NZ));
2065     // Test parsing RFC3966 format with a phone context.
2066     assertEquals(NZ_NUMBER, phoneUtil.parse("tel:03-331-6005;phone-context=+64", RegionCode.NZ));
2067     assertEquals(NZ_NUMBER, phoneUtil.parse("tel:331-6005;phone-context=+64-3", RegionCode.NZ));
2068     assertEquals(NZ_NUMBER, phoneUtil.parse("tel:331-6005;phone-context=+64-3", RegionCode.US));
2069     assertEquals(NZ_NUMBER, phoneUtil.parse(
2070         "My number is tel:03-331-6005;phone-context=+64", RegionCode.NZ));
2071     // Test parsing RFC3966 format with optional user-defined parameters. The parameters will appear
2072     // after the context if present.
2073     assertEquals(NZ_NUMBER, phoneUtil.parse("tel:03-331-6005;phone-context=+64;a=%A1",
2074         RegionCode.NZ));
2075     // Test parsing RFC3966 with an ISDN subaddress.
2076     assertEquals(NZ_NUMBER, phoneUtil.parse("tel:03-331-6005;isub=12345;phone-context=+64",
2077         RegionCode.NZ));
2078     assertEquals(NZ_NUMBER, phoneUtil.parse("tel:+64-3-331-6005;isub=12345", RegionCode.NZ));
2079     // Test parsing RFC3966 with "tel:" missing.
2080     assertEquals(NZ_NUMBER, phoneUtil.parse("03-331-6005;phone-context=+64", RegionCode.NZ));
2081     // Testing international prefixes.
2082     // Should strip country calling code.
2083     assertEquals(NZ_NUMBER, phoneUtil.parse("0064 3 331 6005", RegionCode.NZ));
2084     // Try again, but this time we have an international number with Region Code US. It should
2085     // recognise the country calling code and parse accordingly.
2086     assertEquals(NZ_NUMBER, phoneUtil.parse("01164 3 331 6005", RegionCode.US));
2087     assertEquals(NZ_NUMBER, phoneUtil.parse("+64 3 331 6005", RegionCode.US));
2088     // We should ignore the leading plus here, since it is not followed by a valid country code but
2089     // instead is followed by the IDD for the US.
2090     assertEquals(NZ_NUMBER, phoneUtil.parse("+01164 3 331 6005", RegionCode.US));
2091     assertEquals(NZ_NUMBER, phoneUtil.parse("+0064 3 331 6005", RegionCode.NZ));
2092     assertEquals(NZ_NUMBER, phoneUtil.parse("+ 00 64 3 331 6005", RegionCode.NZ));
2093 
2094     assertEquals(US_LOCAL_NUMBER,
2095         phoneUtil.parse("tel:253-0000;phone-context=www.google.com", RegionCode.US));
2096     assertEquals(US_LOCAL_NUMBER,
2097         phoneUtil.parse("tel:253-0000;isub=12345;phone-context=www.google.com", RegionCode.US));
2098     // This is invalid because no "+" sign is present as part of phone-context. The phone context
2099     // is simply ignored in this case just as if it contains a domain.
2100     assertEquals(US_LOCAL_NUMBER,
2101         phoneUtil.parse("tel:2530000;isub=12345;phone-context=1-650", RegionCode.US));
2102     assertEquals(US_LOCAL_NUMBER,
2103         phoneUtil.parse("tel:2530000;isub=12345;phone-context=1234.com", RegionCode.US));
2104 
2105     PhoneNumber nzNumber = new PhoneNumber();
2106     nzNumber.setCountryCode(64).setNationalNumber(64123456L);
2107     assertEquals(nzNumber, phoneUtil.parse("64(0)64123456", RegionCode.NZ));
2108     // Check that using a "/" is fine in a phone number.
2109     assertEquals(DE_NUMBER, phoneUtil.parse("301/23456", RegionCode.DE));
2110 
2111     PhoneNumber usNumber = new PhoneNumber();
2112     // Check it doesn't use the '1' as a country calling code when parsing if the phone number was
2113     // already possible.
2114     usNumber.setCountryCode(1).setNationalNumber(1234567890L);
2115     assertEquals(usNumber, phoneUtil.parse("123-456-7890", RegionCode.US));
2116 
2117     // Test star numbers. Although this is not strictly valid, we would like to make sure we can
2118     // parse the output we produce when formatting the number.
2119     assertEquals(JP_STAR_NUMBER, phoneUtil.parse("+81 *2345", RegionCode.JP));
2120 
2121     PhoneNumber shortNumber = new PhoneNumber();
2122     shortNumber.setCountryCode(64).setNationalNumber(12L);
2123     assertEquals(shortNumber, phoneUtil.parse("12", RegionCode.NZ));
2124 
2125     // Test for short-code with leading zero for a country which has 0 as national prefix. Ensure
2126     // it's not interpreted as national prefix if the remaining number length is local-only in
2127     // terms of length. Example: In GB, length 6-7 are only possible local-only.
2128     shortNumber.setCountryCode(44).setNationalNumber(123456)
2129         .setItalianLeadingZero(true);
2130     assertEquals(shortNumber, phoneUtil.parse("0123456", RegionCode.GB));
2131   }
2132 
testParseNumberWithAlphaCharacters()2133   public void testParseNumberWithAlphaCharacters() throws Exception {
2134     // Test case with alpha characters.
2135     PhoneNumber tollfreeNumber = new PhoneNumber();
2136     tollfreeNumber.setCountryCode(64).setNationalNumber(800332005L);
2137     assertEquals(tollfreeNumber, phoneUtil.parse("0800 DDA 005", RegionCode.NZ));
2138     PhoneNumber premiumNumber = new PhoneNumber();
2139     premiumNumber.setCountryCode(64).setNationalNumber(9003326005L);
2140     assertEquals(premiumNumber, phoneUtil.parse("0900 DDA 6005", RegionCode.NZ));
2141     // Not enough alpha characters for them to be considered intentional, so they are stripped.
2142     assertEquals(premiumNumber, phoneUtil.parse("0900 332 6005a", RegionCode.NZ));
2143     assertEquals(premiumNumber, phoneUtil.parse("0900 332 600a5", RegionCode.NZ));
2144     assertEquals(premiumNumber, phoneUtil.parse("0900 332 600A5", RegionCode.NZ));
2145     assertEquals(premiumNumber, phoneUtil.parse("0900 a332 600A5", RegionCode.NZ));
2146   }
2147 
testParseMaliciousInput()2148   public void testParseMaliciousInput() throws Exception {
2149     // Lots of leading + signs before the possible number.
2150     StringBuilder maliciousNumber = new StringBuilder(6000);
2151     for (int i = 0; i < 6000; i++) {
2152       maliciousNumber.append('+');
2153     }
2154     maliciousNumber.append("12222-33-244 extensioB 343+");
2155     try {
2156       phoneUtil.parse(maliciousNumber.toString(), RegionCode.US);
2157       fail("This should not parse without throwing an exception " + maliciousNumber);
2158     } catch (NumberParseException e) {
2159       // Expected this exception.
2160       assertEquals("Wrong error type stored in exception.",
2161                    NumberParseException.ErrorType.TOO_LONG,
2162                    e.getErrorType());
2163     }
2164     StringBuilder maliciousNumberWithAlmostExt = new StringBuilder(6000);
2165     for (int i = 0; i < 350; i++) {
2166       maliciousNumberWithAlmostExt.append("200");
2167     }
2168     maliciousNumberWithAlmostExt.append(" extensiOB 345");
2169     try {
2170       phoneUtil.parse(maliciousNumberWithAlmostExt.toString(), RegionCode.US);
2171       fail("This should not parse without throwing an exception " + maliciousNumberWithAlmostExt);
2172     } catch (NumberParseException e) {
2173       // Expected this exception.
2174       assertEquals("Wrong error type stored in exception.",
2175                    NumberParseException.ErrorType.TOO_LONG,
2176                    e.getErrorType());
2177     }
2178   }
2179 
testParseWithInternationalPrefixes()2180   public void testParseWithInternationalPrefixes() throws Exception {
2181     assertEquals(US_NUMBER, phoneUtil.parse("+1 (650) 253-0000", RegionCode.NZ));
2182     assertEquals(INTERNATIONAL_TOLL_FREE, phoneUtil.parse("011 800 1234 5678", RegionCode.US));
2183     assertEquals(US_NUMBER, phoneUtil.parse("1-650-253-0000", RegionCode.US));
2184     // Calling the US number from Singapore by using different service providers
2185     // 1st test: calling using SingTel IDD service (IDD is 001)
2186     assertEquals(US_NUMBER, phoneUtil.parse("0011-650-253-0000", RegionCode.SG));
2187     // 2nd test: calling using StarHub IDD service (IDD is 008)
2188     assertEquals(US_NUMBER, phoneUtil.parse("0081-650-253-0000", RegionCode.SG));
2189     // 3rd test: calling using SingTel V019 service (IDD is 019)
2190     assertEquals(US_NUMBER, phoneUtil.parse("0191-650-253-0000", RegionCode.SG));
2191     // Calling the US number from Poland
2192     assertEquals(US_NUMBER, phoneUtil.parse("0~01-650-253-0000", RegionCode.PL));
2193     // Using "++" at the start.
2194     assertEquals(US_NUMBER, phoneUtil.parse("++1 (650) 253-0000", RegionCode.PL));
2195   }
2196 
testParseNonAscii()2197   public void testParseNonAscii() throws Exception {
2198     // Using a full-width plus sign.
2199     assertEquals(US_NUMBER, phoneUtil.parse("\uFF0B1 (650) 253-0000", RegionCode.SG));
2200     // Using a soft hyphen U+00AD.
2201     assertEquals(US_NUMBER, phoneUtil.parse("1 (650) 253\u00AD-0000", RegionCode.US));
2202     // The whole number, including punctuation, is here represented in full-width form.
2203     assertEquals(US_NUMBER, phoneUtil.parse("\uFF0B\uFF11\u3000\uFF08\uFF16\uFF15\uFF10\uFF09"
2204           + "\u3000\uFF12\uFF15\uFF13\uFF0D\uFF10\uFF10\uFF10\uFF10",
2205           RegionCode.SG));
2206     // Using U+30FC dash instead.
2207     assertEquals(US_NUMBER, phoneUtil.parse("\uFF0B\uFF11\u3000\uFF08\uFF16\uFF15\uFF10\uFF09"
2208           + "\u3000\uFF12\uFF15\uFF13\u30FC\uFF10\uFF10\uFF10\uFF10",
2209           RegionCode.SG));
2210 
2211     // Using a very strange decimal digit range (Mongolian digits).
2212     assertEquals(US_NUMBER, phoneUtil.parse("\u1811 \u1816\u1815\u1810 "
2213           + "\u1812\u1815\u1813 \u1810\u1810\u1810\u1810",
2214           RegionCode.US));
2215   }
2216 
testParseWithLeadingZero()2217   public void testParseWithLeadingZero() throws Exception {
2218     assertEquals(IT_NUMBER, phoneUtil.parse("+39 02-36618 300", RegionCode.NZ));
2219     assertEquals(IT_NUMBER, phoneUtil.parse("02-36618 300", RegionCode.IT));
2220 
2221     assertEquals(IT_MOBILE, phoneUtil.parse("345 678 901", RegionCode.IT));
2222   }
2223 
testParseNationalNumberArgentina()2224   public void testParseNationalNumberArgentina() throws Exception {
2225     // Test parsing mobile numbers of Argentina.
2226     PhoneNumber arNumber = new PhoneNumber();
2227     arNumber.setCountryCode(54).setNationalNumber(93435551212L);
2228     assertEquals(arNumber, phoneUtil.parse("+54 9 343 555 1212", RegionCode.AR));
2229     assertEquals(arNumber, phoneUtil.parse("0343 15 555 1212", RegionCode.AR));
2230 
2231     arNumber.clear();
2232     arNumber.setCountryCode(54).setNationalNumber(93715654320L);
2233     assertEquals(arNumber, phoneUtil.parse("+54 9 3715 65 4320", RegionCode.AR));
2234     assertEquals(arNumber, phoneUtil.parse("03715 15 65 4320", RegionCode.AR));
2235     assertEquals(AR_MOBILE, phoneUtil.parse("911 876 54321", RegionCode.AR));
2236 
2237     // Test parsing fixed-line numbers of Argentina.
2238     assertEquals(AR_NUMBER, phoneUtil.parse("+54 11 8765 4321", RegionCode.AR));
2239     assertEquals(AR_NUMBER, phoneUtil.parse("011 8765 4321", RegionCode.AR));
2240 
2241     arNumber.clear();
2242     arNumber.setCountryCode(54).setNationalNumber(3715654321L);
2243     assertEquals(arNumber, phoneUtil.parse("+54 3715 65 4321", RegionCode.AR));
2244     assertEquals(arNumber, phoneUtil.parse("03715 65 4321", RegionCode.AR));
2245 
2246     arNumber.clear();
2247     arNumber.setCountryCode(54).setNationalNumber(2312340000L);
2248     assertEquals(arNumber, phoneUtil.parse("+54 23 1234 0000", RegionCode.AR));
2249     assertEquals(arNumber, phoneUtil.parse("023 1234 0000", RegionCode.AR));
2250   }
2251 
testParseWithXInNumber()2252   public void testParseWithXInNumber() throws Exception {
2253     // Test that having an 'x' in the phone number at the start is ok and that it just gets removed.
2254     assertEquals(AR_NUMBER, phoneUtil.parse("01187654321", RegionCode.AR));
2255     assertEquals(AR_NUMBER, phoneUtil.parse("(0) 1187654321", RegionCode.AR));
2256     assertEquals(AR_NUMBER, phoneUtil.parse("0 1187654321", RegionCode.AR));
2257     assertEquals(AR_NUMBER, phoneUtil.parse("(0xx) 1187654321", RegionCode.AR));
2258     PhoneNumber arFromUs = new PhoneNumber();
2259     arFromUs.setCountryCode(54).setNationalNumber(81429712L);
2260     // This test is intentionally constructed such that the number of digit after xx is larger than
2261     // 7, so that the number won't be mistakenly treated as an extension, as we allow extensions up
2262     // to 7 digits. This assumption is okay for now as all the countries where a carrier selection
2263     // code is written in the form of xx have a national significant number of length larger than 7.
2264     assertEquals(arFromUs, phoneUtil.parse("011xx5481429712", RegionCode.US));
2265   }
2266 
testParseNumbersMexico()2267   public void testParseNumbersMexico() throws Exception {
2268     // Test parsing fixed-line numbers of Mexico.
2269     PhoneNumber mxNumber = new PhoneNumber();
2270     mxNumber.setCountryCode(52).setNationalNumber(4499780001L);
2271     assertEquals(mxNumber, phoneUtil.parse("+52 (449)978-0001", RegionCode.MX));
2272     assertEquals(mxNumber, phoneUtil.parse("01 (449)978-0001", RegionCode.MX));
2273     assertEquals(mxNumber, phoneUtil.parse("(449)978-0001", RegionCode.MX));
2274 
2275     // Test parsing mobile numbers of Mexico.
2276     mxNumber.clear();
2277     mxNumber.setCountryCode(52).setNationalNumber(13312345678L);
2278     assertEquals(mxNumber, phoneUtil.parse("+52 1 33 1234-5678", RegionCode.MX));
2279     assertEquals(mxNumber, phoneUtil.parse("044 (33) 1234-5678", RegionCode.MX));
2280     assertEquals(mxNumber, phoneUtil.parse("045 33 1234-5678", RegionCode.MX));
2281   }
2282 
testFailedParseOnInvalidNumbers()2283   public void testFailedParseOnInvalidNumbers() {
2284     try {
2285       String sentencePhoneNumber = "This is not a phone number";
2286       phoneUtil.parse(sentencePhoneNumber, RegionCode.NZ);
2287       fail("This should not parse without throwing an exception " + sentencePhoneNumber);
2288     } catch (NumberParseException e) {
2289       // Expected this exception.
2290       assertEquals("Wrong error type stored in exception.",
2291                    NumberParseException.ErrorType.NOT_A_NUMBER,
2292                    e.getErrorType());
2293     }
2294     try {
2295       String sentencePhoneNumber = "1 Still not a number";
2296       phoneUtil.parse(sentencePhoneNumber, RegionCode.NZ);
2297       fail("This should not parse without throwing an exception " + sentencePhoneNumber);
2298     } catch (NumberParseException e) {
2299       // Expected this exception.
2300       assertEquals("Wrong error type stored in exception.",
2301                    NumberParseException.ErrorType.NOT_A_NUMBER,
2302                    e.getErrorType());
2303     }
2304     try {
2305       String sentencePhoneNumber = "1 MICROSOFT";
2306       phoneUtil.parse(sentencePhoneNumber, RegionCode.NZ);
2307       fail("This should not parse without throwing an exception " + sentencePhoneNumber);
2308     } catch (NumberParseException e) {
2309       // Expected this exception.
2310       assertEquals("Wrong error type stored in exception.",
2311                    NumberParseException.ErrorType.NOT_A_NUMBER,
2312                    e.getErrorType());
2313     }
2314     try {
2315       String sentencePhoneNumber = "12 MICROSOFT";
2316       phoneUtil.parse(sentencePhoneNumber, RegionCode.NZ);
2317       fail("This should not parse without throwing an exception " + sentencePhoneNumber);
2318     } catch (NumberParseException e) {
2319       // Expected this exception.
2320       assertEquals("Wrong error type stored in exception.",
2321                    NumberParseException.ErrorType.NOT_A_NUMBER,
2322                    e.getErrorType());
2323     }
2324     try {
2325       String tooLongPhoneNumber = "01495 72553301873 810104";
2326       phoneUtil.parse(tooLongPhoneNumber, RegionCode.GB);
2327       fail("This should not parse without throwing an exception " + tooLongPhoneNumber);
2328     } catch (NumberParseException e) {
2329       // Expected this exception.
2330       assertEquals("Wrong error type stored in exception.",
2331                    NumberParseException.ErrorType.TOO_LONG,
2332                    e.getErrorType());
2333     }
2334     try {
2335       String plusMinusPhoneNumber = "+---";
2336       phoneUtil.parse(plusMinusPhoneNumber, RegionCode.DE);
2337       fail("This should not parse without throwing an exception " + plusMinusPhoneNumber);
2338     } catch (NumberParseException e) {
2339       // Expected this exception.
2340       assertEquals("Wrong error type stored in exception.",
2341                    NumberParseException.ErrorType.NOT_A_NUMBER,
2342                    e.getErrorType());
2343     }
2344     try {
2345       String plusStar = "+***";
2346       phoneUtil.parse(plusStar, RegionCode.DE);
2347       fail("This should not parse without throwing an exception " + plusStar);
2348     } catch (NumberParseException e) {
2349       // Expected this exception.
2350       assertEquals("Wrong error type stored in exception.",
2351                    NumberParseException.ErrorType.NOT_A_NUMBER,
2352                    e.getErrorType());
2353     }
2354     try {
2355       String plusStarPhoneNumber = "+*******91";
2356       phoneUtil.parse(plusStarPhoneNumber, RegionCode.DE);
2357       fail("This should not parse without throwing an exception " + plusStarPhoneNumber);
2358     } catch (NumberParseException e) {
2359       // Expected this exception.
2360       assertEquals("Wrong error type stored in exception.",
2361                    NumberParseException.ErrorType.NOT_A_NUMBER,
2362                    e.getErrorType());
2363     }
2364     try {
2365       String tooShortPhoneNumber = "+49 0";
2366       phoneUtil.parse(tooShortPhoneNumber, RegionCode.DE);
2367       fail("This should not parse without throwing an exception " + tooShortPhoneNumber);
2368     } catch (NumberParseException e) {
2369       // Expected this exception.
2370       assertEquals("Wrong error type stored in exception.",
2371                    NumberParseException.ErrorType.TOO_SHORT_NSN,
2372                    e.getErrorType());
2373     }
2374     try {
2375       String invalidCountryCode = "+210 3456 56789";
2376       phoneUtil.parse(invalidCountryCode, RegionCode.NZ);
2377       fail("This is not a recognised region code: should fail: " + invalidCountryCode);
2378     } catch (NumberParseException e) {
2379       // Expected this exception.
2380       assertEquals("Wrong error type stored in exception.",
2381                    NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
2382                    e.getErrorType());
2383     }
2384     try {
2385       String plusAndIddAndInvalidCountryCode = "+ 00 210 3 331 6005";
2386       phoneUtil.parse(plusAndIddAndInvalidCountryCode, RegionCode.NZ);
2387       fail("This should not parse without throwing an exception.");
2388     } catch (NumberParseException e) {
2389       // Expected this exception. 00 is a correct IDD, but 210 is not a valid country code.
2390       assertEquals("Wrong error type stored in exception.",
2391                    NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
2392                    e.getErrorType());
2393     }
2394     try {
2395       String someNumber = "123 456 7890";
2396       phoneUtil.parse(someNumber, RegionCode.ZZ);
2397       fail("'Unknown' region code not allowed: should fail.");
2398     } catch (NumberParseException e) {
2399       // Expected this exception.
2400       assertEquals("Wrong error type stored in exception.",
2401                    NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
2402                    e.getErrorType());
2403     }
2404     try {
2405       String someNumber = "123 456 7890";
2406       phoneUtil.parse(someNumber, RegionCode.CS);
2407       fail("Deprecated region code not allowed: should fail.");
2408     } catch (NumberParseException e) {
2409       // Expected this exception.
2410       assertEquals("Wrong error type stored in exception.",
2411                    NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
2412                    e.getErrorType());
2413     }
2414     try {
2415       String someNumber = "123 456 7890";
2416       phoneUtil.parse(someNumber, null);
2417       fail("Null region code not allowed: should fail.");
2418     } catch (NumberParseException e) {
2419       // Expected this exception.
2420       assertEquals("Wrong error type stored in exception.",
2421                    NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
2422                    e.getErrorType());
2423     }
2424     try {
2425       String someNumber = "0044------";
2426       phoneUtil.parse(someNumber, RegionCode.GB);
2427       fail("No number provided, only region code: should fail");
2428     } catch (NumberParseException e) {
2429       // Expected this exception.
2430       assertEquals("Wrong error type stored in exception.",
2431                    NumberParseException.ErrorType.TOO_SHORT_AFTER_IDD,
2432                    e.getErrorType());
2433     }
2434     try {
2435       String someNumber = "0044";
2436       phoneUtil.parse(someNumber, RegionCode.GB);
2437       fail("No number provided, only region code: should fail");
2438     } catch (NumberParseException e) {
2439       // Expected this exception.
2440       assertEquals("Wrong error type stored in exception.",
2441                    NumberParseException.ErrorType.TOO_SHORT_AFTER_IDD,
2442                    e.getErrorType());
2443     }
2444     try {
2445       String someNumber = "011";
2446       phoneUtil.parse(someNumber, RegionCode.US);
2447       fail("Only IDD provided - should fail.");
2448     } catch (NumberParseException e) {
2449       // Expected this exception.
2450       assertEquals("Wrong error type stored in exception.",
2451                    NumberParseException.ErrorType.TOO_SHORT_AFTER_IDD,
2452                    e.getErrorType());
2453     }
2454     try {
2455       String someNumber = "0119";
2456       phoneUtil.parse(someNumber, RegionCode.US);
2457       fail("Only IDD provided and then 9 - should fail.");
2458     } catch (NumberParseException e) {
2459       // Expected this exception.
2460       assertEquals("Wrong error type stored in exception.",
2461                    NumberParseException.ErrorType.TOO_SHORT_AFTER_IDD,
2462                    e.getErrorType());
2463     }
2464     try {
2465       String emptyNumber = "";
2466       // Invalid region.
2467       phoneUtil.parse(emptyNumber, RegionCode.ZZ);
2468       fail("Empty string - should fail.");
2469     } catch (NumberParseException e) {
2470       // Expected this exception.
2471       assertEquals("Wrong error type stored in exception.",
2472                    NumberParseException.ErrorType.NOT_A_NUMBER,
2473                    e.getErrorType());
2474     }
2475     try {
2476       String nullNumber = null;
2477       // Invalid region.
2478       phoneUtil.parse(nullNumber, RegionCode.ZZ);
2479       fail("Null string - should fail.");
2480     } catch (NumberParseException e) {
2481       // Expected this exception.
2482       assertEquals("Wrong error type stored in exception.",
2483                    NumberParseException.ErrorType.NOT_A_NUMBER,
2484                    e.getErrorType());
2485     } catch (NullPointerException e) {
2486       fail("Null string - but should not throw a null pointer exception.");
2487     }
2488     try {
2489       String nullNumber = null;
2490       phoneUtil.parse(nullNumber, RegionCode.US);
2491       fail("Null string - should fail.");
2492     } catch (NumberParseException e) {
2493       // Expected this exception.
2494       assertEquals("Wrong error type stored in exception.",
2495                    NumberParseException.ErrorType.NOT_A_NUMBER,
2496                    e.getErrorType());
2497     } catch (NullPointerException e) {
2498       fail("Null string - but should not throw a null pointer exception.");
2499     }
2500     try {
2501       String domainRfcPhoneContext = "tel:555-1234;phone-context=www.google.com";
2502       phoneUtil.parse(domainRfcPhoneContext, RegionCode.ZZ);
2503       fail("'Unknown' region code not allowed: should fail.");
2504     } catch (NumberParseException e) {
2505       // Expected this exception.
2506       assertEquals("Wrong error type stored in exception.",
2507                    NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
2508                    e.getErrorType());
2509     }
2510     try {
2511       // This is invalid because no "+" sign is present as part of phone-context. This should not
2512       // succeed in being parsed.
2513       String invalidRfcPhoneContext = "tel:555-1234;phone-context=1-331";
2514       phoneUtil.parse(invalidRfcPhoneContext, RegionCode.ZZ);
2515       fail("'Unknown' region code not allowed: should fail.");
2516     } catch (NumberParseException e) {
2517       // Expected this exception.
2518       assertEquals("Wrong error type stored in exception.",
2519                    NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
2520                    e.getErrorType());
2521     }
2522     try {
2523       // Only the phone-context symbol is present, but no data.
2524       String invalidRfcPhoneContext = ";phone-context=";
2525       phoneUtil.parse(invalidRfcPhoneContext, RegionCode.ZZ);
2526       fail("No number is present: should fail.");
2527     } catch (NumberParseException e) {
2528       // Expected this exception.
2529       assertEquals("Wrong error type stored in exception.",
2530                    NumberParseException.ErrorType.NOT_A_NUMBER,
2531                    e.getErrorType());
2532     }
2533   }
2534 
testParseNumbersWithPlusWithNoRegion()2535   public void testParseNumbersWithPlusWithNoRegion() throws Exception {
2536     // RegionCode.ZZ is allowed only if the number starts with a '+' - then the country calling code
2537     // can be calculated.
2538     assertEquals(NZ_NUMBER, phoneUtil.parse("+64 3 331 6005", RegionCode.ZZ));
2539     // Test with full-width plus.
2540     assertEquals(NZ_NUMBER, phoneUtil.parse("\uFF0B64 3 331 6005", RegionCode.ZZ));
2541     // Test with normal plus but leading characters that need to be stripped.
2542     assertEquals(NZ_NUMBER, phoneUtil.parse("Tel: +64 3 331 6005", RegionCode.ZZ));
2543     assertEquals(NZ_NUMBER, phoneUtil.parse("+64 3 331 6005", null));
2544     assertEquals(INTERNATIONAL_TOLL_FREE, phoneUtil.parse("+800 1234 5678", null));
2545     assertEquals(UNIVERSAL_PREMIUM_RATE, phoneUtil.parse("+979 123 456 789", null));
2546 
2547     // Test parsing RFC3966 format with a phone context.
2548     assertEquals(NZ_NUMBER, phoneUtil.parse("tel:03-331-6005;phone-context=+64", RegionCode.ZZ));
2549     assertEquals(NZ_NUMBER, phoneUtil.parse("  tel:03-331-6005;phone-context=+64", RegionCode.ZZ));
2550     assertEquals(NZ_NUMBER, phoneUtil.parse("tel:03-331-6005;isub=12345;phone-context=+64",
2551         RegionCode.ZZ));
2552 
2553     PhoneNumber nzNumberWithRawInput = new PhoneNumber().mergeFrom(NZ_NUMBER).
2554         setRawInput("+64 3 331 6005").
2555         setCountryCodeSource(CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN);
2556     assertEquals(nzNumberWithRawInput, phoneUtil.parseAndKeepRawInput("+64 3 331 6005",
2557                                                                       RegionCode.ZZ));
2558     // Null is also allowed for the region code in these cases.
2559     assertEquals(nzNumberWithRawInput, phoneUtil.parseAndKeepRawInput("+64 3 331 6005", null));
2560   }
2561 
testParseNumberTooShortIfNationalPrefixStripped()2562   public void testParseNumberTooShortIfNationalPrefixStripped() throws Exception {
2563     // Test that a number whose first digits happen to coincide with the national prefix does not
2564     // get them stripped if doing so would result in a number too short to be a possible (regular
2565     // length) phone number for that region.
2566     PhoneNumber byNumber = new PhoneNumber().setCountryCode(375).setNationalNumber(8123L);
2567     assertEquals(byNumber, phoneUtil.parse("8123", RegionCode.BY));
2568     byNumber.setNationalNumber(81234L);
2569     assertEquals(byNumber, phoneUtil.parse("81234", RegionCode.BY));
2570 
2571     // The prefix doesn't get stripped, since the input is a viable 6-digit number, whereas the
2572     // result of stripping is only 5 digits.
2573     byNumber.setNationalNumber(812345L);
2574     assertEquals(byNumber, phoneUtil.parse("812345", RegionCode.BY));
2575 
2576     // The prefix gets stripped, since only 6-digit numbers are possible.
2577     byNumber.setNationalNumber(123456L);
2578     assertEquals(byNumber, phoneUtil.parse("8123456", RegionCode.BY));
2579   }
2580 
testParseExtensions()2581   public void testParseExtensions() throws Exception {
2582     PhoneNumber nzNumber = new PhoneNumber();
2583     nzNumber.setCountryCode(64).setNationalNumber(33316005L).setExtension("3456");
2584     assertEquals(nzNumber, phoneUtil.parse("03 331 6005 ext 3456", RegionCode.NZ));
2585     assertEquals(nzNumber, phoneUtil.parse("03-3316005x3456", RegionCode.NZ));
2586     assertEquals(nzNumber, phoneUtil.parse("03-3316005 int.3456", RegionCode.NZ));
2587     assertEquals(nzNumber, phoneUtil.parse("03 3316005 #3456", RegionCode.NZ));
2588     // Test the following do not extract extensions:
2589     assertEquals(ALPHA_NUMERIC_NUMBER, phoneUtil.parse("1800 six-flags", RegionCode.US));
2590     assertEquals(ALPHA_NUMERIC_NUMBER, phoneUtil.parse("1800 SIX FLAGS", RegionCode.US));
2591     assertEquals(ALPHA_NUMERIC_NUMBER, phoneUtil.parse("0~0 1800 7493 5247", RegionCode.PL));
2592     assertEquals(ALPHA_NUMERIC_NUMBER, phoneUtil.parse("(1800) 7493.5247", RegionCode.US));
2593     // Check that the last instance of an extension token is matched.
2594     PhoneNumber extnNumber = new PhoneNumber().mergeFrom(ALPHA_NUMERIC_NUMBER).setExtension("1234");
2595     assertEquals(extnNumber, phoneUtil.parse("0~0 1800 7493 5247 ~1234", RegionCode.PL));
2596     // Verifying bug-fix where the last digit of a number was previously omitted if it was a 0 when
2597     // extracting the extension. Also verifying a few different cases of extensions.
2598     PhoneNumber ukNumber = new PhoneNumber();
2599     ukNumber.setCountryCode(44).setNationalNumber(2034567890L).setExtension("456");
2600     assertEquals(ukNumber, phoneUtil.parse("+44 2034567890x456", RegionCode.NZ));
2601     assertEquals(ukNumber, phoneUtil.parse("+44 2034567890x456", RegionCode.GB));
2602     assertEquals(ukNumber, phoneUtil.parse("+44 2034567890 x456", RegionCode.GB));
2603     assertEquals(ukNumber, phoneUtil.parse("+44 2034567890 X456", RegionCode.GB));
2604     assertEquals(ukNumber, phoneUtil.parse("+44 2034567890 X 456", RegionCode.GB));
2605     assertEquals(ukNumber, phoneUtil.parse("+44 2034567890 X  456", RegionCode.GB));
2606     assertEquals(ukNumber, phoneUtil.parse("+44 2034567890 x 456  ", RegionCode.GB));
2607     assertEquals(ukNumber, phoneUtil.parse("+44 2034567890  X 456", RegionCode.GB));
2608     assertEquals(ukNumber, phoneUtil.parse("+44-2034567890;ext=456", RegionCode.GB));
2609     assertEquals(ukNumber, phoneUtil.parse("tel:2034567890;ext=456;phone-context=+44",
2610                                            RegionCode.ZZ));
2611     // Full-width extension, "extn" only.
2612     assertEquals(ukNumber, phoneUtil.parse("+442034567890\uFF45\uFF58\uFF54\uFF4E456",
2613                                            RegionCode.GB));
2614     // "xtn" only.
2615     assertEquals(ukNumber, phoneUtil.parse("+442034567890\uFF58\uFF54\uFF4E456",
2616                                            RegionCode.GB));
2617     // "xt" only.
2618     assertEquals(ukNumber, phoneUtil.parse("+442034567890\uFF58\uFF54456",
2619                                            RegionCode.GB));
2620 
2621     PhoneNumber usWithExtension = new PhoneNumber();
2622     usWithExtension.setCountryCode(1).setNationalNumber(8009013355L).setExtension("7246433");
2623     assertEquals(usWithExtension, phoneUtil.parse("(800) 901-3355 x 7246433", RegionCode.US));
2624     assertEquals(usWithExtension, phoneUtil.parse("(800) 901-3355 , ext 7246433", RegionCode.US));
2625     assertEquals(usWithExtension, phoneUtil.parse("(800) 901-3355 ; 7246433", RegionCode.US));
2626     // To test an extension character without surrounding spaces.
2627     assertEquals(usWithExtension, phoneUtil.parse("(800) 901-3355;7246433", RegionCode.US));
2628     assertEquals(usWithExtension,
2629                  phoneUtil.parse("(800) 901-3355 ,extension 7246433", RegionCode.US));
2630     assertEquals(usWithExtension,
2631                  phoneUtil.parse("(800) 901-3355 ,extensi\u00F3n 7246433", RegionCode.US));
2632     // Repeat with the small letter o with acute accent created by combining characters.
2633     assertEquals(usWithExtension,
2634                  phoneUtil.parse("(800) 901-3355 ,extensio\u0301n 7246433", RegionCode.US));
2635     assertEquals(usWithExtension, phoneUtil.parse("(800) 901-3355 , 7246433", RegionCode.US));
2636     assertEquals(usWithExtension, phoneUtil.parse("(800) 901-3355 ext: 7246433", RegionCode.US));
2637     // Testing Russian extension \u0434\u043E\u0431 with variants found online.
2638     PhoneNumber ruWithExtension = new PhoneNumber();
2639     ruWithExtension.setCountryCode(7).setNationalNumber(4232022511L).setExtension("100");
2640     assertEquals(ruWithExtension,
2641 		 phoneUtil.parse("8 (423) 202-25-11, \u0434\u043E\u0431. 100", RegionCode.RU));
2642     assertEquals(ruWithExtension,
2643 		 phoneUtil.parse("8 (423) 202-25-11 \u0434\u043E\u0431. 100", RegionCode.RU));
2644     assertEquals(ruWithExtension,
2645 		 phoneUtil.parse("8 (423) 202-25-11, \u0434\u043E\u0431 100", RegionCode.RU));
2646     assertEquals(ruWithExtension,
2647 		 phoneUtil.parse("8 (423) 202-25-11 \u0434\u043E\u0431 100", RegionCode.RU));
2648     assertEquals(ruWithExtension,
2649 		 phoneUtil.parse("8 (423) 202-25-11\u0434\u043E\u0431100", RegionCode.RU));
2650     // In upper case
2651     assertEquals(ruWithExtension,
2652                  phoneUtil.parse("8 (423) 202-25-11, \u0414\u041E\u0411. 100", RegionCode.RU));
2653 
2654     // Test that if a number has two extensions specified, we ignore the second.
2655     PhoneNumber usWithTwoExtensionsNumber = new PhoneNumber();
2656     usWithTwoExtensionsNumber.setCountryCode(1).setNationalNumber(2121231234L).setExtension("508");
2657     assertEquals(usWithTwoExtensionsNumber, phoneUtil.parse("(212)123-1234 x508/x1234",
2658                                                             RegionCode.US));
2659     assertEquals(usWithTwoExtensionsNumber, phoneUtil.parse("(212)123-1234 x508/ x1234",
2660                                                             RegionCode.US));
2661     assertEquals(usWithTwoExtensionsNumber, phoneUtil.parse("(212)123-1234 x508\\x1234",
2662                                                             RegionCode.US));
2663 
2664     // Test parsing numbers in the form (645) 123-1234-910# works, where the last 3 digits before
2665     // the # are an extension.
2666     usWithExtension.clear();
2667     usWithExtension.setCountryCode(1).setNationalNumber(6451231234L).setExtension("910");
2668     assertEquals(usWithExtension, phoneUtil.parse("+1 (645) 123 1234-910#", RegionCode.US));
2669     // Retry with the same number in a slightly different format.
2670     assertEquals(usWithExtension, phoneUtil.parse("+1 (645) 123 1234 ext. 910#", RegionCode.US));
2671   }
2672 
testParseAndKeepRaw()2673   public void testParseAndKeepRaw() throws Exception {
2674     PhoneNumber alphaNumericNumber = new PhoneNumber().mergeFrom(ALPHA_NUMERIC_NUMBER).
2675         setRawInput("800 six-flags").
2676         setCountryCodeSource(CountryCodeSource.FROM_DEFAULT_COUNTRY);
2677     assertEquals(alphaNumericNumber,
2678                  phoneUtil.parseAndKeepRawInput("800 six-flags", RegionCode.US));
2679 
2680     PhoneNumber shorterAlphaNumber = new PhoneNumber().
2681         setCountryCode(1).setNationalNumber(8007493524L).
2682         setRawInput("1800 six-flag").
2683         setCountryCodeSource(CountryCodeSource.FROM_NUMBER_WITHOUT_PLUS_SIGN);
2684     assertEquals(shorterAlphaNumber,
2685                  phoneUtil.parseAndKeepRawInput("1800 six-flag", RegionCode.US));
2686 
2687     shorterAlphaNumber.setRawInput("+1800 six-flag").
2688         setCountryCodeSource(CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN);
2689     assertEquals(shorterAlphaNumber,
2690                  phoneUtil.parseAndKeepRawInput("+1800 six-flag", RegionCode.NZ));
2691 
2692     shorterAlphaNumber.setRawInput("001800 six-flag").
2693         setCountryCodeSource(CountryCodeSource.FROM_NUMBER_WITH_IDD);
2694     assertEquals(shorterAlphaNumber,
2695                  phoneUtil.parseAndKeepRawInput("001800 six-flag", RegionCode.NZ));
2696 
2697     // Invalid region code supplied.
2698     try {
2699       phoneUtil.parseAndKeepRawInput("123 456 7890", RegionCode.CS);
2700       fail("Deprecated region code not allowed: should fail.");
2701     } catch (NumberParseException e) {
2702       // Expected this exception.
2703       assertEquals("Wrong error type stored in exception.",
2704                    NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
2705                    e.getErrorType());
2706     }
2707 
2708     PhoneNumber koreanNumber = new PhoneNumber();
2709     koreanNumber.setCountryCode(82).setNationalNumber(22123456).setRawInput("08122123456").
2710         setCountryCodeSource(CountryCodeSource.FROM_DEFAULT_COUNTRY).
2711         setPreferredDomesticCarrierCode("81");
2712     assertEquals(koreanNumber, phoneUtil.parseAndKeepRawInput("08122123456", RegionCode.KR));
2713   }
2714 
testParseItalianLeadingZeros()2715   public void testParseItalianLeadingZeros() throws Exception {
2716     // Test the number "011".
2717     PhoneNumber oneZero = new PhoneNumber();
2718     oneZero.setCountryCode(61).setNationalNumber(11L).setItalianLeadingZero(true);
2719     assertEquals(oneZero, phoneUtil.parse("011", RegionCode.AU));
2720 
2721     // Test the number "001".
2722     PhoneNumber twoZeros = new PhoneNumber();
2723     twoZeros.setCountryCode(61).setNationalNumber(1).setItalianLeadingZero(true)
2724         .setNumberOfLeadingZeros(2);
2725     assertEquals(twoZeros, phoneUtil.parse("001", RegionCode.AU));
2726 
2727     // Test the number "000". This number has 2 leading zeros.
2728     PhoneNumber stillTwoZeros = new PhoneNumber();
2729     stillTwoZeros.setCountryCode(61).setNationalNumber(0L).setItalianLeadingZero(true)
2730         .setNumberOfLeadingZeros(2);
2731     assertEquals(stillTwoZeros, phoneUtil.parse("000", RegionCode.AU));
2732 
2733     // Test the number "0000". This number has 3 leading zeros.
2734     PhoneNumber threeZeros = new PhoneNumber();
2735     threeZeros.setCountryCode(61).setNationalNumber(0L).setItalianLeadingZero(true)
2736         .setNumberOfLeadingZeros(3);
2737     assertEquals(threeZeros, phoneUtil.parse("0000", RegionCode.AU));
2738   }
2739 
testCountryWithNoNumberDesc()2740   public void testCountryWithNoNumberDesc() {
2741     // Andorra is a country where we don't have PhoneNumberDesc info in the metadata.
2742     PhoneNumber adNumber = new PhoneNumber();
2743     adNumber.setCountryCode(376).setNationalNumber(12345L);
2744     assertEquals("+376 12345", phoneUtil.format(adNumber, PhoneNumberFormat.INTERNATIONAL));
2745     assertEquals("+37612345", phoneUtil.format(adNumber, PhoneNumberFormat.E164));
2746     assertEquals("12345", phoneUtil.format(adNumber, PhoneNumberFormat.NATIONAL));
2747     assertEquals(PhoneNumberType.UNKNOWN, phoneUtil.getNumberType(adNumber));
2748     assertFalse(phoneUtil.isValidNumber(adNumber));
2749 
2750     // Test dialing a US number from within Andorra.
2751     assertEquals("00 1 650 253 0000",
2752                  phoneUtil.formatOutOfCountryCallingNumber(US_NUMBER, RegionCode.AD));
2753   }
2754 
testUnknownCountryCallingCode()2755   public void testUnknownCountryCallingCode() {
2756     assertFalse(phoneUtil.isValidNumber(UNKNOWN_COUNTRY_CODE_NO_RAW_INPUT));
2757     // It's not very well defined as to what the E164 representation for a number with an invalid
2758     // country calling code is, but just prefixing the country code and national number is about
2759     // the best we can do.
2760     assertEquals("+212345",
2761         phoneUtil.format(UNKNOWN_COUNTRY_CODE_NO_RAW_INPUT, PhoneNumberFormat.E164));
2762   }
2763 
testIsNumberMatchMatches()2764   public void testIsNumberMatchMatches() throws Exception {
2765     // Test simple matches where formatting is different, or leading zeros, or country calling code
2766     // has been specified.
2767     assertEquals(PhoneNumberUtil.MatchType.EXACT_MATCH,
2768                  phoneUtil.isNumberMatch("+64 3 331 6005", "+64 03 331 6005"));
2769     assertEquals(PhoneNumberUtil.MatchType.EXACT_MATCH,
2770                  phoneUtil.isNumberMatch("+800 1234 5678", "+80012345678"));
2771     assertEquals(PhoneNumberUtil.MatchType.EXACT_MATCH,
2772                  phoneUtil.isNumberMatch("+64 03 331-6005", "+64 03331 6005"));
2773     assertEquals(PhoneNumberUtil.MatchType.EXACT_MATCH,
2774                  phoneUtil.isNumberMatch("+643 331-6005", "+64033316005"));
2775     assertEquals(PhoneNumberUtil.MatchType.EXACT_MATCH,
2776                  phoneUtil.isNumberMatch("+643 331-6005", "+6433316005"));
2777     assertEquals(PhoneNumberUtil.MatchType.EXACT_MATCH,
2778                  phoneUtil.isNumberMatch("+64 3 331-6005", "+6433316005"));
2779     assertEquals(PhoneNumberUtil.MatchType.EXACT_MATCH,
2780                  phoneUtil.isNumberMatch("+64 3 331-6005", "tel:+64-3-331-6005;isub=123"));
2781     // Test alpha numbers.
2782     assertEquals(PhoneNumberUtil.MatchType.EXACT_MATCH,
2783                  phoneUtil.isNumberMatch("+1800 siX-Flags", "+1 800 7493 5247"));
2784     // Test numbers with extensions.
2785     assertEquals(PhoneNumberUtil.MatchType.EXACT_MATCH,
2786                  phoneUtil.isNumberMatch("+64 3 331-6005 extn 1234", "+6433316005#1234"));
2787     assertEquals(PhoneNumberUtil.MatchType.EXACT_MATCH,
2788                  phoneUtil.isNumberMatch("+64 3 331-6005 ext. 1234", "+6433316005;1234"));
2789     assertEquals(PhoneNumberUtil.MatchType.EXACT_MATCH,
2790                  phoneUtil.isNumberMatch("+7 423 202-25-11 ext 100",
2791 					 "+7 4232022511 \u0434\u043E\u0431. 100"));
2792     // Test proto buffers.
2793     assertEquals(PhoneNumberUtil.MatchType.EXACT_MATCH,
2794                  phoneUtil.isNumberMatch(NZ_NUMBER, "+6403 331 6005"));
2795 
2796     PhoneNumber nzNumber = new PhoneNumber().mergeFrom(NZ_NUMBER).setExtension("3456");
2797     assertEquals(PhoneNumberUtil.MatchType.EXACT_MATCH,
2798                  phoneUtil.isNumberMatch(nzNumber, "+643 331 6005 ext 3456"));
2799     // Check empty extensions are ignored.
2800     nzNumber.setExtension("");
2801     assertEquals(PhoneNumberUtil.MatchType.EXACT_MATCH,
2802                  phoneUtil.isNumberMatch(nzNumber, "+6403 331 6005"));
2803     // Check variant with two proto buffers.
2804     assertEquals("Number " + nzNumber.toString() + " did not match " + NZ_NUMBER.toString(),
2805                  PhoneNumberUtil.MatchType.EXACT_MATCH,
2806                  phoneUtil.isNumberMatch(nzNumber, NZ_NUMBER));
2807 
2808   }
2809 
testIsNumberMatchShortMatchIfDiffNumLeadingZeros()2810   public void testIsNumberMatchShortMatchIfDiffNumLeadingZeros() throws Exception {
2811     PhoneNumber nzNumberOne = new PhoneNumber();
2812     PhoneNumber nzNumberTwo = new PhoneNumber();
2813     nzNumberOne.setCountryCode(64).setNationalNumber(33316005L).setItalianLeadingZero(true);
2814     nzNumberTwo.setCountryCode(64).setNationalNumber(33316005L).setItalianLeadingZero(true)
2815         .setNumberOfLeadingZeros(2);
2816     assertEquals(PhoneNumberUtil.MatchType.SHORT_NSN_MATCH,
2817                  phoneUtil.isNumberMatch(nzNumberOne, nzNumberTwo));
2818 
2819     nzNumberOne.setItalianLeadingZero(false).setNumberOfLeadingZeros(1);
2820     nzNumberTwo.setItalianLeadingZero(true).setNumberOfLeadingZeros(1);
2821     // Since one doesn't have the "italian_leading_zero" set to true, we ignore the number of
2822     // leading zeros present (1 is in any case the default value).
2823     assertEquals(PhoneNumberUtil.MatchType.SHORT_NSN_MATCH,
2824                  phoneUtil.isNumberMatch(nzNumberOne, nzNumberTwo));
2825   }
2826 
testIsNumberMatchAcceptsProtoDefaultsAsMatch()2827   public void testIsNumberMatchAcceptsProtoDefaultsAsMatch() throws Exception {
2828     PhoneNumber nzNumberOne = new PhoneNumber();
2829     PhoneNumber nzNumberTwo = new PhoneNumber();
2830     nzNumberOne.setCountryCode(64).setNationalNumber(33316005L).setItalianLeadingZero(true);
2831     // The default for number_of_leading_zeros is 1, so it shouldn't normally be set, however if it
2832     // is it should be considered equivalent.
2833     nzNumberTwo.setCountryCode(64).setNationalNumber(33316005L).setItalianLeadingZero(true)
2834         .setNumberOfLeadingZeros(1);
2835     assertEquals(PhoneNumberUtil.MatchType.EXACT_MATCH,
2836                  phoneUtil.isNumberMatch(nzNumberOne, nzNumberTwo));
2837   }
2838 
testIsNumberMatchMatchesDiffLeadingZerosIfItalianLeadingZeroFalse()2839   public void testIsNumberMatchMatchesDiffLeadingZerosIfItalianLeadingZeroFalse() throws Exception {
2840     PhoneNumber nzNumberOne = new PhoneNumber();
2841     PhoneNumber nzNumberTwo = new PhoneNumber();
2842     nzNumberOne.setCountryCode(64).setNationalNumber(33316005L);
2843     // The default for number_of_leading_zeros is 1, so it shouldn't normally be set, however if it
2844     // is it should be considered equivalent.
2845     nzNumberTwo.setCountryCode(64).setNationalNumber(33316005L).setNumberOfLeadingZeros(1);
2846     assertEquals(PhoneNumberUtil.MatchType.EXACT_MATCH,
2847                  phoneUtil.isNumberMatch(nzNumberOne, nzNumberTwo));
2848 
2849     // Even if it is set to ten, it is still equivalent because in both cases
2850     // italian_leading_zero is not true.
2851     nzNumberTwo.setNumberOfLeadingZeros(10);
2852     assertEquals(PhoneNumberUtil.MatchType.EXACT_MATCH,
2853                  phoneUtil.isNumberMatch(nzNumberOne, nzNumberTwo));
2854   }
2855 
testIsNumberMatchIgnoresSomeFields()2856   public void testIsNumberMatchIgnoresSomeFields() throws Exception {
2857     // Check raw_input, country_code_source and preferred_domestic_carrier_code are ignored.
2858     PhoneNumber brNumberOne = new PhoneNumber();
2859     PhoneNumber brNumberTwo = new PhoneNumber();
2860     brNumberOne.setCountryCode(55).setNationalNumber(3121286979L)
2861         .setCountryCodeSource(PhoneNumber.CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN)
2862         .setPreferredDomesticCarrierCode("12").setRawInput("012 3121286979");
2863     brNumberTwo.setCountryCode(55).setNationalNumber(3121286979L)
2864         .setCountryCodeSource(PhoneNumber.CountryCodeSource.FROM_DEFAULT_COUNTRY)
2865         .setPreferredDomesticCarrierCode("14").setRawInput("143121286979");
2866     assertEquals(PhoneNumberUtil.MatchType.EXACT_MATCH,
2867                  phoneUtil.isNumberMatch(brNumberOne, brNumberTwo));
2868   }
2869 
testIsNumberMatchNonMatches()2870   public void testIsNumberMatchNonMatches() throws Exception {
2871     // Non-matches.
2872     assertEquals(PhoneNumberUtil.MatchType.NO_MATCH,
2873                  phoneUtil.isNumberMatch("03 331 6005", "03 331 6006"));
2874     assertEquals(PhoneNumberUtil.MatchType.NO_MATCH,
2875                  phoneUtil.isNumberMatch("+800 1234 5678", "+1 800 1234 5678"));
2876     // Different country calling code, partial number match.
2877     assertEquals(PhoneNumberUtil.MatchType.NO_MATCH,
2878                  phoneUtil.isNumberMatch("+64 3 331-6005", "+16433316005"));
2879     // Different country calling code, same number.
2880     assertEquals(PhoneNumberUtil.MatchType.NO_MATCH,
2881                  phoneUtil.isNumberMatch("+64 3 331-6005", "+6133316005"));
2882     // Extension different, all else the same.
2883     assertEquals(PhoneNumberUtil.MatchType.NO_MATCH,
2884                  phoneUtil.isNumberMatch("+64 3 331-6005 extn 1234", "0116433316005#1235"));
2885     assertEquals(PhoneNumberUtil.MatchType.NO_MATCH,
2886                  phoneUtil.isNumberMatch(
2887                      "+64 3 331-6005 extn 1234", "tel:+64-3-331-6005;ext=1235"));
2888     // NSN matches, but extension is different - not the same number.
2889     assertEquals(PhoneNumberUtil.MatchType.NO_MATCH,
2890                  phoneUtil.isNumberMatch("+64 3 331-6005 ext.1235", "3 331 6005#1234"));
2891 
2892     // Invalid numbers that can't be parsed.
2893     assertEquals(PhoneNumberUtil.MatchType.NOT_A_NUMBER,
2894                  phoneUtil.isNumberMatch("4", "3 331 6043"));
2895     assertEquals(PhoneNumberUtil.MatchType.NOT_A_NUMBER,
2896                  phoneUtil.isNumberMatch("+43", "+64 3 331 6005"));
2897     assertEquals(PhoneNumberUtil.MatchType.NOT_A_NUMBER,
2898                  phoneUtil.isNumberMatch("+43", "64 3 331 6005"));
2899     assertEquals(PhoneNumberUtil.MatchType.NOT_A_NUMBER,
2900                  phoneUtil.isNumberMatch("Dog", "64 3 331 6005"));
2901   }
2902 
testIsNumberMatchNsnMatches()2903   public void testIsNumberMatchNsnMatches() throws Exception {
2904     // NSN matches.
2905     assertEquals(PhoneNumberUtil.MatchType.NSN_MATCH,
2906                  phoneUtil.isNumberMatch("+64 3 331-6005", "03 331 6005"));
2907     assertEquals(PhoneNumberUtil.MatchType.NSN_MATCH,
2908                  phoneUtil.isNumberMatch(
2909                      "+64 3 331-6005", "tel:03-331-6005;isub=1234;phone-context=abc.nz"));
2910     assertEquals(PhoneNumberUtil.MatchType.NSN_MATCH,
2911                  phoneUtil.isNumberMatch(NZ_NUMBER, "03 331 6005"));
2912     // Here the second number possibly starts with the country calling code for New Zealand,
2913     // although we are unsure.
2914     PhoneNumber unchangedNzNumber = new PhoneNumber().mergeFrom(NZ_NUMBER);
2915     assertEquals(PhoneNumberUtil.MatchType.NSN_MATCH,
2916                  phoneUtil.isNumberMatch(unchangedNzNumber, "(64-3) 331 6005"));
2917     // Check the phone number proto was not edited during the method call.
2918     assertEquals(NZ_NUMBER, unchangedNzNumber);
2919 
2920     // Here, the 1 might be a national prefix, if we compare it to the US number, so the resultant
2921     // match is an NSN match.
2922     assertEquals(PhoneNumberUtil.MatchType.NSN_MATCH,
2923                  phoneUtil.isNumberMatch(US_NUMBER, "1-650-253-0000"));
2924     assertEquals(PhoneNumberUtil.MatchType.NSN_MATCH,
2925                  phoneUtil.isNumberMatch(US_NUMBER, "6502530000"));
2926     assertEquals(PhoneNumberUtil.MatchType.NSN_MATCH,
2927                  phoneUtil.isNumberMatch("+1 650-253 0000", "1 650 253 0000"));
2928     assertEquals(PhoneNumberUtil.MatchType.NSN_MATCH,
2929                  phoneUtil.isNumberMatch("1 650-253 0000", "1 650 253 0000"));
2930     assertEquals(PhoneNumberUtil.MatchType.NSN_MATCH,
2931                  phoneUtil.isNumberMatch("1 650-253 0000", "+1 650 253 0000"));
2932     // For this case, the match will be a short NSN match, because we cannot assume that the 1 might
2933     // be a national prefix, so don't remove it when parsing.
2934     PhoneNumber randomNumber = new PhoneNumber();
2935     randomNumber.setCountryCode(41).setNationalNumber(6502530000L);
2936     assertEquals(PhoneNumberUtil.MatchType.SHORT_NSN_MATCH,
2937                  phoneUtil.isNumberMatch(randomNumber, "1-650-253-0000"));
2938   }
2939 
testIsNumberMatchShortNsnMatches()2940   public void testIsNumberMatchShortNsnMatches() throws Exception {
2941     // Short NSN matches with the country not specified for either one or both numbers.
2942     assertEquals(PhoneNumberUtil.MatchType.SHORT_NSN_MATCH,
2943                  phoneUtil.isNumberMatch("+64 3 331-6005", "331 6005"));
2944     assertEquals(PhoneNumberUtil.MatchType.SHORT_NSN_MATCH,
2945                  phoneUtil.isNumberMatch("+64 3 331-6005", "tel:331-6005;phone-context=abc.nz"));
2946     assertEquals(PhoneNumberUtil.MatchType.SHORT_NSN_MATCH,
2947                  phoneUtil.isNumberMatch("+64 3 331-6005",
2948                      "tel:331-6005;isub=1234;phone-context=abc.nz"));
2949     assertEquals(PhoneNumberUtil.MatchType.SHORT_NSN_MATCH,
2950                  phoneUtil.isNumberMatch("+64 3 331-6005",
2951                      "tel:331-6005;isub=1234;phone-context=abc.nz;a=%A1"));
2952     // We did not know that the "0" was a national prefix since neither number has a country code,
2953     // so this is considered a SHORT_NSN_MATCH.
2954     assertEquals(PhoneNumberUtil.MatchType.SHORT_NSN_MATCH,
2955                  phoneUtil.isNumberMatch("3 331-6005", "03 331 6005"));
2956     assertEquals(PhoneNumberUtil.MatchType.SHORT_NSN_MATCH,
2957                  phoneUtil.isNumberMatch("3 331-6005", "331 6005"));
2958     assertEquals(PhoneNumberUtil.MatchType.SHORT_NSN_MATCH,
2959                  phoneUtil.isNumberMatch("3 331-6005", "tel:331-6005;phone-context=abc.nz"));
2960     assertEquals(PhoneNumberUtil.MatchType.SHORT_NSN_MATCH,
2961                  phoneUtil.isNumberMatch("3 331-6005", "+64 331 6005"));
2962     // Short NSN match with the country specified.
2963     assertEquals(PhoneNumberUtil.MatchType.SHORT_NSN_MATCH,
2964                  phoneUtil.isNumberMatch("03 331-6005", "331 6005"));
2965     assertEquals(PhoneNumberUtil.MatchType.SHORT_NSN_MATCH,
2966                  phoneUtil.isNumberMatch("1 234 345 6789", "345 6789"));
2967     assertEquals(PhoneNumberUtil.MatchType.SHORT_NSN_MATCH,
2968                  phoneUtil.isNumberMatch("+1 (234) 345 6789", "345 6789"));
2969     // NSN matches, country calling code omitted for one number, extension missing for one.
2970     assertEquals(PhoneNumberUtil.MatchType.SHORT_NSN_MATCH,
2971                  phoneUtil.isNumberMatch("+64 3 331-6005", "3 331 6005#1234"));
2972     // One has Italian leading zero, one does not.
2973     PhoneNumber italianNumberOne = new PhoneNumber();
2974     italianNumberOne.setCountryCode(39).setNationalNumber(1234L).setItalianLeadingZero(true);
2975     PhoneNumber italianNumberTwo = new PhoneNumber();
2976     italianNumberTwo.setCountryCode(39).setNationalNumber(1234L);
2977     assertEquals(PhoneNumberUtil.MatchType.SHORT_NSN_MATCH,
2978                  phoneUtil.isNumberMatch(italianNumberOne, italianNumberTwo));
2979     // One has an extension, the other has an extension of "".
2980     italianNumberOne.setExtension("1234").clearItalianLeadingZero();
2981     italianNumberTwo.setExtension("");
2982     assertEquals(PhoneNumberUtil.MatchType.SHORT_NSN_MATCH,
2983                  phoneUtil.isNumberMatch(italianNumberOne, italianNumberTwo));
2984   }
2985 
testCanBeInternationallyDialled()2986   public void testCanBeInternationallyDialled() throws Exception {
2987     // We have no-international-dialling rules for the US in our test metadata that say that
2988     // toll-free numbers cannot be dialled internationally.
2989     assertFalse(phoneUtil.canBeInternationallyDialled(US_TOLLFREE));
2990 
2991     // Normal US numbers can be internationally dialled.
2992     assertTrue(phoneUtil.canBeInternationallyDialled(US_NUMBER));
2993 
2994     // Invalid number.
2995     assertTrue(phoneUtil.canBeInternationallyDialled(US_LOCAL_NUMBER));
2996 
2997     // We have no data for NZ - should return true.
2998     assertTrue(phoneUtil.canBeInternationallyDialled(NZ_NUMBER));
2999     assertTrue(phoneUtil.canBeInternationallyDialled(INTERNATIONAL_TOLL_FREE));
3000   }
3001 
testIsAlphaNumber()3002   public void testIsAlphaNumber() throws Exception {
3003     assertTrue(phoneUtil.isAlphaNumber("1800 six-flags"));
3004     assertTrue(phoneUtil.isAlphaNumber("1800 six-flags ext. 1234"));
3005     assertTrue(phoneUtil.isAlphaNumber("+800 six-flags"));
3006     assertTrue(phoneUtil.isAlphaNumber("180 six-flags"));
3007     assertFalse(phoneUtil.isAlphaNumber("1800 123-1234"));
3008     assertFalse(phoneUtil.isAlphaNumber("1 six-flags"));
3009     assertFalse(phoneUtil.isAlphaNumber("18 six-flags"));
3010     assertFalse(phoneUtil.isAlphaNumber("1800 123-1234 extension: 1234"));
3011     assertFalse(phoneUtil.isAlphaNumber("+800 1234-1234"));
3012   }
3013 
testIsMobileNumberPortableRegion()3014   public void testIsMobileNumberPortableRegion() {
3015     assertTrue(phoneUtil.isMobileNumberPortableRegion(RegionCode.US));
3016     assertTrue(phoneUtil.isMobileNumberPortableRegion(RegionCode.GB));
3017     assertFalse(phoneUtil.isMobileNumberPortableRegion(RegionCode.AE));
3018     assertFalse(phoneUtil.isMobileNumberPortableRegion(RegionCode.BS));
3019   }
3020 }
3021