100 lines
2.9 KiB
Swift
100 lines
2.9 KiB
Swift
//
|
|
// JSONParsingTests.swift
|
|
//
|
|
//
|
|
// Created by Nut.Tech on 17.02.2023.
|
|
//
|
|
|
|
import XCTest
|
|
@testable import WalletKit
|
|
|
|
fileprivate struct User: Decodable {
|
|
let id: Int
|
|
let name: String
|
|
var employer: String?
|
|
static var employerUserInfoKey: CodingUserInfoKey? {
|
|
return CodingUserInfoKey(rawValue: "employer")
|
|
}
|
|
|
|
private enum CodingKeys: String, CodingKey {
|
|
case id
|
|
case name
|
|
}
|
|
|
|
init(from decoder: Decoder) throws {
|
|
let keyedContainer = try decoder.container(keyedBy: CodingKeys.self)
|
|
self.id = try keyedContainer.decode(Int.self, forKey: .id)
|
|
self.name = try keyedContainer.decode(String.self, forKey: .name)
|
|
|
|
guard let employerKey = Self.employerUserInfoKey,
|
|
let employer = decoder.userInfo[employerKey] as? String else {
|
|
return
|
|
}
|
|
self.employer = employer
|
|
}
|
|
}
|
|
|
|
final class JSONParsingTests: XCTestCase {
|
|
|
|
private enum Locals {
|
|
static let username1 = "Username1"
|
|
static let username2 = "Username2"
|
|
static let userId1 = 1
|
|
static let userId2 = 2
|
|
static let companyName = "Company Name"
|
|
}
|
|
|
|
func testJsonDecoded() {
|
|
let jsonData = """
|
|
{"id": \(Locals.userId1), "name": "\(Locals.username1)"}
|
|
""".data(using: .utf8)!
|
|
|
|
guard let user: User = jsonData.jsonDecoded(type: User.self) else {
|
|
XCTFail("Error decoding data")
|
|
return
|
|
}
|
|
|
|
XCTAssertEqual(user.id, Locals.userId1)
|
|
XCTAssertEqual(user.name, Locals.username1)
|
|
}
|
|
|
|
func testJsonDecodedArray() {
|
|
let jsonData = """
|
|
[{"id": \(Locals.userId1), "name": "\(Locals.username1)"}, {"id": \(Locals.userId2), "name": "\(Locals.username2)"}]
|
|
""".data(using: .utf8)!
|
|
|
|
guard let users: [User] = jsonData.jsonDecoded(type: User.self) else {
|
|
XCTFail("Error decoding data")
|
|
return
|
|
}
|
|
|
|
XCTAssertEqual(users.count, 2)
|
|
XCTAssertEqual(users[0].id, Locals.userId1)
|
|
XCTAssertEqual(users[0].name, Locals.username1)
|
|
XCTAssertEqual(users[1].id, Locals.userId2)
|
|
XCTAssertEqual(users[1].name, Locals.username2)
|
|
}
|
|
|
|
func testJsonDecodedWithUserInfo() {
|
|
let jsonData = """
|
|
{"id": \(Locals.userId1), "name": "\(Locals.username1)"}
|
|
""".data(using: .utf8)!
|
|
|
|
guard let key = CodingUserInfoKey(rawValue: "employer") else {
|
|
XCTFail("Error creating user key")
|
|
return
|
|
}
|
|
|
|
let userInfo = [key: Locals.companyName]
|
|
|
|
guard let user: User = jsonData.jsonDecoded(type: User.self, userInfo: userInfo) else {
|
|
XCTFail("Error decoding data")
|
|
return
|
|
}
|
|
|
|
XCTAssertEqual(user.id, Locals.userId1)
|
|
XCTAssertEqual(user.name, Locals.username1)
|
|
XCTAssertEqual(user.employer, Locals.companyName)
|
|
}
|
|
}
|