在Python中,如何以编程方式执行存储在字符串中的单元测试?

Chr*_*ris 5 python testing

以下代码用于在Google App Engine应用中执行doctests.对于作为单元测试断言而不是作为doctests编写的测试,你会如何做到这一点?

#The solution and tests are untrusted code passed in to the GAE app. 
solution = 'b=5'
unittest = 'assertEqual(b, 5)'

#Here is the doctest version as a reference. 
solution = 'b=5'
doctest = '>>> b \n 5'

#Compile and exec the untrusted solution provided by the user. 
compiled = compile(solution, 'submitted code', 'exec')
sandbox = {}
exec compiled in sandbox

#Compile and exec each of the doctests
test_cases = doctest.DocTestParser().get_examples(doctest)
  for test in test_cases:
    if not test.want:
      exec test.source in sandbox
Run Code Online (Sandbox Code Playgroud)

Ale*_*lli 3

类的方法(例如unittest.TestCase.assertEqual)不会在该类的实例提供的上下文之外执行。所以,像你这样的字符串'assertEqual(b, 5)'确实是一个非常非常糟糕的情况 - 请注意,编写的字符串永远不会正确执行(你需要在前面添加,至少,像'self.',然后self需要将其制作为一个实例班级等)。

我不确定为什么你想要支持这种灾难性的构造,但是,如果你坚持不惜一切代价想要支持,那么这就是一般的想法:创建类的实例unittest.Testcase,在实例引用之前添加实例引用该字符串的名称和点,然后执行复合字符串。然后,当然,您会遇到各种其他有趣的要求,例如捕获可能引发的异常(因为您实际上没有测试运行程序来为您完成所有此类内务任务)。耶奇。