使用 unittest 模拟多输入函数中的 Python 输入

Simulating Python Inputs in multi-input functions using unittest

我想使用 Python 3.8 在 unittest 中模拟用户的输入。我有一个功能,首先询问用户要执行哪个程序,然后多个其他输入以获得所述应用程序所需的值。我想在单元测试中模拟这些输入 (input())。我无法从 this post 中找到答案,因为该答案使用“输入”文本,然后将其插入函数,并且不能与 input()[ 无缝协作=24=]。我想要一个与 input() 无缝协作的解决方案,就好像人是 运行 程序,returns 程序中函数的值一样输出。使用单独的函数非常乏味,并且意味着要更新程序两次,这并不理想。如果这是唯一的方法,我愿意处理它,但我宁愿不这样做。这是一些需要测试的代码。

main.py:

import numworksLibs

def page1():
    if (prgrmchoice == "1"):
        numer = int(input("Enter the Numerator of the Fraction: "))
        denom = int(input("Enter the Denominator of the Fraction: "))
        numworksLibs.simplify_fraction(numer, denom)

然后库文件接受这个输入并吐出一个答案(numworksLibs.py)。

我不确定你到底想测试什么(可能是 numworksLibs 生成的输出),但由于这是关于模拟输入,我将展示一个不使用未知的简化示例变量或函数:

main.py

def page1():
    number = int(input("Enter the Numerator of the Fraction: "))
    denom = int(input("Enter the Denominator of the Fraction: "))
    return number, denom

test_main.py

from unittest import mock
from main import page1

@mock.patch("main.input")
def test_input(mocked_input):
    mocked_input.side_effect = ['20', '10']
    assert page1() == (20, 10)

您可以根据需要将任意数量的输入值放入 side_effect 数组 - 这将模拟单独调用 input 的 return 值。当然,您必须使您的测试代码适应您的真实代码。

这假设 pytest,对于 unittest 它看起来与添加的 self 参数接受相同。