summaryrefslogtreecommitdiff
path: root/tests/test_parse_number_function.py
blob: 5ac5700723c540e156c81cfb7cfac70ce764c761 (plain)
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
# -*- coding: utf-8 -*-
"""These test the utils.py functions."""

from typing import Optional, Tuple, Union

import pytest
from hypothesis import given
from hypothesis.strategies import floats, integers
from natsort.ns_enum import NSType, ns
from natsort.utils import NumTransformer, parse_number_or_none_factory


@pytest.mark.usefixtures("with_locale_en_us")
@pytest.mark.parametrize(
    "alg, example_func",
    [
        (ns.DEFAULT, lambda x: ("", x)),
        (ns.PATH, lambda x: (("", x),)),
        (ns.UNGROUPLETTERS | ns.LOCALE, lambda x: (("xx",), ("", x))),
        (ns.PATH | ns.UNGROUPLETTERS | ns.LOCALE, lambda x: ((("xx",), ("", x)),)),
    ],
)
@given(x=floats(allow_nan=False, allow_infinity=False) | integers())
def test_parse_number_factory_makes_function_that_returns_tuple(
    x: Union[float, int], alg: NSType, example_func: NumTransformer
) -> None:
    parse_number_func = parse_number_or_none_factory(alg, "", "xx")
    assert parse_number_func(x) == example_func(x)


@pytest.mark.parametrize(
    "alg, x, result",
    [
        (ns.DEFAULT, 57, ("", 57)),
        (
            ns.DEFAULT,
            float("nan"),
            ("", float("-inf"), "2"),
        ),  # NaN transformed to -infinity
        (
            ns.NANLAST,
            float("nan"),
            ("", float("+inf"), "2"),
        ),  # NANLAST makes it +infinity
        (ns.DEFAULT, None, ("", float("-inf"), "1")),  # None transformed to -infinity
        (ns.NANLAST, None, ("", float("+inf"), "1")),  # NANLAST makes it +infinity
        (ns.DEFAULT, float("-inf"), ("", float("-inf"), "3")),
        (ns.NANLAST, float("+inf"), ("", float("+inf"), "3")),
    ],
)
def test_parse_number_factory_treats_nan_and_none_special(
    alg: NSType, x: Optional[Union[float, int]], result: Tuple[str, Union[float, int]]
) -> None:
    parse_number_func = parse_number_or_none_factory(alg, "", "xx")
    assert parse_number_func(x) == result