File: test_config.py

package info (click to toggle)
asterisk-testsuite 0.0.0%2Bsvn.5781-2
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd, stretch
  • size: 18,632 kB
  • sloc: xml: 33,912; python: 32,904; ansic: 1,599; sh: 395; makefile: 170; sql: 17
file content (470 lines) | stat: -rw-r--r-- 16,187 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
#!/usr/bin/env python
"""Test configuration parsing and dependency checking

Copyright (C) 2011, Digium, Inc.
Russell Bryant <russell@digium.com>
Matt Jordan    <mjordan@digium.com>

This program is free software, distributed under the terms of
the GNU General Public License Version 2.
"""

import sys
import os
import subprocess
import yaml
import socket
import traceback

sys.path.append("lib/python")

import test_suite_utils

from version import AsteriskVersion
from asterisk import Asterisk
from buildoptions import AsteriskBuildOptions
from sippversion import SIPpVersion

class TestConditionConfig(object):
    """This class creates a test condition config and will build up an
    object that derives from TestCondition based on that configuration
    """

    def __init__(self, config, definition, pre_post_type):
        """Construct a new test condition

        Keyword Arguments:
        config        The test condition specific configuration, from a
                      test-config.yaml file
        definition    The global type information, obtained from the global
                      test-config.yaml file
        pre_post_type 'pre' or 'post', depending on the type to build
        """
        self.pass_expected = True
        self.related_condition = ""
        self.type = pre_post_type.upper().strip()
        self.class_type_name = definition[self.type.lower()]['typename']
        self.enabled = True
        if 'related-type' in definition[self.type.lower()]:
            ppt_def = definition[self.type.lower()]
            self.related_condition = ppt_def['related-type'].strip()
        if 'enabled' in config:
            self.enabled = config['enabled']
        else:
            self.enabled = True
        self.expected_result = (config.get('expected_result') or
                                config.get('expectedResult') or
                                False)
        # Let non-standard configuration items be obtained from the
        # config object
        self.config = config

    def get_type(self):
        """The type of TestCondition (either PRE or POST)"""
        return self.type

    def get_related_condition(self):
        """The type name of the related condition that this condition uses"""
        return self.related_condition

    def make_condition(self):
        """Build and return the condition object defined by this config"""
        parts = self.class_type_name.split('.')
        module = '.'.join(parts[:-1])
        if module != '':
            mod = __import__(module)
            for comp in parts[1:]:
                mod = getattr(mod, comp)
            obj = mod(self)
            return obj
        return None

