| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
"""Self tests |
| 26 |
|
| 27 |
These tests should perform quickly and can ideally be used every time an |
| 28 |
application runs. |
| 29 |
""" |
| 30 |
|
| 31 |
import sys |
| 32 |
import unittest |
| 33 |
from importlib import import_module |
| 34 |
from Crypto.Util.py3compat import StringIO |
| 35 |
|
| 36 |
|
| 37 |
class SelfTestError(Exception): |
| 38 |
def __init__(self, message, result): |
| 39 |
Exception.__init__(self, message, result) |
| 40 |
self.message = message |
| 41 |
self.result = result |
| 42 |
|
| 43 |
|
| 44 |
def run(module=None, verbosity=0, stream=None, tests=None, config=None, **kwargs): |
| 45 |
"""Execute self-tests. |
| 46 |
|
| 47 |
This raises SelfTestError if any test is unsuccessful. |
| 48 |
|
| 49 |
You may optionally pass in a sub-module of SelfTest if you only want to |
| 50 |
perform some of the tests. For example, the following would test only the |
| 51 |
hash modules: |
| 52 |
|
| 53 |
Crypto.SelfTest.run(Crypto.SelfTest.Hash) |
| 54 |
|
| 55 |
""" |
| 56 |
|
| 57 |
if config is None: |
| 58 |
config = {} |
| 59 |
suite = unittest.TestSuite() |
| 60 |
if module is None: |
| 61 |
if tests is None: |
| 62 |
tests = get_tests(config=config) |
| 63 |
suite.addTests(tests) |
| 64 |
else: |
| 65 |
if tests is None: |
| 66 |
suite.addTests(module.get_tests(config=config)) |
| 67 |
else: |
| 68 |
raise ValueError("'module' and 'tests' arguments are mutually exclusive") |
| 69 |
if stream is None: |
| 70 |
kwargs['stream'] = StringIO() |
| 71 |
else: |
| 72 |
kwargs['stream'] = stream |
| 73 |
runner = unittest.TextTestRunner(verbosity=verbosity, **kwargs) |
| 74 |
result = runner.run(suite) |
| 75 |
if not result.wasSuccessful(): |
| 76 |
if stream is None: |
| 77 |
sys.stderr.write(kwargs['stream'].getvalue()) |
| 78 |
raise SelfTestError("Self-test failed", result) |
| 79 |
return result |
| 80 |
|
| 81 |
|
| 82 |
def get_tests(config={}): |
| 83 |
tests = [] |
| 84 |
|
| 85 |
module_names = [ |
| 86 |
"Cipher", "Hash", "Protocol", "PublicKey", "Random", |
| 87 |
"Util", "Signature", "IO", "Math", |
| 88 |
] |
| 89 |
|
| 90 |
for name in module_names: |
| 91 |
module = import_module("Crypto.SelfTest." + name) |
| 92 |
tests += module.get_tests(config=config) |
| 93 |
|
| 94 |
return tests |
| 95 |
|
| 96 |
|
| 97 |
if __name__ == '__main__': |
| 98 |
def suite(): |
| 99 |
return unittest.TestSuite(get_tests()) |
| 100 |
unittest.main(defaultTest='suite') |
| 101 |
|
| 102 |
|