SHARE
TWEET

Lock test case generator

a guest Aug 22nd, 2016 29 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. def generate_initial(level = 0):
  2.     import random
  3.     if random.random() > 0.8 ** level: # generate more branches near root
  4.         return random.randint(1, 12) # limit amount of distinct keys for more interesting test cases
  5.     else:
  6.         return [generate_initial(level + 1), random.choice(["&", "|"]), generate_initial(level + 1)]
  7.  
  8. def stringify_tree(tree = None):
  9.     tree = tree if tree is not None else generate_clean()
  10.     return str(tree) if isinstance(tree, (int, str, bool)) else "(" + "".join(map(stringify_tree, tree)) + ")"
  11.  
  12. def get_keys(tree):
  13.     return {tree} if isinstance(tree, int) else get_keys(tree[0]) | get_keys(tree[2])
  14.  
  15. def powerset(iterable):
  16.     import itertools
  17.     s = list(iterable)
  18.     return list(itertools.chain.from_iterable(itertools.combinations(s, r) for r in range(len(s) + 1)))
  19.  
  20. def replace_keys(tree, keys, newkeys):
  21.     if isinstance(tree, int):
  22.         return newkeys[keys.index(tree)]
  23.     return [replace_keys(tree[0], keys, newkeys), tree[1], replace_keys(tree[2], keys, newkeys)]
  24.  
  25. def get_security(tree):
  26.     keys = sorted(get_keys(tree))
  27.     combs = powerset(keys)
  28.     valid = []
  29.     for comb in combs:
  30.         newkeys = [key in comb for key in keys]
  31.         modify = replace_keys(tree, keys, newkeys)
  32.         if eval(stringify_tree(modify)):
  33.             valid.append(comb[::-1])
  34.     return sorted(valid)[0]
  35.  
  36. trees = [generate_initial() for n in range(10)]
  37. keys = set()
  38. for tree in trees:
  39.     keys |= get_keys(tree)
  40. keys = sorted(keys)
  41. for tree in trees:
  42.     tree = replace_keys(tree, keys, range(1, len(keys) + 1))
  43.     print(tree)
  44.     print(get_security(tree))
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top