Repository Public
1// SP Notes Core2// File: Tests/SPNotesAPITests/NextFixtureSupport.swift3// Description: Loads the fixtures recorded from the scratch backend by Scripts/record-next-fixtures.sh4// (Tests/SPNotesAPITests/Fixtures/next/<group>/<name>.json + _index.json).5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import XCTest10@testable import SPNotesAPI1112/// One recorded answer of the scratch backend.13struct NextFixture {14 struct Entry: Decodable {15 var name: String16 var file: String17 var method: String18 var path: String19 var status: Int20 var headers: [String: String]21 }2223 var entry: Entry24 var data: Data2526 private static func directory(_ group: String) throws -> URL {27 let root = try XCTUnwrap(Bundle.module.url(forResource: "Fixtures", withExtension: nil), "Fixtures resource")28 return root.appendingPathComponent("next").appendingPathComponent(group)29 }3031 static func index(_ group: String) throws -> [Entry] {32 try JSONDecoder().decode([Entry].self, from: Data(contentsOf: directory(group).appendingPathComponent("_index.json")))33 }3435 static func load(_ group: String, _ name: String, file: StaticString = #filePath, line: UInt = #line) throws -> NextFixture {36 let entry = try XCTUnwrap(index(group).first { $0.name == name }, "no fixture \(group)/\(name)", file: file, line: line)37 return NextFixture(entry: entry, data: try Data(contentsOf: directory(group).appendingPathComponent(entry.file)))38 }3940 /// Decodes a 2xx fixture with the decoder of the client.41 static func decode<T: Decodable>(_ type: T.Type, _ group: String, _ name: String, file: StaticString = #filePath, line: UInt = #line) throws -> T {42 let fixture = try load(group, name, file: file, line: line)43 XCTAssertTrue((200..<300).contains(fixture.entry.status), "\(group)/\(name) is a \(fixture.entry.status)", file: file, line: line)44 do { return try APIJSON.decoder().decode(T.self, from: fixture.data) } catch {45 XCTFail("\(group)/\(name) does not decode as \(T.self): \(error)", file: file, line: line)46 throw error47 }48 }4950 /// The typed error the client builds from a non-2xx fixture.51 static func error(_ group: String, _ name: String, file: StaticString = #filePath, line: UInt = #line) throws -> APIError {52 let fixture = try load(group, name, file: file, line: line)53 XCTAssertFalse((200..<300).contains(fixture.entry.status), "\(group)/\(name) is not an error", file: file, line: line)54 return APIError.fromResponse(status: fixture.entry.status, body: fixture.data)55 }56}57