File: test_constraints.py

package info (click to toggle)
python-cloup 3.0.8-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 936 kB
  • sloc: python: 5,371; makefile: 120
file content (359 lines) | stat: -rw-r--r-- 14,654 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
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
from functools import partial
from typing import Sequence
from unittest import mock
from unittest.mock import Mock

import click
import pytest
from click import Command, Context, Parameter
from pytest import mark

from cloup.constraints import (
    AcceptAtMost,
    AcceptBetween,
    Constraint,
    ErrorFmt,
    Rephraser,
    RequireAtLeast,
    RequireExactly,
    require_all,
)
from cloup.constraints.exceptions import ConstraintViolated, UnsatisfiableConstraint
from tests.util import (
    make_context, make_fake_context, make_options, parametrize, should_raise,
)


class FakeConstraint(Constraint):
    """Sometimes it's useful to use

        Mock(wraps=FakeConstraint(...))

    to create a test double with characteristics of both a mock and a fake."""

    def __init__(
        self, satisfied=True, consistent=True, help='help',
        error='error', inconsistency_reason='consistency_error'
    ):
        self.satisfied = satisfied
        self.consistent = consistent
        self._help = help
        self.error = error
        self.inconsistency_reason = inconsistency_reason
        self.check_consistency_calls = []
        self.check_values_calls = []

    def help(self, ctx: Context) -> str:
        return self._help

    def check_consistency(self, params: Sequence[Parameter]) -> None:
        self.check_consistency_calls.append(dict(params=params))
        if not self.consistent:
            raise UnsatisfiableConstraint(self, params, self.inconsistency_reason)

    def check_values(self, params: Sequence[Parameter], ctx: Context):
        self.check_values_calls.append(dict(params=params, ctx=ctx))
        if not self.satisfied:
            raise ConstraintViolated(self.error, ctx=ctx, constraint=self, params=params)


class TestBaseConstraint:
    def test_rephrased_calls_Rephraser_correctly(self):
        with mock.patch('cloup.constraints._core.Rephraser') as rephraser_cls:
            cons = FakeConstraint()
            cons.rephrased(help='ciao')
            rephraser_cls.assert_called_with(cons, help='ciao', error=None)
            cons.rephrased(error='ciao')
            rephraser_cls.assert_called_with(cons, help=None, error='ciao')

    def test_hidden_constraint_returns_empty_help(self, dummy_ctx):
        hidden = FakeConstraint(help='non-empty help').hidden()
        assert isinstance(hidden, Rephraser)
        assert hidden.help(dummy_ctx) == ''

    @mark.parametrize('satisfied', [True, False])
    @mark.parametrize('consistent', [True, False])
    def test__call__raises_iff_check_raises(self, satisfied, consistent):
        ctx = make_fake_context(make_options('abc'))
        cons = FakeConstraint(satisfied=satisfied, consistent=consistent)
        exc_class = UnsatisfiableConstraint if not consistent else ConstraintViolated
        with should_raise(exc_class, when=not (consistent and satisfied)):
            cons.check(['a', 'b'], ctx)

    @parametrize(
        ['ctx_kwargs', 'should_check'],
        pytest.param(dict(cls=click.Context), True, id='click.Context [no setting]'),
        pytest.param(dict(), True, id='cloup.Context [default]'),
        pytest.param(dict(check_constraints_consistency=False), False, id='disabled'),
    )
    def test_check_consistency_is_called_unless_disabled(self, ctx_kwargs, should_check):
        ctx = make_fake_context(make_options('abc'), **ctx_kwargs)
        constr = FakeConstraint()
        constr.check(['a', 'b'], ctx)
        assert Constraint.must_check_consistency(ctx) == should_check
        assert len(constr.check_consistency_calls) == int(should_check)

    def test_error_is_raised_when_using_call_the_old_way(self):
        constr = FakeConstraint()
        with pytest.raises(TypeError, match='since Cloup v0.9, calling a constraint'):
            constr(['a', 'b'])


