Exemple #1
0
    def _test(self, outer, inner, args, kwargs, expected, expected_get,
              exp_src, exp_src_get):
        outer_f = support.f(outer, name='outer')
        inner_f = support.f(inner, name='inner')
        forw = specifiers.forwards_to_function(inner_f, *args,
                                               **kwargs)(outer_f)

        sig = specifiers.signature(forw)
        self.assertSigsEqual(sig, support.s(expected))

        self.assertSourcesEqual(
            sig.sources, {
                'outer': exp_src[0],
                'inner': exp_src[1],
                '+depths': ['outer', 'inner']
            })

        sig_get = specifiers.signature(_util.safe_get(forw, object(), object))
        self.assertSigsEqual(sig_get, support.s(expected_get))

        self.assertSourcesEqual(
            sig_get.sources, {
                'outer': exp_src_get[0],
                'inner': exp_src_get[1],
                '+depths': ['outer', 'inner']
            })
Exemple #2
0
 def test_success(self):
     self.assertSigsEqual(s('a, b:1'),
                          signature(modifiers.annotate(b=1)(f('a, b'))))
     self.assertSigsEqual(
         s('a:1, b:2'), signature(modifiers.annotate(a=1, b=2)(f('a, b'))))
     self.assertSigsEqual(s('a:1, b', 2),
                          signature(modifiers.annotate(2, a=1)(f('a, b'))))
Exemple #3
0
 def test_call(self):
     outer = support.f('*args, **kwargs')
     inner = support.f('a, *, b')
     forw = specifiers.forwards_to_function(inner)(outer)
     instance = object()
     forw_get_prox = _util.safe_get(forw, instance, object)
     self.assertEqual(
         forw_get_prox(1, b=2),
         {'args': (instance, 1), 'kwargs': {'b': 2}})
Exemple #4
0
class ExtraParamsTests(object):
    _func = support.f('')
    _func2 = support.f('')
    alt_cmd = ('', [
        parser.AlternateCommandParameter(func=_func, aliases=['--alt'])
    ], ('--alt', 'a', '-b', '--third'), ['test --alt', 'a', '-b',
                                         '--third'], {}, _func)
    alt_cmd2 = ('', [
        parser.AlternateCommandParameter(func=_func, aliases=['--alt'])
    ], ('--alt', '--alpha', '-b'), ['test --alt', '--alpha', '-b'], {}, _func)
    flb_cmd_start = ('', [
        parser.FallbackCommandParameter(func=_func, aliases=['--alt'])
    ], ('--alt', '-a', 'b', '--third'), ['test --alt', '-a', 'b',
                                         '--third'], {}, _func)
    flb_cmd_valid = ('*a', [
        parser.FallbackCommandParameter(func=_func, aliases=['--alt'])
    ], ('a', '--alt', 'b', '-c', '--fourth'), ['test --alt'], {}, _func)
    flb_cmd_invalid = ('', [
        parser.FallbackCommandParameter(func=_func, aliases=['--alt'])
    ], ('a', '--alt', 'a', '-b'), ['test --alt'], {}, _func)
    flb_cmd_invalid_valid = ('a: int, b', [
        parser.FallbackCommandParameter(func=_func, aliases=['--alt'])
    ], ('xyz', 'abc', '--alt', 'def', '-g', '--hij'), ['test --alt'], {},
                             _func)
    flb_after_alt = ('a: int, b', [
        parser.AlternateCommandParameter(func=_func, aliases=['--alt']),
        parser.FallbackCommandParameter(func=_func2, aliases=['--flb']),
    ], ('--invalid', '--alt', '--flb'), ['test --flb'], {}, _func2)

    def test_alt_middle(self):
        _func = support.f('')
        args = [
            '*a',
            [parser.AlternateCommandParameter(func=_func, aliases=['--alt'])],
            ('a', '--alt', 'a', 'b'), ['a', 'b'], {}, _func
        ]
        self.assertRaises(errors.ArgsBeforeAlternateCommand, self._test_func,
                          *args)
        try:
            self._test_func(*args)
        except errors.ArgsBeforeAlternateCommand as e:
            self.assertEqual(
                'Error: Arguments found before alternate '
                'action parameter --alt', str(e))

    def test_param_extras(self):
        extra_params = [
            parser.FlagParameter(value=True,
                                 conv=parser.is_true,
                                 aliases=['-' + name],
                                 argument_name=name) for name in 'abc'
        ]
        param = parser.PositionalParameter(display_name='one',
                                           argument_name='one')
        param.extras = extra_params
        csig = parser.CliSignature([param])
        self.assertEqual('[-a] [-b] [-c] one', str(csig))
def forwards_tests(self, outer, inner, args, kwargs, expected, expected_get):
    outer_f = support.f(outer)
    inner_f = support.f(inner)
    forw = specifiers.forwards_to_function(inner_f, *args, **kwargs)(outer_f)

    self.assertSigsEqual(specifiers.signature(forw), support.s(expected))

    self.assertSigsEqual(
        specifiers.signature(_util.safe_get(forw, object(), object)),
        support.s(expected_get))
Exemple #6
0
 def test_use_twice(self):
     annotator = modifiers.annotate(a=1)
     self.assertSigsEqual(
         s('a:1, b'),
         signature(annotator(f('a, b')))
         )
     self.assertSigsEqual(
         s('a:1'),
         signature(annotator(f('a')))
         )
