|
| 1 | +import pytest |
| 2 | +from sqlalchemy import select |
| 3 | + |
| 4 | + |
| 5 | +async def test_can_delete_by_instance(repository_class, model_class, sa_manager): |
| 6 | + model = model_class( |
| 7 | + model_id=1, |
| 8 | + name="Someone", |
| 9 | + ) |
| 10 | + model2 = model_class( |
| 11 | + model_id=2, |
| 12 | + name="SomeoneElse", |
| 13 | + ) |
| 14 | + repo = repository_class(sa_manager.get_bind()) |
| 15 | + await repo.save_many({model, model2}) |
| 16 | + |
| 17 | + results = [x for x in await repo.find()] |
| 18 | + assert len(results) == 2 |
| 19 | + |
| 20 | + await repo.delete_many([model]) |
| 21 | + results = [x for x in await repo.find()] |
| 22 | + assert len(results) == 1 |
| 23 | + assert results[0].model_id == 2 |
| 24 | + assert results[0].name == "SomeoneElse" |
| 25 | + |
| 26 | + |
| 27 | +async def test_delete_inexistent_raises_exception( |
| 28 | + repository_class, model_class, sa_manager |
| 29 | +): |
| 30 | + repo = repository_class(sa_manager.get_bind()) |
| 31 | + |
| 32 | + results = [x for x in await repo.find()] |
| 33 | + assert len(results) == 0 |
| 34 | + |
| 35 | + with pytest.raises(Exception): |
| 36 | + await repo.delete_many([4]) |
| 37 | + |
| 38 | + with pytest.raises(Exception): |
| 39 | + await repo.delete_many( |
| 40 | + [ |
| 41 | + model_class( |
| 42 | + model_id=823, |
| 43 | + name="Someone", |
| 44 | + ) |
| 45 | + ] |
| 46 | + ) |
| 47 | + |
| 48 | + |
| 49 | +async def test_relationships_are_respected( |
| 50 | + related_repository_class, related_model_classes, sa_manager |
| 51 | +): |
| 52 | + parent = related_model_classes[0]( |
| 53 | + name="A Parent", |
| 54 | + ) |
| 55 | + child = related_model_classes[1](name="A Child") |
| 56 | + child2 = related_model_classes[1](name="Another Child") |
| 57 | + parent.children.append(child) |
| 58 | + parent.children.append(child2) |
| 59 | + repo = related_repository_class(sa_manager.get_bind()) |
| 60 | + await repo.save(parent) |
| 61 | + |
| 62 | + retrieved_parent = await repo.get(parent.parent_model_id) |
| 63 | + assert len(retrieved_parent.children) == 2 |
| 64 | + |
| 65 | + await repo.delete_many([retrieved_parent]) |
| 66 | + |
| 67 | + async with repo._get_session() as session: |
| 68 | + result = [ |
| 69 | + x |
| 70 | + for x in (await session.execute(select(related_model_classes[1]))).scalars() |
| 71 | + ] |
| 72 | + assert len(result) == 0 |
0 commit comments