menubar-pet/Tests/PetKitTests/PetStateTests.swift
46 lines · 2076 bytes
1import XCTest
2@testable import PetKit
3
4/// The other half of the contract with `pet-life`. Its JSON is pinned to exact
5/// bytes by a Rust test; this asserts Swift reads those same bytes. The wire
6/// format between the daemon and the collector drifted twice in this project,
7/// and both times a pinned fixture is what caught it.
8final class PetStateTests: XCTestCase {
9 /// Verbatim from pet-life's own `the_json_contract_is_exact` test.
10 let living = #"""
11 {"alive":true,"name":"Ash","generation":2,"stage":"content","face":"(^ω^)","age_days":0.50,"quiet_days":0.50,"cemetery":[{"name":"Marble","generation":1,"lived_days":7.00}]}
12 """#
13
14 /// A pet that has died: name and generation are null, not absent.
15 let dead = #"""
16 {"alive":false,"name":null,"generation":null,"stage":"dead","face":"†","age_days":0.00,"quiet_days":31.00,"cemetery":[{"name":"Marble","generation":1,"lived_days":7.00}]}
17 """#
18
19 func testDecodesALivingPet() throws {
20 let pet = try PetState.decode(Data(living.utf8))
21 XCTAssertTrue(pet.alive)
22 XCTAssertEqual(pet.name, "Ash")
23 XCTAssertEqual(pet.generation, 2)
24 XCTAssertEqual(pet.stage, "content")
25 XCTAssertEqual(pet.face, "(^ω^)")
26 XCTAssertEqual(pet.age_days, 0.5, accuracy: 0.001)
27 XCTAssertEqual(pet.cemetery.count, 1)
28 XCTAssertEqual(pet.cemetery[0].name, "Marble")
29 XCTAssertEqual(pet.cemetery[0].lived_days, 7.0, accuracy: 0.001)
30 }
31
32 /// The null case is the one a naive `String` rather than `String?` would
33 /// break on, and it is exactly the state the app must render.
34 func testDecodesADeadPet() throws {
35 let pet = try PetState.decode(Data(dead.utf8))
36 XCTAssertFalse(pet.alive)
37 XCTAssertNil(pet.name)
38 XCTAssertNil(pet.generation)
39 XCTAssertEqual(pet.stage, "dead")
40 XCTAssertEqual(pet.cemetery.count, 1, "the dead are still remembered")
41 }
42
43 func testRejectsSomethingThatIsNotAPet() {
44 XCTAssertThrowsError(try PetState.decode(Data(#"{"nope":1}"#.utf8)))
45 }
46}