Exemple #7
0
 def test_specifiers_sig_after(self):
     inner = f('a, b', name='inner')
     outer = f('x, y, z, *args, **kwargs', name='outer')
     pt = modifiers.kwoargs('z')(outer)
     pt = specifiers.forwards_to_function(inner)(pt)
     sig = specifiers.signature(pt)
     self.assertSigsEqual(sig, s('x, y, a, b, *, z'))
     self.assertSourcesEqual(
         sig.sources, {'inner': 'ab', 'outer': 'xyz',
                       '+depths': ['outer', 'inner']})
     self.assertEqual(sig.sources['x'], [pt])
 def test_call(self):
     outer = support.f('*args, **kwargs')
     inner = support.f('a, *, b')
     forw = specifiers.forwards_to_function(inner)(outer)
     instance = object()
     forw_get_prox = _util.safe_get(forw, instance, object)
     self.assertEqual(forw_get_prox(1, b=2), {
         'args': (instance, 1),
         'kwargs': {
             'b': 2
         }
     })
Exemple #9
0
 def _test_func(self, sig, wrapper_sigs, doc, wrapper_docs, help_str):
     ifunc = f(sig, pre="from clize import Parameter")
     ifunc.__doc__ = doc
     func = ifunc
     for sig, doc in zip(wrapper_sigs, wrapper_docs):
         wfunc = f('func, ' + sig, pre="from clize import Parameter")
         wfunc.__doc__ = doc
         func = wrapper_decorator(wfunc)(func)
     r = runner.Clize(func)
     h = help.ClizeHelp(r, None)
     h.prepare()
     p_help_str = str(h.show('func'))
     self.assertEqual(help_str.split(), p_help_str.split())
Exemple #10
0
 def _test_func(self, sig, wrapper_sigs, doc, wrapper_docs, help_str):
     ifunc = f(sig, pre="from clize import Parameter")
     ifunc.__doc__ = doc
     func = ifunc
     for sig, doc in zip(wrapper_sigs, wrapper_docs):
         wfunc = f('func, ' + sig, pre="from clize import Parameter")
         wfunc.__doc__ = doc
         func = wrapper_decorator(wfunc)(func)
     r = runner.Clize(func)
     h = help.ClizeHelp(r, None)
     h.prepare()
     p_help_str = str(h.show('func'))
     self.assertEqual(help_str.split(), p_help_str.split())
Exemple #11
0
 def test_success(self):
     self.assertSigsEqual(
         s('a, b:1'),
         signature(modifiers.annotate(b=1)(f('a, b')))
         )
     self.assertSigsEqual(
         s('a:1, b:2'),
         signature(modifiers.annotate(a=1, b=2)(f('a, b')))
         )
     self.assertSigsEqual(
         s('a:1, b', 2),
         signature(modifiers.annotate(2, a=1)(f('a, b')))
         )
Exemple #12
0
 def test_specifiers_sig_after(self):
     inner = f('a, b', name='inner')
     outer = f('x, y, z, *args, **kwargs', name='outer')
     pt = modifiers.kwoargs('z')(outer)
     pt = specifiers.forwards_to_function(inner)(pt)
     sig = specifiers.signature(pt)
     self.assertSigsEqual(sig, s('x, y, a, b, *, z'))
     self.assertSourcesEqual(sig.sources, {
         'inner': 'ab',
         'outer': 'xyz',
         '+depths': ['outer', 'inner']
     })
     self.assertEqual(sig.sources['x'], [pt])
Exemple #13
0
    def test_custom_param_help(self):
        class CustParam(parser.OptionParameter):
            def show_help(self, desc, after, f, cols):
                cols.append('I am', 'a custom parameter!')
                f.append("There is stuff after me.")
                f.append(desc)
                f.extend(after)
        func = f(
            "*, param: a",
            locals={'a': parser.use_class(named=CustParam)})
        func.__doc__ = """
            param: Param desc

            After param

            _:_

        """
        r = runner.Clize(func)
        self._do_test(r, ['func --param=STR', USAGE_HELP], """
            Usage: func [OPTIONS]

            Options:
                I am    a custom parameter!

            There is stuff after me.

            Param desc

            After param

            Other actions:
                -h, --help  Show the help
        """)
Exemple #14
0
    def test_custom_param_help(self):
        class CustParam(parser.OptionParameter):
            def show_help(self, desc, after, f, cols):
                cols.append('I am', 'a custom parameter!')
                f.append("There is stuff after me.")
                f.append(desc)
                f.extend(after)

        func = f("*, param: a",
                 locals={'a': parser.use_class(named=CustParam)})
        func.__doc__ = """
            param: Param desc

            After param

            _:_

        """
        r = runner.Clize(func)
        self._do_test(
            r, ['func --param=STR', USAGE_HELP], """
            Usage: func [OPTIONS]

            Options:
                I am    a custom parameter!

            There is stuff after me.

            Param desc

            After param

            Other actions:
                -h, --help  Show the help
        """)
class PartialSigTests(Fixtures):
    def _test(self, obj, exp_sig, exp_src=None):
        sig = signature(obj)
        self.assertSigsEqual(sig, s(exp_sig))
        if exp_src is None:
            exp_src = dict((p, [obj.func]) for p in sig.parameters)
            exp_src['+depths'] = {obj: 0, obj.func: 1}
        self.assertEqual(sig.sources, exp_src)

    _func1 = f('a, b, c, *args, d, e, **kwargs')

    pos = partial(_func1, 1), 'b, c, *args, d, e, **kwargs'
    kwkw = partial(_func1, d=1), 'a, b, c, *args, e, d=1, **kwargs'

    kwposlast_1 = partial(_func1, c=1), 'a, b, *, d, e, c=1, **kwargs'
    kwposlast_2 = partial(_func1, b=1), 'a, *, d, e, c, b=1, **kwargs'

    def _kw_create(_func1):
        par = partial(_func1, f=1)
        src = dict(
            (p, [_func1]) for p in ['a', 'b', 'c', 'args', 'd', 'e', 'kwargs'])
        src['f'] = [par]
        src['+depths'] = {_func1: 1, par: 0}
        return par, 'a, b, c, *args, d, e, f=1, **kwargs', src

    kw_create = _kw_create(_func1)
