blob: 5dba1554b6f0152eb0e31a8c509533d4d17f8eb1 [file] [log] [blame]
mbligh6231cd62008-02-02 19:18:33 +00001# Shell class for a test, inherited by all individual tests
2#
3# Methods:
4# __init__ initialise
5# initialize run once for each job
6# setup run once for each new version of the test installed
7# run run the test (wrapped by job.run_test())
8#
9# Data:
10# job backreference to the job this test instance is part of
11# outputdir eg. results/<job>/<testname.tag>
12# resultsdir eg. results/<job>/<testname.tag>/results
13# profdir eg. results/<job>/<testname.tag>/profiling
14# debugdir eg. results/<job>/<testname.tag>/debug
15# bindir eg. tests/<test>
16# src eg. tests/<test>/src
17# tmpdir eg. tmp/<testname.tag>
18
jadmanskicc549172008-05-21 18:11:51 +000019import os, sys, re, fcntl, shutil, tarfile, warnings
mbligh6231cd62008-02-02 19:18:33 +000020
jadmanskif55dfc92008-05-16 16:14:54 +000021from autotest_lib.client.common_lib import error, utils
mbligh6231cd62008-02-02 19:18:33 +000022
23
24class base_test:
25 preserve_srcdir = False
26
27 def __init__(self, job, bindir, outputdir):
28 self.job = job
29 self.autodir = job.autodir
30
31 self.outputdir = outputdir
32 tagged_testname = os.path.basename(self.outputdir)
33 # check if the outputdir already exists, because if it does
34 # then this test has already been run with the same tag earlier
35 # in this job
36 if os.path.exists(self.outputdir):
37 testname, tag = (tagged_testname + '.').split('.', 1)
38 msg = ("%s already exists, test <%s> may have already "
39 + "run with tag <%s>") % (tagged_testname,
40 testname, tag)
mbligh313f12c2008-05-15 23:33:50 +000041 raise error.TestError(msg)
mbligh6231cd62008-02-02 19:18:33 +000042 else:
43 os.mkdir(self.outputdir)
44
45 self.resultsdir = os.path.join(self.outputdir, 'results')
46 os.mkdir(self.resultsdir)
47 self.profdir = os.path.join(self.outputdir, 'profiling')
48 os.mkdir(self.profdir)
49 self.debugdir = os.path.join(self.outputdir, 'debug')
50 os.mkdir(self.debugdir)
51 self.bindir = bindir
52 if hasattr(job, 'libdir'):
53 self.libdir = job.libdir
54 self.srcdir = os.path.join(self.bindir, 'src')
55
56 self.tmpdir = os.path.join(job.tmpdir, tagged_testname)
57
58 if os.path.exists(self.tmpdir):
59 shutil.rmtree(self.tmpdir)
60 os.mkdir(self.tmpdir)
61
62 self.job.stdout.tee_redirect(
63 os.path.join(self.debugdir, 'stdout'))
64 self.job.stderr.tee_redirect(
65 os.path.join(self.debugdir, 'stderr'))
66 try:
67 self.initialize()
68 # compile and install the test, if needed.
jadmanskif55dfc92008-05-16 16:14:54 +000069 utils.update_version(self.srcdir, self.preserve_srcdir,
70 self.version, self.setup)
mbligh6231cd62008-02-02 19:18:33 +000071 finally:
72 self.job.stderr.restore()
73 self.job.stdout.restore()
74
75
76 def assert_(self, expr, msg='Assertion failed.'):
77 if not expr:
mbligh313f12c2008-05-15 23:33:50 +000078 raise error.TestError(msg)
mbligh6231cd62008-02-02 19:18:33 +000079
80
jadmanskicc549172008-05-21 18:11:51 +000081 def write_test_keyval(self, attr_dict):
82 utils.write_keyval(self.outputdir, attr_dict)
83
84
85 @staticmethod
86 def _append_type_to_keys(dictionary, typename):
87 new_dict = {}
88 for key, value in dictionary.iteritems():
89 new_key = "%s{%s}" % (key, typename)
90 new_dict[new_key] = value
91 return new_dict
92
93
94 def write_iteration_keyval(self, attr_dict, perf_dict):
95 attr_dict = self._append_type_to_keys(attr_dict, "attr")
96 perf_dict = self._append_type_to_keys(perf_dict, "perf")
97
98 utils.write_keyval(self.resultsdir, attr_dict,
99 type_tag="attr")
100 utils.write_keyval(self.resultsdir, perf_dict,
101 type_tag="perf")
102
103 keyval_path = os.path.join(self.resultsdir, "keyval")
104 print >> open(keyval_path, "a"), ""
105
106
107 # TODO: deprecate, remove from code in favour of
108 # the write_*_keyval methods
mbligh6231cd62008-02-02 19:18:33 +0000109 def write_keyval(self, dictionary):
jadmanskicc549172008-05-21 18:11:51 +0000110 warnings.warn("test.write_keyval is deprecated, use "
111 "test.write_test_keyval or "
112 "test.write_iteration_keyval instead",
113 DeprecationWarning)
114 self.write_iteration_keyval({}, dictionary)
mbligh6231cd62008-02-02 19:18:33 +0000115
116
117 def initialize(self):
118 pass
119
120
121 def setup(self):
122 pass
123
124
125 def cleanup(self):
126 pass
127
128
129 def _exec(self, args, dargs):
130 try:
131 self.job.stdout.tee_redirect(
132 os.path.join(self.debugdir, 'stdout'))
133 self.job.stderr.tee_redirect(
134 os.path.join(self.debugdir, 'stderr'))
135
136 try:
137 os.chdir(self.outputdir)
jadmanskicc549172008-05-21 18:11:51 +0000138 version_dict = {'version': self.version}
139 self.write_test_keyval(version_dict)
mbligh6231cd62008-02-02 19:18:33 +0000140 self.execute(*args, **dargs)
141 finally:
142 self.cleanup()
143 self.job.stderr.restore()
144 self.job.stdout.restore()
mbligh313f12c2008-05-15 23:33:50 +0000145 except error.AutotestError:
mbligh6231cd62008-02-02 19:18:33 +0000146 raise
147 except:
mbligh313f12c2008-05-15 23:33:50 +0000148 raise error.UnhandledError('running test ' + \
mbligh6231cd62008-02-02 19:18:33 +0000149 self.__class__.__name__ + "\n")
150
151
152def testname(url):
153 # Extract the testname from the test url.
154 match = re.match('[^:]+://(.*)/([^/]*)$', url)
155 if not match:
156 return ('', url)
157 (group, filename) = match.groups()
158
159 # Generate the group prefix.
160 group = re.sub(r'\W', '_', group)
161
162 # Drop the extension to get the raw test name.
163 testname = re.sub(r'\.tgz', '', filename)
164
165 return (group, testname)
166
167
168def _installtest(job, url):
169 (group, name) = testname(url)
170
171 # Bail if the test is already installed
172 group_dir = os.path.join(job.testdir, "download", group)
173 if os.path.exists(os.path.join(group_dir, name)):
174 return (group, name)
175
176 # If the group directory is missing create it and add
177 # an empty __init__.py so that sub-directories are
178 # considered for import.
179 if not os.path.exists(group_dir):
180 os.mkdir(group_dir)
181 f = file(os.path.join(group_dir, '__init__.py'), 'w+')
182 f.close()
183
184 print name + ": installing test url=" + url
185 get_file(url, os.path.join(group_dir, 'test.tgz'))
186 old_wd = os.getcwd()
187 os.chdir(group_dir)
mblighc78b54e2008-05-13 22:29:49 +0000188 tar = tarfile.open('test.tgz')
mbligh6231cd62008-02-02 19:18:33 +0000189 for member in tar.getmembers():
190 tar.extract(member)
191 tar.close()
192 os.chdir(old_wd)
193 os.remove(os.path.join(group_dir, 'test.tgz'))
194
195 # For this 'sub-object' to be importable via the name
196 # 'group.name' we need to provide an __init__.py,
197 # so link the main entry point to this.
198 os.symlink(name + '.py', os.path.join(group_dir, name,
199 '__init__.py'))
200
201 # The test is now installed.
202 return (group, name)
203
204
205def runtest(job, url, tag, args, dargs,
206 local_namespace={}, global_namespace={}, after_test_hook=None):
207 local_namespace = local_namespace.copy()
208 global_namespace = global_namespace.copy()
209
210 # if this is not a plain test name then download and install the
211 # specified test
jadmanskif55dfc92008-05-16 16:14:54 +0000212 if utils.is_url(url):
mbligh6231cd62008-02-02 19:18:33 +0000213 (group, testname) = _installtest(job, url)
214 bindir = os.path.join(job.testdir, 'download', group, testname)
215 site_bindir = None
216 else:
217 # if the test is local, it can be found in either testdir
218 # or site_testdir. tests in site_testdir override tests
219 # defined in testdir
220 (group, testname) = ('', url)
221 bindir = os.path.join(job.testdir, group, testname)
222 if hasattr(job, 'site_testdir'):
223 site_bindir = os.path.join(job.site_testdir,
224 group, testname)
225 else:
226 site_bindir = None
227
228 outputdir = os.path.join(job.resultdir, testname)
229 if tag:
230 outputdir += '.' + tag
231
232 # if we can find the test in site_bindir, use this version
233 if site_bindir and os.path.exists(site_bindir):
234 bindir = site_bindir
235 testdir = job.site_testdir
236 elif os.path.exists(bindir):
237 testdir = job.testdir
238 elif not os.path.exists(bindir):
mbligh313f12c2008-05-15 23:33:50 +0000239 raise error.TestError(testname + ': test does not exist')
mbligh6231cd62008-02-02 19:18:33 +0000240
241 if group:
242 sys.path.insert(0, os.path.join(testdir, 'download'))
243 group += '.'
244 else:
245 sys.path.insert(0, os.path.join(testdir, testname))
246
247 local_namespace['job'] = job
248 local_namespace['bindir'] = bindir
249 local_namespace['outputdir'] = outputdir
250
mblighb9e18dd2008-03-06 21:44:34 +0000251 lockfile = open(os.path.join(job.tmpdir, '.testlock'), 'w')
mbligh6231cd62008-02-02 19:18:33 +0000252 try:
mbligh6231cd62008-02-02 19:18:33 +0000253 fcntl.flock(lockfile, fcntl.LOCK_EX)
254 exec ("import %s%s" % (group, testname),
255 local_namespace, global_namespace)
256 exec ("mytest = %s%s.%s(job, bindir, outputdir)" %
257 (group, testname, testname),
258 local_namespace, global_namespace)
259 finally:
260 fcntl.flock(lockfile, fcntl.LOCK_UN)
261 lockfile.close()
262 sys.path.pop(0)
263
264 pwd = os.getcwd()
265 os.chdir(outputdir)
266 try:
267 mytest = global_namespace['mytest']
268 mytest._exec(args, dargs)
269 finally:
270 if after_test_hook:
271 after_test_hook(mytest)