来自__main__的单元测试的命令行调用失败

时间:2016-12-31 02:31:13

标签: python command-line runtime-error command-line-arguments python-unittest

我正在使用Python解决一些练习,并使用unittest自动执行一些代码验证。一个程序运行单个unittest就好了,它通过了。第二个出现以下错误:

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

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

1 个答案:

答案 0 :(得分:2)

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

$ python s1c5.py

$ python s1c6.py s1c6.txt

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

相关问题