summaryrefslogtreecommitdiffstats
path: root/ipalib/tests/test_base.py
blob: f11f1f4f488d1093c087cee59548a1064df97c54 (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
# Authors:
#   Jason Gerard DeRose <jderose@redhat.com>
#
# Copyright (C) 2008  Red Hat
# see file 'COPYING' for use and warranty information
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; version 2 only
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

"""
Unit tests for `ipalib.base` module.
"""

from ipalib import base, exceptions, crud


def read_only(obj, name):
	"""
	Check that a given property is read-only.
	Returns the value of the property.
	"""
	assert isinstance(obj, object)
	assert hasattr(obj, name)
	raised = False
	try:
		setattr(obj, name, 'some new obj')
	except AttributeError:
		raised = True
	assert raised
	return getattr(obj, name)


class ClassChecker(object):
	cls = None # Override this is subclasses

	def new(self, *args, **kw):
		return self.cls(*args, **kw)

	def args(self):
		return []

	def kw(self):
		return {}

	def std(self):
		return self.new(*self.args(), **self.kw())


class test_NameSpace:
	"""
	Unit tests for `NameSpace` class.
	"""

	def	ns(self, kw):
		"""
		Returns a new NameSpace instance.
		"""
		return base.NameSpace(kw)

	def kw(self):
		"""
		Returns standard test kw dict suitable for passing to
		NameSpace.__init__().
		"""
		return dict(
			attr_a='Hello',
			attr_b='all',
			attr_c='yall!',
		)

	def std(self):
		"""
		Returns standard (kw, ns) tuple.
		"""
		kw = self.kw()
		ns = self.ns(kw)
		return (kw, ns)

	def test_public(self):
		"""
		Tests that a NameSpace instance created with empty dict has no public
		attributes (that would then conflict with names we want to assign to
		the NameSpace). Also tests that a NameSpace instance created with a
		non-empty dict has no unexpected public methods.
		"""
		ns = self.ns({})
		assert list(ns) == []
		assert len(ns) == 0
		for name in dir(ns):
			assert name.startswith('__') or name.startswith('_NameSpace__')
		(kw, ns) = self.std()
		keys = set(kw)
		for name in dir(ns):
			assert (
				name.startswith('__') or
				name.startswith('_NameSpace__') or
				name in keys
			)

	def test_dict_vs_attr(self):
		"""
		Tests that NameSpace.__getitem__() and NameSpace.__getattr__() return
		the same values.
		"""
		(kw, ns) = self.std()
		assert len(kw) > 0
		assert len(kw) == len(list(ns))
		for (key, val) in kw.items():
			assert ns[key] is val
			assert getattr(ns, key) is val

	def test_setattr(self):
		"""
		Tests that attributes cannot be set on NameSpace instance.
		"""
		(kw, ns) = self.std()
		value = 'new value'
		for key in kw:
			raised = False
			try:
				setattr(ns, key, value)
			except exceptions.SetError:
				raised = True
			assert raised
			assert getattr(ns, key, None) != value
			assert ns[key] != value

	def test_setitem(self):
		"""
		Tests that attributes cannot be set via NameSpace dict interface.
		"""
		(kw, ns) = self.std()
		value = 'new value'
		for key in kw:
			raised = False
			try:
				ns[key] = value
			except TypeError:
				raised = True
			assert raised
			assert getattr(ns, key, None) != value
			assert ns[key] != value

	def test_hasitem(self):
		"""
		Test __hasitem__() membership method.
		"""
		(kw, ns) = self.std()
		nope = [
			'attr_d',
			'attr_e',
			'whatever',
		]
		for key in kw:
			assert key in ns
		for key in nope:
			assert key not in kw
			assert key not in ns

	def test_iter(self):
		"""
		Tests that __iter__() method returns sorted list of attribute names.
		"""
		(kw, ns) = self.std()
		assert list(ns) == sorted(kw)
		assert [ns[k] for k in ns] == ['Hello', 'all', 'yall!']

	def test_len(self):
		"""
		Test __len__() method.
		"""
		(kw, ns) = self.std()
		assert len(kw) == len(ns) == 3


def test_Named():
	class named_class(base.Named):
		pass

	i = named_class()
	assert i.name == 'named_class'


def test_Attribute():
	class user__add(base.Attribute):
		pass
	i = user__add()
	assert i.obj_name == 'user'
	assert i.attr_name == 'add'
	assert i.obj is None
	class user(base.Object):
		pass
	u = user()
	i.obj = u
	assert i.obj is u
	raised = False
	try:
		i.obj = u
	except exceptions.TwiceSetError:
		raised = True
	assert raised


def test_Method():
	class user__mod(base.Method):
		pass
	i = user__mod()
	assert isinstance(i, base.Attribute)
	assert isinstance(i, base.AbstractCommand)
	assert i.obj_name == 'user'
	assert i.attr_name == 'mod'
	assert i.name == 'mod_user'


def test_Property():
	class user__firstname(base.Property):
		pass
	i = user__firstname()
	assert isinstance(i, base.Attribute)
	assert i.obj_name == 'user'
	assert i.attr_name == 'firstname'
	assert i.name == 'firstname'


def test_Command():
	class dostuff(base.Command):
		pass
	i = dostuff()
	assert isinstance(i, base.AbstractCommand)
	assert i.name == 'dostuff'



def test_AttributeCollector():
	class user__add(base.Attribute):
		pass
	class user__mod(base.Attribute):
		pass
	class group__add(base.Attribute):
		pass
	u_a = user__add()
	u_m = user__mod()
	g_a = group__add()

	ac = base.AttributeCollector()
	ac.add(u_a)
	ac.add(u_m)
	ac.add(g_a)

	assert set(ac) == set(['user', 'group'])

	u = ac['user']
	assert set(u) == set(['add', 'mod'])
	assert set(u.values()) == set([u_a, u_m])

	g = ac['group']
	assert g.keys() == ['add']
	assert g.values() == [g_a]


def test_Collector():
	class user(base.Object):
		pass
	class group(base.Object):
		pass
	u = user()
	g = group()
	c = base.Collector()
	c.add(u)
	c.add(g)
	ns = c.ns()
	assert isinstance(ns, base.NameSpace)
	assert set(ns) == set(['user', 'group'])
	assert ns.user is u
	assert ns.group is g





def test_Registar():
	class kinit(base.Command):
		pass
	class user__add(base.Method):
		pass
	class user__del(base.Method):
		pass
	class user__firstname(base.Property):
		pass
	class user__lastname(base.Property):
		pass
	class user__login(base.Property):
		pass
	class user(base.Object):
		pass
	class group(base.Object):
		pass

	r = base.Registrar()
	assert read_only(r, 'objects') is None
	assert read_only(r, 'commands') is None


	r.register(kinit)
	r.register(user__add)
	r.register(user__del)
	r.register(user__firstname)
	r.register(user__lastname)
	r.register(user__login)
	r.register(user)
	r.register(group)

	r.finalize()

	objects = read_only(r, 'objects')
	assert isinstance(objects, base.NameSpace)
	assert len(objects) == 2
	assert list(objects) == ['group', 'user']
	assert type(objects.user) is user
	assert type(objects.group) is group

	u = objects.user
	assert len(u.methods) == 2
	assert list(u.methods) == ['add', 'del']
	assert len(u.properties) == 3
	assert list(u.properties) == ['firstname', 'lastname', 'login']

	for m in u.methods():
		assert m.obj is u
	for p in u.properties():
		assert p.obj is u

	g = objects.group
	assert len(g.methods) == 0
	assert len(g.properties) == 0


	assert len(r.commands) == 3
	assert list(r.commands) == sorted(['kinit', 'add_user', 'del_user'])


class test_Register():
	r = base.Register()

	assert set(r) == set(['Command', 'Object', 'Method', 'Property'])


	class wrong_base(object):
		pass

	class krbtest(base.Command):
		pass

	class user(base.Object):
		pass

	class user__add(base.Method):
		pass

	class user__firstname(base.Property):
		pass




	#r(wrong_base)
	#r(user())

	# Check that exception is raised trying to register an instance of a
	# class of a correct base:
	raised = False
	try:
		r(user())
	except exceptions.RegistrationError:
		raised = True

	# Check that exception is raised trying to register class of wrong base:
	raised = False
	try:
		r(wrong_base)
	except exceptions.RegistrationError:
		raised = True
	assert raised

	# Check that added a valid class works
	for cls in (krbtest, user, user__add, user__firstname):
		r(cls)
		key = cls.__bases__[0].__name__
		d = r[key]
		assert d.keys() == [cls.__name__]
		assert d.values() == [cls]
		# Check that a copy is returned
		d2 = r[key]
		assert d2 == d
		assert d2 is not d
		p = getattr(r, key)
		assert isinstance(p, base.Proxy)
		# Check that same instance is returned
		assert p is getattr(r, key)
		assert getattr(p, cls.__name__) is cls