class TestAnd:

    @mark.parametrize('b_satisfied', [False, True])
    @mark.parametrize('a_satisfied', [False, True])
    def test_check(self, a_satisfied, b_satisfied):
        ctx = make_fake_context(make_options(['arg1', 'str_opt', 'int_opt', 'flag']))
        a = FakeConstraint(satisfied=a_satisfied)
        b = FakeConstraint(satisfied=b_satisfied)
        c = a & b
        with should_raise(ConstraintViolated, when=not (a_satisfied and b_satisfied)):
            c.check(params=['arg1', 'str_opt'], ctx=ctx)

    def test_operand_merging(self):
        a, b, c, d = (FakeConstraint() for _ in range(4))
        res = (a & b) & c
        assert res.constraints == (a, b, c)
        res = (a & b) & (c & d)
        assert res.constraints == (a, b, c, d)
        res = (a & b) & (c | d)
        assert len(res.constraints) == 3


class TestOr:
    @mark.parametrize('b_satisfied', [False, True])
    @mark.parametrize('a_satisfied', [False, True])
    def test_check(self, a_satisfied, b_satisfied):
        ctx = make_fake_context(make_options(['arg1', 'str_opt', 'int_opt', 'flag']))
        a = FakeConstraint(satisfied=a_satisfied)
        b = FakeConstraint(satisfied=b_satisfied)
        c = a | b
        with should_raise(ConstraintViolated, when=not (a_satisfied or b_satisfied)):
            c.check(params=['arg1', 'str_opt'], ctx=ctx)

    def test_operands_merging(self):
        a, b, c, d = (FakeConstraint() for _ in range(4))
        res = (a | b) | c
        assert res.constraints == (a, b, c)
        res = (a | b) | (c | d)
        assert res.constraints == (a, b, c, d)
        res = (a | b) | (c & d)
        assert len(res.constraints) == 3


def test_operator_help(dummy_ctx):
    ctx = dummy_ctx
    a, b, c = RequireAtLeast(3), AcceptAtMost(10), RequireExactly(8)
    a_help, b_help, c_help = (cons.help(ctx) for cons in [a, b, c])
    assert (a | b | c).help(ctx) == f'{a_help} or {b_help} or {c_help}'
    assert (a | b & c).help(ctx) == f'{a_help} or ({b_help} and {c_help})'


class TestRequireAtLeast:
    def test_init_raises_for_invalid_n(self):
        RequireAtLeast(0)
        with pytest.raises(ValueError):
            RequireAtLeast(-1)

    def test_help(self, dummy_ctx):
        assert '3' in RequireAtLeast(3).help(dummy_ctx)

    def test_check_consistency(self):
        check_consistency = RequireAtLeast(3).check_consistency
        check_consistency(make_options('abc'))
        with pytest.raises(UnsatisfiableConstraint):
            check_consistency(make_options('ab'))

    def test_check(self, sample_cmd: Command):
        ctx = make_context(sample_cmd, 'a1 --str-opt=ciao --bool-opt=0')
        check = partial(RequireAtLeast(2).check, ctx=ctx)
        check(['str_opt', 'int_opt', 'bool_opt'])  # str-opt and bool-opt
        check(['arg1', 'int_opt', 'def1'])  # arg1 and def1
        check(['arg1', 'str_opt', 'def1'])  # arg1, str-opt and def1
        with pytest.raises(ConstraintViolated):
            check(['str_opt', 'arg2', 'flag'])  # only str-opt is set


