Debian Codegraph @

test/units/plugins/become/test_su.py

raw
1 # (c) 2012-2014, Michael DeHaan <[email protected]>
2 # (c) 2020 Ansible Project
3 #
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import annotations
7
8 import re
9
10 import pytest
11
12 from ansible import context
13 from ansible.plugins.loader import become_loader, shell_loader
14
15
16 def test_su(mocker, parser, reset_cli_args):
17 options = parser.parse_args([])
18 context._init_global_context(options)
19
20 su = become_loader.get('su')
21 sh = shell_loader.get('sh')
22 sh.executable = "/bin/bash"
23
24 su.set_options(direct={
25 'become_user': 'foo',
26 'become_flags': '',
27 })
28
29 cmd = su.build_become_command('/bin/foo', sh)
30 assert re.match(r"""su\s+foo -c '/bin/bash -c '"'"'echo BECOME-SUCCESS-.+?; /bin/foo'"'"''""", cmd)
31
32
33 def test_no_cmd() -> None:
34 cmd = ''
35
36 assert become_loader.get('su').build_become_command(cmd, shell_loader.get('sh')) is cmd
37
38
39 @pytest.mark.parametrize("prefix, prompt", (
40 ("", "Password:"),
41 (" ", "Password :"),
42 ("\n", "Password :"),
43 ("x", "Password :"),
44 ("", "口令:"),
45 (" ", "口令 :"),
46 ("\n", "口令 :"),
47 ("x", "口令 :"),
48 ))
49 def test_check_password_prompt_success(prefix: str, prompt: str) -> None:
50 become = become_loader.get('su')
51
52 assert become.check_password_prompt((prefix + prompt).encode()) is True
53 assert become.prompt == prompt
54
55
56 @pytest.mark.parametrize("data", (
57 "Password",
58 "Passwort",
59 "Pass:",
60 ))
61 def test_check_password_prompt_failure(data: str) -> None:
62 become = become_loader.get('su')
63
64 assert become.check_password_prompt(data.encode()) is False
65 assert become.prompt == ''
66
67
68 def test_check_password_prompt_escaping(mocker) -> None:
69 become = become_loader.get('su')
70
71 mocker.patch.object(become, 'get_option', return_value=['(invalid regex'])
72
73 assert become.check_password_prompt(b'(invalid regex:') is True