def test_has_attribute_predicate(): def f(x): return x.count(2) g = guard(Any.has('count'))(f) with pytest.raises(NoMatch): g({}) with pytest.raises(NoMatch): g(1) assert g((1, 2, 2, 3)) == 2
def test_with_regex_matching(): def f(s): return s g = guard(Any.re('A|B'))(f) with pytest.raises(NoMatch): g('Cat') with pytest.raises(NoMatch): g('CAT') assert g('About') == 'About'
def test_check_varargs(): def count_args(*args): return len(args) g = guard(1, Any.args(Any(int)))(count_args) with pytest.raises(NoMatch): g(0) with pytest.raises(NoMatch): g(1, 'a') with pytest.raises(NoMatch): g(1, *(['a'] * 20)) assert g(1, 2, 3) == 3 assert g(*([1] * 20)) == 20
def test_has_with_predicate(): X = type('X', (object, ), {'value': None}) def f(x): return x.value g = guard(Any.has(value=Any(int)))(f) with pytest.raises(NoMatch): g('123') with pytest.raises(NoMatch): x = X() x.value = '321' g(x) x = X() x.value = 321 assert g(x) == 321
def test_explicitly_combined_patterns(): @guard(Any.of(0, 1)) def fib0(n): return 1 @guard(Any(int)) def fib(n): return fib(n - 1) + fib(n - 2) fib = Pattern(fib0, fib) assert fib(0) == 1 assert fib(1) == 1 assert fib(2) == 2 assert fib(3) == 3 with pytest.raises(NoMatch): fib('not a number')