예제 #1
0
def test_ReltionshipFields_DOT_dict__by_order(connection: dcdb.DBConnection):
    # TODO should refactor to have a stack based dictionary class because
    # otherwise this behavior is a tad confusing.

    @dataclass()
    class Box:
        widget = dcdb.RelationshipFields.dict("Thing.name",
                                              "parent_id",
                                              by_order="version")

    @dataclass()
    class Thing:
        name: str
        version: int
        parent_id: int = None

    connection.binds(Box, Thing)

    b = connection.t.Box()

    object1 = b.widget.create(name="Foo", version=1)
    object2 = b.widget.create(name="Foo", version=3)
    object3 = b.widget.create(name="Foo", version=2)

    assert b.widget['Foo'].id == 2

    object3 = b.widget.create(name="Foo", version=4)

    assert b.widget['Foo'].id == 4
예제 #2
0
def test_RelationshipFields_dot_dict__works(connection: dcdb.DBConnection):
    @dataclass()
    class House:
        price: float
        name: str
        furniture = dcdb.RelationshipFields.dict("Furniture", "type",
                                                 "house_id")

    @dataclass()
    class Furniture:
        type: str
        material: str
        quantity: int

        house_id: int = None  # TODO foreign key constraint

    # setup
    connection.binds(House, Furniture)
    house = connection.t.House(price=123.45, name="The Manor")

    # Ensure relationship is bound on direct creation
    house.furniture.create(type="Chair", material="Wood", quantity=10)
    assert len(house.furniture) == 1
    assert house.furniture["chair"] is None
    assert house.furniture["Chair"].material == "Wood"

    # ensure binding is independant
    sofa = connection.t.Furniture(type="Sofa", material="cloth", quantity=2)
    assert len(house.furniture) == 1

    # test count and retrieval
    house.furniture.add(sofa)
    assert len(house.furniture) == 2
    assert house.furniture["Sofa"].quantity == 2

    # verify integrity
    keys = house.furniture.keys()
    assert "Sofa" in keys
    assert "Chair" in keys

    #
    del house.furniture['Chair']
    furniture_count = connection.direct(
        "SELECT count(*) FROM Furniture").fetchone()[0]
    assert furniture_count == 2
    assert len(house.furniture) == 1