import Foundation import HelderCore import Testing @Suite struct SchemaLayoutTests { private typealias F = SchemaFixtures @Test func lanesFollowTheForeignKeyDepth() { #expect(SchemaLayout.lanes(F.contractModel) == ["users": 0, "conversations": 1, "messages": 2]) } @Test func aTableTakesTheLaneAfterItsDeepestTarget() { let model = F.model(["a", "b", "c"], edges: [F.edge("c", "a"), F.edge("c", "b", column: "c0", index: 0), F.edge("b", "a")]) #expect(SchemaLayout.lanes(model) == ["a": 0, "b": 1, "c": 2]) } @Test func aSelfReferenceIsIgnored() { let model = F.model(["a", "b"], edges: [F.edge("a", "a"), F.edge("b", "a", column: "c0", index: 0)]) #expect(SchemaLayout.lanes(model) == ["a": 0, "b": 1]) } @Test func aCycleIsBrokenWhereItCloses() { let model = F.model(["a", "b", "c"], edges: [F.edge("a", "b"), F.edge("b", "c"), F.edge("c", "a")]) #expect(SchemaLayout.lanes(model) == ["c": 0, "b": 1, "a": 2]) } @Test func lanesAreSpacedAndCentredAgainstTheTallest() { let model = F.model(["a", "b", "x"], edges: [F.edge("x", "a")]) let positions = SchemaLayout.defaultPositions(model) // Cards of two columns are 79 tall: lane 0 holds two (254 with gaps), lane 1 one (127). #expect(positions["a"] == SchemaPoint(x: 40, y: 40)) #expect(positions["b"] == SchemaPoint(x: 40, y: 167)) #expect(positions["x"] == SchemaPoint(x: 380, y: 104)) } @Test func aLaneIsOrderedByTheHeightOfItsTargets() { let model = F.model(["a", "b", "x", "y"], edges: [F.edge("x", "b"), F.edge("y", "a")]) let positions = SchemaLayout.defaultPositions(model) #expect(positions["y"]!.y < positions["x"]!.y) } @Test func cardsInALaneDoNotOverlap() { let model = F.model(["a", "b", "c", "d"], edges: [], columns: 5) let ys = SchemaLayout.defaultPositions(model).values.map(\.y).sorted() for (upper, lower) in zip(ys, ys.dropFirst()) { #expect(lower - upper == SchemaGeometry.cardHeight(columns: 5) + SchemaMetrics.cardGap) } } @Test func theLayoutIsDeterministic() { let edges = [F.edge("a", "b"), F.edge("b", "a"), F.edge("c", "a"), F.edge("d", "c"), F.edge("e", "e")] let model = F.model(["a", "b", "c", "d", "e"], edges: edges) let reversed = SchemaModel(connectionLabel: "test", tables: model.tables.reversed(), edges: edges.reversed()) let first = SchemaLayout.defaultPositions(model) #expect(first.count == 5) #expect(SchemaLayout.defaultPositions(model) == first) #expect(SchemaLayout.defaultPositions(reversed) == first) } @Test func anEmptyModelHasNoPositions() { #expect(SchemaLayout.defaultPositions(F.model([], edges: [])).isEmpty) } @Test func savedPositionsWinForTablesThatStillExist() { let model = F.model(["a", "b"], edges: []) let positions = SchemaLayout.positions(model, saved: ["a": SchemaPoint(x: 1, y: 2), "gone": SchemaPoint(x: 9, y: 9)]) #expect(positions["a"] == SchemaPoint(x: 1, y: 2)) #expect(positions["b"] == SchemaLayout.defaultPositions(model)["b"]) #expect(positions["gone"] == nil) } }