aboutsummaryrefslogtreecommitdiff
blob: 00a6cd49d7d30f1f52436fcb66354dfae0d614a4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
#	vim:fileencoding=utf-8
# (c) 2011 Michał Górny <mgorny@gentoo.org>
# Released under the terms of the 2-clause BSD license.

import copy, itertools, random, re
from gentoopm.util import ABCObject, BoolCompat

from abc import ABCMeta, abstractmethod, abstractproperty

# XXX: move to some consts module?
phase_func_names = [
	'pkg_pretend', 'pkg_setup', 'src_unpack', 'src_prepare',
	'src_configure', 'src_compile', 'src_install',
	'pkg_preinst', 'pkg_postinst'
]

""" Names of all phase functions supported in EAPIs. """

known_eapis = frozenset((0, 1, 2, 3, 4))

""" All known EAPIs. """

ebuild_header = '''# Copyright 1999-2011 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
# $Header: $

EAPI=%d

inherit %s

'''

""" A common ebuild header. """

pn_re = re.compile('([^A-Z])([A-Z])')

def cleanup_test_case_name(classname):
	"""
	Create the ebuild PN from classname.

	>>> cleanup_test_case_name('Testzor')
	'testzor'
	>>> cleanup_test_case_name('TestzorTest')
	'testzor'
	>>> cleanup_test_case_name('TestZorTest')
	'test-zor'
	>>> cleanup_test_case_name('veryRandomCamelCaseTest')
	'very-random-camel-case'
	>>> cleanup_test_case_name('RDependTest')
	'rdepend'

	@param classname: the class name to clean up
	@type classname: string
	"""

	if classname.endswith('Test'):
		classname = classname[:-4]
	return pn_re.sub('\\1-\\2', classname).lower()

class AssertionResult(ABCObject, BoolCompat):
	def __init__(self, name):
		self._name = name
		self._undefined = False

	@property
	def name(self):
		return self._name

	@property
	def prefix(self):
		return None

	@property
	def unprefixed_name(self):
		return self.name

	@property
	def undefined(self):
		return self._undefined

	@abstractproperty
	def expected(self):
		pass

	@abstractproperty
	def actual(self):
		pass

	@abstractmethod
	def __bool__(self):
		pass

	def __str__(self):
		return '%s == %s' % (self.actual, self.expected)

class BoolAssertionResult(AssertionResult):
	def __init__(self, name, expect, cond):
		AssertionResult.__init__(self, name)
		self._expect = bool(expect)
		self._cond = bool(cond) if cond is not None else None

	@property
	def expected(self):
		return self._expect

	@property
	def actual(self):
		return self._cond if self._cond is not None else '?'

	def __bool__(self):
		if self._cond is None:
			return False
		return self._expect == self._cond

class ContainsAssertionResult(AssertionResult):
	def __init__(self, name, needle, container):
		AssertionResult.__init__(self, name)
		self._cont = container
		self._need = needle

	@property
	def expected(self):
		return 'contains %s' % repr(self._need)

	@property
	def actual(self):
		return repr(self._cont) if self._cont is not None else '?'

	def __str__(self):
		return '%s %s' % (self.actual, self.expected)

	def __bool__(self):
		if self._cont is None:
			return False
		return self._need in self._cont

class EqualAssertionResult(AssertionResult):
	def __init__(self, name, expect, value):
		AssertionResult.__init__(self, name)
		self._expect = expect
		self._value = value

	@property
	def expected(self):
		return repr(self._expect)

	@property
	def actual(self):
		return repr(self._value) if self._value is not None else '?'

	def __bool__(self):
		return self._expect == self._value

class NotEqualAssertionResult(EqualAssertionResult):
	def __bool__(self):
		if self._value is None:
			return False
		return self._expect != self._value

	@property
	def expected(self):
		return 'not %s' % repr(self._expect)

	def __str__(self):
		return '%s != %s' % (self.actual,
				repr(self._expect))