Exemple #16
0
def test_whole_help(self, sig, doc, help_str):
    func = f(sig, pre="from clize import Parameter")
    func.__doc__ = doc
    r = runner.Clize(func)
    h = help.ClizeHelp(r, None)
    p_help_str = str(h.show('func'))
    self.assertEqual(p_help_str.split(), help_str.split())
Exemple #17
0
    def test_preserve_annotations(self):
        func = f('self, a:2, b, c:3', 4)

        tr = modifiers._PokTranslator(func, kwoargs=('a', 'b'))
        self.assertSigsEqual(s('self, c:3, *, a:2, b', 4), signature(tr))
        self.assertSigsEqual(s('c:3, *, a:2, b', 4),
                             signature(safe_get(tr, object(), object)))
Exemple #18
0
 def _test_func(self, sig, doc, help_str):
     func = f(sig, pre="from clize import Parameter as P")
     func.__doc__ = doc
     r = runner.Clize(func)
     h = help.ClizeHelp(r, None)
     h.prepare()
     p_help_str = str(h.show('func'))
     self.assertEqual(help_str, p_help_str)
Exemple #19
0
 def test_attr_conservation_after(self):
     func = f('s, a')
     pt = modifiers.kwoargs('a')(func)
     pt.attr = object()
     self.assertIs(pt.attr, modifiers.kwoargs('a')(pt).attr)
     bpt = pt.__get__(object(), object)
     self.assertIs(pt.attr, bpt.attr)
     self.assertIs(pt.attr, modifiers.kwoargs('a')(bpt).attr)
Exemple #20
0
 def test_attr_conservation_after(self):
     func = f('s, a')
     pt = modifiers.kwoargs('a')(func)
     pt.attr = object()
     self.assertIs(pt.attr, modifiers.kwoargs('a')(pt).attr)
     bpt = pt.__get__(object(), object)
     self.assertIs(pt.attr, bpt.attr)
     self.assertIs(pt.attr, modifiers.kwoargs('a')(bpt).attr)
Exemple #21
0
 def test_show_list(self):
     func = support.f('par:a', locals={'a': RepTests.oneof_help[1]})
     out, err = util.run(func, ['name', 'list'])
     self.assertEqual('', err.getvalue())
     self.assertEqual(
         """name: Possible values for par:
         hello h1
         bye h2""".split(),
         out.getvalue().split())
Exemple #22
0
 def _test_func(self, description, footer, sigs, docs, usage, help_str):
     funcs = []
     for i, sig, doc in zip(count(1), sigs, docs):
         func = f(sig)
         func.__doc__ = doc
         func.__name__ = 'func' + str(i)
         funcs.append(func)
     sd = runner.SubcommandDispatcher(funcs, description, footer)
     self._do_test(sd, usage, help_str)
Exemple #23
0
 def test_show_list(self):
     func = support.f('par:a', locals={'a': RepTests.mapped_basic[1]})
     out, err = self.crun(func, ['name', 'list'])
     self.assertEqual('', err.getvalue())
     self.assertLinesEqual(
         """
         name: Possible values for par:
           hello     h1
           goodbye   h2""", out.getvalue())
Exemple #24
0
 def _test_func(self, description, footer, sigs, docs, usage, help_str):
     funcs = []
     for i, sig, doc in zip(count(1), sigs, docs):
         func = f(sig)
         func.__doc__ = doc
         func.__name__ = 'func' + str(i)
         funcs.append(func)
     sd = runner.SubcommandDispatcher(funcs, description, footer)
     self._do_test(sd, usage, help_str)
Exemple #25
0
 def test_show_list_morekw(self):
     func = support.f('par:a', locals={'a': RepTests.mapped_basic[1]})
     out, err = util.run(func, ['name', 'list', '-k', 'xyz'])
     self.assertEqual('', err.getvalue())
     self.assertEqual(
         """name: Possible values for par:
         hello h1
         goodbye h2""".split(),
         out.getvalue().split())
Exemple #26
0
 def test_show_list(self):
     func = support.f('par:a', locals={'a': RepTests.oneof_help[1]})
     out, err = util.run(func, ['name', 'list'])
     self.assertEqual('', err.getvalue())
     self.assertEqual(
         """name: Possible values for par:
         hello h1
         bye h2""".split(),
         out.getvalue().split())
Exemple #27
0
 def test_show_list_morekw(self):
     func = support.f('par:a', locals={'a': RepTests.mapped_basic[1]})
     out, err = util.run(func, ['name', 'list', '-k', 'xyz'])
     self.assertEqual('', err.getvalue())
     self.assertEqual(
         """name: Possible values for par:
         hello h1
         goodbye h2""".split(),
         out.getvalue().split())
