- test node group functions a little more rigorously
[plcapi.git] / Test.py
1 #!/usr/bin/env ./Shell.py
2 #
3 # Test script example
4 #
5 # Mark Huang <mlhuang@cs.princeton.edu>
6 # Copyright (C) 2006 The Trustees of Princeton University
7 #
8 # $Id: Test.py,v 1.5 2006/09/14 15:47:27 tmack Exp $
9 #
10
11 from pprint import pprint
12 from string import letters, digits, punctuation
13
14 from random import Random
15 random = Random()
16
17 import re
18
19 def randfloat(min = 0.0, max = 1.0):
20     return float(min) + (random.random() * (float(max) - float(min)))
21
22 def randint(min = 0, max = 1):
23     return int(randfloat(min, max + 1))
24
25 # See "2.2 Characters" in the XML specification:
26 #
27 # #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD]
28 # avoiding
29 # [#x7F-#x84], [#x86-#x9F], [#xFDD0-#xFDDF]
30
31 low_xml_chars  = map(unichr, [0x9, 0xA, 0xD])
32 low_xml_chars += map(unichr, xrange(0x20, 0x7F - 1))
33 low_xml_chars += map(unichr, xrange(0x84 + 1, 0x86 - 1))
34 low_xml_chars += map(unichr, xrange(0x9F + 1, 0xFF))
35 valid_xml_chars  = list(low_xml_chars)
36 valid_xml_chars += map(unichr, xrange(0xFF + 1, 0xD7FF))
37 valid_xml_chars += map(unichr, xrange(0xE000, 0xFDD0 - 1))
38 valid_xml_chars += map(unichr, xrange(0xFDDF + 1, 0xFFFD))
39
40 def randstr(length, pool = valid_xml_chars, encoding = "utf-8"):
41     sample = random.sample(pool, min(length, len(pool)))
42     while True:
43         s = u''.join(sample)
44         bytes = len(s.encode(encoding))
45         if bytes > length:
46             sample.pop()
47         elif bytes < length:
48             sample += random.sample(pool, min(length - bytes, len(pool)))
49             random.shuffle(sample)
50         else:
51             break
52     return s
53
54 def randhostname():
55     # 1. Each part begins and ends with a letter or number.
56     # 2. Each part except the last can contain letters, numbers, or hyphens.
57     # 3. Each part is between 1 and 64 characters, including the trailing dot.
58     # 4. At least two parts.
59     # 5. Last part can only contain between 2 and 6 letters.
60     hostname = 'a' + randstr(61, letters + digits + '-') + '1.' + \
61                'b' + randstr(61, letters + digits + '-') + '2.' + \
62                'c' + randstr(5, letters)
63     return hostname
64
65 def unicmp(a, b, encoding = "utf-8"):
66     """
67     When connected directly to the DB, values are returned as raw
68     8-bit strings that may need to be decoded (as UTF-8 by default) in
69     order to compare them against expected Python Unicode strings.
70     """
71     
72     is8bit = re.compile("[\x80-\xff]").search
73     if isinstance(a, str) and is8bit(a):
74         a = unicode(a, encoding)
75     if isinstance(b, str) and is8bit(b):
76         b = unicode(b, encoding)
77     return a == b
78
79 admin = {'AuthMethod': "capability",
80          'Username': config.PLC_API_MAINTENANCE_USER,
81          'AuthString': config.PLC_API_MAINTENANCE_PASSWORD,
82          'Role': "admin"}
83
84 user = {'AuthMethod': "password",
85         'Role': "user"}
86
87 pi = {'AuthMethod': "password",
88       'Role': "pi"}
89
90 tech = {'AuthMethod': "password",
91         'Role': "tech"}
92
93 # Add sites
94 site_ids = []
95 for i in range(3):
96     name = randstr(254)
97     abbreviated_name = randstr(50)
98     login_base = randstr(20, letters).lower()
99     latitude = int(randfloat(-90.0, 90.0) * 1000) / 1000.0
100     longitude = int(randfloat(-180.0, 180.0) * 1000) / 1000.0
101
102     # Add site
103     print "AdmAddSite(%s)" % login_base,
104     site_id = AdmAddSite(admin, name, abbreviated_name, login_base,
105                          {'latitude': latitude, 'longitude': longitude})
106
107     # Should return a unique site_id
108     assert site_id not in site_ids
109     site_ids.append(site_id)
110     print "=>", site_id
111
112     print "AdmGetSites(%d)" % site_id,
113     site = AdmGetSites(admin, [site_id])[0]
114     for key in 'name', 'abbreviated_name', 'login_base', 'latitude', 'longitude', 'site_id':
115         assert unicmp(site[key], locals()[key])
116     print "=> OK"
117
118 print "AdmGetSites",
119 sites = AdmGetSites(admin, site_ids)
120 assert set(site_ids) == set([site['site_id'] for site in sites])
121 print "=>", site_ids
122
123 print "AdmGetAllRoles",
124 role_ids = AdmGetAllRoles(admin)
125 roles = dict(zip(role_ids.values(), map(int, role_ids.keys())))
126 print "=>", role_ids
127
128 # Add users
129 person_ids = []
130 for auth in user, pi, tech:
131     first_name = randstr(128)
132     last_name = randstr(128)
133     # 119 + 1 + 64 + 64 + 6 = 254
134     email = randstr(119, letters + digits) + "@" + randhostname()
135     bio = randstr(254)
136     # Accounts are disabled by default
137     enabled = False
138
139     auth['Username'] = email
140     auth['AuthString'] = randstr(254)
141
142     print "AdmAddPerson(%s)" % email,
143     person_id = AdmAddPerson(admin, first_name, last_name,
144                              {'email': email, 'bio': bio,
145                               'password': auth['AuthString']})
146
147     # Should return a unique person_id
148     assert person_id not in person_ids
149     person_ids.append(person_id)
150     print "=>", person_id
151
152     # Check account
153     print "AdmGetPersons(%d)" % person_id,
154     person = AdmGetPersons(admin, [person_id])[0]
155     for key in 'first_name', 'last_name', 'bio', 'person_id', 'enabled':
156         assert unicmp(person[key], locals()[key])
157     print "=> OK"
158
159     # Enable account
160     print "AdmSetPersonEnabled(%d, True)" % person_id,
161     AdmSetPersonEnabled(admin, person_id, True)
162     person = AdmGetPersons(admin, [person_id])[0]
163     assert person['enabled']
164     print "=> OK"
165
166     # Add role
167     role_id = roles[auth['Role']]
168     print "AdmGrantRoleToPerson(%d, %d)" % (person_id, role_id),
169     AdmGrantRoleToPerson(admin, person_id, role_id)
170     print "=> OK"
171
172     print "AdmGetPersonRoles(%d)" % person_id,
173     person_roles = AdmGetPersonRoles(admin, person_id)
174     person_role_ids = map(int, person_roles.keys())
175     assert [role_id] == person_role_ids
176     person = AdmGetPersons(admin, [person_id])[0]
177     assert [role_id] == person['role_ids']
178     print "=>", person_role_ids
179
180     # Associate account with each site
181     for site_id in site_ids:
182         print "AdmAddPersonToSite(%d, %d)" % (person_id, site_id),
183         AdmAddPersonToSite(admin, person_id, site_id)
184         print "=> OK"
185
186     # Make sure it really did it
187     print "AdmGetPersonSites(%d)" % person_id,
188     person_site_ids = AdmGetPersonSites(auth, person_id)
189     assert set(site_ids) == set(person_site_ids)
190     person = AdmGetPersons(admin, [person_id])[0]
191     assert set(site_ids) == set(person['site_ids'])
192     print "=>", person_site_ids
193
194     # First site should be the primary site
195     print "AdmSetPersonPrimarySite(%d, %d)" % (person_id, person_site_ids[1]),
196     AdmSetPersonPrimarySite(auth, person_id, person_site_ids[1])
197     assert AdmGetPersonSites(auth, person_id)[0] == person_site_ids[1]
198     person = AdmGetPersons(admin, [person_id])[0]
199     assert person['site_ids'][0] == person_site_ids[1]
200     print "=> OK"
201
202 print "AdmGetPersons",
203 persons = AdmGetPersons(admin, person_ids)
204 assert set(person_ids) == set([person['person_id'] for person in persons])
205 print "=>", person_ids
206
207 # Add node groups
208 nodegroup_ids = []
209 for i in range(3):
210     name = randstr(50)
211     description = randstr(200)
212     print "AdmAddNodeGroup(%s)" % name,
213     nodegroup_id = AdmAddNodeGroup(admin, name, description)
214
215     # Should return a unique nodegroup_id
216     assert nodegroup_id not in nodegroup_ids
217     nodegroup_ids.append(nodegroup_id)
218     print "=>", nodegroup_id
219
220     # Check nodegroup
221     print "AdmGetNodeGroups(%d)" % nodegroup_id,
222     nodegroup = AdmGetNodeGroups(admin, [nodegroup_id])[0]
223     for key in 'name', 'description', 'nodegroup_id':
224         assert unicmp(nodegroup[key], locals()[key])
225     print "=> OK"
226
227     # Update node group
228     name = randstr(50)
229     description = randstr(200)
230     print "AdmUpdateNodeGroup(%s)" % name,
231     AdmUpdateNodeGroup(admin, nodegroup_id, name, description)
232     nodegroup = AdmGetNodeGroups(admin, [nodegroup_id])[0]
233     for key in 'name', 'description', 'nodegroup_id':
234         assert unicmp(nodegroup[key], locals()[key])
235     print "=> OK"
236
237 print "AdmGetNodeGroups",
238 nodegroups = AdmGetNodeGroups(admin, nodegroup_ids)
239 assert set(nodegroup_ids) == set([nodegroup['nodegroup_id'] for nodegroup in nodegroups])
240 print "=>", nodegroup_ids
241
242 # Add nodes
243 node_ids = []
244 for site_id in site_ids:
245     for i in range(3):
246         hostname = randhostname()
247         boot_state = 'inst'
248         model = randstr(255)
249
250         # Add node
251         print "AdmAddNode(%s)" % hostname,
252         node_id = AdmAddNode(admin, site_id, hostname, boot_state,
253                              {'model': model})
254
255         # Should return a unique node_id
256         assert node_id not in node_ids
257         node_ids.append(node_id)
258         print "=>", node_id
259
260         # Check node
261         print "AdmGetNodes(%d)" % node_id,
262         node = AdmGetNodes(admin, [node_id])[0]
263         for key in 'hostname', 'boot_state', 'model', 'node_id':
264             assert unicmp(node[key], locals()[key])
265         print "=> OK"
266
267         # Update node
268         hostname = randhostname()
269         model = randstr(255)
270         print "AdmUpdateNode(%s)" % hostname,
271         AdmUpdateNode(admin, node_id, {'hostname': hostname, 'model': model})
272         node = AdmGetNodes(admin, [node_id])[0]
273         for key in 'hostname', 'boot_state', 'model', 'node_id':
274             assert unicmp(node[key], locals()[key])
275         print "=> OK"
276
277         # Add to node groups
278         for nodegroup_id in nodegroup_ids:
279             print "AdmAddNodeToNodeGroup(%d, %d)" % (nodegroup_id, node_id),
280             AdmAddNodeToNodeGroup(admin, nodegroup_id, node_id)
281             print "=> OK"
282
283 print "AdmGetNodes",
284 nodes = AdmGetNodes(admin, node_ids)
285 assert set(node_ids) == set([node['node_id'] for node in nodes])
286 print "=>", node_ids
287
288 print "AdmGetSiteNodes" % site_ids,
289 site_node_ids = AdmGetSiteNodes(admin, site_ids)
290 assert set(node_ids) == set(reduce(lambda a, b: a + b, site_node_ids.values()))
291 print "=>", site_node_ids
292
293 for nodegroup_id in nodegroup_ids:
294     print "AdmGetNodeGroupNodes(%d)" % nodegroup_id,
295     nodegroup_node_ids = AdmGetNodeGroupNodes(admin, nodegroup_id)
296     assert set(nodegroup_node_ids) == set(node_ids)
297     print "=>", nodegroup_node_ids
298
299 # Delete nodes
300 for node_id in node_ids:
301     # Remove from node groups
302     for nodegroup_id in nodegroup_ids:
303         print "AdmRemoveNodeFromNodeGroup(%d, %d)" % (nodegroup_id, node_id),
304         AdmRemoveNodeFromNodeGroup(admin, nodegroup_id, node_id)
305         # Make sure it really deleted it
306         assert node_id not in AdmGetNodeGroupNodes(nodegroup_id)
307         print "=> OK"
308
309     # Delete node
310     print "AdmDeleteNode(%d)" % node_id,
311     AdmDeleteNode(admin, node_id)
312     assert not AdmGetNodes(admin, [node_id])
313
314     # Make sure it really deleted it
315     nodes = AdmGetNodes(admin, node_ids)
316     assert node_id not in [node['node_id'] for node in nodes]
317     print "=> OK"
318
319 print "AdmGetNodes",
320 assert not AdmGetNodes(admin, node_ids)
321 print "=> []"
322
323 for nodegroup_id in nodegroup_ids:
324     print "AdmGetNodeGroupNodes(%d)" % nodegroup_id,
325     assert not AdmGetNodeGroupNodes(nodegroup_id)
326     print "=> []"
327
328 # Delete users
329 for person_id in person_ids:
330     # Remove from each site
331     for site_id in site_ids:
332         print "AdmRemovePersonFromSite(%d, %d)" % (person_id, site_id),
333         AdmRemovePersonFromSite(admin, person_id, site_id)
334         assert site_id not in AdmGetPersonSites(admin, person_id)
335         person = AdmGetPersons(admin, [person_id])[0]
336         assert site_id not in person['site_ids']
337         print "=> OK"
338
339     assert not AdmGetPersonSites(admin, person_id)
340
341     # Revoke role
342     person_roles = AdmGetPersonRoles(admin, person_id)
343     role_id = int(person_roles.keys()[0])
344     print "AdmRevokeRoleFromPerson(%d, %d)" % (person_id, role_id),
345     AdmRevokeRoleFromPerson(admin, person_id, role_id)
346     assert not AdmGetPersonRoles(admin, person_id)
347     person = AdmGetPersons(admin, [person_id])[0]
348     assert not person['role_ids']
349     print "=> OK"
350
351     # Disable account
352     print "AdmSetPersonEnabled(%d, False)" % person_id,
353     AdmSetPersonEnabled(admin, person_id, False)
354     person = AdmGetPersons(admin, [person_id])[0]
355     assert not person['enabled']
356     print "=> OK"
357
358     # Delete account
359     print "AdmDeletePerson(%d)" % person_id,
360     AdmDeletePerson(admin, person_id)
361     assert not AdmGetPersons(admin, [person_id])                         
362     print "=> OK"
363
364 print "AdmGetPersons",
365 assert not AdmGetPersons(admin, person_ids)
366 print "=> []"
367
368 # Delete node groups
369 for nodegroup_id in nodegroup_ids:
370     print "AdmDeleteNodeGroup(%d)" % nodegroup_id,
371     AdmDeleteNodeGroup(admin, nodegroup_id)
372     assert not AdmGetNodeGroups(admin, [nodegroup_id])
373     print "=> OK"
374
375 print "AdmGetNodeGroups",
376 assert not AdmGetNodeGroups(admin, nodegroup_ids)
377 print "=> []"
378
379 # Delete sites
380 for site_id in site_ids:
381     print "AdmDeleteSite(%d)" % site_id,
382     AdmDeleteSite(admin, site_id)
383     assert not AdmGetSites(admin, [site_id])
384     print "=> OK"
385
386 print "AdmGetSites",
387 assert not AdmGetSites(admin, site_ids)
388 print "=> []"
389