blob: 6a1796f2c807de9bc1e042a0866c97307d0c2db2 [file] [log] [blame]
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +02001# osmo_gsm_tester: test suite
2#
3# Copyright (C) 2016-2017 by sysmocom - s.f.m.c. GmbH
4#
5# Author: Neels Hofmeyr <neels@hofmeyr.de>
6#
7# This program is free software: you can redistribute it and/or modify
8# it under the terms of the GNU Affero General Public License as
9# published by the Free Software Foundation, either version 3 of the
10# License, or (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15# GNU Affero General Public License for more details.
16#
17# You should have received a copy of the GNU Affero General Public License
18# along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20import os
Neels Hofmeyr3531a192017-03-28 14:30:28 +020021import sys
22import time
Your Name44af3412017-04-13 03:11:59 +020023import copy
Pau Espin Pedrol0ffb4142017-05-15 18:24:35 +020024import traceback
Neels Hofmeyr2d1d5612017-05-22 20:02:41 +020025import pprint
Neels Hofmeyr798e5922017-05-18 15:24:02 +020026from . import config, log, template, util, resource, schema, ofono_client, event_loop
27from . import osmo_nitb
28from . import osmo_hlr, osmo_mgcpgw, osmo_msc, osmo_bsc
Neels Hofmeyr3531a192017-03-28 14:30:28 +020029from . import test
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +020030
Neels Hofmeyr1ffc3fe2017-05-07 02:15:21 +020031class Timeout(Exception):
32 pass
33
Pau Espin Pedrol0ffb4142017-05-15 18:24:35 +020034class Failure(Exception):
35 '''Test failure exception, provided to be raised by tests. fail_type is
36 usually a keyword used to quickly identify the type of failure that
37 occurred. fail_msg is a more extensive text containing information about
38 the issue.'''
39
40 def __init__(self, fail_type, fail_msg):
41 self.fail_type = fail_type
42 self.fail_msg = fail_msg
43
Neels Hofmeyr3531a192017-03-28 14:30:28 +020044class SuiteDefinition(log.Origin):
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +020045 '''A test suite reserves resources for a number of tests.
46 Each test requires a specific number of modems, BTSs etc., which are
47 reserved beforehand by a test suite. This way several test suites can be
48 scheduled dynamically without resource conflicts arising halfway through
49 the tests.'''
50
51 CONF_FILENAME = 'suite.conf'
52
Neels Hofmeyr3531a192017-03-28 14:30:28 +020053 CONF_SCHEMA = util.dict_add(
54 {
55 'defaults.timeout': schema.STR,
56 },
57 dict([('resources.%s' % k, t) for k,t in resource.WANT_SCHEMA.items()])
58 )
59
60
61 def __init__(self, suite_dir):
62 self.set_log_category(log.C_CNF)
63 self.suite_dir = suite_dir
64 self.set_name(os.path.basename(self.suite_dir))
65 self.read_conf()
66
67 def read_conf(self):
68 with self:
69 self.dbg('reading %s' % SuiteDefinition.CONF_FILENAME)
70 if not os.path.isdir(self.suite_dir):
71 raise RuntimeError('No such directory: %r' % self.suite_dir)
72 self.conf = config.read(os.path.join(self.suite_dir,
73 SuiteDefinition.CONF_FILENAME),
74 SuiteDefinition.CONF_SCHEMA)
75 self.load_tests()
76
Neels Hofmeyr3531a192017-03-28 14:30:28 +020077 def load_tests(self):
78 with self:
79 self.tests = []
80 for basename in sorted(os.listdir(self.suite_dir)):
81 if not basename.endswith('.py'):
82 continue
83 self.tests.append(Test(self, basename))
84
85 def add_test(self, test):
86 with self:
87 if not isinstance(test, Test):
88 raise ValueError('add_test(): pass a Test() instance, not %s' % type(test))
89 if test.suite is None:
90 test.suite = self
91 if test.suite is not self:
92 raise ValueError('add_test(): test already belongs to another suite')
93 self.tests.append(test)
94
Neels Hofmeyr3531a192017-03-28 14:30:28 +020095class Test(log.Origin):
Pau Espin Pedrol0ffb4142017-05-15 18:24:35 +020096 UNKNOWN = 'UNKNOWN'
97 SKIP = 'SKIP'
98 PASS = 'PASS'
99 FAIL = 'FAIL'
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200100
101 def __init__(self, suite, test_basename):
102 self.suite = suite
103 self.basename = test_basename
104 self.path = os.path.join(self.suite.suite_dir, self.basename)
105 super().__init__(self.path)
106 self.set_name(self.basename)
107 self.set_log_category(log.C_TST)
Pau Espin Pedrol0ffb4142017-05-15 18:24:35 +0200108 self.status = Test.UNKNOWN
109 self.start_timestamp = 0
110 self.duration = 0
111 self.fail_type = None
112 self.fail_message = None
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200113
114 def run(self, suite_run):
115 assert self.suite is suite_run.definition
Pau Espin Pedrol0ffb4142017-05-15 18:24:35 +0200116 try:
117 with self:
118 self.status = Test.UNKNOWN
119 self.start_timestamp = time.time()
Pau Espin Pedrol927344b2017-05-22 16:38:49 +0200120 test.setup(suite_run, self, ofono_client, sys.modules[__name__], event_loop)
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200121 self.log('START')
122 with self.redirect_stdout():
123 util.run_python_file('%s.%s' % (self.suite.name(), self.name()),
124 self.path)
Pau Espin Pedrol0ffb4142017-05-15 18:24:35 +0200125 if self.status == Test.UNKNOWN:
126 self.set_pass()
127 except Exception as e:
128 self.log_exn()
129 if isinstance(e, Failure):
130 ftype = e.fail_type
131 fmsg = e.fail_msg + '\n' + traceback.format_exc().rstrip()
132 else:
133 ftype = type(e).__name__
134 fmsg = repr(e) + '\n' + traceback.format_exc().rstrip()
135 if isinstance(e, resource.NoResourceExn):
Neels Hofmeyr2d1d5612017-05-22 20:02:41 +0200136 fmsg += suite_run.resource_status_str()
137
Pau Espin Pedrol0ffb4142017-05-15 18:24:35 +0200138 self.set_fail(ftype, fmsg, False)
139
140 finally:
141 if self.status == Test.PASS or self.status == Test.SKIP:
142 self.log(self.status)
143 else:
144 self.log('%s (%s)' % (self.status, self.fail_type))
145 return self.status
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200146
147 def name(self):
148 l = log.get_line_for_src(self.path)
149 if l is not None:
150 return '%s:%s' % (self._name, l)
151 return super().name()
152
Pau Espin Pedrol0ffb4142017-05-15 18:24:35 +0200153 def set_fail(self, fail_type, fail_message, tb=True):
154 self.status = Test.FAIL
155 self.duration = time.time() - self.start_timestamp
156 self.fail_type = fail_type
157 self.fail_message = fail_message
158 if tb:
159 self.fail_message += '\n' + ''.join(traceback.format_stack()[:-1]).rstrip()
160
161 def set_pass(self):
162 self.status = Test.PASS
163 self.duration = time.time() - self.start_timestamp
164
165 def set_skip(self):
166 self.status = Test.SKIP
167 self.duration = 0
168
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200169class SuiteRun(log.Origin):
Pau Espin Pedrol0ffb4142017-05-15 18:24:35 +0200170 UNKNOWN = 'UNKNOWN'
171 PASS = 'PASS'
172 FAIL = 'FAIL'
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200173
174 trial = None
175 resources_pool = None
176 reserved_resources = None
177 _resource_requirements = None
178 _config = None
179 _processes = None
180
Your Name44af3412017-04-13 03:11:59 +0200181 def __init__(self, current_trial, suite_scenario_str, suite_definition, scenarios=[]):
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200182 self.trial = current_trial
183 self.definition = suite_definition
184 self.scenarios = scenarios
Your Name44af3412017-04-13 03:11:59 +0200185 self.set_name(suite_scenario_str)
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200186 self.set_log_category(log.C_TST)
187 self.resources_pool = resource.ResourcesPool()
188
Pau Espin Pedrol0ffb4142017-05-15 18:24:35 +0200189 def mark_start(self):
190 self.tests = []
191 self.start_timestamp = time.time()
192 self.duration = 0
193 self.test_failed_ctr = 0
194 self.test_skipped_ctr = 0
195 self.status = SuiteRun.UNKNOWN
196
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200197 def combined(self, conf_name):
Your Name44af3412017-04-13 03:11:59 +0200198 self.dbg(combining=conf_name)
199 with log.Origin(combining_scenarios=conf_name):
200 combination = copy.deepcopy(self.definition.conf.get(conf_name) or {})
201 self.dbg(definition_conf=combination)
202 for scenario in self.scenarios:
203 with scenario:
204 c = scenario.get(conf_name)
205 self.dbg(scenario=scenario.name(), conf=c)
206 if c is None:
207 continue
208 config.combine(combination, c)
209 return combination
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200210
211 def resource_requirements(self):
212 if self._resource_requirements is None:
213 self._resource_requirements = self.combined('resources')
214 return self._resource_requirements
215
216 def config(self):
217 if self._config is None:
218 self._config = self.combined('config')
219 return self._config
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200220
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200221 def reserve_resources(self):
222 if self.reserved_resources:
223 raise RuntimeError('Attempt to reserve resources twice for a SuiteRun')
Neels Hofmeyr7e2e8f12017-05-14 03:37:13 +0200224 self.log('reserving resources in', self.resources_pool.state_dir, '...')
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200225 with self:
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200226 self.reserved_resources = self.resources_pool.reserve(self, self.resource_requirements())
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200227
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200228 def run_tests(self, names=None):
Your Name44af3412017-04-13 03:11:59 +0200229 self.log('Suite run start')
Pau Espin Pedrol469316f2017-05-17 14:51:31 +0200230 try:
231 self.mark_start()
Pau Espin Pedrol927344b2017-05-22 16:38:49 +0200232 event_loop.register_poll_func(self.poll)
Pau Espin Pedrol469316f2017-05-17 14:51:31 +0200233 if not self.reserved_resources:
234 self.reserve_resources()
235 for test in self.definition.tests:
236 if names and not test.name() in names:
237 test.set_skip()
238 self.test_skipped_ctr += 1
239 self.tests.append(test)
240 continue
241 with self:
242 st = test.run(self)
243 if st == Test.FAIL:
244 self.test_failed_ctr += 1
245 self.tests.append(test)
246 finally:
247 # if sys.exit() called from signal handler (e.g. SIGINT), SystemExit
248 # base exception is raised. Make sure to stop processes in this
249 # finally section. Resources are automatically freed with 'atexit'.
250 self.stop_processes()
Neels Hofmeyred4e5282017-05-29 02:53:54 +0200251 self.free_resources()
Pau Espin Pedrol927344b2017-05-22 16:38:49 +0200252 event_loop.unregister_poll_func(self.poll)
Pau Espin Pedrol0ffb4142017-05-15 18:24:35 +0200253 self.duration = time.time() - self.start_timestamp
254 if self.test_failed_ctr:
255 self.status = SuiteRun.FAIL
256 else:
257 self.status = SuiteRun.PASS
258 self.log(self.status)
259 return self.status
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200260
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200261 def remember_to_stop(self, process):
262 if self._processes is None:
263 self._processes = []
Pau Espin Pedrolecf10792017-05-08 16:56:38 +0200264 self._processes.insert(0, process)
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200265
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200266 def stop_processes(self):
267 if not self._processes:
268 return
269 for process in self._processes:
270 process.terminate()
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200271
Neels Hofmeyred4e5282017-05-29 02:53:54 +0200272 def free_resources(self):
273 if self.reserved_resources is None:
274 return
275 self.reserved_resources.free()
276
Neels Hofmeyr76d81032017-05-18 18:35:32 +0200277 def ip_address(self):
278 return self.reserved_resources.get(resource.R_IP_ADDRESS)
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200279
Neels Hofmeyr76d81032017-05-18 18:35:32 +0200280 def nitb(self, ip_address=None):
281 if ip_address is None:
282 ip_address = self.ip_address()
283 return osmo_nitb.OsmoNitb(self, ip_address)
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200284
Neels Hofmeyr798e5922017-05-18 15:24:02 +0200285 def hlr(self, ip_address=None):
286 if ip_address is None:
287 ip_address = self.ip_address()
288 return osmo_hlr.OsmoHlr(self, ip_address)
289
290 def mgcpgw(self, ip_address=None, bts_ip=None):
291 if ip_address is None:
292 ip_address = self.ip_address()
293 return osmo_mgcpgw.OsmoMgcpgw(self, ip_address, bts_ip)
294
295 def msc(self, hlr, mgcpgw, ip_address=None):
296 if ip_address is None:
297 ip_address = self.ip_address()
298 return osmo_msc.OsmoMsc(self, hlr, mgcpgw, ip_address)
299
300 def bsc(self, msc, ip_address=None):
301 if ip_address is None:
302 ip_address = self.ip_address()
303 return osmo_bsc.OsmoBsc(self, msc, ip_address)
304
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200305 def bts(self):
306 return bts_obj(self, self.reserved_resources.get(resource.R_BTS))
307
308 def modem(self):
309 return modem_obj(self.reserved_resources.get(resource.R_MODEM))
310
Neels Hofmeyrf2d279c2017-05-06 15:05:02 +0200311 def modems(self, count):
312 l = []
313 for i in range(count):
314 l.append(self.modem())
315 return l
316
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200317 def msisdn(self):
318 msisdn = self.resources_pool.next_msisdn(self.origin)
319 self.log('using MSISDN', msisdn)
320 return msisdn
321
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200322 def poll(self):
323 if self._processes:
324 for process in self._processes:
Neels Hofmeyr5356d0a2017-04-10 03:45:30 +0200325 if process.terminated():
Neels Hofmeyr85eb3242017-04-09 22:01:16 +0200326 process.log_stdout_tail()
327 process.log_stderr_tail()
328 process.raise_exn('Process ended prematurely')
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200329
330 def prompt(self, *msgs, **msg_details):
331 'ask for user interaction. Do not use in tests that should run automatically!'
332 if msg_details:
333 msgs = list(msgs)
334 msgs.append('{%s}' %
335 (', '.join(['%s=%r' % (k,v)
336 for k,v in sorted(msg_details.items())])))
337 msg = ' '.join(msgs) or 'Hit Enter to continue'
338 self.log('prompt:', msg)
Neels Hofmeyracf0c932017-05-06 16:05:33 +0200339 sys.__stdout__.write('\n\n--- PROMPT ---\n')
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200340 sys.__stdout__.write(msg)
Neels Hofmeyracf0c932017-05-06 16:05:33 +0200341 sys.__stdout__.write('\n')
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200342 sys.__stdout__.flush()
Neels Hofmeyracf0c932017-05-06 16:05:33 +0200343 entered = util.input_polling('> ', self.poll)
344 self.log('prompt entered:', repr(entered))
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200345 return entered
346
Neels Hofmeyr2d1d5612017-05-22 20:02:41 +0200347 def resource_status_str(self):
348 return '\n'.join(('',
349 'SUITE RUN: %s' % self.origin_id(),
350 'ASKED FOR:', pprint.pformat(self._resource_requirements),
351 'RESERVED COUNT:', pprint.pformat(self.reserved_resources.counts()),
352 'RESOURCES STATE:', repr(self.reserved_resources)))
353
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200354loaded_suite_definitions = {}
355
356def load(suite_name):
357 global loaded_suite_definitions
358
359 suite = loaded_suite_definitions.get(suite_name)
360 if suite is not None:
361 return suite
362
363 suites_dir = config.get_suites_dir()
364 suite_dir = suites_dir.child(suite_name)
365 if not suites_dir.exists(suite_name):
366 raise RuntimeError('Suite not found: %r in %r' % (suite_name, suites_dir))
367 if not suites_dir.isdir(suite_name):
368 raise RuntimeError('Suite name found, but not a directory: %r' % (suite_dir))
369
370 suite_def = SuiteDefinition(suite_dir)
371 loaded_suite_definitions[suite_name] = suite_def
372 return suite_def
373
374def parse_suite_scenario_str(suite_scenario_str):
375 tokens = suite_scenario_str.split(':')
376 if len(tokens) > 2:
377 raise RuntimeError('invalid combination string: %r' % suite_scenario_str)
378
379 suite_name = tokens[0]
380 if len(tokens) <= 1:
381 scenario_names = []
382 else:
383 scenario_names = tokens[1].split('+')
384
385 return suite_name, scenario_names
386
387def load_suite_scenario_str(suite_scenario_str):
388 suite_name, scenario_names = parse_suite_scenario_str(suite_scenario_str)
389 suite = load(suite_name)
390 scenarios = [config.get_scenario(scenario_name) for scenario_name in scenario_names]
Your Name44af3412017-04-13 03:11:59 +0200391 return (suite_scenario_str, suite, scenarios)
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200392
393def bts_obj(suite_run, conf):
394 bts_type = conf.get('type')
395 log.dbg(None, None, 'create BTS object', type=bts_type)
396 bts_class = resource.KNOWN_BTS_TYPES.get(bts_type)
397 if bts_class is None:
398 raise RuntimeError('No such BTS type is defined: %r' % bts_type)
399 return bts_class(suite_run, conf)
400
401def modem_obj(conf):
402 log.dbg(None, None, 'create Modem object', conf=conf)
403 return ofono_client.Modem(conf)
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200404
405# vim: expandtab tabstop=4 shiftwidth=4