summaryrefslogtreecommitdiffstats
path: root/scripts/automation/trex_control_plane/python_lib/python-daemon-2.0.5/test/scaffold.py
blob: 9a4f11509cf1a66c61b1fa03869fa82bf3c23a0c (plain)
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
# -*- coding: utf-8 -*-

# test/scaffold.py
# Part of ‘python-daemon’, an implementation of PEP 3143.
#
# Copyright © 2007–2015 Ben Finney <ben+python@benfinney.id.au>
#
# This is free software: you may copy, modify, and/or distribute this work
# under the terms of the Apache License, version 2.0 as published by the
# Apache Software Foundation.
# No warranty expressed or implied. See the file ‘LICENSE.ASF-2’ for details.

""" Scaffolding for unit test modules.
    """

from __future__ import (absolute_import, unicode_literals)

import unittest
import doctest
import logging
import os
import sys
import operator
import textwrap
from copy import deepcopy
import functools

try:
    # Python 2 has both ‘str’ (bytes) and ‘unicode’ (text).
    basestring = basestring
    unicode = unicode
except NameError:
    # Python 3 names the Unicode data type ‘str’.
    basestring = str
    unicode = str

import testscenarios
import testtools.testcase


test_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(test_dir)
if not test_dir in sys.path:
    sys.path.insert(1, test_dir)
if not parent_dir in sys.path:
    sys.path.insert(1, parent_dir)

# Disable all but the most critical logging messages.
logging.disable(logging.CRITICAL)


def get_function_signature(func):
    """ Get the function signature as a mapping of attributes.

        :param func: The function object to interrogate.
        :return: A mapping of the components of a function signature.

        The signature is constructed as a mapping:

        * 'name': The function's defined name.
        * 'arg_count': The number of arguments expected by the function.
        * 'arg_names': A sequence of the argument names, as strings.
        * 'arg_defaults': A sequence of the default values for the arguments.
        * 'va_args': The name bound to remaining positional arguments.
        * 'va_kw_args': The name bound to remaining keyword arguments.

        """
    try:
        # Python 3 function attributes.
        func_code = func.__code__
        func_defaults = func.__defaults__
    except AttributeError:
        # Python 2 function attributes.
        func_code = func.func_code
        func_defaults = func.func_defaults

    arg_count = func_code.co_argcount
    arg_names = func_code.co_varnames[:arg_count]

    arg_defaults = {}
    if func_defaults is not None:
        arg_defaults = dict(
                (name, value)
                for (name, value) in
                    zip(arg_names[::-1], func_defaults[::-1]))

    signature = {
            'name': func.__name__,
            'arg_count': arg_count,
            'arg_names': arg_names,
            'arg_defaults': arg_defaults,
            }

    non_pos_names = list(func_code.co_varnames[arg_count:])
    COLLECTS_ARBITRARY_POSITIONAL_ARGS = 0x04
    if func_code.co_flags & COLLECTS_ARBITRARY_POSITIONAL_ARGS:
        signature['var_args'] = non_pos_names.pop(0)
    COLLECTS_ARBITRARY_KEYWORD_ARGS = 0x08
    if func_code.co_flags & COLLECTS_ARBITRARY_KEYWORD_ARGS:
        signature['var_kw_args'] = non_pos_names.pop(0)

    return signature


def format_function_signature(func):
    """ Format the function signature as printable text.

        :param func: The function object to interrogate.
        :return: A formatted text representation of the function signature.

        The signature is rendered a text; for example::

            foo(spam, eggs, ham=True, beans=None, *args, **kwargs)

        """
    signature = get_function_signature(func)

    args_text = []
    for arg_name in signature['arg_names']:
        if arg_name in signature['arg_defaults']:
            arg_text = "{name}={value!r}".format(
                    name=arg_name, value=signature['arg_defaults'][arg_name])
        else:
            arg_text = "{name}".format(
                    name=arg_name)
        args_text.append(arg_text)
    if 'var_args' in signature:
        args_text.append("*{var_args}".format(signature))
    if 'var_kw_args' in signature:
        args_text.append("**{var_kw_args}".format(signature))
    signature_args_text = ", ".join(args_text)

    func_name = signature['name']
    signature_text = "{name}({args})".format(
            name=func_name, args=signature_args_text)

    return signature_text


