Exemple #1
0
    def test_015_args_blacklist(self):
        new_logger = mock.Mock(spec=logging.Logger, name='logger')
        log = mock.Mock(name='log')
        new_logger.attach_mock(log, 'log')

        arg1 = 'test arg 1'
        arg2 = 'test arg 2'

        @logwrap.logwrap(log=new_logger, blacklisted_names=['test_arg2'])
        def func(test_arg1, test_arg2):
            return test_arg1, test_arg2

        result = func(arg1, arg2)
        self.assertEqual(result, (arg1, arg2))
        self.assertEqual(log.mock_calls, [
            mock.call(level=logging.DEBUG,
                      msg=("Calling: \n"
                           "'func'(\n"
                           "    # POSITIONAL_OR_KEYWORD:\n"
                           "    'test_arg1'={},\n"
                           ")".format(
                               logwrap.pretty_repr(
                                   arg1, indent=8, no_indent_start=True)))),
            mock.call(level=logging.DEBUG,
                      msg="Done: 'func' with result:\n{}".format(
                          logwrap.pretty_repr(result))),
        ])
Exemple #2
0
 def test_009_indent(self):
     obj = [[[[[[[[[[123]]]]]]]]]]
     self.assertEqual(
         "[\n"
         "    [\n"
         "        [\n"
         "            [\n"
         "                [\n"
         "                    [\n"
         "                        [\n"
         "                            [\n"
         "                                [\n"
         "                                    [\n"
         "                                        123,\n"
         "                                    ],\n"
         "                                ],\n"
         "                            ],\n"
         "                        ],\n"
         "                    ],\n"
         "                ],\n"
         "            ],\n"
         "        ],\n"
         "    ],\n"
         "]",
         logwrap.pretty_repr(obj, max_indent=40),
     )
     self.assertEqual(
         "[\n" "    [\n" "        [\n" "            [[[[[[[123]]]]]]],\n" "        ],\n" "    ],\n" "]",
         logwrap.pretty_repr(obj, max_indent=10),
     )
Exemple #3
0
    def test_004_args_complex(self):
        string = 'string'
        dictionary = {'key': 'dictionary'}

        @logwrap.logwrap
        def func(param_string, param_dictionary):
            return param_string, param_dictionary

        result = func(string, dictionary)
        self.assertEqual(result, (string, dictionary))

        self.assertEqual(
            [
                mock.call.log(level=logging.DEBUG,
                              msg=("Calling: \n"
                                   "'func'(\n"
                                   "    # POSITIONAL_OR_KEYWORD:\n"
                                   "    'param_string'={string},\n"
                                   "    'param_dictionary'={dictionary},\n"
                                   ")".format(string=logwrap.pretty_repr(
                                       string, indent=8, no_indent_start=True),
                                              dictionary=logwrap.pretty_repr(
                                                  dictionary,
                                                  indent=8,
                                                  no_indent_start=True)))),
                mock.call.log(level=logging.DEBUG,
                              msg="Done: 'func' with result:\n{}".format(
                                  logwrap.pretty_repr(result))),
            ],
            self.logger.mock_calls,
        )
Exemple #4
0
    def test_018_disable_args_exc(self):
        new_logger = mock.Mock(spec=logging.Logger, name='logger')
        log = mock.Mock(name='log')
        new_logger.attach_mock(log, 'log')

        arg1 = 'test arg 1'
        arg2 = 'test arg 2'

        @logwrap.logwrap(log=new_logger, log_call_args_on_exc=False)
        def func(test_arg1, test_arg2):
            raise TypeError('Blacklisted')

        with self.assertRaises(TypeError):
            func(arg1, arg2)

        self.assertEqual(
            [
                mock.call(level=logging.DEBUG,
                          msg=("Calling: \n"
                               "'func'(\n"
                               "    # POSITIONAL_OR_KEYWORD:\n"
                               "    'test_arg1'={},\n"
                               "    'test_arg2'={},\n"
                               ")".format(
                                   logwrap.pretty_repr(
                                       arg1, indent=8, no_indent_start=True),
                                   logwrap.pretty_repr(
                                       arg2, indent=8, no_indent_start=True),
                               ))),
                mock.call(level=logging.ERROR,
                          msg=AnyStringWith("Failed: \n'func'()"),
                          exc_info=False),
            ],
            log.mock_calls,
        )
