← All repositories

reportage

A life-logging app for iPhone

git clone https://code.inqk.net/reportage.git


Tests/Unit/ReporterArchiveTests.swift (2190B)

1import Foundation
2import Testing
3
4@testable import Reportage
5
6@Suite("ReporterArchive")
7struct ReporterArchiveTests {
8
9    @Test("The junk prefix before the opening brace is skipped")
10    func junkPrefix() throws {
11        let data = try Fixtures.reporterExport()
12        #expect(data.prefix(3) == Data([0xEF, 0xBF, 0xBF]))
13
14        let archive = try ReporterArchive(data: data)
15        #expect(archive.questions.count == 8)
16        #expect(archive.snapshots.count == 14)
17        #expect(archive.snapshots.allSatisfy { $0.fields != nil })
18    }
19
20    @Test("Data without an object is rejected")
21    func noObject() {
22        #expect(throws: ReporterArchive.Error.noJSONObject) {
23            try ReporterArchive(data: Data([0xEF, 0xBF, 0xBF]))
24        }
25    }
26
27    @Test("Missing arrays are rejected")
28    func missingArray() {
29        #expect(throws: ReporterArchive.Error.missingArray("snapshots")) {
30            try ReporterArchive(data: Data(#"{"questions":[]}"#.utf8))
31        }
32    }
33
34    @Test("A snapshot that can't be decoded is kept with its error")
35    func undecodableSnapshot() throws {
36        let archive = try ReporterArchive(
37            data: Data(#"{"questions":[],"snapshots":[{"date":1}]}"#.utf8))
38        #expect(archive.snapshots.count == 1)
39        #expect(archive.snapshots[0].fields == nil)
40        #expect(archive.snapshots[0].decodingError != nil)
41    }
42
43    @Test("Numbers decode from ints, floats and strings")
44    func lenientNumbers() throws {
45        let decoder = JSONDecoder()
46        let numbers = try decoder.decode(
47            [LenientNumber].self, from: Data(#"[1, 2.5, "50%", " 64 ", "-3"]"#.utf8))
48        #expect(numbers.map(\.value) == [1, 2.5, 50, 64, -3])
49        #expect(numbers[0].int == 1)
50
51        #expect(throws: DecodingError.self) {
52            try decoder.decode(LenientNumber.self, from: Data(#""N/A""#.utf8))
53        }
54    }
55
56    @Test("Numeric answers decode exactly")
57    func lenientDecimals() throws {
58        let decimals = try JSONDecoder().decode(
59            [LenientDecimal].self, from: Data(#"["0", "6.5", 7.25]"#.utf8))
60        #expect(decimals.map(\.value) == [0, Decimal(string: "6.5")!, Decimal(string: "7.25")!])
61    }
62}