Debian Codegraph @

ansible_collections/community/mongodb/roles/mongodb_auth/molecule/default/tests/test_default.py

raw
1 import os
2 import yaml
3
4 import testinfra.utils.ansible_runner
5
6 testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
7 os.environ["MOLECULE_INVENTORY_FILE"]
8 ).get_hosts("all")
9
10
11 def include_vars(host):
12 current_dir = os.path.dirname(os.path.abspath(__file__))
13 path_components = current_dir.split(os.sep)
14 trim_count = 0
15 # Weird bug where the path of this file is incorrect
16 # It seems the ansible module, at least when used here
17 # Used to run in a different directory, meaning the
18 # relative path was not correct. This method should mean it's
19 # always correct whatever the context.
20 for component in path_components:
21 if component.startswith("mongodb_"):
22 break
23 else:
24 trim_count += 1
25 trim_count = (len(path_components) - 1) - trim_count
26 # Trim off the dirs after the role dir
27 trimmed_components = path_components[:-trim_count]
28 trimmed_path = os.sep.join(trimmed_components)
29 vars_file_path = os.path.join(trimmed_path, 'defaults', 'main.yml')
30 ansible = host.ansible('include_vars',
31 f'file="{vars_file_path}"',
32 False,
33 False)
34 # print(str(ansible))
35 return ansible
36
37
38 def test_mongod_cnf_file(host):
39 f = host.file("/etc/mongod.conf")
40
41 assert f.exists
42 assert yaml.safe_load(f.content)["security"]["authorization"] == "enabled"
43
44
45 def test_mongod_service(host):
46 mongod_service = include_vars(host)["ansible_facts"].get("mongod_service", "mongod")
47 s = host.service(mongod_service)
48
49 assert s.is_running
50 assert s.is_enabled
51
52
53 def test_mongod_port(host):
54 port = include_vars(host)["ansible_facts"].get("mongod_port", 27017)
55 s = host.socket("tcp://0.0.0.0:{0}".format(port))
56 assert s.is_listening
57
58
59 def test_mongo_shell_connectivity(host):
60 """
61 Tests that we can connect to mongos via the shell annd run a cmd
62 """
63 facts = include_vars(host)["ansible_facts"]
64 port = facts.get("mongod_port", 27017)
65 user = facts.get("mongod_admin_user", "admin")
66 pwd = facts.get("mongodb_default_admin_pwd", "admin")
67
68 cmd = host.run(
69 "mongosh admin --username {user} --password {pwd} --port {port} --eval 'db.runCommand({{listDatabases: 1}})'".format(
70 user=user, pwd=pwd, port=port
71 )
72 )
73
74 assert cmd.rc == 0
75 assert "admin" in cmd.stdout