Exemple #5
0
 def test_text(self):
     self.assertEqual(
         logwrap.pretty_repr('Unicode text'), "u'''Unicode text'''"
     )
     self.assertEqual(
         logwrap.pretty_repr(b'bytes text\x01'), "b'''bytes text\x01'''"
     )
Exemple #6
0
    def test_005_args_kwargs(self):
        targs = ['string1', 'string2']
        tkwargs = {'key': 'tkwargs'}

        @logwrap.logwrap
        def func(*args, **kwargs):
            return tuple(args), kwargs

        result = func(*targs, **tkwargs)
        self.assertEqual(result, (tuple(targs), tkwargs))

        self.assertEqual(
            [
                mock.call.log(
                    level=logging.DEBUG,
                    msg=("Calling: \n"
                         "'func'(\n"
                         "    # VAR_POSITIONAL:\n"
                         "    'args'={args},\n"
                         "    # VAR_KEYWORD:\n"
                         "    'kwargs'={kwargs},\n)".format(
                             args=logwrap.pretty_repr(
                                 tuple(targs), indent=8, no_indent_start=True),
                             kwargs=logwrap.pretty_repr(
                                 tkwargs, indent=8, no_indent_start=True)))),
                mock.call.log(level=logging.DEBUG,
                              msg="Done: 'func' with result:\n{}".format(
                                  logwrap.pretty_repr(result))),
            ],
            self.logger.mock_calls,
        )
Exemple #7
0
    def test_002_args_simple(self):
        arg = 'test arg'

        @logwrap.logwrap
        def func(tst):
            return tst

        result = func(arg)
        self.assertEqual(result, arg)
        self.assertEqual(
            [
                mock.call.log(
                    level=logging.DEBUG,
                    msg=("Calling: \n"
                         "'func'(\n"
                         "    # POSITIONAL_OR_KEYWORD:\n"
                         "    'tst'={},\n"
                         ")".format(
                             logwrap.pretty_repr(
                                 arg, indent=8, no_indent_start=True)))),
                mock.call.log(level=logging.DEBUG,
                              msg="Done: 'func' with result:\n{}".format(
                                  logwrap.pretty_repr(result))),
            ],
            self.logger.mock_calls,
        )
Exemple #8
0
 def test_003_iterable(self):
     self.assertEqual(
         "[{nl:<5}1,{nl:<5}2,{nl:<5}3,\n]".format(nl="\n"),
         logwrap.pretty_repr([1, 2, 3]),
     )
     self.assertEqual(
         "({nl:<5}1,{nl:<5}2,{nl:<5}3,\n)".format(nl="\n"),
         logwrap.pretty_repr((1, 2, 3)),
     )
     res = logwrap.pretty_repr({1, 2, 3})
     self.assertTrue(res.startswith("{") and res.endswith("\n}"))
     res = logwrap.pretty_repr(frozenset({1, 2, 3}))
     self.assertTrue(res.startswith("frozenset({") and res.endswith("\n})"))
Exemple #9
0
 def test_iterable(self):
     self.assertEqual(
         'list([{nl:<5}1,{nl:<5}2,{nl:<5}3,\n'
         '])'.format(nl='\n'),
         logwrap.pretty_repr([1, 2, 3]),
     )
     self.assertEqual(
         'tuple(({nl:<5}1,{nl:<5}2,{nl:<5}3,\n'
         '))'.format(nl='\n'),
         logwrap.pretty_repr((1, 2, 3)),
     )
     res = logwrap.pretty_repr({1, 2, 3})
     self.assertTrue(res.startswith('set({') and res.endswith('\n})'))
     res = logwrap.pretty_repr(frozenset({1, 2, 3}))
     self.assertTrue(res.startswith('frozenset({') and res.endswith('\n})'))
    def test_015_args_blacklist(self):
        new_logger = mock.Mock(spec=logging.Logger, name="logger")
        log = mock.Mock(name="log")
        new_logger.attach_mock(log, "log")

        arg1 = "test arg 1"
        arg2 = "test arg 2"

        @logwrap.logwrap(log=new_logger, blacklisted_names=["test_arg2"])
        def func(test_arg1, test_arg2):
            return test_arg1, test_arg2

        result = func(arg1, arg2)
        self.assertEqual(result, (arg1, arg2))
        self.assertEqual(
            log.mock_calls,
            [
                mock.call(
                    level=logging.DEBUG,
                    msg=
                    (f"Calling: \n"
                     f"func(\n"
                     f"    # POSITIONAL_OR_KEYWORD:\n"
                     f"    test_arg1={logwrap.pretty_repr(arg1, indent=8, no_indent_start=True)},\n"
                     f")"),
                ),
                mock.call(level=logging.DEBUG,
                          msg="Done: 'func' with result:\n{}".format(
                              logwrap.pretty_repr(result))),
            ],
        )
