Python Unittest测试具有随机变量和不可预测输入的函数

时间:2015-08-21 15:16:32

标签: python function unit-testing random

功能理念:

随机+随机=输出(对或错)

功能:

def input_gener():
    """Generates questions and prints and
    returns status result of user input as a string"""
    a = random.randrange(1,10)
    b = random.randrange(1,10)
    c = input("What is the sum of {0} and {1}? ".format(a,b))
    if c == a+b:
        print("{0} is right!.".format(c))
        status = "was right"
    else:
        print("{0} is wrong!.".format(c))
        status = "was wrong"            
    return status

我可以创建这样的测试:

def test_res_right(self):
    #Test right value
    right_status ="was right"
    self.assertEqual(right_status,input_gener())
def test_res_wrong(self):
    wrong_status = "was wrong"
    self.assertEqual(wrong_status,input_gener())

结果取决于我将如何输入数据。除非以某种方式我可以从变量“a”和“b”中检索值,并且可以通过更自动化的方式修改每个测试是对还是错。 什么是更好的方法来测试这种类型的函数,其中随机值未知和输入是不可预测的。

2 个答案:

答案 0 :(得分:0)

您不应直接在函数中调用random.randrange,而应定义一个单独的本地函数,然后您可以在测试中模拟它以返回一些预期值。

答案 1 :(得分:0)

您可以使用unittest.mockbackport来模拟library(party) dt = data.frame(mtcars) cforest(disp ~ wt, data = dt) # Random Forest using Conditional Inference Trees # # Number of trees: 500 # # Response: disp # Input: wt # Number of observations: 32 # # There were 50 or more warnings (use warnings() to see the first 50) #### see the warnings!! cforest(disp ~ wt+mpg+cyl+vs+gear, data = dt) # Random Forest using Conditional Inference Trees # # Number of trees: 500 # # Response: disp # Inputs: wt, mpg, cyl, vs, gear # Number of observations: 32 ,以便为您的单元测试返回可重复的结果。