我已經通過負載NameError在單元測試的問題在這裏搜索,但我似乎無法找到任何可與我的問題相關的任何東西。Python單元測試無類型名稱錯誤
這是一個家庭作業,所以如果你可以告訴我我哪裏出錯了,而不是如何糾正它,那會很棒。我試圖爲一個函數編寫一個單元測試,用列表中的第一個數字替換列表中的最後一個數字。
這裏是我的功能編寫的代碼:
def swap_k(L, k):
""" (list, int) -> NoneType
Precondtion: 0 <= k <= len(L) // 2
Swap the first k items of L with the last k items of L.
>>> nums = [1, 2, 3, 4, 5, 6]
>>> swap_k(nums, 2)
>>> nums
[5, 6, 3, 4, 1, 2]
>>> nums = [1, 2, 3, 4, 5, 6]
>>> swap_k(nums, 3)
>>> nums
[4, 5, 6, 1, 2, 3]
"""
L[:k], L[-k:] = L[-k:], L[:k]
此代碼工作正常使用文檔測試,沒有錯誤可言,所以我敢肯定,沒有什麼不妥的地方。但是,我爲unittest編寫的代碼不斷給我一個NameError。下面是單元測試代碼:
import a1
import unittest
class TestSwapK(unittest.TestCase):
""" Test class for function a1.swap_k. """
def test_swapk_1(self):
"""Swap the first k items of L with the last k items of L. Where L =
[1, 2, 3, 4, 5, 6] and k = 2."""
L = [1, 2, 3, 4, 5, 6]
expected = [5, 6, 3, 4, 1, 2]
a1.swap_k(L, k)
self.assertEqual(L, expected)
if __name__ == '__main__':
unittest.main(exit=False)
這是錯誤消息:
E
======================================================================
ERROR: test_swapk_1 (__main__.TestSwapK)
Swap the first k items of L with the last k items of L. Where L =
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\xxxxx\xxxxxxxxxx\xxxxxxxxxxxx\test_swap_k.py", line 13, in test_swapk_1
a1.swap_k(L, k)
NameError: global name 'k' is not defined
----------------------------------------------------------------------
Ran 1 test in 0.016s
FAILED (errors=1)`
是否有人可以告訴我,我要去哪裏錯了,它的駕駛我瘋了。如果可以告訴我哪裏出錯,而不告訴我答案,請再這麼做。
我應該知道我錯過了一些簡單的東西,謝謝你花時間回答。對於Python來說很新穎,之前從未有過NameError – user1816131 2013-04-09 15:18:58