test helper: improvements (#9672)

pull/9675/head
Alexei Znamensky 2025-02-02 21:45:52 +13:00 committed by GitHub
parent 250dc1139c
commit 7a6125b99a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 138 additions and 135 deletions

View File

@ -6,6 +6,7 @@
from __future__ import (absolute_import, division, print_function) from __future__ import (absolute_import, division, print_function)
__metaclass__ = type __metaclass__ = type
import os
import sys import sys
import json import json
@ -13,49 +14,49 @@ import yaml
import pytest import pytest
from ansible.module_utils.common._collections_compat import Sequence
class Helper(object): class Helper(object):
TEST_SPEC_VALID_SECTIONS = ["anchors", "test_cases"] TEST_SPEC_VALID_SECTIONS = ["anchors", "test_cases"]
@staticmethod @staticmethod
def from_spec(test_module, ansible_module, test_spec, mocks=None): def from_spec(ansible_module, test_module, test_spec, mocks=None):
helper = Helper(test_module, ansible_module, test_spec=test_spec, mocks=mocks) helper = Helper(ansible_module, test_module, test_spec=test_spec, mocks=mocks)
return helper return helper
@staticmethod @staticmethod
def from_file(test_module, ansible_module, filename, mocks=None): def from_file(ansible_module, test_module, test_spec_filehandle, mocks=None):
with open(filename, "r") as test_cases: test_spec = yaml.safe_load(test_spec_filehandle)
test_spec = yaml.safe_load(test_cases) return Helper.from_spec(ansible_module, test_module, test_spec, mocks)
return Helper.from_spec(test_module, ansible_module, test_spec, mocks)
# @TODO: calculate the test_module_name automatically, remove one more parameter
@staticmethod @staticmethod
def from_module(ansible_module, test_module_name, test_spec=None, mocks=None): def from_module(ansible_module, test_module_name, mocks=None):
test_module = sys.modules[test_module_name] test_module = sys.modules[test_module_name]
if test_spec is None: extensions = ['.yaml', '.yml']
test_spec = test_module.__file__.replace('.py', '.yaml') for ext in extensions:
return Helper.from_file(test_module, ansible_module, test_spec, mocks=mocks) test_spec_filename = test_module.__file__.replace('.py', ext)
if os.path.exists(test_spec_filename):
with open(test_spec_filename, "r") as test_spec_filehandle:
return Helper.from_file(ansible_module, test_module, test_spec_filehandle, mocks=mocks)
raise Exception("Cannot find test case file for {0} with one of the extensions: {1}".format(test_module.__file__, extensions))
def add_func_to_test_module(self, name, func): def add_func_to_test_module(self, name, func):
setattr(self.test_module, name, func) setattr(self.test_module, name, func)
def __init__(self, test_module, ansible_module, test_spec, mocks=None): def __init__(self, ansible_module, test_module, test_spec, mocks=None):
self.test_module = test_module
self.ansible_module = ansible_module self.ansible_module = ansible_module
self.test_module = test_module
self.test_cases = [] self.test_cases = []
self.fixtures = {} self.fixtures = {}
if isinstance(test_spec, Sequence):
test_cases = test_spec spec_diff = set(test_spec.keys()) - set(self.TEST_SPEC_VALID_SECTIONS)
else: # it is a dict if spec_diff:
test_cases = test_spec['test_cases'] raise ValueError("Test specification contain unknown keys: {0}".format(", ".join(spec_diff)))
spec_diff = set(test_spec.keys()) - set(self.TEST_SPEC_VALID_SECTIONS)
if spec_diff:
raise ValueError("Test specification contain unknown keys: {0}".format(", ".join(spec_diff)))
self.mocks_map = {m.name: m for m in mocks} if mocks else {} self.mocks_map = {m.name: m for m in mocks} if mocks else {}
for test_case in test_cases: for spec_test_case in test_spec['test_cases']:
tc = ModuleTestCase.make_test_case(test_case, test_module, self.mocks_map) tc = ModuleTestCase.make_test_case(spec_test_case, test_module, self.mocks_map)
self.test_cases.append(tc) self.test_cases.append(tc)
self.fixtures.update(tc.fixtures) self.fixtures.update(tc.fixtures)
self.set_test_func() self.set_test_func()

View File

@ -386,117 +386,119 @@ ubuntu 24.04
kernel 6.8.0-49-generic kernel 6.8.0-49-generic
""" """
TEST_CASES = [ TEST_SPEC = dict(
dict( test_cases=[
id="simple case", dict(
input={"name": ["hello-world"]}, id="simple case",
output=dict(changed=True, snaps_installed=["hello-world"]), input={"name": ["hello-world"]},
flags={}, output=dict(changed=True, snaps_installed=["hello-world"]),
mocks=dict( flags={},
run_command=[ mocks=dict(
dict( run_command=[
command=['/testbin/snap', 'version'], dict(
environ=default_env, command=['/testbin/snap', 'version'],
rc=0, environ=default_env,
out=default_version_out, rc=0,
err="", out=default_version_out,
), err="",
dict( ),
command=['/testbin/snap', 'info', 'hello-world'], dict(
environ=default_env, command=['/testbin/snap', 'info', 'hello-world'],
rc=0, environ=default_env,
out='name: hello-world\n', rc=0,
err="", out='name: hello-world\n',
), err="",
dict( ),
command=['/testbin/snap', 'list'], dict(
environ=default_env, command=['/testbin/snap', 'list'],
rc=0, environ=default_env,
out="", rc=0,
err="", out="",
), err="",
dict( ),
command=['/testbin/snap', 'install', 'hello-world'], dict(
environ=default_env, command=['/testbin/snap', 'install', 'hello-world'],
rc=0, environ=default_env,
out="hello-world (12345/stable) v12345 from Canonical** installed\n", rc=0,
err="", out="hello-world (12345/stable) v12345 from Canonical** installed\n",
), err="",
dict( ),
command=['/testbin/snap', 'list'], dict(
environ=default_env, command=['/testbin/snap', 'list'],
rc=0, environ=default_env,
out=( rc=0,
"Name Version Rev Tracking Publisher Notes" out=(
"core20 20220826 1623 latest/stable canonical** base" "Name Version Rev Tracking Publisher Notes"
"lxd 5.6-794016a 23680 latest/stable/… canonical** -" "core20 20220826 1623 latest/stable canonical** base"
"hello-world 5.6-794016a 23680 latest/stable/… canonical** -" "lxd 5.6-794016a 23680 latest/stable/… canonical** -"
"snapd 2.57.4 17336 latest/stable canonical** snapd" "hello-world 5.6-794016a 23680 latest/stable/… canonical** -"
""), "snapd 2.57.4 17336 latest/stable canonical** snapd"
err="", ""),
), err="",
], ),
],
),
), ),
), dict(
dict( id="issue_6803",
id="issue_6803", input={"name": ["microk8s", "kubectl"], "classic": True},
input={"name": ["microk8s", "kubectl"], "classic": True}, output=dict(changed=True, snaps_installed=["microk8s", "kubectl"]),
output=dict(changed=True, snaps_installed=["microk8s", "kubectl"]), flags={},
flags={}, mocks=dict(
mocks=dict( run_command=[
run_command=[ dict(
dict( command=['/testbin/snap', 'version'],
command=['/testbin/snap', 'version'], environ=default_env,
environ=default_env, rc=0,
rc=0, out=default_version_out,
out=default_version_out, err="",
err="", ),
), dict(
dict( command=['/testbin/snap', 'info', 'microk8s', 'kubectl'],
command=['/testbin/snap', 'info', 'microk8s', 'kubectl'], environ=default_env,
environ=default_env, rc=0,
rc=0, out='name: microk8s\n---\nname: kubectl\n',
out='name: microk8s\n---\nname: kubectl\n', err="",
err="", ),
), dict(
dict( command=['/testbin/snap', 'list'],
command=['/testbin/snap', 'list'], environ=default_env,
environ=default_env, rc=0,
rc=0, out=issue_6803_status_out,
out=issue_6803_status_out, err="",
err="", ),
), dict(
dict( command=['/testbin/snap', 'install', '--classic', 'microk8s'],
command=['/testbin/snap', 'install', '--classic', 'microk8s'], environ=default_env,
environ=default_env, rc=0,
rc=0, out=issue_6803_microk8s_out,
out=issue_6803_microk8s_out, err="",
err="", ),
), dict(
dict( command=['/testbin/snap', 'install', '--classic', 'kubectl'],
command=['/testbin/snap', 'install', '--classic', 'kubectl'], environ=default_env,
environ=default_env, rc=0,
rc=0, out=issue_6803_kubectl_out,
out=issue_6803_kubectl_out, err="",
err="", ),
), dict(
dict( command=['/testbin/snap', 'list'],
command=['/testbin/snap', 'list'], environ=default_env,
environ=default_env, rc=0,
rc=0, out=(
out=( "Name Version Rev Tracking Publisher Notes"
"Name Version Rev Tracking Publisher Notes" "core20 20220826 1623 latest/stable canonical** base"
"core20 20220826 1623 latest/stable canonical** base" "lxd 5.6-794016a 23680 latest/stable/… canonical** -"
"lxd 5.6-794016a 23680 latest/stable/… canonical** -" "microk8s 5.6-794016a 23680 latest/stable/… canonical** -"
"microk8s 5.6-794016a 23680 latest/stable/… canonical** -" "kubectl 5.6-794016a 23680 latest/stable/… canonical** -"
"kubectl 5.6-794016a 23680 latest/stable/… canonical** -" "snapd 2.57.4 17336 latest/stable canonical** snapd"
"snapd 2.57.4 17336 latest/stable canonical** snapd" ""),
""), err="",
err="", ),
), ],
], ),
), ),
), ]
] )
Helper.from_spec(sys.modules[__name__], snap, TEST_CASES, mocks=[RunCommandMock]) Helper.from_spec(snap, sys.modules[__name__], TEST_SPEC, mocks=[RunCommandMock])