diff --git a/Sources/Path+Extensions.swift b/Sources/Path+Extensions.swift new file mode 100644 index 0000000..98f2d6f --- /dev/null +++ b/Sources/Path+Extensions.swift @@ -0,0 +1,20 @@ + +import Foundation + +extension Path: Codable { + public init?(_ string: String?) { + guard let string = string else { return nil } + self.init(string) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + try container.encode(string) + } + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + let string: String = try container.decode(String.self) + self.init(string) + } +} diff --git a/Tests/PathKitTests/XCTest.swift b/Tests/PathKitTests/XCTest.swift index 6d6fee2..242c9d4 100644 --- a/Tests/PathKitTests/XCTest.swift +++ b/Tests/PathKitTests/XCTest.swift @@ -4,4 +4,37 @@ class PathKitTests: XCTestCase { func testRunSpectre() { testPathKit() } + + func test_codable() throws { + // GIVEN + let path: Path = .init("/testPath") + let encoder: JSONEncoder = .init() + let decoder: JSONDecoder = .init() + + // WHEN + let data: Data = try encoder.encode(path) + let decodedPath: Path = try decoder.decode(Path.self, from: data) + + // THEN + XCTAssertEqual(path, decodedPath) + } + + func test_init_string() { + // GIVEN + let path: Path = .init("/testPath") + + // WHEN + let initPath: Path = .init(path.string) + + // THEN + XCTAssertEqual(path, initPath) + } + + func test_init_nil() { + // WHEN + let initPath: Path? = .init(nil) + + // THEN + XCTAssertNil(initPath) + } }