【发布时间】:2020-07-02 11:27:32
【问题描述】:
我制作了一个只有一个功能的程序。该函数有一个文件作为输入,函数将结果写入输出。我需要测试我的结果是否与预期相同。下面你可以找到一个程序的代码:
import os
def username(input):
with open(input, 'r') as file:
if os.stat(input).st_size == 0:
print('File is empty')
else:
print('File is not empty')
for line in file:
count = 1
id, first, middle, surname, department = line.split(":")
first1 = first.lower()
middle1 = middle.lower()
surname1 = surname.lower()
username = first1[:1] + middle1[:1] + surname1
username1 = username[:8]
if username1 not in usernames:
usernames.append(username1)
data = id + ":" + username1 + ":" + first + ":" + middle + ":" + surname + ":" + department
else:
username2 = username1 + str(count)
usernames.append(username2)
data = id + ":" + username2 + ":" + first + ":" + middle + ":" + surname + ":" + department
count += 1
with open("output.txt", "a+") as username_file:
username_file.write(data)
usernames = []
if __name__ == '__main__':
username("input_file1.txt")
username("input_file2.txt")
username("input_file3.txt")
with open("output.txt", "a+") as username_file:
username_file.write("\n")
如何在这种类型的程序上编写单元测试?我试过这个,但它给了我这个错误 "TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper" 。我的测试代码如下:
import unittest
import program.py
class TestProgram(unittest.TestCase):
def test_username(self):
i_f = open("input_file1.txt", 'r')
result = program.username(i_f)
o_f = open("expected_output.txt", 'r')
self.assertEqual(result, o_f)
if __name__ == '__main__':
unittest.main()
如果你能帮助我,我会很高兴!!!
【问题讨论】:
-
你传递一个文件对象而不是文件名。应该是 program.username('input_file1.txt')
-
还是不行:)
标签: python unit-testing python-unittest