class TestCase(testtools.testcase.TestCase):
    """ Test case behaviour. """

    def failUnlessOutputCheckerMatch(self, want, got, msg=None):
        """ Fail unless the specified string matches the expected.

            :param want: The desired output pattern.
            :param got: The actual text to match.
            :param msg: A message to prefix on the failure message.
            :return: ``None``.
            :raises self.failureException: If the text does not match.

            Fail the test unless ``want`` matches ``got``, as determined by
            a ``doctest.OutputChecker`` instance. This is not an equality
            check, but a pattern match according to the ``OutputChecker``
            rules.

            """
        checker = doctest.OutputChecker()
        want = textwrap.dedent(want)
        source = ""
        example = doctest.Example(source, want)
        got = textwrap.dedent(got)
        checker_optionflags = functools.reduce(operator.or_, [
                doctest.ELLIPSIS,
                ])
        if not checker.check_output(want, got, checker_optionflags):
            if msg is None:
                diff = checker.output_difference(
                        example, got, checker_optionflags)
                msg = "\n".join([
                        "Output received did not match expected output",
                        "{diff}",
                        ]).format(
                            diff=diff)
            raise self.failureException(msg)

    assertOutputCheckerMatch = failUnlessOutputCheckerMatch

    def failUnlessFunctionInTraceback(self, traceback, function, msg=None):
        """ Fail if the function is not in the traceback.

            :param traceback: The traceback object to interrogate.
            :param function: The function object to match.
            :param msg: A message to prefix on the failure message.
            :return: ``None``.

            :raises self.failureException: If the function is not in the
                traceback.

            Fail the test if the function ``function`` is not at any of the
            levels in the traceback object ``traceback``.

            """
        func_in_traceback = False
        expected_code = function.func_code
        current_traceback = traceback
        while current_traceback is not None:
            if expected_code is current_traceback.tb_frame.f_code:
                func_in_traceback = True
                break
            current_traceback = current_traceback.tb_next

        if not func_in_traceback:
            if msg is None:
                msg = (
                        "Traceback did not lead to original function"
                        " {function}"
                        ).format(
                            function=function)
            raise self.failureException(msg)

    assertFunctionInTraceback = failUnlessFunctionInTraceback

    def failUnlessFunctionSignatureMatch(self, first, second, msg=None):
        """ Fail if the function signatures do not match.

            :param first: The first function to compare.
            :param second: The second function to compare.
            :param msg: A message to prefix to the failure message.
            :return: ``None``.

            :raises self.failureException: If the function signatures do
                not match.

            Fail the test if the function signature does not match between
            the ``first`` function and the ``second`` function.

            The function signature includes:

            * function name,

            * count of named parameters,

            * sequence of named parameters,

            * default values of named parameters,

            * collector for arbitrary positional arguments,

            * collector for arbitrary keyword arguments.

            """
        first_signature = get_function_signature(first)
        second_signature = get_function_signature(second)

        if first_signature != second_signature:
            if msg is None:
                first_signature_text = format_function_signature(first)
                second_signature_text = format_function_signature(second)
                msg = (textwrap.dedent("""\
                        Function signatures do not match:
                            {first!r} != {second!r}
                        Expected:
                            {first_text}
                        Got:
                            {second_text}""")
                        ).format(
                            first=first_signature,
                            first_text=first_signature_text,
                            second=second_signature,
                            second_text=second_signature_text,
                            )
            raise self.failureException(msg)

    assertFunctionSignatureMatch = failUnlessFunctionSignatureMatch


class TestCaseWithScenarios(testscenarios.WithScenarios, TestCase):
    """ Test cases run per scenario. """


class Exception_TestCase(TestCaseWithScenarios):
    """ Test cases for exception classes. """

    def test_exception_instance(self):
        """ Exception instance should be created. """
        self.assertIsNot(self.instance, None)

    def test_exception_types(self):
        """ Exception instance should match expected types. """
        for match_type in self.types:
            self.assertIsInstance(self.instance, match_type)


def make_exception_scenarios(scenarios):
    """ Make test scenarios for exception classes.

        :param scenarios: Sequence of scenarios.
        :return: List of scenarios with additional mapping entries.

        Use this with `testscenarios` to adapt `Exception_TestCase`_ for
        any exceptions that need testing.

        Each scenario is a tuple (`name`, `map`) where `map` is a mapping
        of attributes to be applied to each test case. Attributes map must
        contain items for:

            :key exc_type:
                The exception type to be tested.
            :key min_args:
                The minimum argument count for the exception instance
                initialiser.
            :key types:
                Sequence of types that should be superclasses of each
                instance of the exception type.

        """
    updated_scenarios = deepcopy(scenarios)
    for (name, scenario) in updated_scenarios:
        args = (None,) * scenario['min_args']
        scenario['args'] = args
        instance = scenario['exc_type'](*args)
        scenario['instance'] = instance

    return updated_scenarios


# Local variables:
# coding: utf-8
# mode: python
# End:
# vim: fileencoding=utf-8 filetype=python :