print "Restoring Fedora pidspace: %s" % _stored_default_fedora_pidspace
        settings.FEDORA_PIDSPACE = _stored_default_fedora_pidspace        
    if _stored_default_fedora_root is not None:
        print "Restoring Fedora root: %s" % _stored_default_fedora_root
        settings.FEDORA_ROOT = _stored_default_fedora_root
        # re-initialize pooled connection with restored fedora root
        init_pooled_connection()

def remove_test_objects():
    # remove any leftover test object before or after running tests
    # NOTE: This method expects to be called only when FEDORA_PIDSPACE has been
    # switched to a test pidspace
    
    # use test fedora credentials if they are set
    repo = Repository(username=getattr(settings, 'FEDORA_TEST_USER', None),
                            password=getattr(settings, 'FEDORA_TEST_PASSWORD', None))
    test_objects = repo.find_objects(pid__contains='%s:*' % settings.FEDORA_PIDSPACE)
    count = 0
    for obj in test_objects:
        # if objects are unexpectedly not being cleaned up, pid/label may help
        # to isolate which test is creating the leftover objects
        logger.info('Purging test object %s - %s' % (obj.pid, obj.label))
        repo.purge_object(obj.pid, "removing test object")
        count += 1
    if count:
        print "Removed %s test object(s) with pidspace %s" % (count, settings.FEDORA_PIDSPACE)


starting_tests.connect(_use_test_fedora)
finished_tests.connect(_restore_fedora_root)
    print "Creating eXist Test Collection: %s" % settings.EXISTDB_ROOT_COLLECTION
    # now that existdb root collection has been set to test collection, init db connection
    db = ExistDB()
    # create test collection (don't complain if collection already exists)
    db.createCollection(settings.EXISTDB_ROOT_COLLECTION, True)


def _restore_root_collection(sender, **kwargs):
    global _stored_default_collection
    # if use_test_collection didn't run, don't change anything
    if _stored_default_collection is None:
        print "eXist test-start handler does not appear to have run; not restoring eXist Root Collection"
        print "Is 'eulcore.django.existdb' in your installed apps?"
    else:
        print "Removing eXist Test Collection: %s" % settings.EXISTDB_ROOT_COLLECTION
        # before restoring existdb non-test root collection, init db connection
        db = ExistDB()
        try:            
            # remove test collection
            db.removeCollection(settings.EXISTDB_ROOT_COLLECTION)
        except ExistDBException, e:
            print "Error removing collection ", settings.EXISTDB_ROOT_COLLECTION, ': ', e

        print "Restoring eXist Root Collection: %s" % _stored_default_collection
        settings.EXISTDB_ROOT_COLLECTION = _stored_default_collection


starting_tests.connect(_use_test_collection)
finished_tests.connect(_restore_root_collection)