Coverage for tests/test_context.py: 100.00%

27 statements  

« prev     ^ index     » next       coverage.py v7.3.0, created at 2023-09-03 19:58 +0200

1"""Tests for the `context` module.""" 

2 

3from __future__ import annotations 

4 

5import os 

6from collections import namedtuple 

7 

8from shellman.context import _get_cli_context, _get_context, _get_env_context, _update 

9 

10 

11def test_get_cli_context() -> None: 

12 """Test getting context from CLI arguments.""" 

13 assert _get_cli_context([]) == {} 

14 assert _get_cli_context([""]) == {} 

15 assert _get_cli_context([" "]) == {} 

16 

17 assert _get_cli_context(["hello=world"]) == {"hello": "world"} 

18 assert _get_cli_context(["hello=world", "hello=universe"]) == {"hello": "universe"} 

19 

20 assert ( 

21 _get_cli_context(["hello.world=universe"]) 

22 == _get_cli_context(["hello=world", "hello.world=universe"]) 

23 == {"hello": {"world": "universe"}} 

24 ) 

25 assert _get_cli_context(["hello.world=universe", "hello=world"]) == {"hello": "world"} 

26 assert _get_cli_context(["hello.world.and.foobars=hello"]) == {"hello": {"world": {"and": {"foobars": "hello"}}}} 

27 

28 assert _get_cli_context(['{"hello": "world", "number": [1, 2]}']) == {"hello": "world", "number": [1, 2]} 

29 assert _get_cli_context(['{"hello": "world"}', "hello=universe"]) == {"hello": "universe"} 

30 

31 

32def test_get_env_context() -> None: 

33 """Test getting context from environment variables.""" 

34 os.environ["SHELLMAN_CONTEXT_HELLO"] = "world" 

35 assert _get_env_context() == {"hello": "world"} 

36 del os.environ["SHELLMAN_CONTEXT_HELLO"] 

37 

38 

39def test_get_context() -> None: 

40 """Test getting context from default JSON file.""" 

41 args = namedtuple("args", "context_file context")(None, None) # type: ignore[arg-type,call-arg] # noqa: PYI024 

42 assert _get_context(args) == {} # type: ignore[arg-type] 

43 

44 

45def test_update() -> None: 

46 """Test the context updater/merger function.""" 

47 d1 = {"hello": {"world": "what's up?"}} 

48 d2 = {"hello": {"universe": "????"}, "byebye": "universe"} 

49 _update(d1, d2) 

50 assert d1 == {"hello": {"world": "what's up?", "universe": "????"}, "byebye": "universe"}