首页 > 解决方案 > 如何测试创建文件的 class::method()?

问题描述

我正在尝试实现一个类,该类具有基于键盘输入创建新文件的方法。我有一个名为FileManipulator.py的文件,其中包含类 + 方法:

class FileManipulator:
    def __init__(self):
        pass

    def fileChecker(self):
        print("+++ EXECUTING FILE CREATION METHOD +++")
        new_custom_filename = input("Give filename: ")
        custom_file_path = input("Give path where to create file: ")
        print(custom_file_path)
        try:
            new_file = open(custom_file_path + "/" + new_custom_filename + ".ttcn3", "x+")
        except OSError:
            print("Creation of the file %s failed" % new_custom_filename)
        else:
            print("Successfully created the file %s" % new_custom_filename)

以这种方式执行:

fm_obj = FileManipulator()
result = fm_obj.fileChecker()

我可以看到在我也作为输入提供的路径上创建的“file_name_give_as_input.ttcn3” 。

问题是结果的类型为 NONE

在这种情况下,我无法正确测试我的方法。我已经像这样创建了python unittest:

from unittest import TestCase
from FileManipulator import FileManipulator
import os

class FileManipulatorTest(TestCase):
    def test_fileChecker(self):
       FM = FileManipulator()
       result = FM.fileChecker()
       self.assertEqual(os.path.abspath(result, "ut_testing.ttcn3"))

if __name__ == '__main__':
   unittest.main()

测试失败,因为:

预期:无

实际:.\test_cases\ut\ut_testing.ttcn3

我的问题是: 我如何创建单元测试来测试“file.ttcn3”是否是在特定位置“物理”创建的?

也许我测试错了,因为我启动了等待用户输入的方法,这破坏了这个特定测试的自动化并可能导致 - 测试挂起执行。

标签: pythonpython-3.xunit-testingfilepython-unittest

解决方案


推荐阅读