Exemple #11
0
    def test_011_method(self):
        class Tst(object):
            @logwrap.logwrap
            def func(tst_self):
                return 'No args'

            def __repr__(tst_self):
                return '<Tst_instance>'

        tst = Tst()
        result = tst.func()
        self.assertEqual(result, 'No args')
        self.assertEqual(
            [
                mock.call.log(level=logging.DEBUG,
                              msg="Calling: \n"
                              "'func'(\n"
                              "    # POSITIONAL_OR_KEYWORD:\n"
                              "    'tst_self'=<Tst_instance>,\n"
                              ")"),
                mock.call.log(level=logging.DEBUG,
                              msg="Done: 'func' with result:\n{}".format(
                                  logwrap.pretty_repr(result))),
            ],
            self.logger.mock_calls,
        )
Exemple #12
0
    def test_003_complex(self):
        fmt = "\n{spc:<{indent}}<{obj!r} with interface ({args}){annotation}>".format
        namespace = {}

        exec("""
import typing
def func(a: typing.Optional[int]=None) -> None:
    pass
                                """,
             namespace
             )
        func = namespace['func']  # type: typing.Callable[..., None]

        self.assertEqual(
            logwrap.pretty_repr(func),
            fmt(
                spc='',
                indent=0,
                obj=func,
                args="\n    a: typing.Union[int, NoneType]=None,\n",
                annotation=" -> None"
            )
        )

        self.assertEqual(
            logwrap.pretty_str(func),
            fmt(
                spc='',
                indent=0,
                obj=func,
                args="\n    a: typing.Union[int, NoneType]=None,\n",
                annotation=" -> None"
            )
        )
Exemple #13
0
    def test_002_annotation_return(self):
        fmt = "\n{spc:<{indent}}<{obj!r} with interface ({args}){annotation}>".format
        namespace = {}

        exec("""
import typing
def func() -> None:
    pass
                                """,
             namespace
             )
        func = namespace['func']  # type: typing.Callable[[], None]

        self.assertEqual(
            logwrap.pretty_repr(func),
            fmt(
                spc='',
                indent=0,
                obj=func,
                args='',
                annotation=' -> None'
            )
        )

        self.assertEqual(
            logwrap.pretty_str(func),
            fmt(
                spc='',
                indent=0,
                obj=func,
                args='',
                annotation=' -> None'
            )
        )
Exemple #14
0
    def test_magic_override(self):
        # noinspection PyMissingOrEmptyDocstring
        class Tst(object):
            def __repr__(self):
                return 'Test'

            def __pretty_repr__(
                self,
                parser,
                indent,
                no_indent_start
            ):
                return parser.process_element(
                    "<Test Class at 0x{:X}>".format(id(self.__class__)),
                    indent=indent,
                    no_indent_start=no_indent_start
                )

        result = logwrap.pretty_repr(Tst())
        self.assertNotEqual(
            result,
            'Test'
        )
        self.assertEqual(
            result,
            "u'''<Test Class at 0x{:X}>'''".format(id(Tst))
        )
Exemple #15
0
    def test_001_dict_subclass(self):
        class MyDict(dict):
            """Dict subclass."""

        val = MyDict(key="value")
        self.assertEqual("MyDict({\n" "    'key': 'value',\n" "})", logwrap.pretty_repr(val))

        self.assertEqual("{\n" "    key: value,\n" "}", logwrap.pretty_str(val))
