如何在 Python 中模拟用户输入 [英] How to Mock a user input in Python

查看:34
本文介绍了如何在 Python 中模拟用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试学习如何使用 Python 进行单元测试,并了解了 Mocking 的概念,我是一名 Python 初学者,希望在开发 Python 技能的同时学习 TDD 的概念.我正在努力学习使用用户的给定输入为 Python unittest.mock 文档. 如果我能得到一个如何模拟某个函数的示例,我将不胜感激.我将使用此处找到的示例:例题

I am currently trying to learn how to Unit Test with Python and was introduced to the concept of Mocking, I am a beginner Python developer hoping to learn the concepts of TDD alongside my development of Python skills. I am struggling to learn the concept of mocking a class with a given input from the user for 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 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 的年份.

Please could somebody create my an example Unit Test using Mocking to automate the input for age so that it would return the year which the mock'ed age would be 100.

谢谢.

推荐答案

Here - I fixed calculate_age(), 你试试 `calculate_year.

Here - I fixed calculate_age(), You try `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()

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

From what I see in your code, you should look up how to build functions - And please don't take that in an offensive manner. Also you could just test your function by hand by running it. As your code stands, it does not run.

祝你好运!

这篇关于如何在 Python 中模拟用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