class TestCase(ABCObject):
	"""
	Base class for a test case.

	@ivar _finalized: has the case initialization been finished yet?
		Set by L{_finalize()}.
	@type _finalized: bool
	"""

	_finalized = False

	def __init__(self, short_name):
		self.assertions = []
		self._short_name = short_name

	@property
	def short_name(self):
		return self._short_name

	@property
	def _stripped_docstring(self):
		descdoc = ' '.join(self.__doc__.split())
		return descdoc.rstrip('.')

	def __str__(self):
		""" Return freetext test description. """
		return '%s (%s)' % (self.short_name, self._stripped_docstring)

	def _finalize(self):
		"""
		Do any final modifications to test case data. Mark it finalized.
		This function shall be called at most once per object.
		"""
		self._finalized = True

	@abstractmethod
	def get_output_files(self):
		"""
		Get a dict of files to output in the repository for the test case.

		@return: a dict where keys are file paths (relative to the repository
			root), and values evaluate to file contents
		@rtype: dict (string -> stringifiable)
		"""
		pass

	@abstractmethod
	def clean(self, pm):
		"""
		Schedule cleaning the test.

		@param pm: the package manager instance
		@type pm: L{PackageManager}
		"""
		pass

	@abstractmethod
	def start(self, pm):
		"""
		Schedule starting the test.

		@param pm: the package manager instance
		@type pm: L{PackageManager}
		"""
		pass

	def _append_assert(self, a, undefined = False):
		all_eapis = itertools.chain.from_iterable(self.supported_eapis)
		if undefined or self.eapi not in all_eapis:
			a._undefined = True

		self.assertions.append(a)
		if not a.undefined and not a:
			raise AssertionError(str(a))

	def assertTrue(self, cond, msg, undefined = False):
		"""
		Assert that the condition evaluates to True.

		@param cond: the condition
		@type cond: bool
		@param msg: assertion description
		@type msg: string
		@param undefined: whether the result is undefined
		@type undefined: bool
		"""
		self.assertBool(True, cond, msg, undefined)

	def assertFalse(self, cond, msg, undefined = False):
		"""
		Assert that the condition evaluates to False.

		@param cond: the condition
		@type cond: bool
		@param msg: assertion description
		@type msg: string
		@param undefined: whether the result is undefined
		@type undefined: bool
		"""
		self.assertBool(False, cond, msg, undefined)

	def assertBool(self, expect, cond, msg, undefined = False):
		"""
		Assert that the condition evaluates to expected boolean result.

		@param expect: expected result
		@type expect: bool
		@param cond: the condition
		@type cond: bool
		@param msg: assertion description
		@type msg: string
		@param undefined: whether the result is undefined
		@type undefined: bool
		"""
		self._append_assert(BoolAssertionResult(msg, expect, cond),
				undefined = undefined)

	def assertContains(self, needle, container, msg = None, undefined = False):
		"""
		Assert the following condition: C{needle in container}.

		@param needle: the needle to look for
		@type needle: any
		@param container: the container to look for needle in
		@type container: iterable
		@param msg: assertion description or C{None} for default one
		@type msg: string/C{None}
		@param undefined: whether the result is undefined
		@type undefined: bool
		"""
		if msg is None:
			msg = '%s in %s' % (repr(needle), repr(container))
		self._append_assert(ContainsAssertionResult(msg, needle, container),
				undefined = undefined)

	def assertEqual(self, value, expect, msg, undefined = False):
		"""
		Assert that the value is equal to expected one.

		@param value: the actual value
		@type value: any
		@param expect: the expected value
		@type expect: any
		@param msg: assertion description
		@type msg: string
		@param undefined: whether the result is undefined
		@type undefined: bool
		"""
		self._append_assert(EqualAssertionResult(msg, expect, value),
				undefined = undefined)

	def assertNotEqual(self, value, unallowed, msg, undefined = False):
		"""
		Assert that the value is other than an unallowed one.

		@param value: the actual value
		@type value: any
		@param expect: the unallowed value
		@type expect: any
		@param msg: assertion description
		@type msg: string
		@param undefined: whether the result is undefined
		@type undefined: bool
		"""
		self._append_assert(NotEqualAssertionResult(msg, unallowed, value),
				undefined = undefined)

	@abstractmethod
	def check_result(self, pm):
		"""
		Check the correctness of the result of test execution.

		@param pm: the package manager instance
		@type pm: L{PackageManager}

		@return: True if the test succeeded, False otherwise
		@rtype: bool
		"""
		pass

	def pop_assertions(self):
		"""
		Get a copy of the assertion list and clear its container afterwards.
		This way, the test case can be reused with other PM.

		@return: assertion list
		@rtype: list(L{AssertionResult})
		"""

		ret = self.assertions
		self.assertions = []
		return ret

