summaryrefslogtreecommitdiffstats
path: root/tests/test___main__.py
blob: 17a4b76b14601e2507fff6acb2663aacaba0f467 (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
"""Test objects in module."""

import subprocess
import sys

import pytest

from colorclass.windows import IS_WINDOWS


def test_import_do_nothing():
    """Make sure importing __main__ doesn't print anything."""
    command = [sys.executable, '-c', "from colorclass.__main__ import TRUTHY; assert TRUTHY"]
    proc = subprocess.Popen(command, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
    output = proc.communicate()
    assert proc.poll() == 0
    assert not output[0]
    assert not output[1]


@pytest.mark.parametrize('colors', [True, False, None])
@pytest.mark.parametrize('light', [True, False, None])
def test(monkeypatch, colors, light):
    """Test package as a script.

    :param monkeypatch: pytest fixture.
    :param bool colors: Enable, disable, or don't touch colors using CLI args or env variables.
    :param bool light: Enable light, dark, or don't touch auto colors using CLI args or env variables.
    """
    command = [sys.executable, '-m', 'colorclass' if sys.version_info >= (2, 7) else 'colorclass.__main__']
    stdin = '{autored}Red{/autored} {red}Red{/red} {hired}Red{/hired}'.encode()

    # Set options.
    if colors is True:
        monkeypatch.setenv('COLOR_ENABLE', 'true')
    elif colors is False:
        monkeypatch.setenv('COLOR_DISABLE', 'true')
    if light is True:
        monkeypatch.setenv('COLOR_LIGHT', 'true')
    elif light is False:
        monkeypatch.setenv('COLOR_DARK', 'true')

    # Run.
    proc = subprocess.Popen(command, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
    output = proc.communicate(stdin)[0].decode()
    assert proc.poll() == 0
    assert 'Red' in output

    # Verify colors. Output is always stripped of all colors on Windows when piped to non-console (e.g. pytest).
    if colors is False or IS_WINDOWS:
        assert '\033[' not in output
        assert 'Red Red Red' in output
        return
    assert '\033[' in output

    # Verify light bg.
    count_dark_fg = output.count('\033[31mRed')
    count_light_fg = output.count('\033[91mRed')
    if light:
        assert count_dark_fg == 2
        assert count_light_fg == 1
    else:
        assert count_dark_fg == 1
        assert count_light_fg == 2