Coverage for tests/unit_tests/utils/test_cmd_util.py: 97%

32 statements  

« prev     ^ index     » next       coverage.py v7.11.0, created at 2025-11-06 10:20 +0000

1""" 

2Tests of cmd_util.py 

3""" 

4 

5import sys 

6import pytest 

7import click 

8from apio.utils.cmd_util import ( 

9 ApioOption, 

10 ApioCmdContext, 

11 check_at_most_one_param, 

12) 

13 

14# TODO: Add more tests. 

15 

16 

17# -- A fake command for testing. 

18@click.command(name="fake_cmd") 

19@click.option("_opt1", "--opt1", is_flag=True, cls=ApioOption) 

20@click.option("_opt2", "--opt2", is_flag=True, cls=ApioOption) 

21@click.option("_opt3", "--opt3", is_flag=True, cls=ApioOption) 

22@click.option("_opt4", "--opt4", is_flag=True, cls=ApioOption) 

23def fake_cmd(_opt1, _opt2, _opt3, _opt4): 

24 """Fake click command for testing.""" 

25 sys.exit(0) 

26 

27 

28def test_check_at_most_one_param(capsys): 

29 """Tests the check_at_most_one_param() function.""" 

30 

31 # -- No option is specified. Should be ok. 

32 cmd_ctx = ApioCmdContext(fake_cmd) 

33 fake_cmd.parse_args(cmd_ctx, []) 

34 check_at_most_one_param(cmd_ctx, ["_opt1", "_opt2", "_opt3"]) 

35 

36 # -- One option is specified. Should be ok. 

37 cmd_ctx = ApioCmdContext(fake_cmd) 

38 fake_cmd.parse_args(cmd_ctx, ["--opt1"]) 

39 check_at_most_one_param(cmd_ctx, ["_opt1", "_opt2", "_opt3"]) 

40 

41 # -- Another option is specified. Should be ok. 

42 cmd_ctx = ApioCmdContext(fake_cmd) 

43 fake_cmd.parse_args(cmd_ctx, ["--opt2"]) 

44 check_at_most_one_param(cmd_ctx, ["_opt1", "_opt2", "_opt3"]) 

45 

46 # -- Two options but one is non related to the check. Should be ok. 

47 cmd_ctx = ApioCmdContext(fake_cmd) 

48 fake_cmd.parse_args(cmd_ctx, ["--opt1", "--opt4"]) 

49 check_at_most_one_param(cmd_ctx, ["_opt1", "_opt2", "_opt3"]) 

50 

51 # -- Two options are specifies. Should fail. 

52 cmd_ctx = ApioCmdContext(fake_cmd) 

53 fake_cmd.parse_args(cmd_ctx, ["--opt1", "--opt2"]) 

54 capsys.readouterr() # Reset capture. 

55 with pytest.raises(SystemExit) as e: 

56 check_at_most_one_param(cmd_ctx, ["_opt1", "_opt2", "_opt3"]) 

57 captured = capsys.readouterr() 

58 assert e.value.code == 1 

59 assert "--opt1 and --opt2 cannot be combined together" in captured.out