class EbuildTestCase(TestCase):
	"""
	Test case using a single ebuild (per EAPI).

	The __init__() function is going to clone (deepcopy()) all the instance
	variables to allow modifying them easily.

	@ivar ebuild_vars: additional global variables
	@type ebuild_vars: dict (string -> string)
	@ivar expect_failure: if set to False (the default), the test is supposed
		to merge successfully. Otherwise, the test ebuild is supposed to fail
		to merge (die)
	@type expect_failure: bool
	@ivar inherits: additional eclasses to inherit
	@type inherits: list (string)
	@ivar phase_funcs: phase function contents
	@type phase_funcs: dict (string -> list(string))
	"""

	ebuild_vars = {}
	expect_failure = False
	inherits = []
	phase_funcs = {}

	@classmethod
	def _eval_prop(cls, prop_or_obj):
		"""
		Evaluate and return the value of a property when passed a property
		object, or return the passed value otherwise.

		@param prop_or_obj: the object to process
		@type prop_or_obj: property/object
		@return: value of the property
		@rtype: object
		"""

		if isinstance(prop_or_obj, property):
			return prop_or_obj.fget(cls)
		else:
			return prop_or_obj

	@property
	def supported_eapis(cls):
		"""
		A list of EAPI groups for which the test can be run and gives
		predictible results. The EAPIs are supposed to be grouped by consistent
		behavior. Defaults to a single group with all available EAPIs.

		For example, a value of C{((1, 2), (3, 4))} would mean the test is
		available since EAPI 1, and it gives same results for EAPI 1 & 2,
		and for EAPI 3 & 4.

		@type: iterable(iterable(string))
		"""
		return (tuple(known_eapis),)

	@classmethod
	def inst_all(cls, short_name, thorough = False, undefined = False):
		"""
		Instantiate the test case, choosing a single EAPI from each EAPI group
		listed in L{supported_eapis}. If thorough mode is enabled, all EAPIs
		from each group will be used instead.

		@param thorough: whether to use the thorough mode
		@type thorough: bool
		@param undefined: whether to run tests on undefined-behavior EAPIs
		@type undefined: bool
		@return: an iterable over test case instances
		@rtype: generator(L{EbuildTestCase})
		"""

		supported_eapis = cls._eval_prop(cls.supported_eapis)

		if undefined:
			all_supp_eapis = set(itertools.chain.from_iterable(supported_eapis))
			remaining = known_eapis - all_supp_eapis
			if remaining:
				supported_eapis = tuple(supported_eapis) + (tuple(remaining),)

		if thorough:
			eapis = itertools.chain.from_iterable(supported_eapis)
		else:
			eapis = [random.choice(x) for x in supported_eapis]

		for eapi in eapis:
			yield cls(eapi = eapi, short_name = short_name)

	@property
	def pn(self):
		return cleanup_test_case_name(self.__class__.__name__)

	@property
	def pv(self):
		return self.eapi

	@property
	def p(self):
		return '%s-%s' % (self.pn, self.pv)

	@property
	def cpv(self):
		""" Return CPV for the test. """
		return 'pms-test/%s' % self.p

	def atom(self, pm):
		""" Return atom for the test. """
		return pm.Atom('=%s' % self.cpv)

	def _finalize(self):
		TestCase._finalize(self)

		if 'DESCRIPTION' not in self.ebuild_vars:
			self.ebuild_vars['DESCRIPTION'] = self._stripped_docstring

	def __str__(self):
		""" Return freetext test description. """
		return '%s:%s (%s)' % (self.short_name, self.eapi,
				self._stripped_docstring)

	def __init__(self, eapi, short_name):
		"""
		Instiantate the test case for a particular EAPI.

		@param eapi: the EAPI
		@type eapi: string
		"""
		TestCase.__init__(self, short_name)
		self.eapi = eapi

		for v in ('ebuild_vars', 'inherits', 'phase_funcs'):
			setattr(self, v, copy.deepcopy(getattr(self, v)))
		for pf in phase_func_names:
			if pf not in self.phase_funcs:
				self.phase_funcs[pf] = []

		# add KEYWORDS to the ebuild
		self.ebuild_vars['KEYWORDS'] = 'alpha amd64 arm hppa ia64 ' + \
				'm68k ~mips ppc ppc64 s390 sh sparc x86'

	def get_output_files(self):
		class EbuildTestCaseEbuildFile(object):
			""" Lazy ebuild contents evaluator for EbuildTestCase. """
			def __init__(self, parent):
				""" Instantiate the evaluator for test case <parent>. """
				assert(isinstance(parent, EbuildTestCase))
				self._parent = parent

			def __str__(self):
				""" Return the ebuild contents as string. """
				contents = [ebuild_header % (self._parent.eapi,
					' '.join(['pms-test'] + self._parent.inherits))]

				for k, v in self._parent.ebuild_vars.items():
					contents.append('%s="%s"\n' % (k, v)) # XXX: escaping

				for f, lines in self._parent.phase_funcs.items():
					if not lines:
						continue

					contents.append('\n%s() {\n' % f)
					for l in lines:
						contents.append('\t%s\n' % l) # XXX: smarter tabs
					contents.append('}\n')

				return ''.join(contents)

		if not self._finalized:
			self._finalize()

		fn = 'pms-test/%s/%s.ebuild' % (self.pn, self.p)

		return {fn: EbuildTestCaseEbuildFile(self)}

	def clean(self, pm):
		if self.atom(pm) in pm.installed:
			pm.unmerge(self.cpv)

	def start(self, pm):
		pm.merge(self.cpv)

	def check_result(self, pm):
		"""
		Check the correctness of the result of test execution. By default,
		checks whether the ebuild was actually merged.
		"""

		merged = self.atom(pm) in pm.installed
		self.assertBool(not self.expect_failure, merged,
				'package merged')