blob: ac56ada789dd8553775ab17e4bdbc39d74619010 [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()
Pau Espin Pedrol927344b2017-05-22 16:38:49 +0200251 event_loop.unregister_poll_func(self.poll)
Pau Espin Pedrol0ffb4142017-05-15 18:24:35 +0200252 self.duration = time.time() - self.start_timestamp
253 if self.test_failed_ctr:
254 self.status = SuiteRun.FAIL
255 else:
256 self.status = SuiteRun.PASS
257 self.log(self.status)
258 return self.status
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200259
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200260 def remember_to_stop(self, process):
261 if self._processes is None:
262 self._processes = []
Pau Espin Pedrolecf10792017-05-08 16:56:38 +0200263 self._processes.insert(0, process)
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200264
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200265 def stop_processes(self):
266 if not self._processes:
267 return
268 for process in self._processes:
269 process.terminate()
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200270
Neels Hofmeyr76d81032017-05-18 18:35:32 +0200271 def ip_address(self):
272 return self.reserved_resources.get(resource.R_IP_ADDRESS)
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200273
Neels Hofmeyr76d81032017-05-18 18:35:32 +0200274 def nitb(self, ip_address=None):
275 if ip_address is None:
276 ip_address = self.ip_address()
277 return osmo_nitb.OsmoNitb(self, ip_address)
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200278
Neels Hofmeyr798e5922017-05-18 15:24:02 +0200279 def hlr(self, ip_address=None):
280 if ip_address is None:
281 ip_address = self.ip_address()
282 return osmo_hlr.OsmoHlr(self, ip_address)
283
284 def mgcpgw(self, ip_address=None, bts_ip=None):
285 if ip_address is None:
286 ip_address = self.ip_address()
287 return osmo_mgcpgw.OsmoMgcpgw(self, ip_address, bts_ip)
288
289 def msc(self, hlr, mgcpgw, ip_address=None):
290 if ip_address is None:
291 ip_address = self.ip_address()
292 return osmo_msc.OsmoMsc(self, hlr, mgcpgw, ip_address)
293
294 def bsc(self, msc, ip_address=None):
295 if ip_address is None:
296 ip_address = self.ip_address()
297 return osmo_bsc.OsmoBsc(self, msc, ip_address)
298
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200299 def bts(self):
300 return bts_obj(self, self.reserved_resources.get(resource.R_BTS))
301
302 def modem(self):
303 return modem_obj(self.reserved_resources.get(resource.R_MODEM))
304
Neels Hofmeyrf2d279c2017-05-06 15:05:02 +0200305 def modems(self, count):
306 l = []
307 for i in range(count):
308 l.append(self.modem())
309 return l
310
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200311 def msisdn(self):
312 msisdn = self.resources_pool.next_msisdn(self.origin)
313 self.log('using MSISDN', msisdn)
314 return msisdn
315
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200316 def poll(self):
317 if self._processes:
318 for process in self._processes:
Neels Hofmeyr5356d0a2017-04-10 03:45:30 +0200319 if process.terminated():
Neels Hofmeyr85eb3242017-04-09 22:01:16 +0200320 process.log_stdout_tail()
321 process.log_stderr_tail()
322 process.raise_exn('Process ended prematurely')
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200323
324 def prompt(self, *msgs, **msg_details):
325 'ask for user interaction. Do not use in tests that should run automatically!'
326 if msg_details:
327 msgs = list(msgs)
328 msgs.append('{%s}' %
329 (', '.join(['%s=%r' % (k,v)
330 for k,v in sorted(msg_details.items())])))
331 msg = ' '.join(msgs) or 'Hit Enter to continue'
332 self.log('prompt:', msg)
Neels Hofmeyracf0c932017-05-06 16:05:33 +0200333 sys.__stdout__.write('\n\n--- PROMPT ---\n')
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200334 sys.__stdout__.write(msg)
Neels Hofmeyracf0c932017-05-06 16:05:33 +0200335 sys.__stdout__.write('\n')
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200336 sys.__stdout__.flush()
Neels Hofmeyracf0c932017-05-06 16:05:33 +0200337 entered = util.input_polling('> ', self.poll)
338 self.log('prompt entered:', repr(entered))
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200339 return entered
340
Neels Hofmeyr2d1d5612017-05-22 20:02:41 +0200341 def resource_status_str(self):
342 return '\n'.join(('',
343 'SUITE RUN: %s' % self.origin_id(),
344 'ASKED FOR:', pprint.pformat(self._resource_requirements),
345 'RESERVED COUNT:', pprint.pformat(self.reserved_resources.counts()),
346 'RESOURCES STATE:', repr(self.reserved_resources)))
347
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200348loaded_suite_definitions = {}
349
350def load(suite_name):
351 global loaded_suite_definitions
352
353 suite = loaded_suite_definitions.get(suite_name)
354 if suite is not None:
355 return suite
356
357 suites_dir = config.get_suites_dir()
358 suite_dir = suites_dir.child(suite_name)
359 if not suites_dir.exists(suite_name):
360 raise RuntimeError('Suite not found: %r in %r' % (suite_name, suites_dir))
361 if not suites_dir.isdir(suite_name):
362 raise RuntimeError('Suite name found, but not a directory: %r' % (suite_dir))
363
364 suite_def = SuiteDefinition(suite_dir)
365 loaded_suite_definitions[suite_name] = suite_def
366 return suite_def
367
368def parse_suite_scenario_str(suite_scenario_str):
369 tokens = suite_scenario_str.split(':')
370 if len(tokens) > 2:
371 raise RuntimeError('invalid combination string: %r' % suite_scenario_str)
372
373 suite_name = tokens[0]
374 if len(tokens) <= 1:
375 scenario_names = []
376 else:
377 scenario_names = tokens[1].split('+')
378
379 return suite_name, scenario_names
380
381def load_suite_scenario_str(suite_scenario_str):
382 suite_name, scenario_names = parse_suite_scenario_str(suite_scenario_str)
383 suite = load(suite_name)
384 scenarios = [config.get_scenario(scenario_name) for scenario_name in scenario_names]
Your Name44af3412017-04-13 03:11:59 +0200385 return (suite_scenario_str, suite, scenarios)
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200386
387def bts_obj(suite_run, conf):
388 bts_type = conf.get('type')
389 log.dbg(None, None, 'create BTS object', type=bts_type)
390 bts_class = resource.KNOWN_BTS_TYPES.get(bts_type)
391 if bts_class is None:
392 raise RuntimeError('No such BTS type is defined: %r' % bts_type)
393 return bts_class(suite_run, conf)
394
395def modem_obj(conf):
396 log.dbg(None, None, 'create Modem object', conf=conf)
397 return ofono_client.Modem(conf)
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200398
399# vim: expandtab tabstop=4 shiftwidth=4