Debian Codegraph @

tests/TLib.py

raw symbols SCIP
1 """
2 Unit test library
3 """
4
5 import logging
6 import os
7 import socket
8 import sys
9 import time
10
11 from tempfile import mkstemp
12 from tempfile import TemporaryFile, NamedTemporaryFile, TemporaryDirectory
13
14 try:
15 import configparser
16 except ImportError:
17 import ConfigParser as configparser
18
19 from io import BytesIO, StringIO
20
21
22 __all__ = ['HOSTNAME', 'which', 'load_cfg', 'make_temp_filename',
23 'make_temp_file', 'make_temp_dir', 'CLI_main']
24
25 # Get machine short hostname
26 HOSTNAME = socket.gethostname().split('.', 1)[0]
27
28 # Replace with shutil.which() once we only support Py3.3+
29 def which(program):
30 """Return path of first executable program found in PATH, or None."""
31 for path in os.environ.get('PATH', '').split(os.pathsep):
32 fpath = os.path.join(path, program)
33 if os.path.isfile(fpath) and os.access(fpath, os.X_OK):
34 return fpath
35 return None
36
37 class TBytesIO(BytesIO):
38 """Standard stream of in memory bytes for testing purpose."""
39
40 def __init__(self, initial_bytes=None):
41 if initial_bytes and type(initial_bytes) is not bytes:
42 initial_bytes = initial_bytes.encode()
43 BytesIO.__init__(self, initial_bytes)
44
45 def write(self, s):
46 BytesIO.write(self, s.encode())
47
48 def isatty(self):
49 return False
50
51
52 def load_cfg(name):
53 """Load test configuration file as a new ConfigParser"""
54 cfgparser = configparser.ConfigParser()
55 cfgparser.read([ \
56 os.path.expanduser('~/.clustershell/tests/%s' % name),
57 '/etc/clustershell/tests/%s' % name])
58 return cfgparser
59
60 #
61 # Temp files and directories
62 #
63 def make_temp_filename(suffix=''):
64 """Return a temporary name for a file."""
65 if len(suffix) > 0 and suffix[0] != '-':
66 suffix = '-' + suffix
67 fd, name = mkstemp(suffix, prefix='cs-test-')
68 os.close(fd) # don't leak open fd
69 return name
70
71 def make_temp_file(text, suffix='', dir=None):
72 """Create a temporary file with the provided text."""
73 assert type(text) is bytes
74 tmp = NamedTemporaryFile(prefix='cs-test-',
75 suffix=suffix, dir=dir)
76 tmp.write(text)
77 tmp.flush()
78 return tmp
79
80 def make_temp_dir(suffix=''):
81 """Create a temporary directory."""
82 if len(suffix) > 0 and suffix[0] != '-':
83 suffix = '-' + suffix
84 return TemporaryDirectory(suffix, prefix='cs-test-')
85
86
87 #
88 # CLI tests
89 #
90 def CLI_main(test, main, args, stdin, expected_stdout, expected_rc=0,
91 expected_stderr=None):
92 """Generic CLI main() direct calling function that allows code coverage
93 checks."""
94 rc = -1
95
96 saved_stdin = sys.stdin
97 saved_stdout = sys.stdout
98 saved_stderr = sys.stderr
99 # a CLI -d run calls logging.basicConfig(); snapshot root logging to restore it
100 saved_log_handlers = logging.root.handlers[:]
101 saved_log_level = logging.root.level
102
103 # Capture standard streams
104
105 # Input: if defined, the stdin argument specifies input data
106 if stdin is not None:
107 if type(stdin) is bytes:
108 # Use temporary file in Python 2 or with buffer (bytes) in Python 3
109 sys.stdin = TemporaryFile()
110 sys.stdin.write(stdin)
111 sys.stdin.seek(0) # ready to be read
112 else:
113 # If stdin is a string in Python 3, use StringIO as sys.stdin
114 # should be read in text mode for some tests (eg. Nodeset).
115 sys.stdin = StringIO(stdin)
116
117 # Output: ClusterShell writes to stdout/stderr using strings, but the tests
118 # expect bytes. TBytesIO is a wrapper that does the conversion until we
119 # migrate all tests to string.
120 sys.stdout = out = TBytesIO()
121 sys.stderr = err = TBytesIO()
122 sys.argv = args
123 try:
124 main()
125 except SystemExit as exc:
126 rc = int(str(exc))
127 finally:
128 sys.stdout = saved_stdout
129 sys.stderr = saved_stderr
130 # undo logging config a CLI -d run leaked (handler bound to closed stderr)
131 for handler in logging.root.handlers:
132 if handler not in saved_log_handlers:
133 handler.close()
134 logging.root.handlers[:] = saved_log_handlers
135 logging.root.setLevel(saved_log_level)
136 # close temporary file if we used one for stdin
137 if saved_stdin != sys.stdin:
138 sys.stdin.close()
139 sys.stdin = saved_stdin
140
141 try:
142 if expected_stdout is not None:
143 # expected_stdout might be a compiled regexp or a string
144 try:
145 if not expected_stdout.search(out.getvalue()):
146 # search failed; use assertEqual() to display
147 # expected/output
148 test.assertEqual(out.getvalue(), expected_stdout.pattern)
149 except AttributeError:
150 # not a regexp
151 test.assertEqual(out.getvalue(), expected_stdout)
152
153 if expected_stderr is not None:
154 # expected_stderr might be a compiled regexp or a string
155 try:
156 if not expected_stderr.match(err.getvalue()):
157 # match failed; use assertEqual() to display expected/output
158 test.assertEqual(err.getvalue(), expected_stderr.pattern)
159 except AttributeError:
160 # check the end as stderr messages are often prefixed with
161 # argv[0]
162 test.assertTrue(err.getvalue().endswith(expected_stderr),
163 err.getvalue() + b' != ' + expected_stderr)
164
165 if expected_rc is not None:
166 test.assertEqual(rc, expected_rc,
167 "rc=%d err=%s" % (rc, err.getvalue()))
168 finally:
169 out.close()
170 err.close()