class TestAcceptAtMost:
    def test_init_raises_for_invalid_n(self):
        AcceptAtMost(0)
        with pytest.raises(ValueError):
            AcceptAtMost(-1)

    def test_help(self, dummy_ctx):
        assert '3' in AcceptAtMost(3).help(dummy_ctx)

    def test_check_consistency(self):
        check_consistency = AcceptAtMost(2).check_consistency
        check_consistency(make_options('abc'))
        with pytest.raises(UnsatisfiableConstraint):
            check_consistency(make_options('abc', required=True))

    def test_check(self, sample_cmd: Command):
        ctx = make_context(sample_cmd, 'a1 --str-opt=ciao --bool-opt=0')
        check = partial(AcceptAtMost(2).check, ctx=ctx)
        check(['str_opt', 'int_opt', 'bool_opt'])  # str-opt and bool-opt
        check(['arg1', 'int_opt', 'flag'])  # arg1
        with pytest.raises(ConstraintViolated):
            check(['arg1', 'str_opt', 'def1'])  # arg1, str-opt, def1


class TestRequireExactly:
    def test_init_raises_for_invalid_n(self):
        with pytest.raises(ValueError):
            RequireExactly(0)
        with pytest.raises(ValueError):
            RequireExactly(-1)

    def test_help(self, dummy_ctx):
        assert '3' in RequireExactly(3).help(dummy_ctx)

    def test_check_consistency(self):
        check_consistency = RequireExactly(3).check_consistency
        check_consistency(make_options('abcd'))
        with pytest.raises(UnsatisfiableConstraint):
            check_consistency(make_options('ab'))
        with pytest.raises(UnsatisfiableConstraint):
            check_consistency(make_options('abcde', required=True))

    def test_check(self, sample_cmd: Command):
        ctx = make_context(sample_cmd, 'a1 --str-opt=ciao --bool-opt=0')
        check = partial(RequireExactly(2).check, ctx=ctx)
        check(['str_opt', 'int_opt', 'bool_opt'])  # str-opt and bool-opt
        check(['arg1', 'int_opt', 'bool_opt'])  # arg1 and bool-opt
        with pytest.raises(ConstraintViolated):
            check(['arg1', 'str_opt', 'def1'])  # arg1, str-opt, def1
        with pytest.raises(ConstraintViolated):
            check(['arg1', 'int_opt', 'flag'])  # arg1


class TestAcceptBetween:
    def test_init_raises_for_invalid_n(self):
        AcceptBetween(0, 10)
        AcceptBetween(0, 1)
        with pytest.raises(ValueError):
            AcceptBetween(-1, 2)
        with pytest.raises(ValueError):
            AcceptBetween(2, 2)
        with pytest.raises(ValueError):
            AcceptBetween(3, 2)

    def test_help(self, dummy_ctx):
        help = AcceptBetween(3, 5).help(dummy_ctx)
        assert help == 'at least 3 required, at most 5 accepted'

    def test_check_consistency(self):
        check_consistency = AcceptBetween(2, 4).check_consistency
        check_consistency(make_options('abcd'))
        with pytest.raises(UnsatisfiableConstraint):
            check_consistency(make_options('a'))  # too little params
        with pytest.raises(UnsatisfiableConstraint):
            check_consistency(make_options('abcde', required=True))  # too many required

    def test_check(self, sample_cmd: Command):
        ctx = make_context(sample_cmd, 'a1 --str-opt=ciao --bool-opt=0 --flag --mul1=4')
        check = partial(AcceptBetween(2, 4).check, ctx=ctx)
        check(['str_opt', 'int_opt', 'bool_opt'])  # str-opt and bool-opt
        check(['arg1', 'int_opt', 'flag'])  # arg1, bool-opt and flag
        check(['def1', 'int_opt', 'flag', 'mul1'])  # all
        with pytest.raises(ConstraintViolated):
            check(['arg2', 'int_opt', 'def1'])  # only def1
        with pytest.raises(ConstraintViolated):
            check(['arg1', 'def1', 'def2', 'str_opt', 'flag'])  # all


