[英]In Python, how do you programmatically execute unit tests stored in a string?
以下代碼用於在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
類的方法(例如unittest.TestCase.assertEqual
)不在該類的實例提供的上下文之外執行。 因此,像'assertEqual(b, 5)'
這樣的字符串實際上是一個非常非常糟糕的情況 - 請注意,寫入的字符串永遠不會正常執行(至少需要預先設置一些像'self.'
這樣'self.'
,然后self
需要成為類的實例等等)。
我不確定你為什么要支持這種災難性的結構,但是,如果你堅持認為你不惜一切代價這么做 ,那么這就是一般的想法:創建一個unittest.Testcase
類的實例,在前面加上實例引用名稱和該字符串的一個點,並執行該復合字符串。 然后,當然,您會遇到各種其他有趣的要求,例如捕獲可能引發的異常(因為您沒有真正有測試運行器來為您執行所有此類內務處理任務)。 Yecch。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.