【问题标题】:Python Unittest testing program with input and output file带有输入和输出文件的 Python Unittest 测试程序
【发布时间】: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


【解决方案1】:

您没有读取文件,只是传递了 IO 对象。

编辑TestProgram并添加.read()

class TestProgram(unittest.TestCase):
    def test_username(self):
        i_f = open("input_file1.txt", 'r').read() # read the file
        result = program.username(i_f)
        o_f = open("expected_output.txt", 'r').read()
        self.assertEqual(result, o_f)

你也可以使用 with-as 来自动关闭文件。

【讨论】:

  • 是否需要关闭这些文件?
  • 你可以关闭它或者希望python自动关闭它,大多数时候它会这样做,但我也读到关闭我们的资源是一个好习惯。 stackoverflow.com/questions/25070854/…
  • 我现在收到此错误 => "OSError: [Errno 22] Invalid argument"
  • 您给定的路径是否与"input_file1.txt" 完全一样或更复杂?
  • 这个文件的路径没问题,因为我在同一个目录运行 unittest
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-08
  • 1970-01-01
  • 1970-01-01
  • 2022-08-18
相关资源
最近更新 更多