From 58bbf5f7493ff32e09e7b0c77f78e97c39737c01 Mon Sep 17 00:00:00 2001 From: Dariusz Rybicki <dariusz@elixxir.io> Date: Fri, 3 Jun 2022 12:33:30 +0200 Subject: [PATCH] Add RestlikeMessage codable model --- Sources/ElixxirDAppsSDK/RestlikeMessage.swift | 37 +++++++++++++++++ .../RestlikeMessageTests.swift | 40 +++++++++++++++++++ 2 files changed, 77 insertions(+) create mode 100644 Sources/ElixxirDAppsSDK/RestlikeMessage.swift create mode 100644 Tests/ElixxirDAppsSDKTests/RestlikeMessageTests.swift diff --git a/Sources/ElixxirDAppsSDK/RestlikeMessage.swift b/Sources/ElixxirDAppsSDK/RestlikeMessage.swift new file mode 100644 index 00000000..48b0e5ef --- /dev/null +++ b/Sources/ElixxirDAppsSDK/RestlikeMessage.swift @@ -0,0 +1,37 @@ +import Foundation + +public struct RestlikeMessage: Equatable { + public init( + version: Int, + headers: Data, + content: Data, + method: Int, + uri: String, + error: String + ) { + self.version = version + self.headers = headers + self.content = content + self.method = method + self.uri = uri + self.error = error + } + + public var version: Int + public var headers: Data + public var content: Data + public var method: Int + public var uri: String + public var error: String +} + +extension RestlikeMessage: Codable { + enum CodingKeys: String, CodingKey { + case version = "Version" + case headers = "Headers" + case content = "Content" + case method = "Method" + case uri = "URI" + case error = "Error" + } +} diff --git a/Tests/ElixxirDAppsSDKTests/RestlikeMessageTests.swift b/Tests/ElixxirDAppsSDKTests/RestlikeMessageTests.swift new file mode 100644 index 00000000..3471119a --- /dev/null +++ b/Tests/ElixxirDAppsSDKTests/RestlikeMessageTests.swift @@ -0,0 +1,40 @@ +import CustomDump +import XCTest +@testable import ElixxirDAppsSDK + +final class RestlikeMessageTests: XCTestCase { + func testCoding() throws { + let headers = secureRandomData(count: 32) + let content = secureRandomData(count: 32) + let jsonString = """ + { + "Version": 1, + "Headers": \(headers.jsonEncodedBase64()), + "Content": \(content.jsonEncodedBase64()), + "Method": 2, + "URI": "xx://CmixRestlike/rest", + "Error": "" + } + """ + let jsonData = jsonString.data(using: .utf8)! + let decoder = JSONDecoder() + decoder.dataDecodingStrategy = .base64 + let message = try decoder.decode(RestlikeMessage.self, from: jsonData) + + XCTAssertNoDifference(message, RestlikeMessage( + version: 1, + headers: headers, + content: content, + method: 2, + uri: "xx://CmixRestlike/rest", + error: "" + )) + + let encoder = JSONEncoder() + encoder.dataEncodingStrategy = .base64 + let encodedMessage = try encoder.encode(message) + let decodedMessage = try decoder.decode(RestlikeMessage.self, from: encodedMessage) + + XCTAssertNoDifference(decodedMessage, message) + } +} -- GitLab