如何在 Python 中模拟用户输入

How to Mock a user input in Python

我目前正在尝试学习如何使用 Python 进行单元测试并被介绍了 Mocking 的概念,我是一名初学者 Python 开发人员希望在我的开发过程中学习 TDD 的概念Python 项技能。我正在努力学习使用 Python unittest.mock documentation. If I could get an example of how I would mock a certain function, I would be really grateful. I will use the example found here: Example Question

的用户给定输入模拟 class 的概念
class AgeCalculator(self):

    def calculate_age(self):
        age = input("What is your age?")
        age = int(age)
        print("Your age is:", age)
        return age

    def calculate_year(self, age)
        current_year = time.strftime("%Y")
        current_year = int(current_year)
        calculated_date = (current_year - age) + 100
        print("You will be 100 in", calculated_date)
        return calculated_date

有人可以使用 Mocking 创建我的示例单元测试来自动输入年龄,以便 return 模拟年龄为 100 的那一年。

谢谢。

你模拟的不是输入,而是函数。在这里,mocking input 基本上是最简单的事情了。

from unittest.mock import patch

@patch('yourmodule.input')
def test(mock_input):
    mock_input.return_value = 100
    # Your test goes here

可以mock Python3.x中的buildins.input方法,使用with语句控制mock周期的范围

import unittest.mock
def test_input_mocking():
    with unittest.mock.patch('builtins.input', return_value=100):
         xxx

这里 - 我修复了 calculate_age(),你试试`calculate_year.

    class AgeCalculator:  #No arg needed to write this simple class

        def calculate_age():  # Check your sample code, no 'self' arg needed
            #age = input("What is your age?") #Can't use for testing
            print ('What is your age?') #Can use for testing 
            age = '9' # Here is where I put in a test age, substitutes for User Imput
            age = int(age)
            print("Your age is:", age)
            #return age -- Also this is not needed for this simple function

        def calculate_year(age): # Again, no 'Self' arg needed - I cleaned up your top function, you try to fix this one using my example
            current_year = time.strftime("%Y")
            current_year = int(current_year)
            calculated_date = (current_year - age) + 100
            print("You will be 100 in", calculated_date)
            return calculated_date


    AgeCalculator.calculate_age()

根据我在您的代码中看到的内容,您应该了解如何构建函数 - 请不要以冒犯的方式看待它。您也可以通过 运行ning 手动测试您的功能。正如您的代码所代表的那样,它不会 运行.

祝你好运!