Exemple #16
0
    def test_002_annotation_return(self):
        def func() -> None:
            pass

        self.assertEqual(
            f"{'':<{0}}<{func.__class__.__name__} {func.__module__}.{func.__name__} with interface ({''}){' -> None'}>",
            logwrap.pretty_repr(func),
        )
Exemple #17
0
    def test_002_typing_specific_dict(self):
        class MyDict(typing.Dict[str, str]):
            """Dict subclass."""

        val = MyDict(key="value")
        self.assertEqual("MyDict({\n" "    'key': 'value',\n" "})", logwrap.pretty_repr(val))

        self.assertEqual("{\n" "    key: value,\n" "}", logwrap.pretty_str(val))
Exemple #18
0
 def test_dict(self):
     self.assertEqual(
         'dict({\n'
         '    1 : 1,\n'
         '    2 : 2,\n'
         '    33: 33,\n'
         '})',
         logwrap.pretty_repr({1: 1, 2: 2, 33: 33}),
     )
Exemple #19
0
    def test_006_callable_simple(self):
        def empty_func():
            pass

        self.assertEqual(
            f"{'':<{0}}"
            f"<{empty_func.__class__.__name__} {empty_func.__module__}.{empty_func.__name__} with interface ({''})>",
            logwrap.pretty_repr(empty_func),
        )
Exemple #20
0
    def test_003_typed_dict(self):
        # noinspection PyMissingOrEmptyDocstring
        class MyDict(typing.TypedDict):
            key: str

        val = MyDict(key="value")
        self.assertEqual("{\n" "    'key': 'value',\n" "}", logwrap.pretty_repr(val))

        self.assertEqual("{\n" "    key: value,\n" "}", logwrap.pretty_str(val))
Exemple #21
0
    def test_001_annotation_args(self):
        def func(a: typing.Optional[int] = None):
            pass

        args = "\n    a: typing.Optional[int]=None,\n"

        self.assertEqual(
            f"{'':<{0}}<{func.__class__.__name__} {func.__module__}.{func.__name__} with interface ({args}){''}>",
            logwrap.pretty_repr(func),
        )
Exemple #22
0
    def test_007_callable_with_args(self):
        def full_func(arg, darg=1, *positional, **named):
            pass

        args = "\n" "    arg,\n" "    darg=1,\n" "    *positional,\n" "    **named,\n"

        self.assertEqual(
            f"{'':<{0}}"
            f"<{full_func.__class__.__name__} {full_func.__module__}.{full_func.__name__} with interface ({args})>",
            logwrap.pretty_repr(full_func),
        )
Exemple #23
0
    def test_003_complex(self):
        def func(a: typing.Optional[int] = None) -> None:
            pass

        args = "\n    a: typing.Optional[int]=None,\n"

        self.assertEqual(
            f"{'':<{0}}"
            f"<{func.__class__.__name__} {func.__module__}.{func.__name__} with interface ({args}){' -> None'}>",
            logwrap.pretty_repr(func),
        )
Exemple #24
0
    def test_002_annotation_return(self):
        fmt = "\n{spc:<{indent}}<{obj!r} with interface ({args}){annotation}>".format

        def func() -> None:
            pass

        self.assertEqual(
            logwrap.pretty_repr(func),
            fmt(spc='', indent=0, obj=func, args='', annotation=' -> None'))

        self.assertEqual(
            logwrap.pretty_str(func),
            fmt(spc='', indent=0, obj=func, args='', annotation=' -> None'))
Exemple #25
0
    def test_010_magic_override(self):
        # noinspection PyMissingOrEmptyDocstring
        class Tst(object):
            def __repr__(self):
                return "Test"

            def __pretty_repr__(self, parser, indent, no_indent_start):
                return parser.process_element(
                    f"<Test Class at 0x{id(self.__class__):X}>", indent=indent, no_indent_start=no_indent_start
                )

        result = logwrap.pretty_repr(Tst())
        self.assertNotEqual(result, "Test")
        self.assertEqual(result, f"'<Test Class at 0x{id(Tst):X}>'")
