1
1
import pytest
2
2
3
3
def fix_phone_num (phone_num_to_fix ):
4
- if len (phone_num_to_fix ) == 11 and phone_num_to_fix [0 ] == "1" :
5
- phone_num_to_fix = phone_num_to_fix [1 :] # Remove the country code "1"
4
+
5
+ if len (phone_num_to_fix ) == 11 :
6
+ # The phone number is of length 11, so check if it has the "1" country code.
7
+ if phone_num_to_fix [0 ] != "1" :
8
+ # The country code wasn't a "1", so the number is invalid.
9
+ raise ValueError (f"phone numbers of length 11 must begin with a 1, got \" { phone_num_to_fix } \" " )
10
+ # Strip off the country code "1" from the beginning.
11
+ # Resulting string should be of length 10 to work with formatting code below.
12
+ phone_num_to_fix = phone_num_to_fix [1 :]
6
13
7
14
if len (phone_num_to_fix ) != 10 :
8
15
raise ValueError (f"phone number must be length 10; got \" { phone_num_to_fix } \" which is of length { len (phone_num_to_fix )} " )
9
-
10
16
if not phone_num_to_fix .isdigit ():
11
17
raise ValueError (f"phone number must only contain digits; got \" { phone_num_to_fix } \" " )
12
-
18
+
13
19
# given "5125558823". Split the parts, then recombine and return
14
20
area_code = phone_num_to_fix [0 :3 ] # 512 (first three digits)
15
21
three_part = phone_num_to_fix [3 :6 ] # 555 (next three digits)
16
- four_part = phone_num_to_fix [6 :] # 8823 (last four digits)
22
+ four_part = phone_num_to_fix [6 :] # # 8823 (last four digits)
17
23
18
- fixed_num = f"( { area_code } ) { three_part } { four_part } "
24
+ fixed_num = "(" + area_code + ")" + " " + three_part + " " + four_part
19
25
20
26
return fixed_num
21
27
@@ -30,20 +36,20 @@ def test_fix_phone_num3():
30
36
assert fix_phone_num ("3216543333" ) == '(321) 654 3333'
31
37
32
38
def test_short_num_error ():
33
- with pytest .raises (ValueError ):
34
- fix_phone_num ("51" )
39
+ with pytest .raises (ValueError ):
40
+ fix_phone_num ("51" )
35
41
36
42
def test_long_num_error ():
37
- with pytest .raises (ValueError ):
38
- fix_phone_num ("01234567890" )
43
+ with pytest .raises (ValueError ):
44
+ fix_phone_num ("01234567890" )
39
45
40
46
def test_non_digit_error ():
41
- with pytest .raises (ValueError ):
42
- fix_phone_num ("012345678a" )
47
+ with pytest .raises (ValueError ):
48
+ fix_phone_num ("012345678a" )
43
49
44
50
def test_fix_phone_num_country_code ():
45
51
assert fix_phone_num ("15125558823" ) == '(512) 555 8823'
46
52
47
53
def test_wrong_country_code ():
48
54
with pytest .raises (ValueError ):
49
- fix_phone_num ("25125558823" )
55
+ assert fix_phone_num ("25125558823" )
0 commit comments