Add better function+test for testing collection equality

This commit is contained in:
Sergey Golitsynskiy
2021-10-21 18:37:53 -04:00
parent 5dc9111f45
commit 518cc517fc
2 changed files with 57 additions and 0 deletions
@@ -7503,6 +7503,27 @@ def are_same_entity_collections(collection1, collection2):
return True
def collection_consists_of_objects(collection, *objects):
"""
Returns True iff list(collection) == list(objects), where object equality is determined
by primary key equality: object1.id == object2.id.
"""
if len(collection) != len(objects): # False if lengths are different
return False
if not collection: # True if both are empty
return True
# Sort, then compare each member by its 'id' attribute, which must be its primary key.
collection.sort(key=lambda item: item.id)
objects = list(objects)
objects.sort(key=lambda item: item.id)
for item1, item2 in zip(collection, objects):
if item1.id is None or item2.id is None or item1.id != item2.id:
return False
return True
def _run_average_rating_test(session, obj, user, obj_rating_association_factory):
# obj has been expunged; to access its deferred properties,
# it needs to be added back to the session.
+36
View File
@@ -19,6 +19,7 @@ from sqlalchemy.orm import registry, Session
from galaxy.model import _HasTable
from . test_model_mapping import (
are_same_entity_collections,
collection_consists_of_objects,
dbcleanup,
dbcleanup_wrapper,
delete_from_database,
@@ -182,6 +183,41 @@ def test_are_same_entity_collections(session):
assert not are_same_entity_collections([stored_foo1, stored_foo1, stored_foo2], expected)
def test_collection_consists_of_objects(session):
# create objects
foo1 = Foo()
foo2 = Foo()
foo3 = Foo()
# store objects
persist(session, foo1)
persist(session, foo2)
persist(session, foo3)
# retrieve objects from storage
stored_foo1 = _get_stored_instance_by_id(session, Foo, foo1.id)
stored_foo2 = _get_stored_instance_by_id(session, Foo, foo2.id)
stored_foo3 = _get_stored_instance_by_id(session, Foo, foo3.id)
# verify retrieved objects are not the same python objects as those we stored
assert stored_foo1 is not foo1
assert stored_foo2 is not foo2
assert stored_foo3 is not foo3
# trivial case
assert collection_consists_of_objects([stored_foo1, stored_foo2], foo1, foo2)
# empty collection and no objects
assert collection_consists_of_objects([])
# ordering in collection does not matter
assert collection_consists_of_objects([stored_foo2, stored_foo1], foo1, foo2)
# contains wrong object
assert not collection_consists_of_objects([stored_foo1, stored_foo3], foo1, foo2)
# contains wrong number of objects
assert not collection_consists_of_objects([stored_foo1, stored_foo1, stored_foo2], foo1, foo2)
# if an object's primary key is not set, it cannot be equal to another object
foo1.id, stored_foo1.id = None, None
assert not collection_consists_of_objects([stored_foo1], foo1)
# Test utilities
mapper_registry = registry()