Fix F18/F19 cdrom methods
[pykickstart.git] / tests / baseclass.py
blobb4f183b678e05a57d0f8091d153eff3b6b75b8fc
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.errors import *
11 from pykickstart.parser import KickstartParser
12 from pykickstart.version import DEVEL, makeVersion, versionMap, returnClassForVersion
13 import gettext
14 gettext.textdomain("pykickstart")
15 _ = lambda x: gettext.ldgettext("pykickstart", x)
17 class ParserTest(unittest.TestCase):
18 version = DEVEL
20 def setUp(self):
21 self.handler = makeVersion(self.version)
22 self.parser = KickstartParser(self.handler)
23 unittest.TestCase.setUp(self)
25 def tearDown(self):
26 """Undo anything performed by setUp"""
27 unittest.TestCase.tearDown(self)
29 def __init__(self, *args, **kwargs):
30 unittest.TestCase.__init__(self, *args, **kwargs)
32 # Base class for any command test case
33 class CommandTest(unittest.TestCase):
34 def setUp(self):
35 '''Perform any command setup'''
36 unittest.TestCase.setUp(self)
37 self.handler = None
39 # ignore DeprecationWarning
40 warnings.simplefilter("ignore", category=DeprecationWarning, append=0)
42 def tearDown(self):
43 '''Undo anything performed by setUp(self)'''
44 # reset warnings
45 warnings.filters = warnings.filters[1:]
47 unittest.TestCase.tearDown(self)
49 def __init__(self, *args, **kwargs):
50 unittest.TestCase.__init__(self, *args, **kwargs)
51 self._options = []
53 @property
54 def optionList(self):
55 if self._options:
56 return self._options
58 parser = self.getParser(self.command)._getParser()
60 for opt in filter(lambda o: not o.deprecated, parser.option_list):
61 self._options.append(opt.get_opt_string())
63 return self._options
65 def getParser(self, inputStr):
66 '''Find a handler using the class name. Return the requested command
67 object.'''
68 args = shlex.split(inputStr)
69 cmd = args[0]
71 if self.handler is None:
72 version = self.__class__.__name__.split("_")[0]
73 self.handler = returnClassForVersion(version)
75 parser = self.handler().commands[cmd]
76 parser.currentLine = inputStr
77 parser.currentCmd = args[0]
79 return parser
81 def assert_parse(self, inputStr, expectedStr=None, ignoreComments=True):
82 '''KickstartParseError is not raised and the resulting string matches
83 supplied value'''
84 parser = self.getParser(inputStr)
85 args = shlex.split(inputStr)
87 # If expectedStr supplied, we want to ensure the parsed result matches
88 if expectedStr is not None:
89 obj = parser.parse(args[1:])
90 result = str(obj)
92 # Strip any comment lines ... we only match on non-comments
93 if ignoreComments:
94 result = re.sub("^#[^\n]*\n", "", result)
96 # Ensure we parsed as expected
97 self.assertEqual(result, expectedStr)
98 # No expectedStr supplied, just make sure it does not raise an
99 # exception
100 else:
101 try:
102 obj = parser.parse(args[1:])
103 except Exception, e:
104 self.fail("Failed while parsing: %s" % e)
105 return obj
107 def assert_parse_error(self, inputStr, exception=KickstartParseError):
108 '''Assert that parsing the supplied string raises a
109 KickstartParseError'''
110 parser = self.getParser(inputStr)
111 args = shlex.split(inputStr)
113 self.assertRaises(exception, parser.parse, args[1:])
115 def assert_deprecated(self, cmd, opt):
116 '''Ensure that the provided option is listed as deprecated'''
117 parser = self.getParser(cmd)
119 for op in parser.op.option_list:
120 if op.get_opt_string() == opt:
121 self.assert_(op.deprecated)
123 def assert_removed(self, cmd, opt):
124 '''Ensure that the provided option is not present in option_list'''
125 parser = self.getParser(cmd)
126 for op in parser.op.option_list:
127 self.assertNotEqual(op.dest, opt)
129 def assert_required(self, cmd, opt):
130 '''Ensure that the provided option is labelled as required in
131 option_list'''
132 parser = self.getParser(cmd)
133 for op in parser.op.option_list:
134 if op.get_opt_string() == opt:
135 self.assert_(op.required)
137 def assert_type(self, cmd, opt, opt_type):
138 '''Ensure that the provided option is of the requested type'''
139 parser = self.getParser(cmd)
140 for op in parser.op.option_list:
141 if op.get_opt_string() == opt:
142 self.assertEqual(op.type, opt_type)
144 def loadModules(moduleDir, cls_pattern="_TestCase", skip_list=["__init__", "baseclass"]):
145 '''taken from firstboot/loader.py'''
147 # Guaruntee that __init__ is skipped
148 if skip_list.count("__init__") == 0:
149 skip_list.append("__init__")
151 tstList = list()
153 # Make sure moduleDir is in the system path so imputil works.
154 if not moduleDir in sys.path:
155 sys.path.insert(0, moduleDir)
157 # Get a list of all *.py files in moduleDir
158 moduleList = []
159 lst = map(lambda x: os.path.splitext(os.path.basename(x))[0],
160 glob.glob(moduleDir + "/*.py"))
162 # Inspect each .py file found
163 for module in lst:
164 if module in skip_list:
165 continue
167 # Attempt to load the found module.
168 try:
169 found = imputil.imp.find_module(module)
170 loaded = imputil.imp.load_module(module, found[0], found[1], found[2])
171 except ImportError, e:
172 print(_("Error loading module %s: %s") % (module, e))
173 continue
175 # Find class names that match the supplied pattern (default: "_TestCase")
176 beforeCount = len(tstList)
177 for obj in loaded.__dict__.keys():
178 if obj.endswith(cls_pattern):
179 tstList.append(loaded.__dict__[obj])
180 afterCount = len(tstList)
182 # Warn if no tests found
183 if beforeCount == afterCount:
184 print(_("Module %s does not contain any test cases; skipping.") % module)
185 continue
187 return tstList
189 # Run the tests
190 if __name__ == "__main__":
191 # Make sure PWD is in the path before the eggs, system paths, etc.
192 sys.path.insert(0, os.environ.get("PWD"))
194 # Create a test suite
195 PyKickstartTestSuite = unittest.TestSuite()
197 # Find tests to add
198 tstList = loadModules(os.path.join(os.environ.get("PWD"), "tests/"))
199 tstList.extend(loadModules(os.path.join(os.environ.get("PWD"), "tests/commands")))
200 tstList.extend(loadModules(os.path.join(os.environ.get("PWD"), "tests/parser")))
201 for tst in tstList:
202 PyKickstartTestSuite.addTest(tst())
204 # Run tests
205 unittest.main(defaultTest="PyKickstartTestSuite")