使用用户inpu的python3单元测试

2024-10-17 02:26:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python单元测试绝对是个新手。我需要用它来完成我必须提交的项目。我有点想从哪里开始,看起来我们基本上把测试参数放入我们在程序中定义的函数,然后输入预期的结果。如果预期的结果是输出,我们得到了OK,否则我们将得到失败或错误。在

所以我的问题是,我有多个用户输入存储在for循环或while循环中的变量中。我不知道从哪里开始为它们设置测试值。在

以下是我所有的代码:

studentTripExpenses = {}

def dictCreate(studentAmount):
    for i in range(0, studentAmount):
        studentName = input("What is the name of the student? ")
        expenseList = []
        print("Enter 'done' to move to the next student.")
        while True:
            expense = input("What is the cost of this expense? ")
            if expense.lower() == 'done':
                break
            elif (float(expense) >= 0) or (float(expense) < 0):
                expenseList.append(float(expense))
            elif not expense.isdigit():
                print("Please enter a number or enter 'done' to move on.")
        studentTripExpenses[studentName] = expenseList
    return studentTripExpenses

def studentCost(dct):
    for i in dct:
        #Variable for individual costs of student
        personalCost = 0
        #Determines the total cost for each student
        for x in dct[i]:
            personalCost = personalCost + x
        #Sets each students value to their total cost to two decimal places
        dct[i] = float("%.2f" % personalCost)
    return dct

def amountsDue(expenseLst, studentAvgPrice):
        #Runs through the dictionary of students and individual total trip costs
        for key in expenseLst:
            maxPerson = max(expenseLst, key=expenseLst.get)
            costDifference = 0
            #Determines who owes who how much money
            if max(expenseLst.values()) > expenseLst[key]:
                costDifference = studentAvgPrice-expenseLst[key]
                if (costDifference < 0):
                    costDifference = costDifference * -1
                print("%s owes %s $%.2f" % (key, maxPerson, costDifference))

def main():
    numOfStudents = int(input("How many students are going on the trip? "))
    studentCostDict = dictCreate(numOfStudents)
    studentTripExpenses = studentCost(studentCostDict)

    totalCost = 0

    #Gets the total cost for all students
    for key in (studentTripExpenses):
        totalCost = totalCost + studentTripExpenses[key]

    #Changes the total cost to 2 decimal places
    totalCost = float("%.2f" % totalCost)

    #Determines the average amount spent per student
    avgCost = float("%.2f" % (totalCost/len(studentTripExpenses)))

    amountsDue(studentTripExpenses, avgCost)

main()

Tags: thetokeyinforfloatstudentdct
1条回答
网友
1楼 · 发布于 2024-10-17 02:26:14

你可以用一个版本的函数来替换。您可以使用^{} module完成此操作。在

在这种情况下,您可以修补模块中的input()名称,而不是内置函数,而是调用mock对象:

from unittest import mock
from unittest import TestCase
import module_under_test

class DictCreateTests(TestCase):
    @mock.patch('module_under_test.input', create=True)
    def testdictCreateSimple(self, mocked_input):
        mocked_input.side_effect = ['Albert Einstein', '42.81', 'done']
        result = dictCreate(1)
        self.assertEqual(result, {'Albert Einstein': [42.81]})

因为您的模块中不存在input(它是一个内置函数),所以我告诉^{} decorator来创建名称;现在将使用这个input来代替内置函数。在

^{} attribute允许您声明多个结果;每次调用mock时,它都会返回列表中的下一个值。所以第一次返回'Albert Einstein',下一次返回{},依此类推

这样,您就可以模拟实际的用户输入。在

如果测试正确,您会注意到函数中有一个bug;float()调用将在输入done或有效数值之外的任何内容时抛出ValueError异常。你需要重新编写代码来解释这一点。尝试使用mocked_input.side_effect = ['Albert Einstein', 'Not an expense', '42.81', 'done']来触发错误。在

相关问题 更多 >