1
我正在解決Python中的一些練習,並使用unittest來自動化我的一些代碼驗證。一個程序運行單個單元測試就可以了,並且通過。第二個提供了以下錯誤:從__main__失敗的命令行調用unittests
$ python s1c6.py
E
======================================================================
ERROR: s1c6 (unittest.loader._FailedTest)
----------------------------------------------------------------------
AttributeError: module '__main__' has no attribute 's1c6'
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
下面是工作腳本代碼:
# s1c5.py
import unittest
import cryptopals
class TestRepeatingKeyXor(unittest.TestCase):
def testCase(self):
key = b"ICE"
data = b"Burning 'em, if you ain't quick and nimble\nI go crazy when I hear a cymbal"
expected = bytes.fromhex(
"0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f")
self.assertEqual(expected, cryptopals.xorcrypt(key, data))
if __name__ == "__main__":
unittest.main()
而對於失敗的腳本代碼:
# s1c6.py
import unittest
import bitstring
import cryptopals
class TestHammingDistance(unittest.TestCase):
def testCase(self):
str1 = b'this is a test'
str2 = b'wokka wokka!!!'
expected = 37
self.assertEqual(expected, hamming_distance(str1, str2))
def hamming_distance(str1, str2):
temp = cryptopals.xor(str1, str2)
return sum(bitstring.Bits(temp))
if __name__ == "__main__":
unittest.main()
我沒有看到一個基本這兩個程序之間的差異會導致一個錯誤而不是另一個錯誤。我錯過了什麼?
import itertools
import operator
def xor(a, b):
return bytes(map(operator.xor, a, b))
def xorcrypt(key, cipher):
return b''.join(xor(key, x) for x in grouper(cipher, len(key)))
def grouper(iterable, n):
it = iter(iterable)
group = tuple(itertools.islice(it, n))
while group:
yield group
group = tuple(itertools.islice(it, n))
「原始」 版沒有腳本:
# s1c6_raw.py
import cryptopals
key = b"ICE"
data = b"Burning 'em, if you ain't quick and nimble\nI go crazy when I hear a cymbal"
expected = bytes.fromhex(
"0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f")
print(cryptopals.xorcrypt(key, data))
以上運行正常並打印預期輸出。
如果您將失敗的測試用例中的代碼放入文件(以及必要的導入)並運行它,會發生什麼? – BrenBarn
你是如何安裝隱形眼鏡的?它不在PyPi上,是嗎? – Eddie
@Eddie cryptopals是我自己的.py文件,與所示的兩個文件位於相同的目錄中。 –