class Dependency(object):
    """Class that checks and stores the dependencies for a particular Test."""

    asterisk_build_options = AsteriskBuildOptions()

    ast = Asterisk()

    def __init__(self, dep):
        """Construct a new dependency

        Keyword arguments:
        dep A tuple containing the dependency type name and its subinformation.
        """

        self.name = ""
        self.version = ""
        self.met = False
        if "app" in dep:
            self.name = dep["app"]
            self.met = test_suite_utils.which(self.name) is not None
        elif "python" in dep:
            self.name = dep["python"]
            try:
                __import__(self.name)
                self.met = True
            except ImportError:
                pass
        elif "sipp" in dep:
            self.name = "SIPp"
            version = None
            feature = None
            if 'version' in dep['sipp']:
                version = dep['sipp']['version']
            if 'feature' in dep['sipp']:
                feature = dep['sipp']['feature']
            self.sipp_version = SIPpVersion()
            self.version = SIPpVersion(version, feature)
            if self.sipp_version >= self.version:
                self.met = True
            if self.version.tls and not self.sipp_version.tls:
                self.met = False
            if self.version.pcap and not self.sipp_version.pcap:
                self.met = False
        elif "custom" in dep:
            self.name = dep["custom"]
            method = "depend_%s" % self.name
            found = False
            for dir_method in dir(self):
                if dir_method == method:
                    self.met = getattr(self, dir_method)()
                    found = True
            if not found:
                print "Unknown custom dependency - '%s'" % self.name
        elif "asterisk" in dep:
            self.name = dep["asterisk"]
            self.met = self._find_asterisk_module(self.name)
        elif "buildoption" in dep:
            self.name = dep["buildoption"]
            self.met = self._find_build_flag(self.name)
        elif "pcap" in dep:
            self.name = "pcap"
            from test_case import PCAP_AVAILABLE
            self.met = PCAP_AVAILABLE
        else:
            print "Unknown dependency type specified:"
            for key in dep.keys():
                print key

    def depend_soundcard(self):
        """Check the soundcard custom dependency"""
        try:
            dsp_file = open("/dev/dsp", "r")
            dsp_file.close()
            return True
        except:
            return False

    def depend_ipv6(self):
        """Check the ipv6 custom dependency"""
        try:
            test_sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
            test_sock.close()
            return True
        except:
            return False

    def depend_pjsuav6(self):
        """This tests if pjsua was compiled with IPv6 support.

        To do this, we run pjsua --help and parse the output to determine if
        --ipv6 is a valid option
        """
        if test_suite_utils.which('pjsua') is None:
            return False

        help_output = subprocess.Popen(['pjsua', '--help'],
                                       stdout=subprocess.PIPE).communicate()[0]
        if help_output.find('--ipv6') == -1:
            return False
        return True

    def depend_fax(self):
        """Checks if Asterisk contains the necessary modules for fax tests"""
        fax_providers = [
            "app_fax",
            "res_fax_spandsp",
            "res_fax_digium",
        ]

        for fax in fax_providers:
            if self._find_asterisk_module(fax):
                return True

        return False

    def depend_rawsocket(self):
        """Check the raw socket custom dependency"""
        try:
            test_sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW)
            test_sock.close()
            return True
        except:
            return False

    def _find_build_flag(self, name):
        """Determine if the specified build option exists"""
        return (self.asterisk_build_options.check_option(name))

    def _find_asterisk_module(self, name):
        """Determine if an Asterisk module exists"""
        if Dependency.ast.original_astmoddir == "":
            return False

        module = "%s/%s.so" % (Dependency.ast.original_astmoddir, name)
        if os.path.exists(module):
            return True

        return False