class PartialSigTests(object):
    _func1 = support.f('a, b, c, *args, d, e, **kwargs')

    pos = partial(_func1, 1), 'b, c, *args, d, e, **kwargs'
    kwkw = partial(_func1, d=1), 'a, b, c, *args, e, d=1, **kwargs'
    kwkws = partial(_func1, f=1), 'a, b, c, *args, d, e, f=1, **kwargs'

    kwposlast = partial(_func1, c=1), 'a, b, *, d, e, c=1, **kwargs'
    kwposlast = partial(_func1, b=1), 'a, *, d, e, c, b=1, **kwargs'
Exemple #29
0
    def _test(self, expected_sig_str, orig_sig_str, exceptions):
        orig_func = f(orig_sig_str)
        expected_sig = s(expected_sig_str)

        func = modifiers.autokwoargs(exceptions=exceptions)(orig_func)
        self.assertSigsEqual(expected_sig, signature(func))

        if not exceptions: # test the arg-less form of @autokwargs
            func = modifiers.autokwoargs(orig_func)
            self.assertSigsEqual(expected_sig, signature(func))
Exemple #30
0
 def test_show_list(self):
     func = support.f('par:a', locals={'a': RepTests.mapped_basic[1]})
     out, err = self.crun(func, ['name', 'list'])
     self.assertEqual('', err.getvalue())
     self.assertLinesEqual(
         """
         name: Possible values for par:
           hello     h1
           goodbye   h2""",
         out.getvalue())
Exemple #31
0
    def _test(self, outer, inner, args, kwargs,
                    expected, expected_get, exp_src, exp_src_get):
        outer_f = support.f(outer, name='outer')
        inner_f = support.f(inner, name='inner')
        forw = specifiers.forwards_to_function(inner_f, *args, **kwargs)(outer_f)

        sig = specifiers.signature(forw)
        self.assertSigsEqual(sig, support.s(expected))

        self.assertSourcesEqual(sig.sources, {
                'outer': exp_src[0], 'inner': exp_src[1],
                '+depths': ['outer', 'inner']})

        sig_get = specifiers.signature(_util.safe_get(forw, object(), object))
        self.assertSigsEqual(sig_get, support.s(expected_get))

        self.assertSourcesEqual(sig_get.sources, {
                'outer': exp_src_get[0], 'inner': exp_src_get[1],
                '+depths': ['outer', 'inner']})
Exemple #32
0
    def _test(self, expected_sig_str, orig_sig_str, exceptions):
        orig_func = f(orig_sig_str)
        expected_sig = s(expected_sig_str)

        func = modifiers.autokwoargs(exceptions=exceptions)(orig_func)
        self.assertSigsEqual(expected_sig, signature(func))

        if not exceptions:  # test the arg-less form of @autokwargs
            func = modifiers.autokwoargs(orig_func)
            self.assertSigsEqual(expected_sig, signature(func))
Exemple #33
0
 def test_show_list_alt(self):
     func = support.f('par:a',
                      locals={'a': RepTests.mapped_alternate_list[1]})
     out, err = util.run(func, ['name', 'options'])
     self.assertEqual('', err.getvalue())
     self.assertEqual(
         """name: Possible values for par:
         hello h1
         goodbye h2""".split(),
         out.getvalue().split())
Exemple #34
0
 def test_show_list_alt(self):
     func = support.f('par:a',
                     locals={'a': RepTests.mapped_alternate_list[1]})
     out, err = util.run(func, ['name', 'options'])
     self.assertEqual('', err.getvalue())
     self.assertEqual(
         """name: Possible values for par:
         hello h1
         goodbye h2""".split(),
         out.getvalue().split())
Exemple #35
0
 def test_alt_middle(self):
     _func = support.f('')
     self.assertRaises(
         errors.ArgsBeforeAlternateCommand,
         self._test_func,
         '*a', [
             parser.AlternateCommandParameter(
                 func=_func, aliases=['--alt'])],
         ('a', '--alt', 'a', 'b'), ['a', 'b'], {}, _func
     )
Exemple #36
0
 def test_pok_interact(self):
     pok = f('self, a, *, b')
     annotated = modifiers.annotate(a=1, b=2)(pok)
     self.assertSigsEqual(
         s('self, a:1, *, b:2'),
         signature(annotated)
         )
     self.assertSigsEqual(
         s('a:1, *, b:2'),
         signature(safe_get(annotated, object(), object))
         )
Exemple #37
0
 def test_alt_middle(self):
     _func = support.f('')
     args = [
         '*a', [
             parser.AlternateCommandParameter(
                 func=_func, aliases=['--alt'])],
         ('a', '--alt', 'a', 'b'), ['a', 'b'], {}, _func
         ]
     exp_msg = ('Error: Arguments found before alternate '
                'action parameter --alt')
     with self.assertRaises(errors.ArgsBeforeAlternateCommand, msg=exp_msg):
         self._test(*args)
Exemple #38
0
    def test_preserve_annotations(self):
        func = f('self, a:2, b, c:3', 4)

        tr = modifiers._PokTranslator(func, kwoargs=('a', 'b'))
        self.assertSigsEqual(
            s('self, c:3, *, a:2, b', 4),
            signature(tr)
            )
        self.assertSigsEqual(
            s('c:3, *, a:2, b', 4),
            signature(safe_get(tr, object(), object))
            )
Exemple #39
0
 def test_alt_middle(self):
     _func = support.f('')
     args = [
         '*a',
         [parser.AlternateCommandParameter(func=_func, aliases=['--alt'])],
         ('a', '--alt', 'a', 'b'), ['a', 'b'], {}, _func
     ]
     exp_msg = ('Error: Arguments found before alternate '
                'action parameter --alt')
     with self.assertRaisesRegex(errors.ArgsBeforeAlternateCommand,
                                 exp_msg):
         self._test(*args)
