2014-09-24 42 views
0

在「Check iO」平臺上,其中一項任務是簡單的「Index Power」任務。作爲一個解決方案,我寫了下面,工作代碼:如何使用「Check iO」遊戲中的tests.py文件在本地測試代碼

def index_power(array, n): 
    """ 
     Find Nth power of the element with index N. 
    """ 
    return array[n] ** n if len(array) > n else -1 

if __name__ == '__main__': 
    #These "asserts" using only for self-checking and not necessary for auto-testing 
    assert index_power([1, 2, 3, 4], 2) == 9, "Square" 
    assert index_power([1, 3, 10, 100], 3) == 1000000, "Cube" 
    assert index_power([0, 1], 0) == 1, "Zero power" 
    assert index_power([1, 2], 3) == -1, "IndexError" 

對於這個任務,對於測試本地化GitHub的頁面上的測試文件。這裏有一個鏈接=>「test.py」。該文件包含以下代碼:

""" 
TESTS is a dict with all you tests. 
Keys for this will be categories' names. 
Each test is dict with 
    "input" -- input data for user function 
    "answer" -- your right answer 
    "explanation" -- not necessary key, it's using for additional info in animation. 
""" 

TESTS = { 
    "Basics": [ 
     { 
      "input": ([1, 2, 3, 4], 2), 
      "answer": 9, 
     }, 
     { 
      "input": ([1, 3, 10, 100], 3), 
      "answer": 1000000, 
     }, 
     { 
      "input": ([0, 1], 0), 
      "answer": 1, 
     }, 
     { 
      "input": ([1, 2], 3), 
      "answer": -1, 
     }, 
    ], 
    "Extra": [ 
     { 
      "input": ([0], 0), 
      "answer": 1, 
     }, 
     { 
      "input": ([1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 9), 
      "answer": 1, 
     }, 
    ] 
} 

我的問題是:是否可以測試自己的電腦與測試文件在我的計劃?如果是,我該如何實現和運行測試?

+1

是的,這是可能的 - 文檔字符串解釋了'TESTS'字典的格式。你將不得不寫一些代碼來遍歷測試並將它們應用到你的函數中,但這不是非常複雜。 – jonrsharpe 2014-09-24 14:40:48

回答

1

它不應該是複雜的。正如jonrsharpe所說,只是遍歷案例。

def run_case(input, answer): 
    assert index_power(*input) == answer, 'Failed' # Program stopped on first fail 


def test_index_power(): 
    for level, cases in TESTS.iteritems(): # You can just iterate through dict 
     print "Testing level is: %s" % level 
     for each in cases:     # And then through test cases on each level 
      run_case(**each) 


if __name__ == '__main__': 
    test_index_power() 
+0

非常感謝您的解決方案,特別是現成的代碼! :-) – Scottie 2014-10-01 18:42:21