【发布时间】:2019-08-24 19:52:47
【问题描述】:
基本上我需要创建一个函数,允许我从文件中加载计划旅程的基本细节。我们是这样的:
参数:包含文件路径的字符串
返回:包含从文件中读取的旅程的开始位置、结束位置和到达时间的三元组字符串,如果不成功,则返回 (None, None, None)。
有多个测试都使用幻数作为输入。测试如下:
这是坏数据测试的代码,应该给你一个测试的例子:
PATH = os.path.expanduser('~/test_prev_plan_spec.txt')
def test_missing_file_is_handled(self):
if os.path.exists(self.PATH):
os.unlink(self.PATH)
plan = utils.load_prev_plan_spec(self.PATH)
self.assertEqual(3, len(plan))
self.assertEqual(plan, (None, None, None))
def test_spec_loads_ok(self):
from_ = 'Bournemouth'
to = 'Southampton'
arrive_at = '2019/04/20 13:30'
with open(self.PATH, 'wt') as f:
f.write('{}\n{}\n{}\n'.format(from_, to, arrive_at))
plan = utils.load_prev_plan_spec(self.PATH)
self.assertEqual(3, len(plan))
self.assertEqual(from_, plan[0])
self.assertEqual(to, plan[1])
self.assertEqual(arrive_at, plan[2])
def test_short_spec_is_ignored(self):
from_ = 'Bournemouth'
to = 'Southampton'
with open(self.PATH, 'wt') as f:
f.write('{}\n{}\n'.format(from_, to))
plan = utils.load_prev_plan_spec(self.PATH)
self.assertEqual(3, len(plan))
self.assertEqual(plan, (None, None, None))
with open(self.PATH, 'wt') as f:
f.write('{}\n'.format(from_))
plan = utils.load_prev_plan_spec(self.PATH)
self.assertEqual(3, len(plan))
self.assertEqual(plan, (None, None, None))
def test_empty_line_is_handled(self):
from_ = 'Bournemouth'
to = ''
arrive_at = '2019/04/20 13:30'
with open(self.PATH, 'wt') as f:
f.write('{}\n{}\n{}\n'.format(from_, to, arrive_at))
plan = utils.load_prev_plan_spec(self.PATH)
self.assertEqual(3, len(plan))
self.assertEqual(plan, (None, None, None))
def test_bad_data_line_is_handled(self):
from_ = 'Bournemouth'
to = 'Southampton'
arrive_at = '2019/04/20 13:60'
with open(self.PATH, 'wt') as f:
f.write('{}\n{}\n{}\n'.format(from_, to, arrive_at))
plan = utils.load_prev_plan_spec(self.PATH)
self.assertEqual(3, len(plan))
self.assertEqual(plan, (None, None, None))
这是我到目前为止所拥有的,我正在寻求帮助,任何解释都会很棒!
我的密码ATM:
def load_prev_plan_spec(PATH):
'''
Function: utils.load_prev_plan_specLoads the basic details of a planned journey from a file.
Parameters: A string containing a file path
Returns: A 3-tuple of strings containing start location, end location and arrival time of a journey
read from the file, or (None, None, None) if unsuccessful.
'''
try:
if os.path.exists(PATH):
infomation = []
f = open(PATH, 'r', encoding='cp1252')
for line in f:
infomation.append([line.strip()])
if not line.strip():
infomation = (None, None, None)
tuple(infomation)
f.close()
return infomation
else:
pass
except IOError as err2:
print(err2)
raise IOError
else:
return infomation
【问题讨论】:
-
不清楚您实际要问的是什么。您要做什么也不完全清楚。通常,您应该提供一个简明的工作示例来说明您的问题,并告诉我们您的尝试。如果您只是询问如何处理异常,请阅读here。然后,阅读文档以了解您使用的方法可能引发哪些异常,可能添加一些自定义异常并使用
try-except进行处理。
标签: python python-3.x exception