Merge remote-tracking branch 'origin/pycurl' into planetlab-4_0-branch
[plcapi.git] / Test.py
diff --git a/Test.py b/Test.py
index 9922e3e..3e2e5aa 100755 (executable)
--- a/Test.py
+++ b/Test.py
-#!/usr/bin/env ./Shell.py
+#!/usr/bin/python
 #
-# Test script example
+# Test script for peer caching
 #
 # Mark Huang <mlhuang@cs.princeton.edu>
 # Copyright (C) 2006 The Trustees of Princeton University
 #
-# $Id: Test.py,v 1.6 2006/09/25 15:32:53 mlhuang Exp $
+# $Id: Test.py,v 1.23 2007/09/14 15:34:01 mef Exp $
 #
 
-from pprint import pprint
-from string import letters, digits, punctuation
+"""
+Test script for peer caching. Intended for testing multiple PLCs
+running on the same machine in different chroots. Here is how I set
+things up after installing and configuring MyPLC:
+
+# Shut down MyPLC
+service plc stop
+
+# Copy to /plc2
+cp -ra /plc /plc2
+ln -sf plc /etc/init.d/plc2
+echo 'PLC_ROOT=/plc2/root' > /etc/sysconfig/plc2
+echo 'PLC_DATA=/plc2/data' >> /etc/sysconfig/plc2
+
+# Edit /plc2/data/etc/planetlab/plc_config.xml and change at least the
+# following so that they do not conflict with the defaults:
+#
+# PLC_NAME (e.g., PlanetLab Two)
+# PLC_SLICE_PREFIX (e.g., two)
+# PLC_ROOT_USER (e.g., root@planetlab.two)
+# PLC_API_MAINTENANCE_USER (e.g., maint@planetlab.two)
+# PLC_DB_PORT (e.g., 5433)
+# PLC_WWW_PORT (e.g., 81)
+# PLC_WWW_SSL_PORT (e.g., 444)
+# PLC_API_PORT (must be the same as PLC_WWW_SSL_PORT, e.g., 444)
+# PLC_BOOT_SSL_PORT (must be the same as PLC_WWW_SSL_PORT, e.g., 444)
+# PLC_BOOT_PORT (may be the same as PLC_WWW_PORT, e.g., 81)
+
+# Start up both MyPLC instances
+service plc start
+service plc2 start
+
+# Run test
+./Test.py -f /etc/planetlab/plc_config -f /plc2/data/etc/planetlab/plc_config
+
+# If the test fails and your databases are corrupt and/or you want to
+# start over, you can always just blow the databases away.
+service plc stop
+rm -rf /plc/data/var/lib/pgsql/data
+service plc start
+
+service plc2 stop
+rm -rf /plc2/data/var/lib/pgsql/data
+service plc2 start
+"""
+
 import re
-import socket
-import struct
+from optparse import OptionParser
 
-from random import Random
-random = Random()
+from PLC.Config import Config
+from PLC.GPG import gpg_export
+from PLC.Shell import Shell
+from PLC.Test import Test
 
-def randfloat(min = 0.0, max = 1.0):
-    return float(min) + (random.random() * (float(max) - float(min)))
+def todict(list_of_dicts, key):
+    """
+    Turn a list of dicts into a dict keyed on key.
+    """
 
-def randint(min = 0, max = 1):
-    return int(randfloat(min, max + 1))
+    return dict([(d[key], d) for d in list_of_dicts])
 
