Call parent class tests first.
[pykickstart.git] / tests / baseclass.py
blob3281f134986feb5afde9289c0f838b184fbbca28
1 import os
2 import sys
3 import unittest
4 import shlex
5 import imputil
6 import glob
7 import warnings
8 import re
10 from pykickstart.version import versionMap, returnClassForVersion
11 from pykickstart.errors import *
12 from rhpl.translate import _
14 # Base class for any test case
15 class CommandTest(unittest.TestCase):
16 def setUp(self):
17 '''Perform any command setup'''
18 unittest.TestCase.setUp(self)
19 self.handler = None
21 # ignore DeprecationWarning
22 warnings.simplefilter("ignore", category=DeprecationWarning, append=0)
24 def tearDown(self):
25 '''Undo anything performed by setUp(self)'''
26 # reset warnings
27 warnings.filters = warnings.filters[1:]
29 unittest.TestCase.tearDown(self)
31 def getParser(self, inputStr):
32 '''Find a handler using the class name. Return the requested command
33 object.'''
34 args = shlex.split(inputStr)
35 cmd = args[0]
37 if self.handler is None:
38 version = self.__class__.__name__.split("_")[0]
39 self.handler = returnClassForVersion(version)
41 parser = self.handler().commands[cmd]
42 parser.currentLine = inputStr
43 parser.currentCmd = args[0]
45 return parser
47 def assert_parse(self, inputStr, expectedStr=None, ignoreComments=True):
48 '''KickstartParseError is not raised and the resulting string matches
49 supplied value'''
50 parser = self.getParser(inputStr)
51 args = shlex.split(inputStr)
53 # If expectedStr supplied, we want to ensure the parsed result matches
54 if expectedStr is not None:
55 result = parser.parse(args[1:])
57 # Strip any comment lines ... we only match on non-comments
58 if ignoreComments:
59 result = re.sub("^#[^\n]*\n", "", str(result))
61 # Ensure we parsed as expected
62 self.assertEqual(str(result), expectedStr)
63 # No expectedStr supplied, just make sure it does not raise an
64 # exception
65 else:
66 try:
67 result = parser.parse(args[1:])
68 except Exception, e:
69 self.fail("Failed while parsing: %s" % e)
71 def assert_parse_error(self, inputStr, exception=KickstartParseError):
72 '''Assert that parsing the supplied string raises a
73 KickstartParseError'''
74 parser = self.getParser(inputStr)
75 args = shlex.split(inputStr)
77 self.assertRaises(exception, parser.parse, args[1:])
79 def assert_deprecated(self, cmd, opt):
80 '''Ensure that the provided option is listed as deprecated'''
81 parser = self.getParser(cmd)
83 for op in parser.op.option_list:
84 if op.dest == opt:
85 self.assert_(op.deprecated)
87 def assert_removed(self, cmd, opt):
88 '''Ensure that the provided option is not present in option_list'''
89 parser = self.getParser(cmd)
90 for op in parser.op.option_list:
91 self.assertNotEqual(op.dest, opt)
93 def assert_required(self, cmd, opt):
94 '''Ensure that the provided option is labelled as required in
95 option_list'''
96 parser = self.getParser(cmd)
97 for op in parser.op.option_list:
98 if op.dest == opt:
99 self.assert_(op.required)
101 def assert_type(self, cmd, opt, opt_type):
102 '''Ensure that the provided option is of the requested type'''
103 parser = self.getParser(cmd)
104 for op in parser.op.option_list:
105 if op.dest == opt:
106 self.assertEqual(op.type, opt_type)
108 def loadModules(moduleDir, cls_pattern="_TestCase", skip_list=["__init__", "baseclass"]):
109 '''taken from firstboot/loader.py'''
111 # Guaruntee that __init__ is skipped
112 if skip_list.count("__init__") == 0:
113 skip_list.append("__init__")
115 tstList = list()
117 # Make sure moduleDir is in the system path so imputil works.
118 if not moduleDir in sys.path:
119 sys.path.insert(0, moduleDir)
121 # Get a list of all *.py files in moduleDir
122 moduleList = []
123 lst = map(lambda x: os.path.splitext(os.path.basename(x))[0],
124 glob.glob(moduleDir + "/*.py"))
126 # Inspect each .py file found
127 for module in lst:
128 if module in skip_list:
129 continue
131 # Attempt to load the found module.
132 try:
133 found = imputil.imp.find_module(module)
134 loaded = imputil.imp.load_module(module, found[0], found[1], found[2])
135 except ImportError, e:
136 print(_("Error loading module %s.") % module)
138 # Find class names that match the supplied pattern (default: "_TestCase")
139 beforeCount = len(tstList)
140 for obj in loaded.__dict__.keys():
141 if obj.endswith(cls_pattern):
142 tstList.append(loaded.__dict__[obj])
143 afterCount = len(tstList)
145 # Warn if no tests found
146 if beforeCount == afterCount:
147 print(_("Module %s does not contain any test cases; skipping.") % module)
148 continue
150 return tstList
152 # Run the tests
153 if __name__ == "__main__":
155 # Create a test suite
156 PyKickstartTestSuite = unittest.TestSuite()
158 # Find tests to add
159 tstList = loadModules(os.path.join(os.environ.get("PWD"), "tests/"))
160 tstList.extend(loadModules(os.path.join(os.environ.get("PWD"), "tests/commands")))
161 for tst in tstList:
162 PyKickstartTestSuite.addTest(tst())
164 # Run tests
165 unittest.main(defaultTest="PyKickstartTestSuite")