In Python, how do you programmatically execute unit tests stored in a string?

The following code is used to execute doctrines in a Google App Engine application. How do you do this for tests written as unit test and not as doctrines?

#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
+5
source share
1 answer

, unittest.TestCase.assertEqual, , . , , 'assertEqual(b, 5)', , - , , , ( , , - 'self.', self .. ..).

, , , , : unittest.Testcase, . , , , , ( ). Yecch.

+3

All Articles