-# See "2.2 Characters" in the XML specification:
-#
-# #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD]
-# avoiding
-# [#x7F-#x84], [#x86-#x9F], [#xFDD0-#xFDDF]
-
-low_xml_chars  = map(unichr, [0x9, 0xA, 0xD])
-low_xml_chars += map(unichr, xrange(0x20, 0x7F - 1))
-low_xml_chars += map(unichr, xrange(0x84 + 1, 0x86 - 1))
-low_xml_chars += map(unichr, xrange(0x9F + 1, 0xFF))
-valid_xml_chars  = list(low_xml_chars)
-valid_xml_chars += map(unichr, xrange(0xFF + 1, 0xD7FF))
-valid_xml_chars += map(unichr, xrange(0xE000, 0xFDD0 - 1))
-valid_xml_chars += map(unichr, xrange(0xFDDF + 1, 0xFFFD))
-
-def randstr(length, pool = valid_xml_chars, encoding = "utf-8"):
-    sample = random.sample(pool, min(length, len(pool)))
-    while True:
-        s = u''.join(sample)
-        bytes = len(s.encode(encoding))
-        if bytes > length:
-            sample.pop()
-        elif bytes < length:
-            sample += random.sample(pool, min(length - bytes, len(pool)))
-            random.shuffle(sample)
-        else:
-            break
-    return s
-
-def randhostname():
-    # 1. Each part begins and ends with a letter or number.
-    # 2. Each part except the last can contain letters, numbers, or hyphens.
-    # 3. Each part is between 1 and 64 characters, including the trailing dot.
-    # 4. At least two parts.
-    # 5. Last part can only contain between 2 and 6 letters.
-    hostname = 'a' + randstr(61, letters + digits + '-') + '1.' + \
-               'b' + randstr(61, letters + digits + '-') + '2.' + \
-               'c' + randstr(5, letters)
-    return hostname
-
-def unicmp(a, b, encoding = "utf-8"):
+def RefreshPeers(plcs):
     """
-    When connected directly to the DB, values are returned as raw
-    8-bit strings that may need to be decoded (as UTF-8 by default) in
-    order to compare them against expected Python Unicode strings.
+    Refresh each peer with each other.
     """