class TestConfig(object):
    """Class that contains the configuration for a specific test, as parsed
    by that tests test.yaml file.
    """

    def __init__(self, test_name, global_test_config=None):
        """Create a new TestConfig

        Keyword arguments:
        test_name The path to the directory containing the test-config.yaml
                  file to load
        """
        self.can_run = True
        self.test_name = test_name
        self.skip = None
        self.config = None
        self.summary = None
        self.description = None
        self.maxversion = None
        self.maxversion_check = False
        self.minversion = None
        self.minversion_check = False
        self.forced_version = None
        self.deps = []
        self.tags = []
        self.expect_pass = True
        self.excluded_tests = []
        self.features = []
        self.feature_check = {}
        self.test_configuration = "(none)"
        self.condition_definitions = []
        self.global_test_config = global_test_config

        try:
            self._parse_config()
        except yaml.YAMLError as e:
            print("YAML Parse Error: %s" % e)
            print(traceback.format_exc())
            self.can_run = False
        except:
            print("Exception occurred while parsing config:", sys.exc_info()[0])
            self.can_run = False

    def _process_global_settings(self):
        """Process settings in the top-level test-yaml config file"""

        if self.global_test_config != None:
            settings = self.global_test_config
            self.condition_definitions = settings.condition_definitions
            self.forced_version = settings.forced_version
            return

        if "global-settings" in self.config:
            settings = self.config['global-settings']
            if "condition-definitions" in settings:
                self.condition_definitions = settings['condition-definitions']
            if "test-configuration" in settings:
                self.test_configuration = settings['test-configuration']
                if self.test_configuration in self.config:
                    self.config = self.config[self.test_configuration]

                    if self.config != None and 'exclude-tests' in self.config:
                        self.excluded_tests = self.config['exclude-tests']
                else:
                    print ("WARNING - test configuration [%s] not found in " \
                           "config file" % self.test_configuration)

    def _process_testinfo(self):
        """Process the test information block"""

        self.summary = "(none)"
        self.description = "(none)"
        if self.config == None:
            return
        if "testinfo" not in self.config:
            return
        testinfo = self.config["testinfo"]
        if "skip" in testinfo:
            self.skip = testinfo['skip']
            self.can_run = False
        if "summary" in testinfo:
            self.summary = testinfo["summary"]
        if "description" in testinfo:
            self.description = testinfo["description"]

    def _process_properties(self):
        """Process test properties block"""

        self.minversion = AsteriskVersion("1.4")
        if self.config == None:
            return
        if "properties" not in self.config:
            return
        properties = self.config["properties"]
        if "minversion" in properties:
            self.minversion = AsteriskVersion(properties["minversion"])
            if self.minversion.feature:
                self.features.append(self.minversion.feature)
                self.feature_check[self.minversion.feature] = False
        if "maxversion" in properties:
            self.maxversion = AsteriskVersion(properties["maxversion"])
        self.expect_pass = (
                properties.get("expectedResult", self.expect_pass) and
                properties.get("expected-result", self.expect_pass))
        if "tags" in properties:
            self.tags = properties["tags"]
        if "features" in properties:
            self.features.extend(properties["features"])
            for feature in self.features:
                self.feature_check[feature] = False
        if "forced-version" in properties:
            self.forced_version = AsteriskVersion(properties["forced-version"])

    def _parse_config(self):
        """Parse the test-config YAML file."""

        test_config = "%s/test-config.yaml" % self.test_name
        with open(test_config, "r") as config_file:
            self.config = yaml.load(config_file)

        if not self.config:
            print "ERROR: Failed to load configuration for test '%s'" % \
                    self.test_name
            return

        self._process_global_settings()
        self._process_testinfo()
        self._process_properties()

    def get_conditions(self):
        """
        Gets the pre- and post-test conditions associated with this test

        Returns a list of 3-tuples containing the following:
            0: The actual condition object
            1: The condition type (either PRE or POST)
            2: The name of the related condition that this one depends on
        """
        conditions = []
        conditions_temp = []
        if (not self.config or 'properties' not in self.config or
            'testconditions' not in self.config['properties']):
            return conditions

        for conf in self.config['properties'].get('testconditions'):
            matches = [cond_def for cond_def in self.condition_definitions
                       if cond_def['name'] == conf['name']]
            if len(matches) != 1:
                print ("Unknown or too many matches for condition: " +
                       conf['name'])
            else:
                pre_cond = TestConditionConfig(conf, matches[0], "Pre")
                post_cond = TestConditionConfig(conf, matches[0], "Post")
                conditions_temp.append(pre_cond)
                conditions_temp.append(post_cond)

        for cond in conditions_temp:
            cond_obj = (cond.make_condition(),
                        cond.get_type(),
                        cond.get_related_condition())
            conditions.append(cond_obj)

        return conditions

    def get_deps(self):
        """Get the dependencies for the test

        Raises ValueError if the 'properties' section is missing from the test
        configuration

        Returns:
        A list of Dependency objects
        """
        if not self.config:
            return []

        if not "properties" in self.config:
            raise ValueError("%s: Missing properties section" % self.test_name)

        if not self.deps:
            self.deps = [
                Dependency(dep)
                for dep in self.config["properties"].get("dependencies") or []
            ]
        return self.deps


    def check_deps(self, ast_version):
        """Check whether or not a test should execute based on its dependencies

        Keyword arguments:
        ast_version The AsteriskVersion object containing the version of
                    Asterisk that will be executed
        Returns:
        can_run True if the test can execute, False otherwise
        """

        if not self.config:
            return False

        if self.forced_version is not None:
            ast_version = self.forced_version

        self.minversion_check = True
        if ast_version < self.minversion:
            self.can_run = False
            self.minversion_check = False
            return self.can_run

        self.maxversion_check = True
        if self.maxversion is not None and ast_version > self.maxversion:
            self.can_run = False
            self.maxversion_check = False
            return self.can_run

        for feature in self.features:
            self.feature_check[feature] = ast_version.has_feature(feature)
            if not self.feature_check[feature]:
                self.can_run = False

        for dep in self.get_deps():
            if dep.met is False:
                self.can_run = False
                break
        return self.can_run

    def check_tags(self, requested_tags):
        """Check whether or not a test should execute based on its tags

        Keyword arguments:
        requested_tags The list of tags used for selecting a subset of
                       tests.  The test must have all tags to run.
        Returns:
        can_run True if the test can execute, False otherwise
        """

        if not self.config:
            return False

        # If no tags are requested, this test's tags don't matter
        if not requested_tags:
            return self.can_run

        intersection = set(requested_tags).intersection(set(self.tags))
        if len(intersection) == 0:
            self.can_run = False

        # all tags matched successfully
        return self.can_run