Cotton code
124 lines · 6.9 KB · SwiftRaw
import CottonKitimport SwiftUIimport XCTest@testable import CottonUI// Cotton Health's app is the iPhone's alone (HealthApp/ is iOS-only), so its// tests are too: the Mac guard suites build this target without it.#if os(iOS)/// Cotton Health on iPhone: every screen's answer read as the/// core really sends it (`Fixtures/Health`, written by cotton-ffi's/// `generate_health_screen_fixtures` for an invented person and report), the/// look read by Vault's decoder, and the one model sending each act back as it/// came: a row opens its screen without a call, a person's chip shows their/// records everywhere with every stack back at its root, a field is asked/// first, Set sex asks its choice. Synthetic data only.@MainActorfinal class HealthAppTests: XCTestCase {    private func fixture(_ name: String) throws -> String {        let url = try XCTUnwrap(Bundle(for: Self.self).url(forResource: name, withExtension: "json", subdirectory: "Fixtures/Health"))        return try String(contentsOf: url, encoding: .utf8)    }    private func decode<T: Decodable>(_ name: String, as type: T.Type) throws -> T {        try JSONDecoder().decode(type, from: Data(fixture(name).utf8))    }    /// RULE: every screen's answer and the look decode as the core sends them: Labs' strip and panels with each row's mark and trend, a parameter's points and readings, Reports and a report's facts and sections, Body, Settings, the people and an added report's toast.    func testEveryScreenReadsAsTheCoreSendsIt() throws {        let labs = try decode("labs", as: HealthLabs.self)        XCTAssertFalse(labs.panels.isEmpty)        let row = try XCTUnwrap(labs.panels.first?.rows.first)        XCTAssertEqual(row.act.method, CottonMethod.healthParameter)        XCTAssertTrue(row.latest.mono)        XCTAssertFalse(row.trend.isEmpty)        let parameter = try decode("parameter", as: HealthParameter.self)        XCTAssertFalse(parameter.points.isEmpty)        XCTAssertEqual(parameter.readings.first?.act.method, CottonMethod.healthReport)        let reports = try decode("reports", as: HealthReports.self)        XCTAssertEqual(reports.rows.count, 1)        XCTAssertEqual(reports.add.method, CottonMethod.healthAddReport)        let report = try decode("report", as: HealthReport.self)        XCTAssertFalse(report.facts.isEmpty)        XCTAssertFalse(report.sections.flatMap(\.rows).isEmpty)        XCTAssertEqual(report.pdf?.request["act"]?.string, "open_pdf")        _ = try decode("body", as: HealthBody.self)        let settings = try decode("settings", as: HealthSettings.self)        XCTAssertFalse(settings.sections.isEmpty)        let people = try decode("people", as: HealthPeople.self)        XCTAssertEqual(people.people.first?.owner, true)        XCTAssertEqual(people.add.input?.key, "name")        let added = try decode("add", as: HealthAddAnswer.self)        XCTAssertEqual(added.outcome, "added")        XCTAssertNotNil(added.toast)        let look = try decode("look", as: VaultLook.self)        XCTAssertNotEqual(look.colour("in_range", .light), .clear, "a state's colour is a role the look names")        XCTAssertNotEqual(look.colour("trend_line", .dark), .clear)        XCTAssertNotNil(look.role("value"))    }    /// RULE: a row's act opens its screen and sends nothing until that screen reads; a person's chip shows their records on every place, each stack back at its root; an act with a field asks it first; Set sex asks its choice first.    func testActsOpenScreensAndSwitchPeopleWithoutGuessing() async throws {        let core = ScriptedCore([CottonMethod.healthPeople: .ok(try fixture("people"))])        let model = HealthModel(core: core, toasts: ToastCenter())        let labs = try decode("labs", as: HealthLabs.self)        let row = try XCTUnwrap(labs.panels.first?.rows.first)        await model.run(row.act)        XCTAssertEqual(model.paths[.labs], [.parameter(row.act.request)])        let none = await core.calls        XCTAssertTrue(none.isEmpty, "opening a screen sends nothing itself")        let other = VaultAct(id: "switch", label: "Show", method: CottonMethod.healthLabs, request: .object(["person": .string("p-2")]))        await model.run(other)        XCTAssertEqual(model.person, "p-2")        XCTAssertTrue(model.paths.isEmpty, "nothing of one person stands over another's")        XCTAssertEqual(model.personal()["person"]?.string, "p-2")        let people = try decode("people", as: HealthPeople.self)        await model.run(people.add)        guard case .input(let asked)? = model.sheet else { return XCTFail("the name is asked first") }        XCTAssertEqual(asked.input?.key, "name")        let settings = try decode("settings", as: HealthSettings.self)        let setSex = try XCTUnwrap(settings.sections.flatMap(\.rows).flatMap(\.acts).first { $0.request["act"]?.string == "set_sex" })        await model.run(setSex)        guard case .choice(let sex)? = model.sheet else { return XCTFail("Set sex asks its choice") }        XCTAssertEqual(sex.input?.choices?.map(\.label).count, 3, "the core's choices, Not said among them")        XCTAssertEqual(sex.input?.choices?.last?.value, "", "Not said is sent as no value")    }    /// RULE: Settings ends with Account, and Sign in opens this device's own flow from the core's answer (the shell's, as every app opens it); nothing else is drawn for it.    func testSignInOpensThisDevicesOwnFlow() async throws {        let settings = try decode("settings", as: HealthSettings.self)        XCTAssertEqual(settings.sections.last?.id, "account")        let signIn = try XCTUnwrap(settings.sections.last?.rows.flatMap(\.acts).first { $0.id == "sign_in" })        let core = ScriptedCore([CottonMethod.healthAct: .ok(try fixture("sign_in")), CottonMethod.healthPeople: .ok(try fixture("people"))])        let model = HealthModel(core: core, toasts: ToastCenter())        var opened: [RecordKeptFlow.Flow] = []        model.nativeFlow = { flow in            opened.append(flow.flow)            return true        }        await model.run(signIn)        XCTAssertEqual(opened, [.signIn])        XCTAssertNil(model.sheet)    }    /// RULE: a history's scale holds every point, its least and most and the lab's band; a single reading stands in the middle.    func testAHistorysScaleHoldsEveryPointAndTheBand() throws {        let points = try decode("parameter", as: HealthParameter.self).points        let band = HealthBand(low: 0, high: 400, said: "")        let scale = HealthTrendScale(points, band: band)        XCTAssertLessThan(scale.low, 0)        XCTAssertGreaterThan(scale.high, 400)        for point in points {            let y = scale.y(point.value, height: 100)            XCTAssertTrue((0...100).contains(y))        }        XCTAssertEqual(scale.x("2024-03-12", width: 200, single: true), 100)        XCTAssertEqual(HealthDay.string(try XCTUnwrap(HealthTrendScale.date("2024-03-12"))).count, 10)    }}#endif