File: test_dispatching.py

package info (click to toggle)
python-argh 0.26.2-1.1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 296 kB
  • sloc: python: 1,586; makefile: 4
file content (94 lines) | stat: -rw-r--r-- 2,130 bytes parent folder | download | duplicates (2)
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
# coding: utf-8
"""
Dispatching tests
~~~~~~~~~~~~~~~~~
"""
import argh
from mock import Mock, patch
import pytest

from .base import make_IO


def _dispatch_and_capture(func, command_string, **kwargs):
    if hasattr(command_string, 'split'):
        args = command_string.split()
    else:
        args = command_string

    io = make_IO()
    if 'output_file' not in kwargs:
        kwargs['output_file'] = io

    result = argh.dispatch_command(func, args, **kwargs)

    if kwargs.get('output_file') is None:
        return result
    else:
        io.seek(0)
        return io.read()


def run_func(func, command_string, **kwargs):
    try:
        result = _dispatch_and_capture(func, command_string, **kwargs)
    except SystemExit:
        raise
    else:
        return result


def test_dispatch_command_shortcut():

    def cmd(foo=1):
        return foo

    assert run_func(cmd, '') == '1\n'
    assert run_func(cmd, '--foo 2') == '2\n'


@patch('argh.dispatching.dispatch')
@patch('argh.dispatching.add_commands')
@patch('argparse.ArgumentParser')
def test_entrypoint(ap_cls_mock, add_commands_mock, dispatch_mock):

    entrypoint = argh.EntryPoint('my cool app')

    # no commands

    with pytest.raises(argh.exceptions.DispatchingError) as excinfo:
        entrypoint()
    assert excinfo.exconly().endswith(
        'DispatchingError: no commands for entry point "my cool app"')

    mocked_parser = Mock()
    ap_cls_mock.return_value = mocked_parser

    # a single command

    @entrypoint
    def greet():
        return 'hello'

    entrypoint()

    assert add_commands_mock.called
    add_commands_mock.assert_called_with(mocked_parser, [greet])
    assert dispatch_mock.called
    dispatch_mock.assert_called_with(mocked_parser)

    # multiple commands

    add_commands_mock.reset_mock()
    dispatch_mock.reset_mock()

    @entrypoint
    def hit():
        return 'knight with a chicken'

    entrypoint()

    assert add_commands_mock.called
    add_commands_mock.assert_called_with(mocked_parser, [greet, hit])
    assert dispatch_mock.called
    dispatch_mock.assert_called_with(mocked_parser)