Exemple #40
0
 def test_alt_middle(self):
     _func = support.f('')
     args = [
         '*a',
         [parser.AlternateCommandParameter(func=_func, aliases=['--alt'])],
         ('a', '--alt', 'a', 'b'), ['a', 'b'], {}, _func
     ]
     self.assertRaises(errors.ArgsBeforeAlternateCommand, self._test_func,
                       *args)
     try:
         self._test_func(*args)
     except errors.ArgsBeforeAlternateCommand as e:
         self.assertEqual(
             'Error: Arguments found before alternate '
             'action parameter --alt', str(e))
Exemple #41
0
 def test_alt_middle(self):
     _func = support.f("")
     args = [
         "*a",
         [parser.AlternateCommandParameter(func=_func, aliases=["--alt"])],
         ("a", "--alt", "a", "b"),
         ["a", "b"],
         {},
         _func,
     ]
     self.assertRaises(errors.ArgsBeforeAlternateCommand, self._test_func, *args)
     try:
         self._test_func(*args)
     except errors.ArgsBeforeAlternateCommand as e:
         self.assertEqual("Error: Arguments found before alternate " "action parameter --alt", str(e))
Exemple #42
0
 def _test_func(self, sig, doc, help_str):
     try:
         backw = util.get_terminal_width
     except AttributeError:
         backw = None
     try:
         util.get_terminal_width = lambda: 80
         func = f(sig, pre="from clize import Parameter as P")
         func.__doc__ = doc
         r = runner.Clize(func)
         h = help.ClizeHelp(r, None)
         h.prepare()
         p_help_str = str(h.show('func'))
         self.assertEqual(help_str, p_help_str)
     finally:
         if backw is not None:
             util.get_terminal_width = backw
Exemple #43
0
 def _test_func(self, sig, doc, help_str):
     try:
         backw = util.get_terminal_width
     except AttributeError:
         backw = None
     try:
         util.get_terminal_width = lambda: 80
         func = f(sig, pre="from clize import Parameter as P")
         func.__doc__ = doc
         r = runner.Clize(func)
         h = help.ClizeHelp(r, None)
         h.prepare()
         p_help_str = str(h.show('func'))
         self.assertEqual(help_str, p_help_str)
     finally:
         if backw is not None:
             util.get_terminal_width = backw
Exemple #44
0
 def test_alt_middle(self):
     _func = support.f('')
     args = [
         '*a', [
             parser.AlternateCommandParameter(
                 func=_func, aliases=['--alt'])],
         ('a', '--alt', 'a', 'b'), ['a', 'b'], {}, _func
         ]
     self.assertRaises(
         errors.ArgsBeforeAlternateCommand,
         self._test_func, *args)
     try:
         self._test_func(*args)
     except errors.ArgsBeforeAlternateCommand as e:
         self.assertEqual(
             'Error: Arguments found before alternate '
             'action parameter --alt', str(e))
Exemple #45
0
 def test_use_twice(self):
     annotator = modifiers.annotate(a=1)
     self.assertSigsEqual(s('a:1, b'), signature(annotator(f('a, b'))))
     self.assertSigsEqual(s('a:1'), signature(annotator(f('a'))))
Exemple #46
0
 def _test_func(self, sig_str, annotation, doc, expected):
     f = support.f(sig_str, locals={'a': annotation})
     f.__doc__ = doc
     cli = runner.Clize.get_cli(f)
     self.assertEqual(expected.split(), cli('func', '--help').split())
Exemple #47
0
 def _test(self, expected_sig_str, orig_sig_str, start):
     orig_func = f(orig_sig_str)
     func = modifiers.kwoargs(start=start)(orig_func)
     self.assertSigsEqual(s(expected_sig_str), signature(func))
from mock import patch
import ast

from sigtools import support, modifiers, specifiers, signatures, _util, _autoforwards
from sigtools.tests.util import Fixtures, tup

if sys.version_info >= (3, ):
    from sigtools.tests import autoforwards_py3
    Py3AutoforwardsTests = autoforwards_py3.Py3AutoforwardsTests
    Py3UnknownAutoforwardsTests = autoforwards_py3.Py3UnknownAutoforwardsTests

if sys.version_info >= (3, 5):
    from sigtools.tests import autoforwards_py35
    Py35AutoforwardsTests = autoforwards_py35.Py35UnknownAutoforwardsTests

_wrapped = support.f('x, y, *, z', name='_wrapped')


def func(*args, **kwargs):
    pass


class AutoforwardsMarkerReprs(Fixtures):
    def _test(self, obj, exp_repr):
        self.assertEqual(repr(obj), exp_repr)

    _af = _autoforwards

    name = _af.Name('spam'), "<name 'spam'>"
    attribute = _af.Attribute(_af.Name('ham'),
                              'eggs'), "<attribute <name 'ham'>.eggs>"