Exemple #26
0
    def test_006_renamed_args_kwargs(self):
        arg = 'arg'
        targs = ['string1', 'string2']
        tkwargs = {'key': 'tkwargs'}

        # noinspection PyShadowingNames
        @logwrap.logwrap
        def func(arg, *positional, **named):
            return arg, tuple(positional), named

        result = func(arg, *targs, **tkwargs)
        self.assertEqual(result, (arg, tuple(targs), tkwargs))
        self.assertEqual(
            [
                mock.call.log(
                    level=logging.DEBUG,
                    msg=("Calling: \n"
                         "'func'(\n"
                         "    # POSITIONAL_OR_KEYWORD:\n"
                         "    'arg'={arg},\n"
                         "    # VAR_POSITIONAL:\n"
                         "    'positional'={args},\n"
                         "    # VAR_KEYWORD:\n"
                         "    'named'={kwargs},\n)".format(
                             arg=logwrap.pretty_repr(
                                 arg, indent=8, no_indent_start=True),
                             args=logwrap.pretty_repr(
                                 tuple(targs), indent=8, no_indent_start=True),
                             kwargs=logwrap.pretty_repr(
                                 tkwargs, indent=8, no_indent_start=True)))),
                mock.call.log(level=logging.DEBUG,
                              msg="Done: 'func' with result:\n{}".format(
                                  logwrap.pretty_repr(result))),
            ],
            self.logger.mock_calls,
        )
Exemple #27
0
    def test_001_no_args(self):
        @logwrap.logwrap
        def func():
            return 'No args'

        result = func()
        self.assertEqual(result, 'No args')
        self.assertEqual(
            [
                mock.call.log(level=logging.DEBUG, msg="Calling: \n'func'()"),
                mock.call.log(level=logging.DEBUG,
                              msg="Done: 'func' with result:\n{}".format(
                                  logwrap.pretty_repr(result))),
            ],
            self.logger.mock_calls,
        )
Exemple #28
0
    def _make_done_record(
            self,
            func_name,  # type: str
            result  # type: typing.Any
    ):  # type: (...) -> None
        """Construct success record.

        :type func_name: str
        :type result: typing.Any
        """
        msg = "Done: {name!r}".format(name=func_name)

        if self.log_result_obj:
            msg += " with result:\n{result}".format(result=core.pretty_repr(
                result,
                max_indent=self.max_indent,
            ))
        self._logger.log(level=self.log_level, msg=msg)
Exemple #29
0
 def test_pretty_repr(self):
     """Test repr with logwrap."""
     result = exec_helpers.ExecResult("test",
                                      stdout=[b"{test: data}"],
                                      stderr=[b"{test: stderr}"])
     pretty_repr = logwrap.pretty_repr(result)
     self.assertEqual(
         f"ExecResult(\n"
         f"    cmd='test',\n"
         f"    stdout=(\n"
         f"        b'{{test: data}}',\n"
         f"    ),\n"
         f"    stderr=(\n"
         f"        b'{{test: stderr}}',\n"
         f"    ),\n"
         f"    exit_code={result.exit_code!s},\n"
         f")",
         pretty_repr,
     )
Exemple #30
0
 def test_nested_obj(self):
     test_obj = [
         {
             1: 2
         },
         {
             3: {4}
         },
         [5, 6, 7],
         (8, 9, 10),
         {},
         [],
         (),
         set(),
     ]
     exp_repr = ('list([\n'
                 '    dict({\n'
                 '        1: 2,\n'
                 '    }),\n'
                 '    dict({\n'
                 '        3: \n'
                 '            set({\n'
                 '                4,\n'
                 '            }),\n'
                 '    }),\n'
                 '    list([\n'
                 '        5,\n'
                 '        6,\n'
                 '        7,\n'
                 '    ]),\n'
                 '    tuple((\n'
                 '        8,\n'
                 '        9,\n'
                 '        10,\n'
                 '    )),\n'
                 '    {},\n'
                 '    [],\n'
                 '    (),\n'
                 '    set(),\n'
                 '])')
     self.assertEqual(exp_repr, logwrap.pretty_repr(test_obj))