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)) 

以上运行正常并打印预期输出。

+0

如果您将失败的测试用例中的代码放入文件(以及必要的导入)并运行它,会发生什么? – BrenBarn

+0

你是如何安装隐形眼镜的?它不在PyPi上,是吗? – Eddie

+0

@Eddie cryptopals是我自己的.py文件,与所示的两个文件位于相同的目录中。 –

回答

2

的问题是,我以不同的方式运行两个脚本:

$ python s1c5.py 

$ python s1c6.py s1c6.txt 

由于unittest.main()解析命令行参数,还有在第二种情况下的错误。如果我将命令行参数传递给第一个程序,我也会得到相同的错误。