简体   繁体   English

fileinput.input 的单元测试

[英]Unit Test for fileinput.input

I have some code I'm trying to write a unit test for.我有一些代码正在尝试为其编写单元测试。

This is the function I have:这是我的功能:

def sanitize_text():
    total_text = []

    # Regex split to strip non-alphanumeric characters
    for line in fileinput.input():
        line.casefold()
        words = [x for x in re.split("\W",line) if x]
        total_text += words

    return total_text

My intention is to have this function work with an unspecified number of files passed in as an argument, or with stdin, so fileinput seemed like a good way to do that.我的目的是让这个函数使用作为参数传入的未指定数量的文件,或者使用标准输入,所以fileinput似乎是一个很好的方法来做到这一点。

However, I can't figure out how to write a unit test for this, mainly because I can't figure out how to pass this function "fake" input.但是,我无法弄清楚如何为此编写单元测试,主要是因为我无法弄清楚如何通过此函数“假”输入。

I've tried using mock patch and opening a fake file, but it doesn't seem to get passed to the function properly.我试过使用模拟补丁并打开一个假文件,但它似乎没有正确传递给函数。 I've also tried using mock patch to spoof sys.argv[1] , but that only lets me spoof a file name, not the content.我还尝试使用模拟补丁来欺骗sys.argv[1] ,但这只能让我欺骗文件名,而不是内容。

What's a good way to fool this function into accepting fake input for the sake of the unit test?为了单元测试,欺骗这个函数接受虚假输入的好方法是什么?

You said this code is not in its final shape yet, so I will focus only on the part about how to pass "fake input".你说这段代码还没有最终成型,所以我只关注如何传递“假输入”的部分。 One commonly useful trick is to separate the part of your code that does the calculations from the part that is interacting with other code/libraries/IO:一个常用的技巧是将进行计算的代码部分与与其他代码/库/IO 交互的部分分开:

def add_sanitized_line(text, line):
    line.casefold()
    # Regex split to strip non-alphanumeric characters
    words = [x for x in re.split("\W",line) if x]
    text += words

This function can be nicely unit-tested without need for mocking.这个函数可以很好地进行单元测试,而无需模拟。 You provide it "fake input" by passing any kind of input for line you consider necessary.您可以通过为您认为必要的line传递任何类型的输入来提供“假输入”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM