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