Python单元测试跳过主应用程序中的特定步骤

标签 python unit-testing user-input

我有一个温度应用程序,它需要用户输入(什么单位,温度)在不同的温度单位之间进行转换。它涉及通过正常的 str(input(xyz)) 和 float(input(123)) 类型的提示提示用户输入这些单位和数字,之后应用程序的其余部分获取该数据并使用它来执行任务,从一些基本的手动测试中我发现它是正确的。

我想练习使用unittest为我的应用程序编写单元测试,因此也编写了这些单元测试(我相信也是正确的)。测试按预期通过。然而,我的问题是,即使我提供了测试在测试本身中工作所需的数据,我仍然需要完成主应用程序中的输入提示。虽然我可以按 Enter 跳过它并且测试将按预期进行,但我宁愿找到某种方法让单元测试本身填写这些输入提示,完全绕过该输入位,或者至少将其静音,以便我不这样做不必每次都执行所有输入提示。可以用单元测试来做到这一点吗?

这是我为主应用程序编写的基本结构

def main():
  unit_from, unit_to, temperature = user_input

  # continues with the rest of the application using above data...


#function to get user input
def user_input():
#gets user input using str and float prompts.
#and then returns those values for use in the rest of the program

main()

对于单元测试:

import unittest

#module containing classes where the formulas for conversion live
import temperature
#main application that utilzes temperature classes and drives it all
import temp_converter

class FahrenheitConvertTestCase(unittest.TestCase):
#one of my example tests
  def test_f_to_c(self):
    from_unit = 'FAHRENHEIT'
    to_unit = 'CELSIUS'
    temp = 32.0
    t_convert = temperature.Fahrenheit(temp, from_unit, to_unit)
    converted_temp = t_convert.convert()
    self.assertEqual(converted_temp, 0.0) 

最佳答案

当你有一个带有函数调用的模块时

main()

它将在导入模块时调用。

您可以通过将其包装在条件中来避免这种情况

if __name__ == '__main__':
    main()

那么 main 仅当该模块作为主程序执行时才会被调用,而不是在导入时被调用。

关于Python单元测试跳过主应用程序中的特定步骤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37898366/

相关文章:

python - 无法对提供给加载的朴素贝叶斯模型的用户输入值进行编码?

python - 有没有办法根据列表中的所有数字检查数字?

python - pandas - 如何过滤 "most frequent"日期时间对象

javascript - 从用户输入创建 3D 形状?

java - 只需一个 Setter 即可实现多个输入

python - 启用详细日志记录的更简单方法

ruby - 为什么 MiniTest::Spec 没有 wont_raise 断言?

python - django 使用装置进行单元测试 - 对象匹配查询不存在

Python单元测试: Unit test the message passed in raised exception

php - 创建电话号码格式标准 php