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