class AutoforwardsTests(Fixtures):
    def _test(self, func, expected, sources, incoherent=False):
        sig = specifiers.signature(func)
        self.assertSigsEqual(sig, support.s(expected))
        self.assertSourcesEqual(sig.sources, sources, func)
        if not incoherent:
            support.test_func_sig_coherent(func,
                                           check_return=False,
                                           check_invalid=False)

    @tup('a, b, x, y, *, z', {
        'global_': ('a', 'b'),
        '_wrapped': ('x', 'y', 'z')
    })
    def global_(a, b, *args, **kwargs):
        return _wrapped(*args, **kwargs)

    def _make_closure():
        wrapped = _wrapped

        def wrapper(b, a, *args, **kwargs):
            return wrapped(*args, **kwargs)

        return wrapper

    closure = (_make_closure(), 'b, a, x, y, *, z', {
        'wrapper': 'ba',
        '_wrapped': 'xyz'
    })

    @tup('a, b, y', {'args': 'ab', '_wrapped': 'y'})
    def args(a, b, *args, **kwargs):
        return _wrapped(a, *args, z=b, **kwargs)

    @tup('a, b, *, z', {'using_other_varargs': 'ab', '_wrapped': 'z'})
    def using_other_varargs(a, b, **kwargs):
        return _wrapped(a, *b, **kwargs)

    # def test_external_args(self):
    #     def l1():
    #         a = None
    #         def l2(**kwargs):
    #             nonlocal a
    #             _wrapped(*a, **kwargs)
    #         return l2
    #     self._test_func(l1(), '*, z')

    @tup('x, y, /, *, kwop', {'kwo': ['kwop'], '_wrapped': 'xy'})
    @modifiers.kwoargs('kwop')
    def kwo(kwop, *args):
        _wrapped(*args, z=kwop)

    @tup('a, b, y, *, z', {'subdef': 'ab', '_wrapped': 'yz'})
    def subdef(a, b, *args, **kwargs):
        def func():
            _wrapped(42, *args, **kwargs)

        func()

    @tup('a, b, y, *, z', {'subdef_lambda': 'ab', '_wrapped': 'yz'})
    def subdef_lambda(a, b, *args, **kwargs):
        (lambda: _wrapped(42, *args, **kwargs))()

    @tup('a, b, x, y, *, z', {0: 'ab', '_wrapped': 'xyz'})
    def rebind_in_subdef(a, b, *args, **kwargs):
        def func():
            args = 1,
            kwargs = {'z': 2}
            _wrapped(42, *args, **kwargs)

        _wrapped(*args, **kwargs)
        func()

    @tup('a, b, x, y, *, z', {'rebind_subdef_param': 'ab', '_wrapped': 'xyz'})
    def rebind_subdef_param(a, b, *args, **kwargs):
        def func(*args, **kwargs):
            _wrapped(42, *args, **kwargs)

        _wrapped(*args, **kwargs)
        func(2, z=3)

    @tup('a, b, *args, **kwargs',
         {'rebind_subdef_lambda_param': ['a', 'b', 'args', 'kwargs']})
    def rebind_subdef_lambda_param(a, b, *args, **kwargs):
        f = lambda *args, **kwargs: _wrapped(*args, **kwargs)
        f(1, 2, z=3)

    # @tup('a, b, x, y, *, z', {0: 'ab', '_wrapped': 'xyz'})
    # def nonlocal_already_executed(a, b, *args, **kwargs):
    #     def make_ret2(args, kwargs):
    #         def ret2():
    #             _wrapped(*args, **kwargs)
    #     make_ret2(args, kwargs)
    #     def ret1():
    #         nonlocal args, kwargs
    #         args = ()
    #         kwargs = {}

    def test_partial(self):
        def _wrapper(wrapped, a, *args, **kwargs):
            return wrapped(*args, **kwargs)

        func = partial(_wrapper, _wrapped)
        sig = specifiers.signature(func)
        self.assertSigsEqual(sig, support.s('a, x, y, *, z'))
        self.assertEqual(
            sig.sources, {
                'a': [_wrapper],
                'x': [_wrapped],
                'y': [_wrapped],
                'z': [_wrapped],
                '+depths': {
                    func: 0,
                    _wrapper: 1,
                    _wrapped: 2
                }
            })
        support.test_func_sig_coherent(func,
                                       check_return=False,
                                       check_invalid=False)

    @staticmethod
    @modifiers.kwoargs('wrapped')
    def _wrapped_kwoarg(a, wrapped, *args, **kwargs):
        return wrapped(*args, **kwargs)  # pragma: no cover

    def test_partial_kwo(self):
        """When given keyword arguments, functools.partial only makes them
        defaults. The full signature is therefore not fully determined, since
        the user can replace wrapped and change the meaning of *args, **kwargs.

        The substitution could be made in good faith that the user wouldn't
        change the value of the parameter, but this would potentially cause
        confusing documentation where a function description says remaining
        arguments will be forwarded to the given function, while the signature
        in the documentation only shows the default target's arguments.
        """
        func = partial(AutoforwardsTests._wrapped_kwoarg, wrapped=_wrapped)
        expected = support.s('a, *args, wrapped=w, **kwargs',
                             locals={'w': _wrapped})
        self.assertSigsEqual(specifiers.signature(func), expected)

    _wrapped_attr = staticmethod(support.f('d, e, *, f'))

    @tup('a, d, e, *, f', {0: 'a', 'func': 'def'})
    def global_attribute(a, *args, **kwargs):
        AutoforwardsTests._wrapped_attr(*args, **kwargs)

    def test_instance_attribute(self):
        class A(object):
            def wrapped(self, x, y):
                pass

            def method(self, a, *args, **kwargs):
                self.wrapped(a, *args, **kwargs)

        a = A()
        self._test(a.method, 'a, y', {0: 'a', 'wrapped': 'y'})

    def test_multiple_method_calls(self):
        class A(object):
            def wrapped_1(self, x, y):
                pass

            def wrapped_2(self, x, y):
                pass

            def method(self, a, *args, **kwargs):
                self.wrapped_1(a, *args, **kwargs)
                self.wrapped_2(a, *args, **kwargs)

        self._test(
            A().method, 'a, y',
            _util.OrderedDict([(0, 'a'), ('method', 'a'), ('wrapped_1', 'y'),
                               ('wrapped_2', 'y'),
                               ('+depths', {
                                   'method': 0,
                                   'wrapped_1': 1,
                                   'wrapped_2': 1
                               })]))

    @staticmethod
    @modifiers.kwoargs('b')
    def _deeparg_l1(l2, b, *args, **kwargs):
        l2(*args, **kwargs)

    @staticmethod
    @modifiers.kwoargs('c')
    def _deeparg_l2(l3, c, *args, **kwargs):
        l3(*args, **kwargs)

    @tup('x, y, *, a, b, c, z', {
        0: 'a',
        '_deeparg_l1': 'b',
        '_deeparg_l2': 'c',
        _wrapped: 'xyz'
    })
    @modifiers.kwoargs('a')
    def deeparg(a, *args, **kwargs):
        AutoforwardsTests._deeparg_l1(AutoforwardsTests._deeparg_l2, _wrapped,
                                      *args, **kwargs)

    @staticmethod
    @modifiers.kwoargs('l2')
    def _deeparg_kwo_l1(l2, b, *args, **kwargs):
        l2(*args, **kwargs)

    @staticmethod
    @modifiers.kwoargs('l3')
    def _deeparg_kwo_l2(l3, c, *args, **kwargs):
        l3(*args, **kwargs)

    @tup('a, b, c, x, y, *, z', {
        0: 'a',
        '_deeparg_kwo_l1': 'b',
        '_deeparg_kwo_l2': 'c',
        _wrapped: 'xyz'
    })
    def deeparg_kwo(a, *args, **kwargs):
        AutoforwardsTests._deeparg_kwo_l1(*args,
                                          l2=AutoforwardsTests._deeparg_kwo_l2,
                                          l3=_wrapped,
                                          **kwargs)

    @tup('a, x, y, *, z', {0: 'a', _wrapped: 'xyz'})
    def call_in_args(a, *args, **kwargs):
        func(_wrapped(*args, **kwargs))

    @tup('a, x, y, *, z', {0: 'a', _wrapped: 'xyz'})
    def call_in_kwargs(a, *args, **kwargs):
        func(kw=_wrapped(*args, **kwargs))

    @tup('a, x, y, *, z', {0: 'a', _wrapped: 'xyz'})
    def call_in_varargs(a, *args, **kwargs):
        func(*_wrapped(*args, **kwargs))

    @tup('a, x, y, *, z', {
        0: 'a',
        _wrapped: 'xyz',
        '+depths': ['call_in_varkwargs', '_wrapped']
    })
    def call_in_varkwargs(a, *args, **kwargs):
        func(**_wrapped(*args, **kwargs))

    def test_functools_wrapped(self):
        @wraps(_wrapped)
        def func(a, *args, **kwargs):
            _wrapped(1, *args, **kwargs)

        sig = specifiers.signature(func)
        self.assertSigsEqual(sig, support.s('a, y, *, z'))
        self.assertEqual(
            sig.sources, {
                '+depths': {
                    func: 0,
                    _wrapped: 1
                },
                'a': [func],
                'y': [_wrapped],
                'z': [_wrapped]
            })
        support.test_func_sig_coherent(func,
                                       check_return=False,
                                       check_invalid=False)

    def test_decorator_wraps(self):
        def decorator(function):
            @wraps(function)
            @modifiers.autokwoargs
            def _decorated(a, b=2, *args, **kwargs):
                function(1, *args, **kwargs)

            return _decorated

        func = decorator(_wrapped)
        sig = specifiers.signature(func)
        self.assertSigsEqual(sig, support.s('a, y, *, b=2, z'))
        self.assertEqual(
            sig.sources, {
                '+depths': {
                    func: 0,
                    _wrapped: 1
                },
                'a': [func],
                'b': [func],
                'y': [_wrapped],
                'z': [_wrapped]
            })
        support.test_func_sig_coherent(func,
                                       check_return=False,
                                       check_invalid=False)

    @tup('a, b, *args, z', {
        'unknown_args': ['a', 'b', 'args'],
        '_wrapped': 'z'
    })
    def unknown_args(a, b, *args, **kwargs):
        args = (1, 2)
        return _wrapped(*args, **kwargs)

    # @tup('a, b, c, x, y, *, z', {0: 'ab', 'sub': 'c', '_wrapped': 'xyz'})
    # def use_subdef(a, b, *args, **kwargs):
    #     def sub(c, *args, **kwargs):
    #         _wrapped(*args, **kwargs)
    #     sub(1, *args, **kwargs)

    @tup('a, b, x=None, y=None, *, z=None', {0: 'ab', '_wrapped': 'xyz'})
    def pass_to_partial(a, b, *args, **kwargs):
        partial(_wrapped, *args, **kwargs)

    @tup('a, b, y=None', {0: 'ab', '_wrapped': 'y'})
    def pass_to_partial_with_args(a, b, *args, **kwargs):
        partial(_wrapped, a, *args, z=b, **kwargs)

    @tup('x, y, *, z', {'_wrapped': 'xyz'})
    def kwargs_passed_to_func_after(*args, **kwargs):
        _wrapped(*args, **kwargs)
        func(kwargs)

    @tup('x, y, *, z', {'_wrapped': 'xyz'})
    def args_passed_to_func(*args, **kwargs):
        func(args)
        _wrapped(*args, **kwargs)
