summaryrefslogtreecommitdiffstats
path: root/tests/envcontext_test.py
blob: c82d3267d8b274bfa50106dd8f6aea118564a614 (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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
from __future__ import annotations

import os
from unittest import mock

import pytest

from pre_commit.envcontext import envcontext
from pre_commit.envcontext import UNSET
from pre_commit.envcontext import Var


def _test(*, before, patch, expected):
    env = before.copy()
    with envcontext(patch, _env=env):
        assert env == expected
    assert env == before


def test_trivial():
    _test(before={}, patch={}, expected={})


def test_noop():
    _test(before={'foo': 'bar'}, patch=(), expected={'foo': 'bar'})


def test_adds():
    _test(before={}, patch=[('foo', 'bar')], expected={'foo': 'bar'})


def test_overrides():
    _test(
        before={'foo': 'baz'},
        patch=[('foo', 'bar')],
        expected={'foo': 'bar'},
    )


def test_unset_but_nothing_to_unset():
    _test(before={}, patch=[('foo', UNSET)], expected={})


def test_unset_things_to_remove():
    _test(
        before={'PYTHONHOME': ''},
        patch=[('PYTHONHOME', UNSET)],
        expected={},
    )


def test_templated_environment_variable_missing():
    _test(
        before={},
        patch=[('PATH', ('~/bin:', Var('PATH')))],
        expected={'PATH': '~/bin:'},
    )


def test_templated_environment_variable_defaults():
    _test(
        before={},
        patch=[('PATH', ('~/bin:', Var('PATH', default='/bin')))],
        expected={'PATH': '~/bin:/bin'},
    )


def test_templated_environment_variable_there():
    _test(
        before={'PATH': '/usr/local/bin:/usr/bin'},
        patch=[('PATH', ('~/bin:', Var('PATH')))],
        expected={'PATH': '~/bin:/usr/local/bin:/usr/bin'},
    )


def test_templated_environ_sources_from_previous():
    _test(
        before={'foo': 'bar'},
        patch=(
            ('foo', 'baz'),
            ('herp', ('foo: ', Var('foo'))),
        ),
        expected={'foo': 'baz', 'herp': 'foo: bar'},
    )


def test_exception_safety():
    class MyError(RuntimeError):
        pass

    env = {'hello': 'world'}
    with pytest.raises(MyError):
        with envcontext((('foo', 'bar'),), _env=env):
            raise MyError()
    assert env == {'hello': 'world'}


def test_integration_os_environ():
    with mock.patch.dict(os.environ, {'FOO': 'bar'}, clear=True):
        assert os.environ == {'FOO': 'bar'}
        with envcontext((('HERP', 'derp'),)):
            assert os.environ == {'FOO': 'bar', 'HERP': 'derp'}
        assert os.environ == {'FOO': 'bar'}