CYCAMORE
Loading...
Searching...
No Matches
helper.py
Go to the documentation of this file.
1"""A set of tools for use in integration tests."""
2import os
3import tempfile
4import subprocess
5import sys
6from hashlib import sha1
7import numpy as np
8
9
10CYCLUS_HAS_COIN = None
11
12
13if sys.version_info[0] >= 3:
14 str_types = (bytes, str)
15else:
16 str_types = (str, unicode)
17
18def hasher(x):
19 return int(sha1(x.encode()).hexdigest(), 16)
20
21def idx(h):
22 ind = [None] * 5
23 for i in range(4, -1, -1):
24 h, ind[i] = divmod(h, 2**32)
25 return tuple(ind)
26
27sha1array = lambda x: np.array(idx(hasher(x)), np.uint32)
28
29def table_exist(db, tables):
30 """Checks if hdf5 database contains the specified tables.
31 """
32 return all([t in db.root for t in tables])
33
34def find_ids(data, data_table, id_table):
35 """Finds ids of the specified data located in the specified data_table,
36 and extracts the corresponding id from the specified id_table.
37 """
38 ids = []
39 for i, d in enumerate(data_table):
40 if isinstance(d, np.ndarray) and isinstance(data, np.ndarray):
41 if (d == data).all():
42 ids.append(id_table[i])
43 elif isinstance(d, np.ndarray) and not isinstance(data, np.ndarray):
44 if (d == sha1array(data)).all():
45 ids.append(id_table[i])
46 elif d == data:
47 ids.append(id_table[i])
48 return ids
49
50def exit_times(agent_id, exit_table):
51 """Finds exit times of the specified agent from the exit table.
52 """
53 i = 0
54 exit_times = []
55 for index in exit_table["AgentId"]:
56 if index == agent_id:
57 exit_times.append(exit_table["ExitTime"][i])
58 i += 1
59
60 return exit_times
61
62
63def run_cyclus(cyclus, cwd, in_path, out_path):
64 """Runs cyclus with various inputs and creates output databases
65 """
66 holdsrtn = [1] # needed because nose does not send() to test generator
67 # make sure the output target directory exists
68 cmd = [cyclus, "-o", out_path, "--input-file", in_path]
69 check_cmd(cmd, cwd, holdsrtn)
70
71
72def check_cmd(args, cwd, holdsrtn):
73 """Runs a command in a subprocess and verifies that it executed properly.
74 """
75 if not isinstance(args, str_types):
76 args = " ".join(args)
77 print("TESTING: running command in {0}:\n\n{1}\n".format(cwd, args))
78 env = dict(os.environ)
79 env['_'] = subprocess.check_output(['which', 'cyclus'], cwd=cwd).strip()
80 with tempfile.NamedTemporaryFile() as f:
81 rtn = subprocess.call(args, shell=True, cwd=cwd, stdout=f, stderr=f, env=env)
82 if rtn != 0:
83 f.seek(0)
84 print("STDOUT + STDERR:\n\n" + f.read().decode())
85 holdsrtn[0] = rtn
86 assert rtn == 0
87
88
90 global CYCLUS_HAS_COIN
91 if CYCLUS_HAS_COIN is not None:
92 return CYCLUS_HAS_COIN
93 s = subprocess.check_output(['cyclus', '--version'], universal_newlines=True)
94 s = s.strip().replace('Dependencies:', '')
95 m = {k.strip(): v.strip() for k,v in [line.split()[:2] for line in s.splitlines()
96 if line != '']}
97 CYCLUS_HAS_COIN = m['Coin-Cbc'] != '-1'
98 return CYCLUS_HAS_COIN
99
check_cmd(args, cwd, holdsrtn)
Definition helper.py:72
exit_times(agent_id, exit_table)
Definition helper.py:50
table_exist(db, tables)
Definition helper.py:29
find_ids(data, data_table, id_table)
Definition helper.py:34
run_cyclus(cyclus, cwd, in_path, out_path)
Definition helper.py:63
np sha1array
Definition helper.py:27
hasher(x)
Definition helper.py:18
cyclus_has_coin()
Definition helper.py:89
idx(h)
Definition helper.py:21