【问题标题】:How to write a simple test code to test a python program that has a function with two arguments?如何编写一个简单的测试代码来测试一个有两个参数的函数的python程序?
【发布时间】:2022-01-08 19:05:13
【问题描述】:

我是python新手,我写了一个python程序,它读取文件列表并将特定字符(ch)的总数保存在一个字典,然后返回它。

程序运行良好,现在我正在尝试编写一个简单的测试代码来测试程序。

我尝试了以下代码,

def test_read_files():
    assert read_files("H:\\SomeTextFiles\\zero-k.txt", 'k') == 0, "Should be 0"

if __name__ == "__main__":
    test_read_files()
    print("Everything passed")

我将程序命名为 test_read_files.py

我的python代码如下:

# This function reads a list of files and saves number of
# a particular character (ch) in dictionary and returns it.

def read_files(filePaths, ch):

    # dictionary for saing no of character's in each file
    dictionary = {}
    
    for filePath in filePaths:

        try:
            # using "with statement" with open() function
            with open(filePath, "r") as file_object:
                # read file content
                fileContent = file_object.read()
                dictionary[filePath] = fileContent.count(ch)
            
        except Exception:
            # handling exception
            print('An Error with opening the file '+filePath)
            dictionary[filePath] = -1

    return dictionary


fileLists = ["H:\\SomeTextFiles\\16.txt", "H:\\SomeTextFiles\\Statement1.txt",
             "H:\\SomeTextFiles\\zero-k.txt", "H:\\SomeTextFiles"]

print(read_files(fileLists, 'k'))

我将其命名为 read_files.py

当我运行测试代码时,出现错误:NameError: name 'read_files' is not defined

程序和测试代码都在同一个文件夹中(虽然不同于python文件夹)。

【问题讨论】:

    标签: python-3.x file testing


    【解决方案1】:

    希望我理解正确,但如果你们两个都是 python 文件:

    1. test_read_files.py
    2. read_files.py

    在同一个目录下。。那么你应该可以在 test_read_files.py 的顶部添加以下导入命令:

    from read_files import read_files
    

    这将从您的 read_files.py 脚本中导入 read_files 函数,这样您就可以在另一个文件中运行它。

    【讨论】:

    • 它解决了之前的错误,但似乎它使用python程序中定义的参数运行,但我想只使用测试代码中的参数运行测试代码。我不得不删除一些行。 {'H:\\SomeTextFiles\\16.txt': 581, 'H:\\SomeTextFiles\\Statement1.txt': 0, 'H:\\SomeTextFiles\\zero-k.txt': 0, 'H :\\SomeTextFiles': -1} Traceback(最近一次调用最后):文件“C:/Python scripts/test_read_files.py”,第 3 行,在 test_read_files 中断言 read_files(["H:\\SomeTextFiles\\zero-k .txt"], 'k') == 0, "应该是 0" AssertionError: 应该是 0 @MiTriPy
    • 我解决了,谢谢。
    • 我现在注意到原始代码中有一些逻辑错误。例如,循环(for filePath in filePaths:) 循环遍历您传递给 read_files 的字符串中的所有单个字符。我认为您的意图是检查多个文件?如果我能提供进一步帮助,请告诉我
    • 请让我知道这些逻辑错误。该代码旨在读取我所做的文件列表。 @MiTriPy
    • @abhimanyue 延迟响应,但看看在 read_files.py 中如何将列表 ([]) 传递给 read_files() 函数?好吧,您的测试用例中也使用了相同的函数,但是您传递的是字符串(“”)而不是列表。这导致抓取列表中每个文件的循环抓取字符串中的每个字符。在测试文件中做这样的事情应该会有所帮助:read_files(["H:\\SomeTextFiles\\zero-k.txt"], 'k')(注意添加 [])
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多