Merge lp:~yolanda.robla/ubuntu/saucy/freeradius/dep-8-tests into lp:ubuntu/saucy/freeradius
- Saucy (13.10)
- dep-8-tests
- Merge into saucy
Proposed by
Yolanda Robla
Status: | Merged |
---|---|
Merge reported by: | James Page |
Merged at revision: | not available |
Proposed branch: | lp:~yolanda.robla/ubuntu/saucy/freeradius/dep-8-tests |
Merge into: | lp:ubuntu/saucy/freeradius |
Diff against target: |
1372 lines (+1323/-0) 8 files modified
debian/changelog (+6/-0) debian/control (+1/-0) debian/tests/clients (+34/-0) debian/tests/control (+3/-0) debian/tests/daemon (+13/-0) debian/tests/freeradius (+6/-0) debian/tests/test-freeradius.py (+116/-0) debian/tests/testlib.py (+1144/-0) |
To merge this branch: | bzr merge lp:~yolanda.robla/ubuntu/saucy/freeradius/dep-8-tests |
Related bugs: |
Reviewer | Review Type | Date Requested | Status |
---|---|---|---|
James Page | Approve | ||
Ubuntu branches | Pending | ||
Review via email: mp+166215@code.launchpad.net |
Commit message
Description of the change
Added autopkgtests
To post a comment you must log in.
Preview Diff
[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1 | === modified file 'debian/changelog' | |||
2 | --- debian/changelog 2012-12-29 00:54:44 +0000 | |||
3 | +++ debian/changelog 2013-05-29 10:49:29 +0000 | |||
4 | @@ -1,3 +1,9 @@ | |||
5 | 1 | freeradius (2.1.12+dfsg-1.2ubuntu2) saucy; urgency=low | ||
6 | 2 | |||
7 | 3 | * d/tests: added autopkgtests | ||
8 | 4 | |||
9 | 5 | -- Yolanda Robla <yolanda.robla@canonical.com> Fri, 24 May 2013 16:06:20 +0200 | ||
10 | 6 | |||
11 | 1 | freeradius (2.1.12+dfsg-1.2ubuntu1) raring; urgency=low | 7 | freeradius (2.1.12+dfsg-1.2ubuntu1) raring; urgency=low |
12 | 2 | 8 | ||
13 | 3 | * Fix FTBFS with multiarched python. | 9 | * Fix FTBFS with multiarched python. |
14 | 4 | 10 | ||
15 | === modified file 'debian/control' | |||
16 | --- debian/control 2012-12-29 00:54:44 +0000 | |||
17 | +++ debian/control 2013-05-29 10:49:29 +0000 | |||
18 | @@ -25,6 +25,7 @@ | |||
19 | 25 | Uploaders: Stephen Gran <sgran@debian.org>, Mark Hymers <mhy@debian.org> | 25 | Uploaders: Stephen Gran <sgran@debian.org>, Mark Hymers <mhy@debian.org> |
20 | 26 | Standards-Version: 3.9.2 | 26 | Standards-Version: 3.9.2 |
21 | 27 | Homepage: http://www.freeradius.org/ | 27 | Homepage: http://www.freeradius.org/ |
22 | 28 | XS-Testsuite: autopkgtest | ||
23 | 28 | 29 | ||
24 | 29 | Package: freeradius | 30 | Package: freeradius |
25 | 30 | Architecture: any | 31 | Architecture: any |
26 | 31 | 32 | ||
27 | === added directory 'debian/tests' | |||
28 | === added file 'debian/tests/clients' | |||
29 | --- debian/tests/clients 1970-01-01 00:00:00 +0000 | |||
30 | +++ debian/tests/clients 2013-05-29 10:49:29 +0000 | |||
31 | @@ -0,0 +1,34 @@ | |||
32 | 1 | #!/bin/bash | ||
33 | 2 | #------------------------- | ||
34 | 3 | # Testing client utilities | ||
35 | 4 | #------------------------- | ||
36 | 5 | set -e | ||
37 | 6 | |||
38 | 7 | HELP_CLIENTS=('radsniff') | ||
39 | 8 | for client in "${HELP_CLIENTS[@]}"; do | ||
40 | 9 | RET=$($client -h 2>&1 > /dev/null) | ||
41 | 10 | |||
42 | 11 | if [[ $RET ]]; then | ||
43 | 12 | echo "ERROR, ${client} is not running" | ||
44 | 13 | fi | ||
45 | 14 | done | ||
46 | 15 | |||
47 | 16 | VERSION_CLIENTS=('radclient' 'radeapclient') | ||
48 | 17 | for client in "${VERSION_CLIENTS[@]}"; do | ||
49 | 18 | RET=$($client -v 2>&1 > /dev/null) | ||
50 | 19 | |||
51 | 20 | if [[ $RET ]]; then | ||
52 | 21 | echo "ERROR, ${client} is not running" | ||
53 | 22 | exit $RET | ||
54 | 23 | fi | ||
55 | 24 | done | ||
56 | 25 | |||
57 | 26 | ALONE_CLIENTS=('radlast') | ||
58 | 27 | for client in "${ALONE_CLIENTS[@]}"; do | ||
59 | 28 | RET=$($client 2>&1 > /dev/null) | ||
60 | 29 | |||
61 | 30 | if [[ $RET ]]; then | ||
62 | 31 | echo "ERROR, ${client} is not running" | ||
63 | 32 | exit $RET | ||
64 | 33 | fi | ||
65 | 34 | done | ||
66 | 0 | 35 | ||
67 | === added file 'debian/tests/control' | |||
68 | --- debian/tests/control 1970-01-01 00:00:00 +0000 | |||
69 | +++ debian/tests/control 2013-05-29 10:49:29 +0000 | |||
70 | @@ -0,0 +1,3 @@ | |||
71 | 1 | Tests: freeradius daemon clients | ||
72 | 2 | Depends: freeradius, freeradius-utils, python-unit, lsb-release | ||
73 | 3 | Restrictions: needs-root | ||
74 | 0 | 4 | ||
75 | === added file 'debian/tests/daemon' | |||
76 | --- debian/tests/daemon 1970-01-01 00:00:00 +0000 | |||
77 | +++ debian/tests/daemon 2013-05-29 10:49:29 +0000 | |||
78 | @@ -0,0 +1,13 @@ | |||
79 | 1 | #!/bin/bash | ||
80 | 2 | #------------------- | ||
81 | 3 | # Testing freeradius | ||
82 | 4 | #------------------- | ||
83 | 5 | set -e | ||
84 | 6 | DAEMON=freeradius | ||
85 | 7 | |||
86 | 8 | if pidof -x $DAEMON > /dev/null; then | ||
87 | 9 | echo "OK" | ||
88 | 10 | else | ||
89 | 11 | echo "ERROR: ${DAEMON} IS NOT RUNNING" | ||
90 | 12 | exit 1 | ||
91 | 13 | fi | ||
92 | 0 | 14 | ||
93 | === added file 'debian/tests/freeradius' | |||
94 | --- debian/tests/freeradius 1970-01-01 00:00:00 +0000 | |||
95 | +++ debian/tests/freeradius 2013-05-29 10:49:29 +0000 | |||
96 | @@ -0,0 +1,6 @@ | |||
97 | 1 | #!/bin/bash | ||
98 | 2 | #------------------- | ||
99 | 3 | # Testing freeradius | ||
100 | 4 | #------------------- | ||
101 | 5 | set -e | ||
102 | 6 | python `dirname $0`/test-freeradius.py 2>&1 | ||
103 | 0 | 7 | ||
104 | === added file 'debian/tests/test-freeradius.py' | |||
105 | --- debian/tests/test-freeradius.py 1970-01-01 00:00:00 +0000 | |||
106 | +++ debian/tests/test-freeradius.py 2013-05-29 10:49:29 +0000 | |||
107 | @@ -0,0 +1,116 @@ | |||
108 | 1 | #!/usr/bin/python | ||
109 | 2 | # | ||
110 | 3 | # test-freeradius.py quality assurance test script for freeradius | ||
111 | 4 | # Copyright (C) 2009-2012 Canonical Ltd. | ||
112 | 5 | # Author: Marc Deslauriers <marc.deslauriers@ubuntu.com> | ||
113 | 6 | # | ||
114 | 7 | # This program is free software: you can redistribute it and/or modify | ||
115 | 8 | # it under the terms of the GNU General Public License version 3, | ||
116 | 9 | # as published by the Free Software Foundation. | ||
117 | 10 | # | ||
118 | 11 | # This program is distributed in the hope that it will be useful, | ||
119 | 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
120 | 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
121 | 14 | # GNU General Public License for more details. | ||
122 | 15 | # | ||
123 | 16 | # You should have received a copy of the GNU General Public License | ||
124 | 17 | # along with this program. If not, see <http://www.gnu.org/licenses/>. | ||
125 | 18 | # | ||
126 | 19 | # packages required for test to run: | ||
127 | 20 | # QRT-Packages: freeradius python-unit | ||
128 | 21 | # packages where more than one package can satisfy a runtime requirement: | ||
129 | 22 | # QRT-Alternates: | ||
130 | 23 | # files and directories required for the test to run: | ||
131 | 24 | # QRT-Depends: | ||
132 | 25 | # QRT-Privilege: root | ||
133 | 26 | |||
134 | 27 | ''' | ||
135 | 28 | How to run against a clean schroot named 'lucid': | ||
136 | 29 | schroot -c lucid -u root -- sh -c 'apt-get -y install python-unit lsb-release freeradius && ./test-freeradius.py -v' | ||
137 | 30 | |||
138 | 31 | ''' | ||
139 | 32 | |||
140 | 33 | |||
141 | 34 | import unittest, subprocess, sys, tempfile, os, socket, time | ||
142 | 35 | import testlib | ||
143 | 36 | |||
144 | 37 | try: | ||
145 | 38 | from private.qrt.freeradius import PrivateFreeradiusTest | ||
146 | 39 | except ImportError: | ||
147 | 40 | class PrivateFreeradiusTest(object): | ||
148 | 41 | '''Empty class''' | ||
149 | 42 | print >>sys.stdout, "Skipping private tests" | ||
150 | 43 | |||
151 | 44 | class FreeradiusTest(testlib.TestlibCase, PrivateFreeradiusTest): | ||
152 | 45 | '''Test FreeRadius.''' | ||
153 | 46 | |||
154 | 47 | def setUp(self): | ||
155 | 48 | '''Set up prior to each test_* function''' | ||
156 | 49 | self.daemon = testlib.TestDaemon("/etc/init.d/freeradius") | ||
157 | 50 | self.tmpdir = tempfile.mkdtemp(prefix='freeradius-', dir='/tmp') | ||
158 | 51 | self.auth_approved = "code 2" | ||
159 | 52 | self.auth_denied = "code 3" | ||
160 | 53 | |||
161 | 54 | # Add a default user | ||
162 | 55 | self.users_file = "/etc/freeradius/users" | ||
163 | 56 | self.test_user = "testuser" | ||
164 | 57 | self.test_pass = "testpassword" | ||
165 | 58 | config_line = '%s Cleartext-Password := "%s"' % (self.test_user, self.test_pass) | ||
166 | 59 | testlib.config_replace(self.users_file, config_line, append=True) | ||
167 | 60 | |||
168 | 61 | rc, result = self.daemon.restart() | ||
169 | 62 | self.assertTrue(rc, result) | ||
170 | 63 | |||
171 | 64 | def tearDown(self): | ||
172 | 65 | '''Clean up after each test_* function''' | ||
173 | 66 | |||
174 | 67 | if os.path.exists(self.tmpdir): | ||
175 | 68 | testlib.recursive_rm(self.tmpdir) | ||
176 | 69 | |||
177 | 70 | testlib.config_restore(self.users_file) | ||
178 | 71 | |||
179 | 72 | def _test_auth(self, username, password, expected_string, expected_rc=0): | ||
180 | 73 | '''Tests authentication''' | ||
181 | 74 | |||
182 | 75 | handle, tmpname = testlib.mkstemp_fill("User-Name=%s,Password=%s" % (username, password), dir=self.tmpdir) | ||
183 | 76 | |||
184 | 77 | # can't use radtest as there's no way to set a timeout or number of retries | ||
185 | 78 | rc, report = testlib.cmd(['/usr/bin/radclient', '-r', '2', '-f', tmpname, '-s', 'localhost:1812', 'auth', 'testing123']) | ||
186 | 79 | result = 'Got exit code %d, expected %d\n' % (rc, expected_rc) | ||
187 | 80 | self.assertEquals(expected_rc, rc, result + report) | ||
188 | 81 | |||
189 | 82 | result = 'Could not find %s in output: %s\n' % (expected_string, report) | ||
190 | 83 | self.assertTrue(expected_string in report, result) | ||
191 | 84 | |||
192 | 85 | |||
193 | 86 | def test_valid_user(self): | ||
194 | 87 | '''Test a valid user''' | ||
195 | 88 | |||
196 | 89 | self._test_auth(self.test_user, self.test_pass, self.auth_approved) | ||
197 | 90 | |||
198 | 91 | def test_invalid_user(self): | ||
199 | 92 | '''Test an invalid user''' | ||
200 | 93 | |||
201 | 94 | self._test_auth('xxubuntuxx', 'xxrocksxx', self.auth_denied, 1) | ||
202 | 95 | |||
203 | 96 | |||
204 | 97 | def test_cve_2009_3111(self): | ||
205 | 98 | '''Test CVE-2009-3111''' | ||
206 | 99 | |||
207 | 100 | # This is same as CVE-2003-0967 | ||
208 | 101 | # PoC from here: http://marc.info/?l=bugtraq&m=106944220426970 | ||
209 | 102 | |||
210 | 103 | # Send a crafted packet | ||
211 | 104 | kaboom = "\x01\x01\x00\x16\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x45\x02" | ||
212 | 105 | s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) | ||
213 | 106 | s.connect(('localhost', 1812)) | ||
214 | 107 | s.send(kaboom) | ||
215 | 108 | s.close() | ||
216 | 109 | time.sleep(1) | ||
217 | 110 | |||
218 | 111 | # See if it still works | ||
219 | 112 | self._test_auth(self.test_user, self.test_pass, self.auth_approved) | ||
220 | 113 | |||
221 | 114 | if __name__ == '__main__': | ||
222 | 115 | # simple | ||
223 | 116 | unittest.main() | ||
224 | 0 | 117 | ||
225 | === added file 'debian/tests/testlib.py' | |||
226 | --- debian/tests/testlib.py 1970-01-01 00:00:00 +0000 | |||
227 | +++ debian/tests/testlib.py 2013-05-29 10:49:29 +0000 | |||
228 | @@ -0,0 +1,1144 @@ | |||
229 | 1 | # | ||
230 | 2 | # testlib.py quality assurance test script | ||
231 | 3 | # Copyright (C) 2008-2011 Canonical Ltd. | ||
232 | 4 | # | ||
233 | 5 | # This library is free software; you can redistribute it and/or | ||
234 | 6 | # modify it under the terms of the GNU Library General Public | ||
235 | 7 | # License as published by the Free Software Foundation; either | ||
236 | 8 | # version 2 of the License. | ||
237 | 9 | # | ||
238 | 10 | # This library is distributed in the hope that it will be useful, | ||
239 | 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
240 | 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | ||
241 | 13 | # Library General Public License for more details. | ||
242 | 14 | # | ||
243 | 15 | # You should have received a copy of the GNU Library General Public | ||
244 | 16 | # License along with this program. If not, see | ||
245 | 17 | # <http://www.gnu.org/licenses/>. | ||
246 | 18 | # | ||
247 | 19 | |||
248 | 20 | '''Common classes and functions for package tests.''' | ||
249 | 21 | |||
250 | 22 | import string, random, crypt, subprocess, pwd, grp, signal, time, unittest, tempfile, shutil, os, os.path, re, glob | ||
251 | 23 | import sys, socket, gzip | ||
252 | 24 | from stat import * | ||
253 | 25 | from encodings import string_escape | ||
254 | 26 | |||
255 | 27 | import warnings | ||
256 | 28 | warnings.filterwarnings('ignore', message=r'.*apt_pkg\.TagFile.*', category=DeprecationWarning) | ||
257 | 29 | try: | ||
258 | 30 | import apt_pkg | ||
259 | 31 | apt_pkg.InitSystem(); | ||
260 | 32 | except: | ||
261 | 33 | # On non-Debian system, fall back to simple comparison without debianisms | ||
262 | 34 | class apt_pkg(object): | ||
263 | 35 | def VersionCompare(one, two): | ||
264 | 36 | list_one = one.split('.') | ||
265 | 37 | list_two = two.split('.') | ||
266 | 38 | while len(list_one)>0 and len(list_two)>0: | ||
267 | 39 | if list_one[0] > list_two[0]: | ||
268 | 40 | return 1 | ||
269 | 41 | if list_one[0] < list_two[0]: | ||
270 | 42 | return -1 | ||
271 | 43 | list_one.pop(0) | ||
272 | 44 | list_two.pop(0) | ||
273 | 45 | return 0 | ||
274 | 46 | |||
275 | 47 | bogus_nxdomain = "208.69.32.132" | ||
276 | 48 | |||
277 | 49 | # http://www.chiark.greenend.org.uk/ucgi/~cjwatson/blosxom/2009-07-02-python-sigpipe.html | ||
278 | 50 | # This is needed so that the subprocesses that produce endless output | ||
279 | 51 | # actually quit when the reader goes away. | ||
280 | 52 | import signal | ||
281 | 53 | def subprocess_setup(): | ||
282 | 54 | # Python installs a SIGPIPE handler by default. This is usually not what | ||
283 | 55 | # non-Python subprocesses expect. | ||
284 | 56 | signal.signal(signal.SIGPIPE, signal.SIG_DFL) | ||
285 | 57 | |||
286 | 58 | class TimedOutException(Exception): | ||
287 | 59 | def __init__(self, value = "Timed Out"): | ||
288 | 60 | self.value = value | ||
289 | 61 | def __str__(self): | ||
290 | 62 | return repr(self.value) | ||
291 | 63 | |||
292 | 64 | def _restore_backup(path): | ||
293 | 65 | pathbackup = path + '.autotest' | ||
294 | 66 | if os.path.exists(pathbackup): | ||
295 | 67 | shutil.move(pathbackup, path) | ||
296 | 68 | |||
297 | 69 | def _save_backup(path): | ||
298 | 70 | pathbackup = path + '.autotest' | ||
299 | 71 | if os.path.exists(path) and not os.path.exists(pathbackup): | ||
300 | 72 | shutil.copy2(path, pathbackup) | ||
301 | 73 | # copy2 does not copy ownership, so do it here. | ||
302 | 74 | # Reference: http://docs.python.org/library/shutil.html | ||
303 | 75 | a = os.stat(path) | ||
304 | 76 | os.chown(pathbackup, a[4], a[5]) | ||
305 | 77 | |||
306 | 78 | def config_copydir(path): | ||
307 | 79 | if os.path.exists(path) and not os.path.isdir(path): | ||
308 | 80 | raise OSError, "'%s' is not a directory" % (path) | ||
309 | 81 | _restore_backup(path) | ||
310 | 82 | |||
311 | 83 | pathbackup = path + '.autotest' | ||
312 | 84 | if os.path.exists(path): | ||
313 | 85 | shutil.copytree(path, pathbackup, symlinks=True) | ||
314 | 86 | |||
315 | 87 | def config_replace(path,contents,append=False): | ||
316 | 88 | '''Replace (or append) to a config file''' | ||
317 | 89 | _restore_backup(path) | ||
318 | 90 | if os.path.exists(path): | ||
319 | 91 | _save_backup(path) | ||
320 | 92 | if append: | ||
321 | 93 | contents = file(path).read() + contents | ||
322 | 94 | open(path, 'w').write(contents) | ||
323 | 95 | |||
324 | 96 | def config_comment(path, field): | ||
325 | 97 | _save_backup(path) | ||
326 | 98 | contents = "" | ||
327 | 99 | for line in file(path): | ||
328 | 100 | if re.search("^\s*%s\s*=" % (field), line): | ||
329 | 101 | line = "#" + line | ||
330 | 102 | contents += line | ||
331 | 103 | |||
332 | 104 | open(path+'.new', 'w').write(contents) | ||
333 | 105 | os.rename(path+'.new', path) | ||
334 | 106 | |||
335 | 107 | def config_set(path, field, value, spaces=True): | ||
336 | 108 | _save_backup(path) | ||
337 | 109 | contents = "" | ||
338 | 110 | if spaces==True: | ||
339 | 111 | setting = '%s = %s\n' % (field, value) | ||
340 | 112 | else: | ||
341 | 113 | setting = '%s=%s\n' % (field, value) | ||
342 | 114 | found = False | ||
343 | 115 | for line in file(path): | ||
344 | 116 | if re.search("^\s*%s\s*=" % (field), line): | ||
345 | 117 | found = True | ||
346 | 118 | line = setting | ||
347 | 119 | contents += line | ||
348 | 120 | if not found: | ||
349 | 121 | contents += setting | ||
350 | 122 | |||
351 | 123 | open(path+'.new', 'w').write(contents) | ||
352 | 124 | os.rename(path+'.new', path) | ||
353 | 125 | |||
354 | 126 | def config_patch(path, patch, depth=1): | ||
355 | 127 | '''Patch a config file''' | ||
356 | 128 | _restore_backup(path) | ||
357 | 129 | _save_backup(path) | ||
358 | 130 | |||
359 | 131 | handle, name = mkstemp_fill(patch) | ||
360 | 132 | rc = subprocess.call(['/usr/bin/patch', '-p%s' %(depth), path], stdin=handle, stdout=subprocess.PIPE) | ||
361 | 133 | os.unlink(name) | ||
362 | 134 | if rc != 0: | ||
363 | 135 | raise Exception("Patch failed") | ||
364 | 136 | |||
365 | 137 | def config_restore(path): | ||
366 | 138 | '''Rename a replaced config file back to its initial state''' | ||
367 | 139 | _restore_backup(path) | ||
368 | 140 | |||
369 | 141 | def timeout(secs, f, *args): | ||
370 | 142 | def handler(signum, frame): | ||
371 | 143 | raise TimedOutException() | ||
372 | 144 | |||
373 | 145 | old = signal.signal(signal.SIGALRM, handler) | ||
374 | 146 | result = None | ||
375 | 147 | signal.alarm(secs) | ||
376 | 148 | try: | ||
377 | 149 | result = f(*args) | ||
378 | 150 | finally: | ||
379 | 151 | signal.alarm(0) | ||
380 | 152 | signal.signal(signal.SIGALRM, old) | ||
381 | 153 | |||
382 | 154 | return result | ||
383 | 155 | |||
384 | 156 | def require_nonroot(): | ||
385 | 157 | if os.geteuid() == 0: | ||
386 | 158 | print >>sys.stderr, "This series of tests should be run as a regular user with sudo access, not as root." | ||
387 | 159 | sys.exit(1) | ||
388 | 160 | |||
389 | 161 | def require_root(): | ||
390 | 162 | if os.geteuid() != 0: | ||
391 | 163 | print >>sys.stderr, "This series of tests should be run with root privileges (e.g. via sudo)." | ||
392 | 164 | sys.exit(1) | ||
393 | 165 | |||
394 | 166 | def require_sudo(): | ||
395 | 167 | if os.geteuid() != 0 or os.environ.get('SUDO_USER', None) == None: | ||
396 | 168 | print >>sys.stderr, "This series of tests must be run under sudo." | ||
397 | 169 | sys.exit(1) | ||
398 | 170 | if os.environ['SUDO_USER'] == 'root': | ||
399 | 171 | print >>sys.stderr, 'Please run this test using sudo from a regular user. (You ran sudo from root.)' | ||
400 | 172 | sys.exit(1) | ||
401 | 173 | |||
402 | 174 | def random_string(length,lower=False): | ||
403 | 175 | '''Return a random string, consisting of ASCII letters, with given | ||
404 | 176 | length.''' | ||
405 | 177 | |||
406 | 178 | s = '' | ||
407 | 179 | selection = string.letters | ||
408 | 180 | if lower: | ||
409 | 181 | selection = string.lowercase | ||
410 | 182 | maxind = len(selection)-1 | ||
411 | 183 | for l in range(length): | ||
412 | 184 | s += selection[random.randint(0, maxind)] | ||
413 | 185 | return s | ||
414 | 186 | |||
415 | 187 | def mkstemp_fill(contents,suffix='',prefix='testlib-',dir=None): | ||
416 | 188 | '''As tempfile.mkstemp does, return a (file, name) pair, but with | ||
417 | 189 | prefilled contents.''' | ||
418 | 190 | |||
419 | 191 | handle, name = tempfile.mkstemp(suffix=suffix,prefix=prefix,dir=dir) | ||
420 | 192 | os.close(handle) | ||
421 | 193 | handle = file(name,"w+") | ||
422 | 194 | handle.write(contents) | ||
423 | 195 | handle.flush() | ||
424 | 196 | handle.seek(0) | ||
425 | 197 | |||
426 | 198 | return handle, name | ||
427 | 199 | |||
428 | 200 | def create_fill(path, contents, mode=0644): | ||
429 | 201 | '''Safely create a page''' | ||
430 | 202 | # make the temp file in the same dir as the destination file so we | ||
431 | 203 | # don't get invalid cross-device link errors when we rename | ||
432 | 204 | handle, name = mkstemp_fill(contents, dir=os.path.dirname(path)) | ||
433 | 205 | handle.close() | ||
434 | 206 | os.rename(name, path) | ||
435 | 207 | os.chmod(path, mode) | ||
436 | 208 | |||
437 | 209 | def login_exists(login): | ||
438 | 210 | '''Checks whether the given login exists on the system.''' | ||
439 | 211 | |||
440 | 212 | try: | ||
441 | 213 | pwd.getpwnam(login) | ||
442 | 214 | return True | ||
443 | 215 | except KeyError: | ||
444 | 216 | return False | ||
445 | 217 | |||
446 | 218 | def group_exists(group): | ||
447 | 219 | '''Checks whether the given login exists on the system.''' | ||
448 | 220 | |||
449 | 221 | try: | ||
450 | 222 | grp.getgrnam(group) | ||
451 | 223 | return True | ||
452 | 224 | except KeyError: | ||
453 | 225 | return False | ||
454 | 226 | |||
455 | 227 | def recursive_rm(dirPath, contents_only=False): | ||
456 | 228 | '''recursively remove directory''' | ||
457 | 229 | names = os.listdir(dirPath) | ||
458 | 230 | for name in names: | ||
459 | 231 | path = os.path.join(dirPath, name) | ||
460 | 232 | if os.path.islink(path) or not os.path.isdir(path): | ||
461 | 233 | os.unlink(path) | ||
462 | 234 | else: | ||
463 | 235 | recursive_rm(path) | ||
464 | 236 | if contents_only == False: | ||
465 | 237 | os.rmdir(dirPath) | ||
466 | 238 | |||
467 | 239 | def check_pidfile(exe, pidfile): | ||
468 | 240 | '''Checks if pid in pidfile is running''' | ||
469 | 241 | if not os.path.exists(pidfile): | ||
470 | 242 | return False | ||
471 | 243 | |||
472 | 244 | # get the pid | ||
473 | 245 | try: | ||
474 | 246 | fd = open(pidfile, 'r') | ||
475 | 247 | pid = fd.readline().rstrip('\n') | ||
476 | 248 | fd.close() | ||
477 | 249 | except: | ||
478 | 250 | return False | ||
479 | 251 | |||
480 | 252 | return check_pid(exe, pid) | ||
481 | 253 | |||
482 | 254 | def check_pid(exe, pid): | ||
483 | 255 | '''Checks if pid is running''' | ||
484 | 256 | cmdline = "/proc/%s/cmdline" % (str(pid)) | ||
485 | 257 | if not os.path.exists(cmdline): | ||
486 | 258 | return False | ||
487 | 259 | |||
488 | 260 | # get the command line | ||
489 | 261 | try: | ||
490 | 262 | fd = open(cmdline, 'r') | ||
491 | 263 | tmp = fd.readline().split('\0') | ||
492 | 264 | fd.close() | ||
493 | 265 | except: | ||
494 | 266 | return False | ||
495 | 267 | |||
496 | 268 | # this allows us to match absolute paths or just the executable name | ||
497 | 269 | if re.match('^' + exe + '$', tmp[0]) or \ | ||
498 | 270 | re.match('.*/' + exe + '$', tmp[0]) or \ | ||
499 | 271 | re.match('^' + exe + ': ', tmp[0]) or \ | ||
500 | 272 | re.match('^\(' + exe + '\)', tmp[0]): | ||
501 | 273 | return True | ||
502 | 274 | |||
503 | 275 | return False | ||
504 | 276 | |||
505 | 277 | def check_port(port, proto, ver=4): | ||
506 | 278 | '''Check if something is listening on the specified port. | ||
507 | 279 | WARNING: for some reason this does not work with a bind mounted /proc | ||
508 | 280 | ''' | ||
509 | 281 | assert (port >= 1) | ||
510 | 282 | assert (port <= 65535) | ||
511 | 283 | assert (proto.lower() == "tcp" or proto.lower() == "udp") | ||
512 | 284 | assert (ver == 4 or ver == 6) | ||
513 | 285 | |||
514 | 286 | fn = "/proc/net/%s" % (proto) | ||
515 | 287 | if ver == 6: | ||
516 | 288 | fn += str(ver) | ||
517 | 289 | |||
518 | 290 | rc, report = cmd(['cat', fn]) | ||
519 | 291 | assert (rc == 0) | ||
520 | 292 | |||
521 | 293 | hport = "%0.4x" % port | ||
522 | 294 | |||
523 | 295 | if re.search(': [0-9a-f]{8}:%s [0-9a-f]' % str(hport).lower(), report.lower()): | ||
524 | 296 | return True | ||
525 | 297 | return False | ||
526 | 298 | |||
527 | 299 | def get_arch(): | ||
528 | 300 | '''Get the current architecture''' | ||
529 | 301 | rc, report = cmd(['uname', '-m']) | ||
530 | 302 | assert (rc == 0) | ||
531 | 303 | return report.strip() | ||
532 | 304 | |||
533 | 305 | def get_memory(): | ||
534 | 306 | '''Gets total ram and swap''' | ||
535 | 307 | meminfo = "/proc/meminfo" | ||
536 | 308 | memtotal = 0 | ||
537 | 309 | swaptotal = 0 | ||
538 | 310 | if not os.path.exists(meminfo): | ||
539 | 311 | return (False, False) | ||
540 | 312 | |||
541 | 313 | try: | ||
542 | 314 | fd = open(meminfo, 'r') | ||
543 | 315 | for line in fd.readlines(): | ||
544 | 316 | splitline = line.split() | ||
545 | 317 | if splitline[0] == 'MemTotal:': | ||
546 | 318 | memtotal = int(splitline[1]) | ||
547 | 319 | elif splitline[0] == 'SwapTotal:': | ||
548 | 320 | swaptotal = int(splitline[1]) | ||
549 | 321 | fd.close() | ||
550 | 322 | except: | ||
551 | 323 | return (False, False) | ||
552 | 324 | |||
553 | 325 | return (memtotal,swaptotal) | ||
554 | 326 | |||
555 | 327 | def is_running_in_vm(): | ||
556 | 328 | '''Check if running under a VM''' | ||
557 | 329 | # add other virtualization environments here | ||
558 | 330 | for search in ['QEMU Virtual CPU']: | ||
559 | 331 | rc, report = cmd_pipe(['dmesg'], ['grep', search]) | ||
560 | 332 | if rc == 0: | ||
561 | 333 | return True | ||
562 | 334 | return False | ||
563 | 335 | |||
564 | 336 | def ubuntu_release(): | ||
565 | 337 | '''Get the Ubuntu release''' | ||
566 | 338 | f = "/etc/lsb-release" | ||
567 | 339 | try: | ||
568 | 340 | size = os.stat(f)[ST_SIZE] | ||
569 | 341 | except: | ||
570 | 342 | return "UNKNOWN" | ||
571 | 343 | |||
572 | 344 | if size > 1024*1024: | ||
573 | 345 | raise IOError, 'Could not open "%s" (too big)' % f | ||
574 | 346 | |||
575 | 347 | try: | ||
576 | 348 | fh = open("/etc/lsb-release", 'r') | ||
577 | 349 | except: | ||
578 | 350 | raise | ||
579 | 351 | |||
580 | 352 | lines = fh.readlines() | ||
581 | 353 | fh.close() | ||
582 | 354 | |||
583 | 355 | pat = re.compile(r'DISTRIB_CODENAME') | ||
584 | 356 | for line in lines: | ||
585 | 357 | if pat.search(line): | ||
586 | 358 | return line.split('=')[1].rstrip('\n').rstrip('\r') | ||
587 | 359 | |||
588 | 360 | return "UNKNOWN" | ||
589 | 361 | |||
590 | 362 | def cmd(command, input = None, stderr = subprocess.STDOUT, stdout = subprocess.PIPE, stdin = None, timeout = None): | ||
591 | 363 | '''Try to execute given command (array) and return its stdout, or return | ||
592 | 364 | a textual error if it failed.''' | ||
593 | 365 | |||
594 | 366 | try: | ||
595 | 367 | sp = subprocess.Popen(command, stdin=stdin, stdout=stdout, stderr=stderr, close_fds=True, preexec_fn=subprocess_setup) | ||
596 | 368 | except OSError, e: | ||
597 | 369 | return [127, str(e)] | ||
598 | 370 | |||
599 | 371 | out, outerr = sp.communicate(input) | ||
600 | 372 | # Handle redirection of stdout | ||
601 | 373 | if out == None: | ||
602 | 374 | out = '' | ||
603 | 375 | # Handle redirection of stderr | ||
604 | 376 | if outerr == None: | ||
605 | 377 | outerr = '' | ||
606 | 378 | return [sp.returncode,out+outerr] | ||
607 | 379 | |||
608 | 380 | def cmd_pipe(command1, command2, input = None, stderr = subprocess.STDOUT, stdin = None): | ||
609 | 381 | '''Try to pipe command1 into command2.''' | ||
610 | 382 | try: | ||
611 | 383 | sp1 = subprocess.Popen(command1, stdin=stdin, stdout=subprocess.PIPE, stderr=stderr, close_fds=True) | ||
612 | 384 | sp2 = subprocess.Popen(command2, stdin=sp1.stdout, stdout=subprocess.PIPE, stderr=stderr, close_fds=True) | ||
613 | 385 | except OSError, e: | ||
614 | 386 | return [127, str(e)] | ||
615 | 387 | |||
616 | 388 | out = sp2.communicate(input)[0] | ||
617 | 389 | return [sp2.returncode,out] | ||
618 | 390 | |||
619 | 391 | def cwd_has_enough_space(cdir, total_bytes): | ||
620 | 392 | '''Determine if the partition of the current working directory has 'bytes' | ||
621 | 393 | free.''' | ||
622 | 394 | rc, df_output = cmd(['df']) | ||
623 | 395 | result = 'Got exit code %d, expected %d\n' % (rc, 0) | ||
624 | 396 | if rc != 0: | ||
625 | 397 | return False | ||
626 | 398 | |||
627 | 399 | kb = total_bytes / 1024 | ||
628 | 400 | |||
629 | 401 | mounts = dict() | ||
630 | 402 | for line in df_output.splitlines(): | ||
631 | 403 | if '/' not in line: | ||
632 | 404 | continue | ||
633 | 405 | tmp = line.split() | ||
634 | 406 | mounts[tmp[5]] = int(tmp[3]) | ||
635 | 407 | |||
636 | 408 | cdir = os.getcwd() | ||
637 | 409 | while cdir != '/': | ||
638 | 410 | if not mounts.has_key(cdir): | ||
639 | 411 | cdir = os.path.dirname(cdir) | ||
640 | 412 | continue | ||
641 | 413 | if kb < mounts[cdir]: | ||
642 | 414 | return True | ||
643 | 415 | else: | ||
644 | 416 | return False | ||
645 | 417 | |||
646 | 418 | if kb < mounts['/']: | ||
647 | 419 | return True | ||
648 | 420 | |||
649 | 421 | return False | ||
650 | 422 | |||
651 | 423 | def get_md5(filename): | ||
652 | 424 | '''Gets the md5sum of the file specified''' | ||
653 | 425 | |||
654 | 426 | (rc, report) = cmd(["/usr/bin/md5sum", "-b", filename]) | ||
655 | 427 | expected = 0 | ||
656 | 428 | assert (expected == rc) | ||
657 | 429 | |||
658 | 430 | return report.split(' ')[0] | ||
659 | 431 | |||
660 | 432 | def dpkg_compare_installed_version(pkg, check, version): | ||
661 | 433 | '''Gets the version for the installed package, and compares it to the | ||
662 | 434 | specified version. | ||
663 | 435 | ''' | ||
664 | 436 | (rc, report) = cmd(["/usr/bin/dpkg", "-s", pkg]) | ||
665 | 437 | assert (rc == 0) | ||
666 | 438 | assert ("Status: install ok installed" in report) | ||
667 | 439 | installed_version = "" | ||
668 | 440 | for line in report.splitlines(): | ||
669 | 441 | if line.startswith("Version: "): | ||
670 | 442 | installed_version = line.split()[1] | ||
671 | 443 | |||
672 | 444 | assert (installed_version != "") | ||
673 | 445 | |||
674 | 446 | (rc, report) = cmd(["/usr/bin/dpkg", "--compare-versions", installed_version, check, version]) | ||
675 | 447 | assert (rc == 0 or rc == 1) | ||
676 | 448 | if rc == 0: | ||
677 | 449 | return True | ||
678 | 450 | return False | ||
679 | 451 | |||
680 | 452 | def prepare_source(source, builder, cached_src, build_src, patch_system): | ||
681 | 453 | '''Download and unpack source package, installing necessary build depends, | ||
682 | 454 | adjusting the permissions for the 'builder' user, and returning the | ||
683 | 455 | directory of the unpacked source. Patch system can be one of: | ||
684 | 456 | - cdbs | ||
685 | 457 | - dpatch | ||
686 | 458 | - quilt | ||
687 | 459 | - quiltv3 | ||
688 | 460 | - None (not the string) | ||
689 | 461 | |||
690 | 462 | This is normally used like this: | ||
691 | 463 | |||
692 | 464 | def setUp(self): | ||
693 | 465 | ... | ||
694 | 466 | self.topdir = os.getcwd() | ||
695 | 467 | self.cached_src = os.path.join(os.getcwd(), "source") | ||
696 | 468 | self.tmpdir = tempfile.mkdtemp(prefix='testlib', dir='/tmp') | ||
697 | 469 | self.builder = testlib.TestUser() | ||
698 | 470 | testlib.cmd(['chgrp', self.builder.login, self.tmpdir]) | ||
699 | 471 | os.chmod(self.tmpdir, 0775) | ||
700 | 472 | |||
701 | 473 | def tearDown(self): | ||
702 | 474 | ... | ||
703 | 475 | self.builder = None | ||
704 | 476 | self.topdir = os.getcwd() | ||
705 | 477 | if os.path.exists(self.tmpdir): | ||
706 | 478 | testlib.recursive_rm(self.tmpdir) | ||
707 | 479 | |||
708 | 480 | def test_suite_build(self): | ||
709 | 481 | ... | ||
710 | 482 | build_dir = testlib.prepare_source('foo', \ | ||
711 | 483 | self.builder, \ | ||
712 | 484 | self.cached_src, \ | ||
713 | 485 | os.path.join(self.tmpdir, \ | ||
714 | 486 | os.path.basename(self.cached_src)), | ||
715 | 487 | "quilt") | ||
716 | 488 | os.chdir(build_dir) | ||
717 | 489 | |||
718 | 490 | # Example for typical build, adjust as necessary | ||
719 | 491 | print "" | ||
720 | 492 | print " make clean" | ||
721 | 493 | rc, report = testlib.cmd(['sudo', '-u', self.builder.login, 'make', 'clean']) | ||
722 | 494 | |||
723 | 495 | print " configure" | ||
724 | 496 | rc, report = testlib.cmd(['sudo', '-u', self.builder.login, './configure', '--prefix=%s' % self.tmpdir, '--enable-debug']) | ||
725 | 497 | |||
726 | 498 | print " make (will take a while)" | ||
727 | 499 | rc, report = testlib.cmd(['sudo', '-u', self.builder.login, 'make']) | ||
728 | 500 | |||
729 | 501 | print " make check (will take a while)", | ||
730 | 502 | rc, report = testlib.cmd(['sudo', '-u', self.builder.login, 'make', 'check']) | ||
731 | 503 | expected = 0 | ||
732 | 504 | result = 'Got exit code %d, expected %d\n' % (rc, expected) | ||
733 | 505 | self.assertEquals(expected, rc, result + report) | ||
734 | 506 | |||
735 | 507 | def test_suite_cleanup(self): | ||
736 | 508 | ... | ||
737 | 509 | if os.path.exists(self.cached_src): | ||
738 | 510 | testlib.recursive_rm(self.cached_src) | ||
739 | 511 | |||
740 | 512 | It is up to the caller to clean up cached_src and build_src (as in the | ||
741 | 513 | above example, often the build_src is in a tmpdir that is cleaned in | ||
742 | 514 | tearDown() and the cached_src is cleaned in a one time clean-up | ||
743 | 515 | operation (eg 'test_suite_cleanup()) which must be run after the build | ||
744 | 516 | suite test (obviously). | ||
745 | 517 | ''' | ||
746 | 518 | |||
747 | 519 | # Make sure we have a clean slate | ||
748 | 520 | assert (os.path.exists(os.path.dirname(build_src))) | ||
749 | 521 | assert (not os.path.exists(build_src)) | ||
750 | 522 | |||
751 | 523 | cdir = os.getcwd() | ||
752 | 524 | if os.path.exists(cached_src): | ||
753 | 525 | shutil.copytree(cached_src, build_src) | ||
754 | 526 | os.chdir(build_src) | ||
755 | 527 | else: | ||
756 | 528 | # Only install the build dependencies on the initial setup | ||
757 | 529 | rc, report = cmd(['apt-get','-y','--force-yes','build-dep',source]) | ||
758 | 530 | assert (rc == 0) | ||
759 | 531 | |||
760 | 532 | os.makedirs(build_src) | ||
761 | 533 | os.chdir(build_src) | ||
762 | 534 | |||
763 | 535 | # These are always needed | ||
764 | 536 | pkgs = ['build-essential', 'dpkg-dev', 'fakeroot'] | ||
765 | 537 | rc, report = cmd(['apt-get','-y','--force-yes','install'] + pkgs) | ||
766 | 538 | assert (rc == 0) | ||
767 | 539 | |||
768 | 540 | rc, report = cmd(['apt-get','source',source]) | ||
769 | 541 | assert (rc == 0) | ||
770 | 542 | shutil.copytree(build_src, cached_src) | ||
771 | 543 | |||
772 | 544 | unpacked_dir = os.path.join(build_src, glob.glob('%s-*' % source)[0]) | ||
773 | 545 | |||
774 | 546 | # Now apply the patches. Do it here so that we don't mess up our cached | ||
775 | 547 | # sources. | ||
776 | 548 | os.chdir(unpacked_dir) | ||
777 | 549 | assert (patch_system in ['cdbs', 'dpatch', 'quilt', 'quiltv3', None]) | ||
778 | 550 | if patch_system != None and patch_system != "quiltv3": | ||
779 | 551 | if patch_system == "quilt": | ||
780 | 552 | os.environ.setdefault('QUILT_PATCHES','debian/patches') | ||
781 | 553 | rc, report = cmd(['quilt', 'push', '-a']) | ||
782 | 554 | assert (rc == 0) | ||
783 | 555 | elif patch_system == "cdbs": | ||
784 | 556 | rc, report = cmd(['./debian/rules', 'apply-patches']) | ||
785 | 557 | assert (rc == 0) | ||
786 | 558 | elif patch_system == "dpatch": | ||
787 | 559 | rc, report = cmd(['dpatch', 'apply-all']) | ||
788 | 560 | assert (rc == 0) | ||
789 | 561 | |||
790 | 562 | cmd(['chown', '-R', '%s:%s' % (builder.uid, builder.gid), build_src]) | ||
791 | 563 | os.chdir(cdir) | ||
792 | 564 | |||
793 | 565 | return unpacked_dir | ||
794 | 566 | |||
795 | 567 | def _aa_status(): | ||
796 | 568 | '''Get aa-status output''' | ||
797 | 569 | exe = "/usr/sbin/aa-status" | ||
798 | 570 | assert (os.path.exists(exe)) | ||
799 | 571 | if os.geteuid() == 0: | ||
800 | 572 | return cmd([exe]) | ||
801 | 573 | return cmd(['sudo', exe]) | ||
802 | 574 | |||
803 | 575 | def is_apparmor_loaded(path): | ||
804 | 576 | '''Check if profile is loaded''' | ||
805 | 577 | rc, report = _aa_status() | ||
806 | 578 | if rc != 0: | ||
807 | 579 | return False | ||
808 | 580 | |||
809 | 581 | for line in report.splitlines(): | ||
810 | 582 | if line.endswith(path): | ||
811 | 583 | return True | ||
812 | 584 | return False | ||
813 | 585 | |||
814 | 586 | def is_apparmor_confined(path): | ||
815 | 587 | '''Check if application is confined''' | ||
816 | 588 | rc, report = _aa_status() | ||
817 | 589 | if rc != 0: | ||
818 | 590 | return False | ||
819 | 591 | |||
820 | 592 | for line in report.splitlines(): | ||
821 | 593 | if re.search('%s \(' % path, line): | ||
822 | 594 | return True | ||
823 | 595 | return False | ||
824 | 596 | |||
825 | 597 | def check_apparmor(path, first_ubuntu_release, is_running=True): | ||
826 | 598 | '''Check if path is loaded and confined for everything higher than the | ||
827 | 599 | first Ubuntu release specified. | ||
828 | 600 | |||
829 | 601 | Usage: | ||
830 | 602 | rc, report = testlib.check_apparmor('/usr/sbin/foo', 8.04, is_running=True) | ||
831 | 603 | if rc < 0: | ||
832 | 604 | return self._skipped(report) | ||
833 | 605 | |||
834 | 606 | expected = 0 | ||
835 | 607 | result = 'Got exit code %d, expected %d\n' % (rc, expected) | ||
836 | 608 | self.assertEquals(expected, rc, result + report) | ||
837 | 609 | ''' | ||
838 | 610 | global manager | ||
839 | 611 | rc = -1 | ||
840 | 612 | |||
841 | 613 | if manager.lsb_release["Release"] < first_ubuntu_release: | ||
842 | 614 | return (rc, "Skipped apparmor check") | ||
843 | 615 | |||
844 | 616 | if not os.path.exists('/sbin/apparmor_parser'): | ||
845 | 617 | return (rc, "Skipped (couldn't find apparmor_parser)") | ||
846 | 618 | |||
847 | 619 | rc = 0 | ||
848 | 620 | msg = "" | ||
849 | 621 | if not is_apparmor_loaded(path): | ||
850 | 622 | rc = 1 | ||
851 | 623 | msg = "Profile not loaded for '%s'" % path | ||
852 | 624 | |||
853 | 625 | # this check only makes sense it the 'path' is currently executing | ||
854 | 626 | if is_running and rc == 0 and not is_apparmor_confined(path): | ||
855 | 627 | rc = 1 | ||
856 | 628 | msg = "'%s' is not running in enforce mode" % path | ||
857 | 629 | |||
858 | 630 | return (rc, msg) | ||
859 | 631 | |||
860 | 632 | def get_gcc_version(gcc, full=True): | ||
861 | 633 | gcc_version = 'none' | ||
862 | 634 | if not gcc.startswith('/'): | ||
863 | 635 | gcc = '/usr/bin/%s' % (gcc) | ||
864 | 636 | if os.path.exists(gcc): | ||
865 | 637 | gcc_version = 'unknown' | ||
866 | 638 | lines = cmd([gcc,'-v'])[1].strip().splitlines() | ||
867 | 639 | version_lines = [x for x in lines if x.startswith('gcc version')] | ||
868 | 640 | if len(version_lines) == 1: | ||
869 | 641 | gcc_version = " ".join(version_lines[0].split()[2:]) | ||
870 | 642 | if not full: | ||
871 | 643 | return gcc_version.split()[0] | ||
872 | 644 | return gcc_version | ||
873 | 645 | |||
874 | 646 | def is_kdeinit_running(): | ||
875 | 647 | '''Test if kdeinit is running''' | ||
876 | 648 | # applications that use kdeinit will spawn it if it isn't running in the | ||
877 | 649 | # test. This is a problem because it does not exit. This is a helper to | ||
878 | 650 | # check for it. | ||
879 | 651 | rc, report = cmd(['ps', 'x']) | ||
880 | 652 | if 'kdeinit4 Running' not in report: | ||
881 | 653 | print >>sys.stderr, ("kdeinit not running (you may start/stop any KDE application then run this script again)") | ||
882 | 654 | return False | ||
883 | 655 | return True | ||
884 | 656 | |||
885 | 657 | def get_pkgconfig_flags(libs=[]): | ||
886 | 658 | '''Find pkg-config flags for libraries''' | ||
887 | 659 | assert (len(libs) > 0) | ||
888 | 660 | rc, pkg_config = cmd(['pkg-config', '--cflags', '--libs'] + libs) | ||
889 | 661 | expected = 0 | ||
890 | 662 | if rc != expected: | ||
891 | 663 | print >>sys.stderr, 'Got exit code %d, expected %d\n' % (rc, expected) | ||
892 | 664 | assert(rc == expected) | ||
893 | 665 | return pkg_config.split() | ||
894 | 666 | |||
895 | 667 | class TestDaemon: | ||
896 | 668 | '''Helper class to manage daemons consistently''' | ||
897 | 669 | def __init__(self, init): | ||
898 | 670 | '''Setup daemon attributes''' | ||
899 | 671 | self.initscript = init | ||
900 | 672 | |||
901 | 673 | def start(self): | ||
902 | 674 | '''Start daemon''' | ||
903 | 675 | rc, report = cmd([self.initscript, 'start']) | ||
904 | 676 | expected = 0 | ||
905 | 677 | result = 'Got exit code %d, expected %d\n' % (rc, expected) | ||
906 | 678 | time.sleep(2) | ||
907 | 679 | if expected != rc: | ||
908 | 680 | return (False, result + report) | ||
909 | 681 | |||
910 | 682 | if "fail" in report: | ||
911 | 683 | return (False, "Found 'fail' in report\n" + report) | ||
912 | 684 | |||
913 | 685 | return (True, "") | ||
914 | 686 | |||
915 | 687 | def stop(self): | ||
916 | 688 | '''Stop daemon''' | ||
917 | 689 | rc, report = cmd([self.initscript, 'stop']) | ||
918 | 690 | expected = 0 | ||
919 | 691 | result = 'Got exit code %d, expected %d\n' % (rc, expected) | ||
920 | 692 | if expected != rc: | ||
921 | 693 | return (False, result + report) | ||
922 | 694 | |||
923 | 695 | if "fail" in report: | ||
924 | 696 | return (False, "Found 'fail' in report\n" + report) | ||
925 | 697 | |||
926 | 698 | return (True, "") | ||
927 | 699 | |||
928 | 700 | def reload(self): | ||
929 | 701 | '''Reload daemon''' | ||
930 | 702 | rc, report = cmd([self.initscript, 'force-reload']) | ||
931 | 703 | expected = 0 | ||
932 | 704 | result = 'Got exit code %d, expected %d\n' % (rc, expected) | ||
933 | 705 | if expected != rc: | ||
934 | 706 | return (False, result + report) | ||
935 | 707 | |||
936 | 708 | if "fail" in report: | ||
937 | 709 | return (False, "Found 'fail' in report\n" + report) | ||
938 | 710 | |||
939 | 711 | return (True, "") | ||
940 | 712 | |||
941 | 713 | def restart(self): | ||
942 | 714 | '''Restart daemon''' | ||
943 | 715 | (res, str) = self.stop() | ||
944 | 716 | if not res: | ||
945 | 717 | return (res, str) | ||
946 | 718 | |||
947 | 719 | (res, str) = self.start() | ||
948 | 720 | if not res: | ||
949 | 721 | return (res, str) | ||
950 | 722 | |||
951 | 723 | return (True, "") | ||
952 | 724 | |||
953 | 725 | def status(self): | ||
954 | 726 | '''Check daemon status''' | ||
955 | 727 | rc, report = cmd([self.initscript, 'status']) | ||
956 | 728 | expected = 0 | ||
957 | 729 | result = 'Got exit code %d, expected %d\n' % (rc, expected) | ||
958 | 730 | if expected != rc: | ||
959 | 731 | return (False, result + report) | ||
960 | 732 | |||
961 | 733 | if "fail" in report: | ||
962 | 734 | return (False, "Found 'fail' in report\n" + report) | ||
963 | 735 | |||
964 | 736 | return (True, "") | ||
965 | 737 | |||
966 | 738 | class TestlibManager(object): | ||
967 | 739 | '''Singleton class used to set up per-test-run information''' | ||
968 | 740 | def __init__(self): | ||
969 | 741 | # Set glibc aborts to dump to stderr instead of the tty so test output | ||
970 | 742 | # is more sane. | ||
971 | 743 | os.environ.setdefault('LIBC_FATAL_STDERR_','1') | ||
972 | 744 | |||
973 | 745 | # check verbosity | ||
974 | 746 | self.verbosity = False | ||
975 | 747 | if (len(sys.argv) > 1 and '-v' in sys.argv[1:]): | ||
976 | 748 | self.verbosity = True | ||
977 | 749 | |||
978 | 750 | # Load LSB release file | ||
979 | 751 | self.lsb_release = dict() | ||
980 | 752 | if not os.path.exists('/usr/bin/lsb_release') and not os.path.exists('/bin/lsb_release'): | ||
981 | 753 | raise OSError, "Please install 'lsb-release'" | ||
982 | 754 | for line in subprocess.Popen(['lsb_release','-a'],stdout=subprocess.PIPE,stderr=subprocess.PIPE).communicate()[0].splitlines(): | ||
983 | 755 | field, value = line.split(':',1) | ||
984 | 756 | value=value.strip() | ||
985 | 757 | field=field.strip() | ||
986 | 758 | # Convert numerics | ||
987 | 759 | try: | ||
988 | 760 | value = float(value) | ||
989 | 761 | except: | ||
990 | 762 | pass | ||
991 | 763 | self.lsb_release.setdefault(field,value) | ||
992 | 764 | |||
993 | 765 | # FIXME: hack OEM releases into known-Ubuntu versions | ||
994 | 766 | if self.lsb_release['Distributor ID'] == "HP MIE (Mobile Internet Experience)": | ||
995 | 767 | if self.lsb_release['Release'] == 1.0: | ||
996 | 768 | self.lsb_release['Distributor ID'] = "Ubuntu" | ||
997 | 769 | self.lsb_release['Release'] = 8.04 | ||
998 | 770 | else: | ||
999 | 771 | raise OSError, "Unknown version of HP MIE" | ||
1000 | 772 | |||
1001 | 773 | # FIXME: hack to assume a most-recent release if we're not | ||
1002 | 774 | # running under Ubuntu. | ||
1003 | 775 | if self.lsb_release['Distributor ID'] not in ["Ubuntu","Linaro"]: | ||
1004 | 776 | self.lsb_release['Release'] = 10000 | ||
1005 | 777 | # Adjust Linaro release to pretend to be Ubuntu | ||
1006 | 778 | if self.lsb_release['Distributor ID'] in ["Linaro"]: | ||
1007 | 779 | self.lsb_release['Distributor ID'] = "Ubuntu" | ||
1008 | 780 | self.lsb_release['Release'] -= 0.01 | ||
1009 | 781 | |||
1010 | 782 | # Load arch | ||
1011 | 783 | if not os.path.exists('/usr/bin/dpkg'): | ||
1012 | 784 | machine = cmd(['uname','-m'])[1].strip() | ||
1013 | 785 | if machine.endswith('86'): | ||
1014 | 786 | self.dpkg_arch = 'i386' | ||
1015 | 787 | elif machine.endswith('_64'): | ||
1016 | 788 | self.dpkg_arch = 'amd64' | ||
1017 | 789 | elif machine.startswith('arm'): | ||
1018 | 790 | self.dpkg_arch = 'armel' | ||
1019 | 791 | else: | ||
1020 | 792 | raise ValueError, "Unknown machine type '%s'" % (machine) | ||
1021 | 793 | else: | ||
1022 | 794 | self.dpkg_arch = cmd(['dpkg','--print-architecture'])[1].strip() | ||
1023 | 795 | |||
1024 | 796 | # Find kernel version | ||
1025 | 797 | self.kernel_is_ubuntu = False | ||
1026 | 798 | self.kernel_version_signature = None | ||
1027 | 799 | self.kernel_version = cmd(["uname","-r"])[1].strip() | ||
1028 | 800 | versig = '/proc/version_signature' | ||
1029 | 801 | if os.path.exists(versig): | ||
1030 | 802 | self.kernel_is_ubuntu = True | ||
1031 | 803 | self.kernel_version_signature = file(versig).read().strip() | ||
1032 | 804 | self.kernel_version_ubuntu = self.kernel_version | ||
1033 | 805 | elif os.path.exists('/usr/bin/dpkg'): | ||
1034 | 806 | # this can easily be inaccurate but is only an issue for Dapper | ||
1035 | 807 | rc, out = cmd(['dpkg','-l','linux-image-%s' % (self.kernel_version)]) | ||
1036 | 808 | if rc == 0: | ||
1037 | 809 | self.kernel_version_signature = out.strip().split('\n').pop().split()[2] | ||
1038 | 810 | self.kernel_version_ubuntu = self.kernel_version_signature | ||
1039 | 811 | if self.kernel_version_signature == None: | ||
1040 | 812 | # Attempt to fall back to something for non-Debian-based | ||
1041 | 813 | self.kernel_version_signature = self.kernel_version | ||
1042 | 814 | self.kernel_version_ubuntu = self.kernel_version | ||
1043 | 815 | # Build ubuntu version without hardware suffix | ||
1044 | 816 | try: | ||
1045 | 817 | self.kernel_version_ubuntu = "-".join([x for x in self.kernel_version_signature.split(' ')[1].split('-') if re.search('^[0-9]', x)]) | ||
1046 | 818 | except: | ||
1047 | 819 | pass | ||
1048 | 820 | |||
1049 | 821 | # Find gcc version | ||
1050 | 822 | self.gcc_version = get_gcc_version('gcc') | ||
1051 | 823 | |||
1052 | 824 | # Find libc | ||
1053 | 825 | self.path_libc = [x.split()[2] for x in cmd(['ldd','/bin/ls'])[1].splitlines() if x.startswith('\tlibc.so.')][0] | ||
1054 | 826 | |||
1055 | 827 | # Report self | ||
1056 | 828 | if self.verbosity: | ||
1057 | 829 | kernel = self.kernel_version_ubuntu | ||
1058 | 830 | if kernel != self.kernel_version_signature: | ||
1059 | 831 | kernel += " (%s)" % (self.kernel_version_signature) | ||
1060 | 832 | print >>sys.stdout, "Running test: '%s' distro: '%s %.2f' kernel: '%s' arch: '%s' uid: %d/%d SUDO_USER: '%s')" % ( \ | ||
1061 | 833 | sys.argv[0], | ||
1062 | 834 | self.lsb_release['Distributor ID'], | ||
1063 | 835 | self.lsb_release['Release'], | ||
1064 | 836 | kernel, | ||
1065 | 837 | self.dpkg_arch, | ||
1066 | 838 | os.geteuid(), os.getuid(), | ||
1067 | 839 | os.environ.get('SUDO_USER', '')) | ||
1068 | 840 | sys.stdout.flush() | ||
1069 | 841 | |||
1070 | 842 | # Additional heuristics | ||
1071 | 843 | #if os.environ.get('SUDO_USER', os.environ.get('USER', '')) in ['mdeslaur']: | ||
1072 | 844 | # sys.stdout.write("Replying to Marc Deslauriers in http://launchpad.net/bugs/%d: " % random.randint(600000, 980000)) | ||
1073 | 845 | # sys.stdout.flush() | ||
1074 | 846 | # time.sleep(0.5) | ||
1075 | 847 | # sys.stdout.write("destroyed\n") | ||
1076 | 848 | # time.sleep(0.5) | ||
1077 | 849 | |||
1078 | 850 | def hello(self, msg): | ||
1079 | 851 | print >>sys.stderr, "Hello from %s" % (msg) | ||
1080 | 852 | # The central instance | ||
1081 | 853 | manager = TestlibManager() | ||
1082 | 854 | |||
1083 | 855 | class TestlibCase(unittest.TestCase): | ||
1084 | 856 | def __init__(self, *args): | ||
1085 | 857 | '''This is called for each TestCase test instance, which isn't much better | ||
1086 | 858 | than SetUp.''' | ||
1087 | 859 | |||
1088 | 860 | unittest.TestCase.__init__(self, *args) | ||
1089 | 861 | |||
1090 | 862 | # Attach to and duplicate dicts from manager singleton | ||
1091 | 863 | self.manager = manager | ||
1092 | 864 | #self.manager.hello(repr(self) + repr(*args)) | ||
1093 | 865 | self.my_verbosity = self.manager.verbosity | ||
1094 | 866 | self.lsb_release = self.manager.lsb_release | ||
1095 | 867 | self.dpkg_arch = self.manager.dpkg_arch | ||
1096 | 868 | self.kernel_version = self.manager.kernel_version | ||
1097 | 869 | self.kernel_version_signature = self.manager.kernel_version_signature | ||
1098 | 870 | self.kernel_version_ubuntu = self.manager.kernel_version_ubuntu | ||
1099 | 871 | self.kernel_is_ubuntu = self.manager.kernel_is_ubuntu | ||
1100 | 872 | self.gcc_version = self.manager.gcc_version | ||
1101 | 873 | self.path_libc = self.manager.path_libc | ||
1102 | 874 | |||
1103 | 875 | def version_compare(self, one, two): | ||
1104 | 876 | return apt_pkg.VersionCompare(one,two) | ||
1105 | 877 | |||
1106 | 878 | def assertFileType(self, filename, filetype): | ||
1107 | 879 | '''Checks the file type of the file specified''' | ||
1108 | 880 | |||
1109 | 881 | (rc, report, out) = self._testlib_shell_cmd(["/usr/bin/file", "-b", filename]) | ||
1110 | 882 | out = out.strip() | ||
1111 | 883 | expected = 0 | ||
1112 | 884 | # Absolutely no idea why this happens on Hardy | ||
1113 | 885 | if self.lsb_release['Release'] == 8.04 and rc == 255 and len(out) > 0: | ||
1114 | 886 | rc = 0 | ||
1115 | 887 | result = 'Got exit code %d, expected %d:\n%s\n' % (rc, expected, report) | ||
1116 | 888 | self.assertEquals(expected, rc, result) | ||
1117 | 889 | |||
1118 | 890 | filetype = '^%s$' % (filetype) | ||
1119 | 891 | result = 'File type reported by file: [%s], expected regex: [%s]\n' % (out, filetype) | ||
1120 | 892 | self.assertNotEquals(None, re.search(filetype, out), result) | ||
1121 | 893 | |||
1122 | 894 | def yank_commonname_from_cert(self, certfile): | ||
1123 | 895 | '''Extract the commonName from a given PEM''' | ||
1124 | 896 | rc, out = cmd(['openssl','asn1parse','-in',certfile]) | ||
1125 | 897 | if rc == 0: | ||
1126 | 898 | ready = False | ||
1127 | 899 | for line in out.splitlines(): | ||
1128 | 900 | if ready: | ||
1129 | 901 | return line.split(':')[-1] | ||
1130 | 902 | if ':commonName' in line: | ||
1131 | 903 | ready = True | ||
1132 | 904 | return socket.getfqdn() | ||
1133 | 905 | |||
1134 | 906 | def announce(self, text): | ||
1135 | 907 | if self.my_verbosity: | ||
1136 | 908 | print >>sys.stdout, "(%s) " % (text), | ||
1137 | 909 | sys.stdout.flush() | ||
1138 | 910 | |||
1139 | 911 | def make_clean(self): | ||
1140 | 912 | rc, output = self.shell_cmd(['make','clean']) | ||
1141 | 913 | self.assertEquals(rc, 0, output) | ||
1142 | 914 | |||
1143 | 915 | def get_makefile_compiler(self): | ||
1144 | 916 | # Find potential compiler name | ||
1145 | 917 | compiler = 'gcc' | ||
1146 | 918 | if os.path.exists('Makefile'): | ||
1147 | 919 | for line in open('Makefile'): | ||
1148 | 920 | if line.startswith('CC') and '=' in line: | ||
1149 | 921 | items = [x.strip() for x in line.split('=')] | ||
1150 | 922 | if items[0] == 'CC': | ||
1151 | 923 | compiler = items[1] | ||
1152 | 924 | break | ||
1153 | 925 | return compiler | ||
1154 | 926 | |||
1155 | 927 | def make_target(self, target, expected=0): | ||
1156 | 928 | '''Compile a target and report output''' | ||
1157 | 929 | |||
1158 | 930 | compiler = self.get_makefile_compiler() | ||
1159 | 931 | rc, output = self.shell_cmd(['make',target]) | ||
1160 | 932 | self.assertEquals(rc, expected, 'rc(%d)!=%d:\n' % (rc, expected) + output) | ||
1161 | 933 | self.assertTrue('%s ' % (compiler) in output, 'Expected "%s":' % (compiler) + output) | ||
1162 | 934 | return output | ||
1163 | 935 | |||
1164 | 936 | # call as return testlib.skipped() | ||
1165 | 937 | def _skipped(self, reason=""): | ||
1166 | 938 | '''Provide a visible way to indicate that a test was skipped''' | ||
1167 | 939 | if reason != "": | ||
1168 | 940 | reason = ': %s' % (reason) | ||
1169 | 941 | self.announce("skipped%s" % (reason)) | ||
1170 | 942 | return False | ||
1171 | 943 | |||
1172 | 944 | def _testlib_shell_cmd(self,args,stdin=None, stdout=subprocess.PIPE, stderr=subprocess.STDOUT): | ||
1173 | 945 | argstr = "'" + "', '".join(args).strip() + "'" | ||
1174 | 946 | rc, out = cmd(args,stdin=stdin,stdout=stdout,stderr=stderr) | ||
1175 | 947 | report = 'Command: ' + argstr + '\nOutput:\n' + out | ||
1176 | 948 | return rc, report, out | ||
1177 | 949 | |||
1178 | 950 | def shell_cmd(self, args, stdin=None): | ||
1179 | 951 | return cmd(args,stdin=stdin) | ||
1180 | 952 | |||
1181 | 953 | def assertShellExitEquals(self, expected, args, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, msg=""): | ||
1182 | 954 | '''Test a shell command matches a specific exit code''' | ||
1183 | 955 | rc, report, out = self._testlib_shell_cmd(args, stdin=stdin, stdout=stdout, stderr=stderr) | ||
1184 | 956 | result = 'Got exit code %d, expected %d\n' % (rc, expected) | ||
1185 | 957 | self.assertEquals(expected, rc, msg + result + report) | ||
1186 | 958 | |||
1187 | 959 | def assertShellExitNotEquals(self, unwanted, args, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, msg=""): | ||
1188 | 960 | '''Test a shell command doesn't match a specific exit code''' | ||
1189 | 961 | rc, report, out = self._testlib_shell_cmd(args, stdin=stdin, stdout=stdout, stderr=stderr) | ||
1190 | 962 | result = 'Got (unwanted) exit code %d\n' % rc | ||
1191 | 963 | self.assertNotEquals(unwanted, rc, msg + result + report) | ||
1192 | 964 | |||
1193 | 965 | def assertShellOutputContains(self, text, args, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, msg="", invert=False): | ||
1194 | 966 | '''Test a shell command contains a specific output''' | ||
1195 | 967 | rc, report, out = self._testlib_shell_cmd(args, stdin=stdin, stdout=stdout, stderr=stderr) | ||
1196 | 968 | result = 'Got exit code %d. Looking for text "%s"\n' % (rc, text) | ||
1197 | 969 | if not invert: | ||
1198 | 970 | self.assertTrue(text in out, msg + result + report) | ||
1199 | 971 | else: | ||
1200 | 972 | self.assertFalse(text in out, msg + result + report) | ||
1201 | 973 | |||
1202 | 974 | def assertShellOutputEquals(self, text, args, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, msg="", invert=False, expected=None): | ||
1203 | 975 | '''Test a shell command matches a specific output''' | ||
1204 | 976 | rc, report, out = self._testlib_shell_cmd(args, stdin=stdin, stdout=stdout, stderr=stderr) | ||
1205 | 977 | result = 'Got exit code %d. Looking for exact text "%s" (%s)\n' % (rc, text, " ".join(args)) | ||
1206 | 978 | if not invert: | ||
1207 | 979 | self.assertEquals(text, out, msg + result + report) | ||
1208 | 980 | else: | ||
1209 | 981 | self.assertNotEquals(text, out, msg + result + report) | ||
1210 | 982 | if expected != None: | ||
1211 | 983 | result = 'Got exit code %d. Expected %d (%s)\n' % (rc, expected, " ".join(args)) | ||
1212 | 984 | self.assertEquals(rc, expected, msg + result + report) | ||
1213 | 985 | |||
1214 | 986 | def _word_find(self, report, content, invert=False): | ||
1215 | 987 | '''Check for a specific string''' | ||
1216 | 988 | if invert: | ||
1217 | 989 | warning = 'Found "%s"\n' % content | ||
1218 | 990 | self.assertTrue(content not in report, warning + report) | ||
1219 | 991 | else: | ||
1220 | 992 | warning = 'Could not find "%s"\n' % content | ||
1221 | 993 | self.assertTrue(content in report, warning + report) | ||
1222 | 994 | |||
1223 | 995 | def _test_sysctl_value(self, path, expected, msg=None, exists=True): | ||
1224 | 996 | sysctl = '/proc/sys/%s' % (path) | ||
1225 | 997 | self.assertEquals(exists, os.path.exists(sysctl), sysctl) | ||
1226 | 998 | value = None | ||
1227 | 999 | if exists: | ||
1228 | 1000 | value = int(file(sysctl).read()) | ||
1229 | 1001 | report = "%s is not %d: %d" % (sysctl, expected, value) | ||
1230 | 1002 | if msg: | ||
1231 | 1003 | report += " (%s)" % (msg) | ||
1232 | 1004 | self.assertEquals(value, expected, report) | ||
1233 | 1005 | return value | ||
1234 | 1006 | |||
1235 | 1007 | def set_sysctl_value(self, path, desired): | ||
1236 | 1008 | sysctl = '/proc/sys/%s' % (path) | ||
1237 | 1009 | self.assertTrue(os.path.exists(sysctl),"%s does not exist" % (sysctl)) | ||
1238 | 1010 | file(sysctl,'w').write(str(desired)) | ||
1239 | 1011 | self._test_sysctl_value(path, desired) | ||
1240 | 1012 | |||
1241 | 1013 | def kernel_at_least(self, introduced): | ||
1242 | 1014 | return self.version_compare(self.kernel_version_ubuntu, | ||
1243 | 1015 | introduced) >= 0 | ||
1244 | 1016 | |||
1245 | 1017 | def kernel_claims_cve_fixed(self, cve): | ||
1246 | 1018 | changelog = "/usr/share/doc/linux-image-%s/changelog.Debian.gz" % (self.kernel_version) | ||
1247 | 1019 | if os.path.exists(changelog): | ||
1248 | 1020 | for line in gzip.open(changelog): | ||
1249 | 1021 | if cve in line and not "revert" in line and not "Revert" in line: | ||
1250 | 1022 | return True | ||
1251 | 1023 | return False | ||
1252 | 1024 | |||
1253 | 1025 | class TestGroup: | ||
1254 | 1026 | '''Create a temporary test group and remove it again in the dtor.''' | ||
1255 | 1027 | |||
1256 | 1028 | def __init__(self, group=None, lower=False): | ||
1257 | 1029 | '''Create a new group''' | ||
1258 | 1030 | |||
1259 | 1031 | self.group = None | ||
1260 | 1032 | if group: | ||
1261 | 1033 | if group_exists(group): | ||
1262 | 1034 | raise ValueError, 'group name already exists' | ||
1263 | 1035 | else: | ||
1264 | 1036 | while(True): | ||
1265 | 1037 | group = random_string(7,lower=lower) | ||
1266 | 1038 | if not group_exists(group): | ||
1267 | 1039 | break | ||
1268 | 1040 | |||
1269 | 1041 | assert subprocess.call(['groupadd',group]) == 0 | ||
1270 | 1042 | self.group = group | ||
1271 | 1043 | g = grp.getgrnam(self.group) | ||
1272 | 1044 | self.gid = g[2] | ||
1273 | 1045 | |||
1274 | 1046 | def __del__(self): | ||
1275 | 1047 | '''Remove the created group.''' | ||
1276 | 1048 | |||
1277 | 1049 | if self.group: | ||
1278 | 1050 | rc, report = cmd(['groupdel', self.group]) | ||
1279 | 1051 | assert rc == 0 | ||
1280 | 1052 | |||
1281 | 1053 | class TestUser: | ||
1282 | 1054 | '''Create a temporary test user and remove it again in the dtor.''' | ||
1283 | 1055 | |||
1284 | 1056 | def __init__(self, login=None, home=True, group=None, uidmin=None, lower=False, shell=None): | ||
1285 | 1057 | '''Create a new user account with a random password. | ||
1286 | 1058 | |||
1287 | 1059 | By default, the login name is random, too, but can be explicitly | ||
1288 | 1060 | specified with 'login'. By default, a home directory is created, this | ||
1289 | 1061 | can be suppressed with 'home=False'.''' | ||
1290 | 1062 | |||
1291 | 1063 | self.login = None | ||
1292 | 1064 | |||
1293 | 1065 | if os.geteuid() != 0: | ||
1294 | 1066 | raise ValueError, "You must be root to run this test" | ||
1295 | 1067 | |||
1296 | 1068 | if login: | ||
1297 | 1069 | if login_exists(login): | ||
1298 | 1070 | raise ValueError, 'login name already exists' | ||
1299 | 1071 | else: | ||
1300 | 1072 | while(True): | ||
1301 | 1073 | login = 't' + random_string(7,lower=lower) | ||
1302 | 1074 | if not login_exists(login): | ||
1303 | 1075 | break | ||
1304 | 1076 | |||
1305 | 1077 | self.salt = random_string(2) | ||
1306 | 1078 | self.password = random_string(8,lower=lower) | ||
1307 | 1079 | self.crypted = crypt.crypt(self.password, self.salt) | ||
1308 | 1080 | |||
1309 | 1081 | creation = ['useradd', '-p', self.crypted] | ||
1310 | 1082 | if home: | ||
1311 | 1083 | creation += ['-m'] | ||
1312 | 1084 | if group: | ||
1313 | 1085 | creation += ['-G',group] | ||
1314 | 1086 | if uidmin: | ||
1315 | 1087 | creation += ['-K','UID_MIN=%d'%uidmin] | ||
1316 | 1088 | if shell: | ||
1317 | 1089 | creation += ['-s',shell] | ||
1318 | 1090 | creation += [login] | ||
1319 | 1091 | assert subprocess.call(creation) == 0 | ||
1320 | 1092 | # Set GECOS | ||
1321 | 1093 | assert subprocess.call(['usermod','-c','Buddy %s' % (login),login]) == 0 | ||
1322 | 1094 | |||
1323 | 1095 | self.login = login | ||
1324 | 1096 | p = pwd.getpwnam(self.login) | ||
1325 | 1097 | self.uid = p[2] | ||
1326 | 1098 | self.gid = p[3] | ||
1327 | 1099 | self.gecos = p[4] | ||
1328 | 1100 | self.home = p[5] | ||
1329 | 1101 | self.shell = p[6] | ||
1330 | 1102 | |||
1331 | 1103 | def __del__(self): | ||
1332 | 1104 | '''Remove the created user account.''' | ||
1333 | 1105 | |||
1334 | 1106 | if self.login: | ||
1335 | 1107 | # sanity check the login name so we don't accidentally wipe too much | ||
1336 | 1108 | if len(self.login)>3 and not '/' in self.login: | ||
1337 | 1109 | subprocess.call(['rm','-rf', '/home/'+self.login, '/var/mail/'+self.login]) | ||
1338 | 1110 | rc, report = cmd(['userdel', '-f', self.login]) | ||
1339 | 1111 | assert rc == 0 | ||
1340 | 1112 | |||
1341 | 1113 | def add_to_group(self, group): | ||
1342 | 1114 | '''Add user to the specified group name''' | ||
1343 | 1115 | rc, report = cmd(['usermod', '-G', group, self.login]) | ||
1344 | 1116 | if rc != 0: | ||
1345 | 1117 | print report | ||
1346 | 1118 | assert rc == 0 | ||
1347 | 1119 | |||
1348 | 1120 | # Timeout handler using alarm() from John P. Speno's Pythonic Avocado | ||
1349 | 1121 | class TimeoutFunctionException(Exception): | ||
1350 | 1122 | """Exception to raise on a timeout""" | ||
1351 | 1123 | pass | ||
1352 | 1124 | class TimeoutFunction: | ||
1353 | 1125 | def __init__(self, function, timeout): | ||
1354 | 1126 | self.timeout = timeout | ||
1355 | 1127 | self.function = function | ||
1356 | 1128 | |||
1357 | 1129 | def handle_timeout(self, signum, frame): | ||
1358 | 1130 | raise TimeoutFunctionException() | ||
1359 | 1131 | |||
1360 | 1132 | def __call__(self, *args, **kwargs): | ||
1361 | 1133 | old = signal.signal(signal.SIGALRM, self.handle_timeout) | ||
1362 | 1134 | signal.alarm(self.timeout) | ||
1363 | 1135 | try: | ||
1364 | 1136 | result = self.function(*args, **kwargs) | ||
1365 | 1137 | finally: | ||
1366 | 1138 | signal.signal(signal.SIGALRM, old) | ||
1367 | 1139 | signal.alarm(0) | ||
1368 | 1140 | return result | ||
1369 | 1141 | |||
1370 | 1142 | def main(): | ||
1371 | 1143 | print "hi" | ||
1372 | 1144 | unittest.main() |
LGTM - uploading.