Exemple #50
0
 def test_unused_annotation(self):
     self.assertRaises(ValueError, modifiers.annotate(a=1, c=2), f('a, b'))
Exemple #51
0
 def test_pok_interact(self):
     pok = f('self, a, *, b')
     annotated = modifiers.annotate(a=1, b=2)(pok)
     self.assertSigsEqual(s('self, a:1, *, b:2'), signature(annotated))
     self.assertSigsEqual(s('a:1, *, b:2'),
                          signature(safe_get(annotated, object(), object)))
Exemple #52
0
class ExtraParamsTests(Fixtures):
    def _test(self, sig_str, extra, args, posargs, kwargs, func):
        sig = support.s(sig_str)
        csig = parser.CliSignature.from_signature(sig, extra=extra)
        ba = self.read_arguments(csig, args)
        self.assertEqual(ba.args, posargs)
        self.assertEqual(ba.kwargs, kwargs)
        self.assertEqual(ba.func, func)

    _func = support.f('')
    _func2 = support.f('')

    alt_cmd = ('', [
        parser.AlternateCommandParameter(func=_func, aliases=['--alt'])
    ], ('--alt', 'a', '-b', '--third'), ['test --alt', 'a', '-b',
                                         '--third'], {}, _func)
    alt_cmd2 = ('', [
        parser.AlternateCommandParameter(func=_func, aliases=['--alt'])
    ], ('--alt', '--alpha', '-b'), ['test --alt', '--alpha', '-b'], {}, _func)
    flb_cmd_start = ('', [
        parser.FallbackCommandParameter(func=_func, aliases=['--alt'])
    ], ('--alt', '-a', 'b', '--third'), ['test --alt', '-a', 'b',
                                         '--third'], {}, _func)
    flb_cmd_valid = ('*a', [
        parser.FallbackCommandParameter(func=_func, aliases=['--alt'])
    ], ('a', '--alt', 'b', '-c', '--fourth'), ['test --alt'], {}, _func)
    flb_cmd_invalid = ('', [
        parser.FallbackCommandParameter(func=_func, aliases=['--alt'])
    ], ('a', '--alt', 'a', '-b'), ['test --alt'], {}, _func)
    flb_cmd_invalid_valid = ('a: int, b', [
        parser.FallbackCommandParameter(func=_func, aliases=['--alt'])
    ], ('xyz', 'abc', '--alt', 'def', '-g', '--hij'), ['test --alt'], {},
                             _func)
    flb_after_alt = ('a: int, b', [
        parser.AlternateCommandParameter(func=_func, aliases=['--alt']),
        parser.FallbackCommandParameter(func=_func2, aliases=['--flb']),
    ], ('--invalid', '--alt', '--flb'), ['test --flb'], {}, _func2)

    def test_alt_middle(self):
        _func = support.f('')
        args = [
            '*a',
            [parser.AlternateCommandParameter(func=_func, aliases=['--alt'])],
            ('a', '--alt', 'a', 'b'), ['a', 'b'], {}, _func
        ]
        exp_msg = ('Error: Arguments found before alternate '
                   'action parameter --alt')
        with self.assertRaisesRegex(errors.ArgsBeforeAlternateCommand,
                                    exp_msg):
            self._test(*args)

    def test_param_extras(self):
        extra_params = [
            parser.FlagParameter(value=True,
                                 conv=parser.is_true,
                                 aliases=['-' + name],
                                 argument_name=name) for name in 'abc'
        ]
        param = parser.PositionalParameter(display_name='one',
                                           argument_name='one')
        param.extras = extra_params
        csig = parser.CliSignature([param])
        self.assertEqual('[-a] [-b] [-c] one', str(csig))
