构建一个程序,该程序创建(字符串)电话号码对象并以多种方式对其进行操作。
测试套件要求许多值错误。实现这些并使程序通过那些测试非常困难。
例如,对下面的number1.number的调用返回:
Interrupted: 1 errors during collection
然后程序停止并且不调用number2。
我的问题:如何编写以下代码,以便在引发第一个异常后继续运行?
class Phone (object):
def __init__(self, phone_number):
punctuation = ['\'', '+', '(', ')', '-', '.',',',' ']
self.clean_number = [item for item in phone_number if item not in punctuation]
self.output = ''.join(self.clean_number)
if self.clean_number[0] == '1' and len(self.clean_number) > 10:
self.clean_number = self.clean_number[1:]
self.verify()
@property
def number(self):
if len(self.output) > 10:
return self.output[1:]
else:
return self.output
@property
def area_code(self):
return self.output[:3]
def pretty(self):
pretty_number = [char for char in self.clean_number]
pretty_number.insert(0, '(')
pretty_number.insert(4, ')')
pretty_number.insert(5, ' ')
pretty_number.insert(9, '-')
return ''.join(pretty_number)
def verify(self):
if 'a' in self.clean_number:
raise ValueError("Letter in number.")
number1 = Phone("123-abc-7890")
print(number1.number)
number2 = Phone("(213) 555-3456")
print(number2.number)
下面是测试,
def test_invalid_with_letters(self):
with self.assertRaisesWithMessage(ValueError):
Phone("123-abc-7890")