class TestRequiredAll:
    def test_help(self, dummy_ctx):
        assert 'all required' in require_all.help(dummy_ctx)

    def test_check_consistency(self):
        require_all.check_consistency(make_options('abc'))

    def test_check(self, sample_cmd: Command):
        ctx = make_context(sample_cmd, 'arg1 --str-opt=0 --bool-opt=0')
        check = partial(require_all.check, ctx=ctx)
        check(['arg1'])
        check(['str_opt'])
        check(['arg1', 'str_opt'])
        check(['arg1', 'str_opt', 'bool_opt'])
        check(['arg1', 'str_opt', 'bool_opt', 'def1'])
        with pytest.raises(ConstraintViolated):
            check(['arg2'])
        with pytest.raises(ConstraintViolated):
            check(['arg1', 'arg2'])
        with pytest.raises(ConstraintViolated):
            check(['arg1', 'def1', 'int_opt'])


class TestRephraser:
    def test_init_raises_if_neither_help_nor_error_is_provided(self):
        with pytest.raises(ValueError):
            Rephraser(FakeConstraint())

    def test_help_override_with_string(self, dummy_ctx):
        wrapped = FakeConstraint()
        rephrased = Rephraser(wrapped, help='rephrased help')
        assert rephrased.help(dummy_ctx) == 'rephrased help'

    def test_help_override_with_function(self, dummy_ctx):
        wrapped = FakeConstraint()
        get_help = Mock(return_value='rephrased help')
        rephrased = Rephraser(wrapped, help=get_help)
        assert rephrased.help(dummy_ctx) == 'rephrased help'
        get_help.assert_called_once_with(dummy_ctx, wrapped)

    def test_error_is_overridden_passing_string(self):
        fake_ctx = make_fake_context(make_options('abcd'))
        wrapped = FakeConstraint(satisfied=False, error='__error__')
        rephrased = Rephraser(wrapped, error=f'error:\n{ErrorFmt.param_list}')
        with pytest.raises(ConstraintViolated) as exc_info:
            rephrased.check(['a', 'b'], ctx=fake_ctx)
        assert exc_info.value.message == 'error:\n  --a\n  --b\n'

    def test_error_template_key(self):
        fake_ctx = make_fake_context(make_options('abcd'))
        wrapped = FakeConstraint(satisfied=False, error='__error__')
        rephrased = Rephraser(wrapped, error=f'{ErrorFmt.error}\nExtra info here.')
        with pytest.raises(ConstraintViolated) as exc_info:
            rephrased.check(['a', 'b'], ctx=fake_ctx)
        assert str(exc_info.value) == '__error__\nExtra info here.'

    def test_error_is_overridden_passing_function(self):
        params = make_options('abc')
        fake_ctx = make_fake_context(params)
        wrapped = FakeConstraint(satisfied=False)
        error_rephraser_mock = Mock(return_value='rephrased error')
        rephrased = Rephraser(wrapped, error=error_rephraser_mock)
        with pytest.raises(ConstraintViolated, match='rephrased error'):
            rephrased.check(params, ctx=fake_ctx)

        # Check the function is called with a single argument of type ConstraintViolated
        error_rephraser_mock.assert_called_once()
        args = error_rephraser_mock.call_args[0]
        assert len(args) == 1
        error = args[0]
        assert isinstance(error, ConstraintViolated)
        # Check the error has all fields set
        assert isinstance(error.ctx, Context)
        assert isinstance(error.constraint, Constraint)
        assert len(error.params) == 3

    def test_check_consistency_raises_if_wrapped_constraint_raises(self):
        constraint = FakeConstraint(consistent=True)
        rephraser = Rephraser(constraint, help='help')
        params = make_options('abc')
        rephraser.check_consistency(params)

    def test_check_consistency_doesnt_raise_if_wrapped_constraint_doesnt_raise(self):
        constraint = FakeConstraint(consistent=False)
        rephraser = Rephraser(constraint, help='help')
        params = make_options('abc')
        with pytest.raises(UnsatisfiableConstraint):
            rephraser.check_consistency(params)


def test_a_constraint_can_be_copied_and_deep_copied():
    import copy
    copy.copy(RequireAtLeast(1))
    copy.deepcopy(RequireAtLeast(1))