Exemple #53
0
 def _test(self, expected_sig_str, orig_sig_str, end):
     orig_func = f(orig_sig_str)
     func = modifiers.posoargs(end=end)(orig_func)
     self.assertSigsEqual(s(expected_sig_str), signature(func))
Exemple #54
0
 def test_merge_other(self):
     orig_func = f('a, b')
     func = modifiers.kwoargs('b')(modifiers.posoargs(end='a')(orig_func))
     self.assertSigsEqual(s('<a>, *, b'), signature(func))
Exemple #55
0
 def _test(self, expected_sig_str, orig_sig_str, end):
     orig_func = f(orig_sig_str)
     func = modifiers.posoargs(end=end)(orig_func)
     self.assertSigsEqual(s(expected_sig_str), signature(func))
Exemple #56
0
 def _test(self, expected_sig_str, orig_sig_str, start):
     orig_func = f(orig_sig_str)
     func = modifiers.kwoargs(start=start)(orig_func)
     self.assertSigsEqual(s(expected_sig_str), signature(func))
Exemple #57
0
 def _test(self, sig_str, posoargs, kwoargs):
     self.assertRaises(
         ValueError,
         modifiers._PokTranslator, f(sig_str), posoargs, kwoargs)
Exemple #58
0
 def test_posoargs_end_missing_raises(self):
     func = f('')
     self.assertRaises(ValueError, modifiers.posoargs(end='a'), func)
Exemple #59
0
 def test_kwoargs_start_missing_raises(self):
     func = f('')
     self.assertRaises(ValueError, modifiers.kwoargs(start='a'), func)
Exemple #60
0
 def test_unused_annotation(self):
     self.assertRaises(
         ValueError,
         modifiers.annotate(a=1, c=2), f('a, b')
         )