【问题标题】:How to Mock a user input in Python如何在 Python 中模拟用户输入
【发布时间】:2018-02-23 15:32:59
【问题描述】:

我目前正在尝试学习如何使用 Python 进行单元测试,并被介绍了 Mocking 的概念,我是一名 Python 初学者开发人员,希望在开发 Python 技能的同时学习 TDD 的概念。我正在努力学习使用来自Python unittest.mock documentation. 的用户的给定输入来模拟类的概念如果我能得到一个如何模拟某个函数的示例,我将非常感激。我将使用此处找到的示例:Example Question

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 自动输入年龄,以便返回模拟年龄为 100 的年份。

谢谢。

【问题讨论】:

  • 我认为最好将计算与用户界面分开。然后计算变得非常容易进行单元测试。

标签: python unit-testing mocking tdd python-mock


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    您不模拟输入,而是模拟函数。在这里,嘲笑input 基本上是最容易做的事情了。

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

    【讨论】:

      【解决方案3】:

      这里 - 我修复了 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()
      

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

      祝你好运!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-11-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-28
        • 1970-01-01
        相关资源
        最近更新 更多