|
| 1 | +import pytest |
| 2 | +from discord.utils import find |
| 3 | + |
| 4 | + |
| 5 | +def is_even(x): |
| 6 | + return x % 2 == 0 |
| 7 | + |
| 8 | + |
| 9 | +@pytest.mark.parametrize( |
| 10 | + ("seq", "predicate", "expected"), |
| 11 | + [ |
| 12 | + ([], lambda x: True, None), |
| 13 | + ([1, 2, 3], lambda x: x > 3, None), |
| 14 | + ([1, 2, 3], lambda x: x == 1, 1), |
| 15 | + ([1, 2, 3], lambda x: x == 2, 2), |
| 16 | + ("abc", lambda c: c == "b", "b"), |
| 17 | + ((10, 20, 30), lambda x: x == 30, 30), |
| 18 | + ([None, False, 0], lambda x: x is None, None), |
| 19 | + ([1, 2, 3, 4], is_even, 2), |
| 20 | + ], |
| 21 | +) |
| 22 | +def test_find_basic_parametrized(seq, predicate, expected): |
| 23 | + assert find(predicate, seq) is expected |
| 24 | + |
| 25 | + |
| 26 | +def test_find_with_truthy_non_boolean_predicate(): |
| 27 | + seq = [2, 4, 5, 6] |
| 28 | + result = find(lambda x: x % 2, seq) |
| 29 | + assert result == 5 |
| 30 | + |
| 31 | + |
| 32 | +def test_find_on_generator_and_stop_early(): |
| 33 | + def bad_gen(): |
| 34 | + yield "first" |
| 35 | + raise RuntimeError("should not be reached") |
| 36 | + |
| 37 | + assert find(lambda x: x == "first", bad_gen()) == "first" |
| 38 | + |
| 39 | + |
| 40 | +def test_find_does_not_evaluate_rest(): |
| 41 | + calls = [] |
| 42 | + |
| 43 | + def predicate(x): |
| 44 | + calls.append(x) |
| 45 | + return x == "stop" |
| 46 | + |
| 47 | + seq = ["go", "stop", "later"] |
| 48 | + result = find(predicate, seq) |
| 49 | + assert result == "stop" |
| 50 | + assert calls == ["go", "stop"] |
| 51 | + |
| 52 | + |
| 53 | +def test_find_with_set_returns_first_iterated_element(): |
| 54 | + data = {"a", "b", "c"} |
| 55 | + result = find(lambda x: x in data, data) |
| 56 | + assert result in data |
| 57 | + |
| 58 | + |
| 59 | +def test_find_none_predicate(): |
| 60 | + seq = [42, 43, 44] |
| 61 | + result = find(lambda x: True, seq) |
| 62 | + assert result == 42 |
0 commit comments