- add missing tests
[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.6 2006/09/25 15:32:53 mlhuang Exp $
9 #
10
11 from pprint import pprint
12 from string import letters, digits, punctuation
13 import re
14 import socket
15 import struct
16
17 from random import Random
18 random = Random()
19
20 def randfloat(min = 0.0, max = 1.0):
21     return float(min) + (random.random() * (float(max) - float(min)))
22
23 def randint(min = 0, max = 1):
24     return int(randfloat(min, max + 1))
25
26 # See "2.2 Characters" in the XML specification:
27 #
28 # #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD]
29 # avoiding
30 # [#x7F-#x84], [#x86-#x9F], [#xFDD0-#xFDDF]
31
32 low_xml_chars  = map(unichr, [0x9, 0xA, 0xD])
33 low_xml_chars += map(unichr, xrange(0x20, 0x7F - 1))
34 low_xml_chars += map(unichr, xrange(0x84 + 1, 0x86 - 1))
35 low_xml_chars += map(unichr, xrange(0x9F + 1, 0xFF))
36 valid_xml_chars  = list(low_xml_chars)
37 valid_xml_chars += map(unichr, xrange(0xFF + 1, 0xD7FF))
38 valid_xml_chars += map(unichr, xrange(0xE000, 0xFDD0 - 1))
39 valid_xml_chars += map(unichr, xrange(0xFDDF + 1, 0xFFFD))
40
41 def randstr(length, pool = valid_xml_chars, encoding = "utf-8"):
42     sample = random.sample(pool, min(length, len(pool)))
43     while True:
44         s = u''.join(sample)
45         bytes = len(s.encode(encoding))
46         if bytes > length:
47             sample.pop()
48         elif bytes < length:
49             sample += random.sample(pool, min(length - bytes, len(pool)))
50             random.shuffle(sample)
51         else:
52             break
53     return s
54
55 def randhostname():
56     # 1. Each part begins and ends with a letter or number.
57     # 2. Each part except the last can contain letters, numbers, or hyphens.
58     # 3. Each part is between 1 and 64 characters, including the trailing dot.
59     # 4. At least two parts.
60     # 5. Last part can only contain between 2 and 6 letters.
61     hostname = 'a' + randstr(61, letters + digits + '-') + '1.' + \
62                'b' + randstr(61, letters + digits + '-') + '2.' + \
63                'c' + randstr(5, letters)
64     return hostname
65
66 def unicmp(a, b, encoding = "utf-8"):
67     """
68     When connected directly to the DB, values are returned as raw
69     8-bit strings that may need to be decoded (as UTF-8 by default) in
70     order to compare them against expected Python Unicode strings.
71     """
72     
73     is8bit = re.compile("[\x80-\xff]").search
74     if isinstance(a, str) and is8bit(a):
75         a = unicode(a, encoding)
76     if isinstance(b, str) and is8bit(b):
77         b = unicode(b, encoding)
78     return a == b
79
80 admin = {'AuthMethod': "capability",
81          'Username': config.PLC_API_MAINTENANCE_USER,
82          'AuthString': config.PLC_API_MAINTENANCE_PASSWORD,
83          'Role': "admin"}
84
85 user = {'AuthMethod': "password",
86         'Role': "user"}
87
88 pi = {'AuthMethod': "password",
89       'Role': "pi"}
90
91 tech = {'AuthMethod': "password",
92         'Role': "tech"}
93
94 # Add sites
95 site_ids = []
96 for i in range(3):
97     name = randstr(254)
98     abbreviated_name = randstr(50)
99     login_base = randstr(20, letters).lower()
100     latitude = int(randfloat(-90.0, 90.0) * 1000) / 1000.0
101     longitude = int(randfloat(-180.0, 180.0) * 1000) / 1000.0
102
103     # Add site
104     print "AdmAddSite(%s)" % login_base,
105     site_id = AdmAddSite(admin, name, abbreviated_name, login_base,
106                          {'latitude': latitude, 'longitude': longitude})
107
108     # Should return a unique site_id
109     assert site_id not in site_ids
110     site_ids.append(site_id)
111     print "=>", site_id
112
113     # Check site
114     print "AdmGetSites(%d)" % site_id,
115     site = AdmGetSites(admin, [site_id])[0]
116     for key in 'name', 'abbreviated_name', 'login_base', 'latitude', 'longitude', 'site_id':
117         assert unicmp(site[key], locals()[key])
118     print "=> OK"
119
120     # Update site
121     name = randstr(254)
122     abbreviated_name = randstr(50)
123     latitude = int(randfloat(-90.0, 90.0) * 1000) / 1000.0
124     longitude = int(randfloat(-180.0, 180.0) * 1000) / 1000.0
125     print "AdmUpdateSite(%s)" % login_base,
126     AdmUpdateSite(admin, site_id, {'name': name, 'abbreviated_name': abbreviated_name,
127                                    'latitude': latitude, 'longitude': longitude})
128     site = AdmGetSites(admin, [site_id])[0]
129     for key in 'name', 'abbreviated_name', 'latitude', 'longitude':
130         assert unicmp(site[key], locals()[key])
131     print "=> OK"
132
133 print "AdmGetSites",
134 sites = AdmGetSites(admin, site_ids)
135 assert set(site_ids) == set([site['site_id'] for site in sites])
136 print "=>", site_ids
137
138 print "AdmGetAllRoles",
139 role_ids = AdmGetAllRoles(admin)
140 roles = dict(zip(role_ids.values(), map(int, role_ids.keys())))
141 print "=>", role_ids
142
143 # Add users
144 person_ids = []
145 for auth in user, pi, tech:
146     first_name = randstr(128)
147     last_name = randstr(128)
148     # 119 + 1 + 64 + 64 + 6 = 254
149     email = (randstr(119, letters + digits) + "@" + randhostname()).lower()
150     bio = randstr(254)
151     # Accounts are disabled by default
152     enabled = False
153
154     auth['Username'] = email
155     auth['AuthString'] = randstr(254)
156
157     print "AdmAddPerson(%s)" % email,
158     person_id = AdmAddPerson(admin, first_name, last_name,
159                              {'email': email, 'bio': bio,
160                               'password': auth['AuthString']})
161
162     # Should return a unique person_id
163     assert person_id not in person_ids
164     person_ids.append(person_id)
165     print "=>", person_id
166
167     # Check account
168     print "AdmGetPersons(%d)" % person_id,
169     person = AdmGetPersons(admin, [person_id])[0]
170     for key in 'first_name', 'last_name', 'email', 'bio', 'person_id', 'enabled':
171         assert unicmp(person[key], locals()[key])
172     print "=> OK"
173
174     # Update account
175     first_name = randstr(128)
176     last_name = randstr(128)
177     bio = randstr(254)
178     print "AdmUpdatePerson(%d)" % person_id,
179     AdmUpdatePerson(admin, person_id, {'first_name': first_name,
180                                        'last_name': last_name,
181                                        'bio': bio})
182     person = AdmGetPersons(admin, [person_id])[0]
183     for key in 'first_name', 'last_name', 'email', 'bio':
184         assert unicmp(person[key], locals()[key])
185     print "=> OK"
186
187     # Enable account
188     print "AdmSetPersonEnabled(%d, True)" % person_id,
189     AdmSetPersonEnabled(admin, person_id, True)
190     person = AdmGetPersons(admin, [person_id])[0]
191     assert person['enabled']
192     print "=> OK"
193
194     # Add role
195     role_id = roles[auth['Role']]
196     print "AdmGrantRoleToPerson(%d, %d)" % (person_id, role_id),
197     AdmGrantRoleToPerson(admin, person_id, role_id)
198     print "=> OK"
199
200     print "AdmGetPersonRoles(%d)" % person_id,
201     person_roles = AdmGetPersonRoles(admin, person_id)
202     person_role_ids = map(int, person_roles.keys())
203     assert [role_id] == person_role_ids
204     person = AdmGetPersons(admin, [person_id])[0]
205     assert [role_id] == person['role_ids']
206     print "=>", person_role_ids
207
208     # Associate account with each site
209     for site_id in site_ids:
210         print "AdmAddPersonToSite(%d, %d)" % (person_id, site_id),
211         AdmAddPersonToSite(admin, person_id, site_id)
212         print "=> OK"
213
214         print "AdmGetSitePersons(%d)" % site_id,
215         site_person_ids = AdmGetSitePersons(admin, site_id)
216         assert person_id in site_person_ids
217         print "=>", site_person_ids
218
219     # Make sure it really did it
220     print "AdmGetPersonSites(%d)" % person_id,
221     person_site_ids = AdmGetPersonSites(auth, person_id)
222     assert set(site_ids) == set(person_site_ids)
223     person = AdmGetPersons(admin, [person_id])[0]
224     assert set(site_ids) == set(person['site_ids'])
225     print "=>", person_site_ids
226
227     # First site should be the primary site
228     print "AdmSetPersonPrimarySite(%d, %d)" % (person_id, person_site_ids[1]),
229     AdmSetPersonPrimarySite(auth, person_id, person_site_ids[1])
230     assert AdmGetPersonSites(auth, person_id)[0] == person_site_ids[1]
231     person = AdmGetPersons(admin, [person_id])[0]
232     assert person['site_ids'][0] == person_site_ids[1]
233     print "=> OK"
234
235     # Check authentication
236     print "AdmAuthCheck(%s)" % auth['Username'],
237     assert AdmAuthCheck(auth)
238     print "=> OK"
239
240 print "AdmGetPersons",
241 persons = AdmGetPersons(admin, person_ids)
242 assert set(person_ids) == set([person['person_id'] for person in persons])
243 print "=>", person_ids
244
245 # Verify PI role
246 for person in persons:
247     if 'pi' in person['roles']:
248         assert AdmIsPersonInRole(admin, pi['Username'], roles['pi'])
249
250 # Add node groups
251 nodegroup_ids = []
252 for i in range(3):
253     name = randstr(50)
254     description = randstr(200)
255     print "AdmAddNodeGroup",
256     nodegroup_id = AdmAddNodeGroup(admin, name, description)
257
258     # Should return a unique nodegroup_id
259     assert nodegroup_id not in nodegroup_ids
260     nodegroup_ids.append(nodegroup_id)
261     print "=>", nodegroup_id
262
263     # Check nodegroup
264     print "AdmGetNodeGroups(%d)" % nodegroup_id,
265     nodegroup = AdmGetNodeGroups(admin, [nodegroup_id])[0]
266     for key in 'name', 'description', 'nodegroup_id':
267         assert unicmp(nodegroup[key], locals()[key])
268     print "=> OK"
269
270     # Update node group
271     name = randstr(50)
272     description = randstr(200)
273     print "AdmUpdateNodeGroup",
274     AdmUpdateNodeGroup(admin, nodegroup_id, name, description)
275     nodegroup = AdmGetNodeGroups(admin, [nodegroup_id])[0]
276     for key in 'name', 'description', 'nodegroup_id':
277         assert unicmp(nodegroup[key], locals()[key])
278     print "=> OK"
279
280 print "AdmGetNodeGroups",
281 nodegroups = AdmGetNodeGroups(admin, nodegroup_ids)
282 assert set(nodegroup_ids) == set([nodegroup['nodegroup_id'] for nodegroup in nodegroups])
283 print "=>", nodegroup_ids
284
285 # Add nodes
286 node_ids = []
287 for site_id in site_ids:
288     for i in range(3):
289         hostname = randhostname()
290         boot_state = 'inst'
291         model = randstr(255)
292
293         # Add node
294         print "AdmAddNode(%s)" % hostname,
295         node_id = AdmAddNode(admin, site_id, hostname, boot_state,
296                              {'model': model})
297
298         # Should return a unique node_id
299         assert node_id not in node_ids
300         node_ids.append(node_id)
301         print "=>", node_id
302
303         # Check node
304         print "AdmGetNodes(%d)" % node_id,
305         node = AdmGetNodes(admin, [node_id])[0]
306         for key in 'hostname', 'boot_state', 'model', 'node_id':
307             assert unicmp(node[key], locals()[key])
308         print "=> OK"
309
310         # Update node
311         hostname = randhostname()
312         model = randstr(255)
313         print "AdmUpdateNode(%s)" % hostname,
314         AdmUpdateNode(admin, node_id, {'hostname': hostname, 'model': model})
315         node = AdmGetNodes(admin, [node_id])[0]
316         for key in 'hostname', 'boot_state', 'model', 'node_id':
317             assert unicmp(node[key], locals()[key])
318         print "=> OK"
319
320         # Add to node groups
321         for nodegroup_id in nodegroup_ids:
322             print "AdmAddNodeToNodeGroup(%d, %d)" % (nodegroup_id, node_id),
323             AdmAddNodeToNodeGroup(admin, nodegroup_id, node_id)
324             print "=> OK"
325
326 print "AdmGetNodes",
327 nodes = AdmGetNodes(admin, node_ids)
328 assert set(node_ids) == set([node['node_id'] for node in nodes])
329 print "=>", node_ids
330
331 print "AdmGetSiteNodes" % site_ids,
332 site_node_ids = AdmGetSiteNodes(admin, site_ids)
333 assert set(node_ids) == set(reduce(lambda a, b: a + b, site_node_ids.values()))
334 print "=>", site_node_ids
335
336 for nodegroup_id in nodegroup_ids:
337     print "AdmGetNodeGroupNodes(%d)" % nodegroup_id,
338     nodegroup_node_ids = AdmGetNodeGroupNodes(admin, nodegroup_id)
339     assert set(nodegroup_node_ids) == set(node_ids)
340     print "=>", nodegroup_node_ids
341
342 print "AdmGetAllNodeNetworkBandwidthLimits",
343 bwlimits = AdmGetAllNodeNetworkBandwidthLimits(admin)
344 print "=>", bwlimits
345
346 # Add node networks
347 nodenetwork_ids = []
348 for node_id in node_ids:
349     ip = randint(0, 0xffffffff)
350     netmask = (0xffffffff << randint(2, 31)) & 0xffffffff
351     network = ip & netmask
352     broadcast = ((ip & netmask) | ~netmask) & 0xffffffff
353     gateway = randint(network + 1, broadcast - 1)
354     dns1 = randint(0, 0xffffffff)
355
356     for method in 'static', 'dhcp':
357         optional = {}
358         if method == 'static':
359             for key in 'ip', 'netmask', 'network', 'broadcast', 'gateway', 'dns1':
360                 optional[key] = socket.inet_ntoa(struct.pack('>L', locals()[key]))
361
362         print "AdmAddNodeNetwork(%s)" % method,
363         nodenetwork_id = AdmAddNodeNetwork(admin, node_id, method, 'ipv4', optional)
364
365         # Should return a unique nodenetwork_id
366         assert nodenetwork_id not in nodenetwork_ids
367         nodenetwork_ids.append(nodenetwork_id)
368         print "=>", nodenetwork_id
369
370     # Check node networks
371     print "AdmGetAllNodeNetworks(%d)" % node_id,
372     nodenetworks = AdmGetAllNodeNetworks(admin, node_id)
373     for nodenetwork in nodenetworks:
374         if nodenetwork['method'] == 'static':
375             for key in 'ip', 'netmask', 'network', 'broadcast', 'gateway', 'dns1':
376                 address = struct.unpack('>L', socket.inet_aton(nodenetwork[key]))[0]
377                 assert address == locals()[key]
378     print "=>", [nodenetwork['nodenetwork_id'] for nodenetwork in nodenetworks]
379
380 # Update node networks
381 for node_id in node_ids:
382     ip = randint(0, 0xffffffff)
383     netmask = (0xffffffff << randint(2, 31)) & 0xffffffff
384     network = ip & netmask
385     broadcast = ((ip & netmask) | ~netmask) & 0xffffffff
386     gateway = randint(network + 1, broadcast - 1)
387     dns1 = randint(0, 0xffffffff)
388
389     nodenetworks = AdmGetAllNodeNetworks(admin, node_id)
390     for nodenetwork in nodenetworks:
391         # Update node network
392         optional = {}
393         if nodenetwork['method'] == 'static':
394             for key in 'ip', 'netmask', 'network', 'broadcast', 'gateway', 'dns1':
395                 optional[key] = socket.inet_ntoa(struct.pack('>L', locals()[key]))
396
397         print "AdmUpdateNodeNetwork(%s)" % nodenetwork['method'],
398         AdmUpdateNodeNetwork(admin, nodenetwork['nodenetwork_id'], optional)
399         print "=> OK"
400
401     # Check node network again
402     print "AdmGetAllNodeNetworks(%d)" % node_id,
403     nodenetworks = AdmGetAllNodeNetworks(admin, node_id)
404     for nodenetwork in nodenetworks:
405         if nodenetwork['method'] == 'static':
406             for key in 'ip', 'netmask', 'network', 'broadcast', 'gateway', 'dns1':
407                 address = struct.unpack('>L', socket.inet_aton(nodenetwork[key]))[0]
408                 assert address == locals()[key]
409     print "=>", [nodenetwork['nodenetwork_id'] for nodenetwork in nodenetworks]
410
411     # Delete node network
412     for nodenetwork in nodenetworks:
413         print "AdmDeleteNodeNetwork(%d, %d)" % (node_id, nodenetwork['nodenetwork_id']),
414         AdmDeleteNodeNetwork(admin, node_id, nodenetwork['nodenetwork_id'])
415         print "=>", "OK"
416     assert not AdmGetAllNodeNetworks(admin, node_id)
417
418 # Delete nodes
419 for node_id in node_ids:
420     # Remove from node groups
421     for nodegroup_id in nodegroup_ids:
422         print "AdmRemoveNodeFromNodeGroup(%d, %d)" % (nodegroup_id, node_id),
423         AdmRemoveNodeFromNodeGroup(admin, nodegroup_id, node_id)
424         # Make sure it really deleted it
425         assert node_id not in AdmGetNodeGroupNodes(nodegroup_id)
426         print "=> OK"
427
428     # Delete node
429     print "AdmDeleteNode(%d)" % node_id,
430     AdmDeleteNode(admin, node_id)
431     assert not AdmGetNodes(admin, [node_id])
432
433     # Make sure it really deleted it
434     nodes = AdmGetNodes(admin, node_ids)
435     assert node_id not in [node['node_id'] for node in nodes]
436     print "=> OK"
437
438 print "AdmGetNodes",
439 assert not AdmGetNodes(admin, node_ids)
440 print "=> []"
441
442 for nodegroup_id in nodegroup_ids:
443     print "AdmGetNodeGroupNodes(%d)" % nodegroup_id,
444     assert not AdmGetNodeGroupNodes(nodegroup_id)
445     print "=> []"
446
447 # Delete users
448 for person_id in person_ids:
449     # Remove from each site
450     for site_id in site_ids:
451         print "AdmRemovePersonFromSite(%d, %d)" % (person_id, site_id),
452         AdmRemovePersonFromSite(admin, person_id, site_id)
453         assert site_id not in AdmGetPersonSites(admin, person_id)
454         person = AdmGetPersons(admin, [person_id])[0]
455         assert site_id not in person['site_ids']
456         print "=> OK"
457
458     assert not AdmGetPersonSites(admin, person_id)
459
460     # Revoke role
461     person_roles = AdmGetPersonRoles(admin, person_id)
462     role_id = int(person_roles.keys()[0])
463     print "AdmRevokeRoleFromPerson(%d, %d)" % (person_id, role_id),
464     AdmRevokeRoleFromPerson(admin, person_id, role_id)
465     assert not AdmGetPersonRoles(admin, person_id)
466     person = AdmGetPersons(admin, [person_id])[0]
467     assert not person['role_ids']
468     print "=> OK"
469
470     # Disable account
471     print "AdmSetPersonEnabled(%d, False)" % person_id,
472     AdmSetPersonEnabled(admin, person_id, False)
473     person = AdmGetPersons(admin, [person_id])[0]
474     assert not person['enabled']
475     print "=> OK"
476
477     # Delete account
478     print "AdmDeletePerson(%d)" % person_id,
479     AdmDeletePerson(admin, person_id)
480     assert not AdmGetPersons(admin, [person_id])                         
481     print "=> OK"
482
483 print "AdmGetPersons",
484 assert not AdmGetPersons(admin, person_ids)
485 print "=> []"
486
487 # Delete node groups
488 for nodegroup_id in nodegroup_ids:
489     print "AdmDeleteNodeGroup(%d)" % nodegroup_id,
490     AdmDeleteNodeGroup(admin, nodegroup_id)
491     assert not AdmGetNodeGroups(admin, [nodegroup_id])
492     print "=> OK"
493
494 print "AdmGetNodeGroups",
495 assert not AdmGetNodeGroups(admin, nodegroup_ids)
496 print "=> []"
497
498 # Delete sites
499 for site_id in site_ids:
500     print "AdmDeleteSite(%d)" % site_id,
501     AdmDeleteSite(admin, site_id)
502     assert not AdmGetSites(admin, [site_id])
503     print "=> OK"
504
505 print "AdmGetSites",
506 assert not AdmGetSites(admin, site_ids)
507 print "=> []"