-    
-    is8bit = re.compile("[\x80-\xff]").search
-    if isinstance(a, str) and is8bit(a):
-        a = unicode(a, encoding)
-    if isinstance(b, str) and is8bit(b):
-        b = unicode(b, encoding)
-    return a == b
-
-admin = {'AuthMethod': "capability",
-         'Username': config.PLC_API_MAINTENANCE_USER,
-         'AuthString': config.PLC_API_MAINTENANCE_PASSWORD,
-         'Role': "admin"}
-
-user = {'AuthMethod': "password",
-        'Role': "user"}
-
-pi = {'AuthMethod': "password",
-      'Role': "pi"}
-
-tech = {'AuthMethod': "password",
-        'Role': "tech"}
-
-# Add sites
-site_ids = []
-for i in range(3):
-    name = randstr(254)
-    abbreviated_name = randstr(50)
-    login_base = randstr(20, letters).lower()
-    latitude = int(randfloat(-90.0, 90.0) * 1000) / 1000.0
-    longitude = int(randfloat(-180.0, 180.0) * 1000) / 1000.0
-
-    # Add site
-    print "AdmAddSite(%s)" % login_base,
-    site_id = AdmAddSite(admin, name, abbreviated_name, login_base,
-                         {'latitude': latitude, 'longitude': longitude})
-
-    # Should return a unique site_id
-    assert site_id not in site_ids
-    site_ids.append(site_id)
-    print "=>", site_id
-
-    # Check site
-    print "AdmGetSites(%d)" % site_id,
-    site = AdmGetSites(admin, [site_id])[0]
-    for key in 'name', 'abbreviated_name', 'login_base', 'latitude', 'longitude', 'site_id':
-        assert unicmp(site[key], locals()[key])
-    print "=> OK"
-
-    # Update site
-    name = randstr(254)
-    abbreviated_name = randstr(50)
-    latitude = int(randfloat(-90.0, 90.0) * 1000) / 1000.0
-    longitude = int(randfloat(-180.0, 180.0) * 1000) / 1000.0
-    print "AdmUpdateSite(%s)" % login_base,
-    AdmUpdateSite(admin, site_id, {'name': name, 'abbreviated_name': abbreviated_name,
-                                   'latitude': latitude, 'longitude': longitude})
-    site = AdmGetSites(admin, [site_id])[0]
-    for key in 'name', 'abbreviated_name', 'latitude', 'longitude':
-        assert unicmp(site[key], locals()[key])
-    print "=> OK"
-
-print "AdmGetSites",
-sites = AdmGetSites(admin, site_ids)
-assert set(site_ids) == set([site['site_id'] for site in sites])
-print "=>", site_ids
-
-print "AdmGetAllRoles",
-role_ids = AdmGetAllRoles(admin)
-roles = dict(zip(role_ids.values(), map(int, role_ids.keys())))
-print "=>", role_ids
-
-# Add users
-person_ids = []
-for auth in user, pi, tech:
-    first_name = randstr(128)
-    last_name = randstr(128)
-    # 119 + 1 + 64 + 64 + 6 = 254
-    email = (randstr(119, letters + digits) + "@" + randhostname()).lower()
-    bio = randstr(254)
-    # Accounts are disabled by default
-    enabled = False
-
-    auth['Username'] = email
-    auth['AuthString'] = randstr(254)
-
-    print "AdmAddPerson(%s)" % email,
-    person_id = AdmAddPerson(admin, first_name, last_name,
-                             {'email': email, 'bio': bio,
-                              'password': auth['AuthString']})
-
-    # Should return a unique person_id
-    assert person_id not in person_ids
-    person_ids.append(person_id)
-    print "=>", person_id
-
-    # Check account
-    print "AdmGetPersons(%d)" % person_id,
-    person = AdmGetPersons(admin, [person_id])[0]
-    for key in 'first_name', 'last_name', 'email', 'bio', 'person_id', 'enabled':
-        assert unicmp(person[key], locals()[key])
-    print "=> OK"
-
-    # Update account
-    first_name = randstr(128)
-    last_name = randstr(128)
-    bio = randstr(254)
-    print "AdmUpdatePerson(%d)" % person_id,
-    AdmUpdatePerson(admin, person_id, {'first_name': first_name,
-                                       'last_name': last_name,
-                                       'bio': bio})
-    person = AdmGetPersons(admin, [person_id])[0]
-    for key in 'first_name', 'last_name', 'email', 'bio':
-        assert unicmp(person[key], locals()[key])
-    print "=> OK"
-
-    # Enable account
-    print "AdmSetPersonEnabled(%d, True)" % person_id,
-    AdmSetPersonEnabled(admin, person_id, True)
-    person = AdmGetPersons(admin, [person_id])[0]
-    assert person['enabled']
-    print "=> OK"
-
-    # Add role
-    role_id = roles[auth['Role']]
-    print "AdmGrantRoleToPerson(%d, %d)" % (person_id, role_id),
-    AdmGrantRoleToPerson(admin, person_id, role_id)
-    print "=> OK"
-
-    print "AdmGetPersonRoles(%d)" % person_id,
-    person_roles = AdmGetPersonRoles(admin, person_id)
-    person_role_ids = map(int, person_roles.keys())
-    assert [role_id] == person_role_ids
-    person = AdmGetPersons(admin, [person_id])[0]
-    assert [role_id] == person['role_ids']
-    print "=>", person_role_ids
-
-    # Associate account with each site
-    for site_id in site_ids:
-        print "AdmAddPersonToSite(%d, %d)" % (person_id, site_id),
-        AdmAddPersonToSite(admin, person_id, site_id)
-        print "=> OK"
-
-        print "AdmGetSitePersons(%d)" % site_id,
-        site_person_ids = AdmGetSitePersons(admin, site_id)
-        assert person_id in site_person_ids
-        print "=>", site_person_ids
-
-    # Make sure it really did it
-    print "AdmGetPersonSites(%d)" % person_id,
-    person_site_ids = AdmGetPersonSites(auth, person_id)
-    assert set(site_ids) == set(person_site_ids)
-    person = AdmGetPersons(admin, [person_id])[0]
-    assert set(site_ids) == set(person['site_ids'])
-    print "=>", person_site_ids
-
-    # First site should be the primary site
-    print "AdmSetPersonPrimarySite(%d, %d)" % (person_id, person_site_ids[1]),
-    AdmSetPersonPrimarySite(auth, person_id, person_site_ids[1])
-    assert AdmGetPersonSites(auth, person_id)[0] == person_site_ids[1]
-    person = AdmGetPersons(admin, [person_id])[0]
-    assert person['site_ids'][0] == person_site_ids[1]
-    print "=> OK"
-
-    # Check authentication
-    print "AdmAuthCheck(%s)" % auth['Username'],
-    assert AdmAuthCheck(auth)
-    print "=> OK"
-
-print "AdmGetPersons",
-persons = AdmGetPersons(admin, person_ids)
-assert set(person_ids) == set([person['person_id'] for person in persons])
-print "=>", person_ids
-
-# Verify PI role
-for person in persons:
-    if 'pi' in person['roles']:
-        assert AdmIsPersonInRole(admin, pi['Username'], roles['pi'])
-
-# Add node groups
-nodegroup_ids = []
-for i in range(3):
-    name = randstr(50)
-    description = randstr(200)
-    print "AdmAddNodeGroup",
-    nodegroup_id = AdmAddNodeGroup(admin, name, description)
-
-    # Should return a unique nodegroup_id
-    assert nodegroup_id not in nodegroup_ids
-    nodegroup_ids.append(nodegroup_id)
-    print "=>", nodegroup_id
-
-    # Check nodegroup
-    print "AdmGetNodeGroups(%d)" % nodegroup_id,
-    nodegroup = AdmGetNodeGroups(admin, [nodegroup_id])[0]
-    for key in 'name', 'description', 'nodegroup_id':
-        assert unicmp(nodegroup[key], locals()[key])
-    print "=> OK"
-
-    # Update node group
-    name = randstr(50)
-    description = randstr(200)
-    print "AdmUpdateNodeGroup",
-    AdmUpdateNodeGroup(admin, nodegroup_id, name, description)
-    nodegroup = AdmGetNodeGroups(admin, [nodegroup_id])[0]
-    for key in 'name', 'description', 'nodegroup_id':
-        assert unicmp(nodegroup[key], locals()[key])
-    print "=> OK"
-
-print "AdmGetNodeGroups",
-nodegroups = AdmGetNodeGroups(admin, nodegroup_ids)
-assert set(nodegroup_ids) == set([nodegroup['nodegroup_id'] for nodegroup in nodegroups])
-print "=>", nodegroup_ids
-
-# Add nodes
-node_ids = []
-for site_id in site_ids:
-    for i in range(3):
-        hostname = randhostname()
-        boot_state = 'inst'
-        model = randstr(255)
-
-        # Add node
-        print "AdmAddNode(%s)" % hostname,
-        node_id = AdmAddNode(admin, site_id, hostname, boot_state,
-                             {'model': model})
-
-        # Should return a unique node_id
-        assert node_id not in node_ids
-        node_ids.append(node_id)
-        print "=>", node_id
-
-        # Check node
-        print "AdmGetNodes(%d)" % node_id,
-        node = AdmGetNodes(admin, [node_id])[0]
-        for key in 'hostname', 'boot_state', 'model', 'node_id':
-            assert unicmp(node[key], locals()[key])
-        print "=> OK"
-
-        # Update node
-        hostname = randhostname()
-        model = randstr(255)
-        print "AdmUpdateNode(%s)" % hostname,
-        AdmUpdateNode(admin, node_id, {'hostname': hostname, 'model': model})
-        node = AdmGetNodes(admin, [node_id])[0]
-        for key in 'hostname', 'boot_state', 'model', 'node_id':
-            assert unicmp(node[key], locals()[key])
-        print "=> OK"
-
-        # Add to node groups
-        for nodegroup_id in nodegroup_ids:
-            print "AdmAddNodeToNodeGroup(%d, %d)" % (nodegroup_id, node_id),
-            AdmAddNodeToNodeGroup(admin, nodegroup_id, node_id)
-            print "=> OK"
-
-print "AdmGetNodes",
-nodes = AdmGetNodes(admin, node_ids)
-assert set(node_ids) == set([node['node_id'] for node in nodes])
-print "=>", node_ids
-
-print "AdmGetSiteNodes" % site_ids,
-site_node_ids = AdmGetSiteNodes(admin, site_ids)
-assert set(node_ids) == set(reduce(lambda a, b: a + b, site_node_ids.values()))
-print "=>", site_node_ids
-
-for nodegroup_id in nodegroup_ids:
-    print "AdmGetNodeGroupNodes(%d)" % nodegroup_id,
-    nodegroup_node_ids = AdmGetNodeGroupNodes(admin, nodegroup_id)
-    assert set(nodegroup_node_ids) == set(node_ids)
-    print "=>", nodegroup_node_ids
-
-print "AdmGetAllNodeNetworkBandwidthLimits",
-bwlimits = AdmGetAllNodeNetworkBandwidthLimits(admin)
-print "=>", bwlimits
-
-# Add node networks
-nodenetwork_ids = []
-for node_id in node_ids:
-    ip = randint(0, 0xffffffff)
-    netmask = (0xffffffff << randint(2, 31)) & 0xffffffff
-    network = ip & netmask
-    broadcast = ((ip & netmask) | ~netmask) & 0xffffffff
-    gateway = randint(network + 1, broadcast - 1)
-    dns1 = randint(0, 0xffffffff)
-
-    for method in 'static', 'dhcp':
-        optional = {}
-        if method == 'static':
-            for key in 'ip', 'netmask', 'network', 'broadcast', 'gateway', 'dns1':
-                optional[key] = socket.inet_ntoa(struct.pack('>L', locals()[key]))
-
-        print "AdmAddNodeNetwork(%s)" % method,
-        nodenetwork_id = AdmAddNodeNetwork(admin, node_id, method, 'ipv4', optional)
-
-        # Should return a unique nodenetwork_id
-        assert nodenetwork_id not in nodenetwork_ids
-        nodenetwork_ids.append(nodenetwork_id)
-        print "=>", nodenetwork_id
-
-    # Check node networks
-    print "AdmGetAllNodeNetworks(%d)" % node_id,
-    nodenetworks = AdmGetAllNodeNetworks(admin, node_id)
-    for nodenetwork in nodenetworks:
-        if nodenetwork['method'] == 'static':
-            for key in 'ip', 'netmask', 'network', 'broadcast', 'gateway', 'dns1':
-                address = struct.unpack('>L', socket.inet_aton(nodenetwork[key]))[0]
-                assert address == locals()[key]
-    print "=>", [nodenetwork['nodenetwork_id'] for nodenetwork in nodenetworks]
-
-# Update node networks
-for node_id in node_ids:
-    ip = randint(0, 0xffffffff)
-    netmask = (0xffffffff << randint(2, 31)) & 0xffffffff
-    network = ip & netmask
-    broadcast = ((ip & netmask) | ~netmask) & 0xffffffff
-    gateway = randint(network + 1, broadcast - 1)
-    dns1 = randint(0, 0xffffffff)
-
-    nodenetworks = AdmGetAllNodeNetworks(admin, node_id)
-    for nodenetwork in nodenetworks:
-        # Update node network
-        optional = {}
-        if nodenetwork['method'] == 'static':
-            for key in 'ip', 'netmask', 'network', 'broadcast', 'gateway', 'dns1':
-                optional[key] = socket.inet_ntoa(struct.pack('>L', locals()[key]))
-
-        print "AdmUpdateNodeNetwork(%s)" % nodenetwork['method'],
-        AdmUpdateNodeNetwork(admin, nodenetwork['nodenetwork_id'], optional)
-        print "=> OK"
-
-    # Check node network again
-    print "AdmGetAllNodeNetworks(%d)" % node_id,
-    nodenetworks = AdmGetAllNodeNetworks(admin, node_id)
-    for nodenetwork in nodenetworks:
-        if nodenetwork['method'] == 'static':
-            for key in 'ip', 'netmask', 'network', 'broadcast', 'gateway', 'dns1':
-                address = struct.unpack('>L', socket.inet_aton(nodenetwork[key]))[0]
-                assert address == locals()[key]
-    print "=>", [nodenetwork['nodenetwork_id'] for nodenetwork in nodenetworks]
-
-    # Delete node network
-    for nodenetwork in nodenetworks:
-        print "AdmDeleteNodeNetwork(%d, %d)" % (node_id, nodenetwork['nodenetwork_id']),
-        AdmDeleteNodeNetwork(admin, node_id, nodenetwork['nodenetwork_id'])
-        print "=>", "OK"
-    assert not AdmGetAllNodeNetworks(admin, node_id)
-
-# Delete nodes
-for node_id in node_ids:
-    # Remove from node groups
-    for nodegroup_id in nodegroup_ids:
-        print "AdmRemoveNodeFromNodeGroup(%d, %d)" % (nodegroup_id, node_id),
-        AdmRemoveNodeFromNodeGroup(admin, nodegroup_id, node_id)
-        # Make sure it really deleted it
-        assert node_id not in AdmGetNodeGroupNodes(nodegroup_id)
-        print "=> OK"
-
-    # Delete node
-    print "AdmDeleteNode(%d)" % node_id,
-    AdmDeleteNode(admin, node_id)
-    assert not AdmGetNodes(admin, [node_id])
-
-    # Make sure it really deleted it
-    nodes = AdmGetNodes(admin, node_ids)
-    assert node_id not in [node['node_id'] for node in nodes]
-    print "=> OK"
-
-print "AdmGetNodes",
-assert not AdmGetNodes(admin, node_ids)
-print "=> []"
-
-for nodegroup_id in nodegroup_ids:
-    print "AdmGetNodeGroupNodes(%d)" % nodegroup_id,
-    assert not AdmGetNodeGroupNodes(nodegroup_id)
-    print "=> []"
-
-# Delete users
-for person_id in person_ids:
-    # Remove from each site
-    for site_id in site_ids:
-        print "AdmRemovePersonFromSite(%d, %d)" % (person_id, site_id),
-        AdmRemovePersonFromSite(admin, person_id, site_id)
-        assert site_id not in AdmGetPersonSites(admin, person_id)
-        person = AdmGetPersons(admin, [person_id])[0]
-        assert site_id not in person['site_ids']
-        print "=> OK"
-
-    assert not AdmGetPersonSites(admin, person_id)
-
-    # Revoke role
-    person_roles = AdmGetPersonRoles(admin, person_id)
-    role_id = int(person_roles.keys()[0])
-    print "AdmRevokeRoleFromPerson(%d, %d)" % (person_id, role_id),
-    AdmRevokeRoleFromPerson(admin, person_id, role_id)
-    assert not AdmGetPersonRoles(admin, person_id)
-    person = AdmGetPersons(admin, [person_id])[0]
-    assert not person['role_ids']
-    print "=> OK"
-
-    # Disable account
-    print "AdmSetPersonEnabled(%d, False)" % person_id,
-    AdmSetPersonEnabled(admin, person_id, False)
-    person = AdmGetPersons(admin, [person_id])[0]
-    assert not person['enabled']
-    print "=> OK"
-
-    # Delete account
-    print "AdmDeletePerson(%d)" % person_id,
-    AdmDeletePerson(admin, person_id)
-    assert not AdmGetPersons(admin, [person_id])                         
-    print "=> OK"
-
-print "AdmGetPersons",
-assert not AdmGetPersons(admin, person_ids)
-print "=> []"
-
-# Delete node groups
-for nodegroup_id in nodegroup_ids:
-    print "AdmDeleteNodeGroup(%d)" % nodegroup_id,
-    AdmDeleteNodeGroup(admin, nodegroup_id)
-    assert not AdmGetNodeGroups(admin, [nodegroup_id])
-    print "=> OK"
-
-print "AdmGetNodeGroups",
-assert not AdmGetNodeGroups(admin, nodegroup_ids)
-print "=> []"
-
-# Delete sites
-for site_id in site_ids:
-    print "AdmDeleteSite(%d)" % site_id,
-    AdmDeleteSite(admin, site_id)
-    assert not AdmGetSites(admin, [site_id])
-    print "=> OK"
-
-print "AdmGetSites",
-assert not AdmGetSites(admin, site_ids)
-print "=> []"
+
+    for plc in plcs:
+        for peer in plcs:
+            if peer == plc:
+                continue
+
+            print plc.config.PLC_NAME, "refreshing", peer.config.PLC_NAME
+            plc.RefreshPeer(peer.config.PLC_NAME)
+
+            peer_id = plc.GetPeers([peer.config.PLC_NAME])[0]['peer_id']
+
+            peer_sites = todict(plc.GetSites({'peer_id': peer_id}), 'site_id')
+            sites_at_peer = todict(peer.GetSites(), 'site_id')
+
+            peer_keys = todict(plc.GetKeys({'peer_id': peer_id}), 'key_id')
+            keys_at_peer = todict(peer.GetKeys(), 'key_id')
+
+            peer_persons = todict(plc.GetPersons({'peer_id': peer_id}), 'person_id')
+            persons_at_peer = todict(peer.GetPersons(), 'person_id')
+
+            peer_nodes = todict(plc.GetNodes({'peer_id': peer_id}), 'node_id')
+            nodes_at_peer = todict(peer.GetNodes(), 'node_id')
+
+            our_nodes = todict(plc.GetNodes({'peer_id': None}), 'node_id')
+            our_peer_id_at_peer = peer.GetPeers([plc.config.PLC_NAME])[0]['peer_id']
+            our_nodes_at_peer = todict(peer.GetNodes({'peer_id': our_peer_id_at_peer,
+                                                      'peer_node_id': our_nodes.keys()}), 'peer_node_id')
+
+            peer_slices = todict(plc.GetSlices({'peer_id': peer_id}), 'peer_slice_id')
+            slices_at_peer = todict(peer.GetSlices(), 'slice_id')
+            for site_id, site in peer_sites.iteritems():
+                # Verify that this site exists at the peer
+                peer_site_id = site['peer_site_id']
+                assert peer_site_id in sites_at_peer
+                peer_site = sites_at_peer[peer_site_id]
+
+                # And is the same
+                for field in ['name', 'abbreviated_name', 'login_base', 'is_public',
+                              'latitude', 'longitude', 'url',
+                              'max_slices', 'max_slivers',]:
+                    assert site[field] == peer_site[field]
+
+            for key_id, key in peer_keys.iteritems():
+                # Verify that this key exists at the peer
+                peer_key_id = key['peer_key_id']
+                assert peer_key_id in keys_at_peer
+                peer_key = keys_at_peer[peer_key_id]
+
+                # And is the same
+                for field in ['key_type', 'key']:
+                    assert key[field] == peer_key[field]
+
+            for person_id, person in peer_persons.iteritems():
+                # Verify that this user exists at the peer
+                peer_person_id = person['peer_person_id']
+                assert peer_person_id in persons_at_peer
+                peer_person = persons_at_peer[peer_person_id]
+
+                # And is the same
+                for field in ['first_name', 'last_name', 'title', 'email', 'phone',
+                              'url', 'bio', 'enabled']:
+                    assert person[field] == peer_person[field]
+
+                for key_id in person['key_ids']:
+                    # Verify that the user is not associated with any local keys
+                    assert key_id in peer_keys
+                    key = peer_keys[key_id]
+                    peer_key_id = key['peer_key_id']
+
+                    # Verify that this key exists at the peer
+                    assert peer_key_id in keys_at_peer
+                    peer_key = keys_at_peer[peer_key_id]
+
+                    # And is related to the same user at the peer
+                    assert peer_key['key_id'] in peer_person['key_ids']
+
+            for node_id, node in peer_nodes.iteritems():
+                # Verify that this node exists at the peer
+                peer_node_id = node['peer_node_id']
+                assert peer_node_id in nodes_at_peer
+                peer_node = nodes_at_peer[peer_node_id]
+
+                # And is the same
+                for field in ['boot_state', 'ssh_rsa_key', 'hostname',
+                              'version', 'model']:
+                    assert node[field] == peer_node[field]
+
+                # Verify that the node is not associated with any local sites
+                assert node['site_id'] in peer_sites
+                site = peer_sites[node['site_id']]
+
+                # Verify that this site exists at the peer
+                peer_site_id = site['peer_site_id']
+                assert peer_site_id in sites_at_peer
+                peer_site = sites_at_peer[peer_site_id]
+
+                # And is related to the same node at the peer
+                assert peer_site['site_id'] == peer_node['site_id']
+
+            for slice_id, slice in peer_slices.iteritems():
+                # Verify that this slice exists at the peer
+                peer_slice_id = slice['peer_slice_id']
+                assert peer_slice_id in slices_at_peer
+                peer_slice = slices_at_peer[peer_slice_id]
+
+                # And is the same
+                for field in ['name', 'instantiation', 'url', 'description',
+                              'max_nodes', 'expires']:
+                    assert slice[field] == peer_slice[field]
+
+                for node_id in slice['node_ids']:
+                    # Verify that the slice is associated only with
+                    # the peer's own nodes, or with our nodes as
+                    # last cached by the peer.
+                    assert node_id in peer_nodes or node_id in our_nodes_at_peer
+                    if node_id in peer_nodes:
+                        node = peer_nodes[node_id]
+                        peer_node_id = node['peer_node_id']
+                    elif node_id in our_nodes_at_peer:
+                        peer_node = our_nodes_at_peer[node_id]
+                        peer_node_id = peer_node['node_id']
+
+                    # Verify that this node exists at the peer
+                    assert peer_node_id in nodes_at_peer
+
+                    # And is related to the same slice at the peer
+                    assert peer_node_id in peer_slice['node_ids']
+
+def TestPeers(plcs, check = True, verbose = True, tiny = False):
+    # Register each peer with each other
+    for plc in plcs:
+        for peer in plcs:
+            if peer == plc:
+                continue
+
+            key = gpg_export(peer.chroot + peer.config.PLC_ROOT_GPG_KEY_PUB)
+            cacert = file(peer.chroot + peer.config.PLC_API_CA_SSL_CRT).read()
+
+            if plc.GetPeers([peer.config.PLC_NAME]):
+                print plc.config.PLC_NAME, "updating peer", peer.config.PLC_NAME
+                plc.UpdatePeer(peer.config.PLC_NAME,
+                               {'peer_url': peer.url, 'key': key, 'cacert': cacert})
+            else:
+                print plc.config.PLC_NAME, "adding peer", peer.config.PLC_NAME
+                plc.AddPeer({'peername': peer.config.PLC_NAME,
+                             'peer_url': peer.url, 'key': key, 'cacert': cacert})
+
+        # Populate the DB
+        plc.test = Test(api = plc, check = check, verbose = verbose)
+
+        if tiny:
+            params = Test.tiny
+        else:
+            params = Test.default
+
+        print "Populating", plc.config.PLC_NAME
+        plc.test.Add(**params)
+
+    # Refresh each other
+    RefreshPeers(plcs)
+
+    # Change some things
+    for plc in plcs:
+        print "Updating", plc.config.PLC_NAME
+        plc.test.Update()
+
+    # Refresh each other again
+    RefreshPeers(plcs)
+
+def main():
+    parser = OptionParser()
+    parser.add_option("-f", "--config", dest = "configs", action = "append", default = [], help = "Configuration file (default: %default)")
+    parser.add_option("-c", "--check", action = "store_true", default = False, help = "Verify actions (default: %default)")
+    parser.add_option("-q", "--quiet", action = "store_true", default = False, help = "Be quiet (default: %default)")
+    parser.add_option("-t", "--tiny", action = "store_true", default = False, help = "Run a tiny test (default: %default)")
+    (options, args) = parser.parse_args()
+
+    # Test single peer by default
+    if not options.configs:
+        options.configs = ["/etc/planetlab/plc_config"]
+
+    plcs = []
+    for path in options.configs:
+        # Load configuration file
+        config = Config(path)
+
+        # Determine path to chroot
+        m = re.match(r'(.*)/etc/planetlab', path)
+        if m is not None:
+            chroot = m.group(1)
+        else:
+            chroot = ""
+
+        # Fix up path to SSL certificate
+        cacert = chroot + config.PLC_API_CA_SSL_CRT
+
+        # Always connect with XML-RPC
+        plc = Shell(config = path, cacert = cacert, xmlrpc = True)
+        plc.chroot = chroot
+        plcs.append(plc)
+
+    TestPeers(plcs, check = options.check, verbose = not options.quiet, tiny = options.tiny)
+
+if __name__ == "__main__":
+    main()