2025-09-24 19:51:39 -07:00
|
|
|
import pytest
|
|
|
|
from tinydb.storages import MemoryStorage
|
|
|
|
|
2025-09-24 21:34:32 -07:00
|
|
|
from grung import examples
|
2025-09-24 19:51:39 -07:00
|
|
|
from grung.db import GrungDB
|
2025-09-27 12:09:43 -07:00
|
|
|
from grung.exceptions import UniqueConstraintError
|
2025-09-24 19:51:39 -07:00
|
|
|
|
|
|
|
|
|
|
|
@pytest.fixture
|
|
|
|
def db():
|
2025-09-24 21:34:32 -07:00
|
|
|
_db = GrungDB.with_schema(examples, storage=MemoryStorage)
|
2025-09-24 19:51:39 -07:00
|
|
|
yield _db
|
|
|
|
print(_db)
|
|
|
|
|
|
|
|
|
|
|
|
def test_crud(db):
|
2025-09-24 21:34:32 -07:00
|
|
|
user = examples.User(name="john", email="john@foo")
|
2025-09-24 19:51:39 -07:00
|
|
|
assert user.uid
|
|
|
|
assert user._metadata.fields["uid"].unique
|
|
|
|
|
|
|
|
# insert
|
|
|
|
john_something = db.save(user)
|
|
|
|
last_insert_id = john_something.doc_id
|
|
|
|
|
|
|
|
# read back
|
|
|
|
assert db.User.get(doc_id=last_insert_id) == john_something
|
|
|
|
assert john_something.name == user.name
|
|
|
|
assert john_something.email == user.email
|
|
|
|
assert john_something.uid == user.uid
|
|
|
|
|
|
|
|
# update
|
|
|
|
john_something.name = "james?"
|
|
|
|
before_update = db.User.get(doc_id=john_something.doc_id)
|
|
|
|
after_update = db.save(john_something)
|
|
|
|
assert after_update == john_something
|
|
|
|
assert before_update != after_update
|
|
|
|
|
|
|
|
# pointers
|
2025-09-24 21:34:32 -07:00
|
|
|
players = examples.Group(name="players", users=[john_something])
|
2025-09-24 19:51:39 -07:00
|
|
|
players = db.save(players)
|
|
|
|
players.users[0]["name"] = "fnord"
|
|
|
|
db.save(players)
|
|
|
|
|
|
|
|
# modify records
|
|
|
|
players.users = []
|
|
|
|
db.save(players)
|
|
|
|
after_update = db.Group.get(doc_id=players.doc_id)
|
|
|
|
assert after_update.users == []
|
|
|
|
|
|
|
|
# delete
|
|
|
|
db.delete(players)
|
|
|
|
assert len(db.Group) == 0
|
2025-09-27 12:09:43 -07:00
|
|
|
|
|
|
|
|
|
|
|
def test_unique(db):
|
|
|
|
user1 = examples.User(name="john", email="john@foo")
|
|
|
|
user2 = examples.User(name="john", email="john@foo")
|
|
|
|
|
|
|
|
user1 = db.save(user1)
|
|
|
|
with pytest.raises(UniqueConstraintError):
|
|
|
|
user2 = db.save(user2)
|
|
|
|
db.save(user1)
|