summaryrefslogtreecommitdiffstats
path: root/tests/conftest.py
blob: 5f404dba82f6abebd92ec346d9816668f051acf0 (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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
"""Configure tests."""

import py
import pytest

from colorclass.codes import ANSICodeMapping
from colorclass.color import Color
from colorclass.core import ColorStr, PARENT_CLASS

PROJECT_ROOT = py.path.local(__file__).dirpath().join('..')


@pytest.fixture(autouse=True)
def set_defaults(monkeypatch):
    """Set ANSICodeMapping defaults before each test.

    :param monkeypatch: pytest fixture.
    """
    monkeypatch.setattr(ANSICodeMapping, 'DISABLE_COLORS', False)
    monkeypatch.setattr(ANSICodeMapping, 'LIGHT_BACKGROUND', False)


def assert_both_values(actual, expected_plain, expected_color, kind=None):
    """Handle asserts for color and non-color strings in color and non-color tests.

    :param ColorStr actual: Return value of ColorStr class method.
    :param expected_plain: Expected non-color value.
    :param expected_color: Expected color value.
    :param str kind: Type of string to test.
    """
    if kind.endswith('plain'):
        assert actual.value_colors == expected_plain
        assert actual.value_no_colors == expected_plain
        assert actual.has_colors is False
    elif kind.endswith('color'):
        assert actual.value_colors == expected_color
        assert actual.value_no_colors == expected_plain
        if '\033' in actual.value_colors:
            assert actual.has_colors is True
        else:
            assert actual.has_colors is False
    else:
        assert actual == expected_plain

    if kind.startswith('ColorStr'):
        assert actual.__class__ == ColorStr
    elif kind.startswith('Color'):
        assert actual.__class__ == Color


def get_instance(kind, sample=None, color='red'):
    """Get either a string, non-color ColorStr, or color ColorStr instance.

    :param str kind: Type of string to test.
    :param iter sample: Input test to derive instances from.
    :param str color: Color tags to use. Default is red.

    :return: Instance.
    """
    # First determine which class/type to use.
    if kind.startswith('ColorStr'):
        cls = ColorStr
    elif kind.startswith('Color'):
        cls = Color
    else:
        cls = PARENT_CLASS

    # Next handle NoneType samples.
    if sample is None:
        return cls()

    # Finally handle non-None samples.
    if kind.endswith('plain'):
        return cls(sample)
    elif kind.endswith('color'):
        tags = '{%s}' % color, '{/%s}' % color
        return cls(tags[0] + sample + tags[1])
    return sample