| 1 |
# Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 2 |
# not use this file except in compliance with the License. You may obtain |
| 3 |
# a copy of the License at |
| 4 |
# |
| 5 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 6 |
# |
| 7 |
# Unless required by applicable law or agreed to in writing, software |
| 8 |
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 9 |
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 10 |
# License for the specific language governing permissions and limitations |
| 11 |
# under the License. |
| 12 |
|
| 13 |
import collections |
| 14 |
import functools |
| 15 |
import inspect |
| 16 |
import time |
| 17 |
import types |
| 18 |
|
| 19 |
from cryptography.hazmat.primitives.asymmetric import rsa |
| 20 |
from cryptography.hazmat.primitives import hashes |
| 21 |
from cryptography.hazmat.primitives import serialization |
| 22 |
from cryptography import x509 |
| 23 |
|
| 24 |
|
| 25 |
def def_method(f, *args, **kwargs): |
| 26 |
@functools.wraps(f) |
| 27 |
def new_method(self): |
| 28 |
return f(self, *args, **kwargs) |
| 29 |
return new_method |
| 30 |
|
| 31 |
|
| 32 |
def parameterized_class(cls): |
| 33 |
"""A class decorator for running parameterized test cases. |
| 34 |
|
| 35 |
Mark your class with @parameterized_class. |
| 36 |
Mark your test cases with @parameterized. |
| 37 |
""" |
| 38 |
test_functions = inspect.getmembers(cls, predicate=inspect.ismethod) |
| 39 |
for (name, f) in test_functions: |
| 40 |
if name.startswith('test_') and not hasattr(f, '_test_data'): |
| 41 |
continue |
| 42 |
|
| 43 |
# remove the original test function from the class |
| 44 |
delattr(cls, name) |
| 45 |
|
| 46 |
# add a new test function to the class for each entry in f._test_data |
| 47 |
for tag, args in f._test_data.items(): |
| 48 |
new_name = "{0}_{1}".format(f.__name__, tag) |
| 49 |
if hasattr(cls, new_name): |
| 50 |
raise Exception( |
| 51 |
"Parameterized test case '{0}.{1}' created from '{0}.{2}' " |
| 52 |
"already exists".format(cls.__name__, new_name, name)) |
| 53 |
|
| 54 |
# Using `def new_method(self): f(self, **args)` is not sufficient |
| 55 |
# (all new_methods use the same args value due to late binding). |
| 56 |
# Instead, use this factory function. |
| 57 |
new_method = def_method(f, **args) |
| 58 |
|
| 59 |
# To add a method to a class, available for all instances: |
| 60 |
# MyClass.method = types.MethodType(f, None, MyClass) |
| 61 |
setattr(cls, new_name, types.MethodType(new_method, None, cls)) |
| 62 |
return cls |
| 63 |
|
| 64 |
|
| 65 |
def parameterized(data): |
| 66 |
"""A function decorator for parameterized test cases. |
| 67 |
|
| 68 |
Example: |
| 69 |
|
| 70 |
@parameterized({ |
| 71 |
'zero': dict(val=0), |
| 72 |
'one': dict(val=1), |
| 73 |
}) |
| 74 |
def test_val(self, val): |
| 75 |
self.assertEqual(val, self.get_val()) |
| 76 |
|
| 77 |
The above will generate two test cases: |
| 78 |
`test_val_zero` which runs with val=0 |
| 79 |
`test_val_one` which runs with val=1 |
| 80 |
|
| 81 |
:param data: A dictionary that looks like {tag: {arg1: val1, ...}} |
| 82 |
""" |
| 83 |
def wrapped(f): |
| 84 |
f._test_data = data |
| 85 |
return f |
| 86 |
return wrapped |
| 87 |
|
| 88 |
|
| 89 |
def wait_for_condition(condition, interval=1, timeout=40): |
| 90 |
start_time = time.time() |
| 91 |
end_time = time.time() + timeout |
| 92 |
while time.time() < end_time: |
| 93 |
result = condition() |
| 94 |
if result: |
| 95 |
return result |
| 96 |
time.sleep(interval) |
| 97 |
raise Exception(("Timed out after %s seconds. Started on %s " |
| 98 |
+ "and ended on %s") % (timeout, start_time, end_time)) |
| 99 |
|
| 100 |
|
| 101 |
def memoized(func): |
| 102 |
"""A decorator to cache function's return value""" |
| 103 |
cache = {} |
| 104 |
|
| 105 |
@functools.wraps(func) |
| 106 |
def wrapper(*args): |
| 107 |
if not isinstance(args, collections.Hashable): |
| 108 |
# args is not cacheable. just call the function. |
| 109 |
return func(*args) |
| 110 |
if args in cache: |
| 111 |
return cache[args] |
| 112 |
else: |
| 113 |
value = func(*args) |
| 114 |
cache[args] = value |
| 115 |
return value |
| 116 |
return wrapper |
| 117 |
|
| 118 |
|
| 119 |
def generate_csr_and_key(): |
| 120 |
"""Return a dict with a new csr, public key and private key.""" |
| 121 |
private_key = rsa.generate_private_key( |
| 122 |
public_exponent=65537, |
| 123 |
key_size=2048 |
| 124 |
) |
| 125 |
|
| 126 |
public_key = private_key.public_key() |
| 127 |
|
| 128 |
csr = x509.CertificateSigningRequestBuilder().subject_name(x509.Name([ |
| 129 |
x509.NameAttribute(x509.oid.NameOID.COMMON_NAME, u"admin"), |
| 130 |
x509.NameAttribute(x509.oid.NameOID.ORGANIZATION_NAME, |
| 131 |
u"system:masters") |
| 132 |
])).sign(private_key, hashes.SHA256()) |
| 133 |
|
| 134 |
result = { |
| 135 |
'csr': csr.public_bytes( |
| 136 |
encoding=serialization.Encoding.PEM).decode("utf-8"), |
| 137 |
'private_key': private_key.private_bytes( |
| 138 |
encoding=serialization.Encoding.PEM, |
| 139 |
format=serialization.PrivateFormat.TraditionalOpenSSL, |
| 140 |
encryption_algorithm=serialization.NoEncryption()).decode("utf-8"), |
| 141 |
'public_key': public_key.public_bytes( |
| 142 |
encoding=serialization.Encoding.PEM, |
| 143 |
format=serialization.PublicFormat.SubjectPublicKeyInfo).decode( |
| 144 |
"utf-8"), |
| 145 |
} |
| 146 |
|
| 147 |
return result |