Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixing decoding times if times was never encoded error #12

Merged
merged 5 commits into from
Mar 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Sources/SpeziMedication/Models/Schedule.swift
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public struct Schedule: Codable, Equatable, Hashable {
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.frequency = try container.decode(Frequency.self, forKey: .frequency)
self.times = try container.decode([ScheduledTime].self, forKey: .times)
self.times = try container.decodeIfPresent([ScheduledTime].self, forKey: .times) ?? []
apgupta3303 marked this conversation as resolved.
Show resolved Hide resolved
self.startDate = try container.decode(Date.self, forKey: .startDate)
}

Expand Down
53 changes: 53 additions & 0 deletions Tests/SpeziMedicationTests/SpeziMedicationTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,59 @@ import XCTest


final class SpeziMedicationTests: XCTestCase {
func testScheduleDecodingWithAndWithoutTimes() throws {
let jsonDecoder = JSONDecoder()
jsonDecoder.dateDecodingStrategy = .iso8601

// Test decoding without times
let noTimesJSON = """
{
"frequency": {
"asNeeded": true
},
"startDate": "2023-12-07T08:00:00Z"
}
"""
guard let data = noTimesJSON.data(using: .utf8) else {
XCTFail("Failed to encode JSON string to Data")
return
}
let noTimesSchedule = try jsonDecoder.decode(Schedule.self, from: data)
XCTAssertEqual(noTimesSchedule.times, [])

// Test decoding with times
let withTimesJSON = """
{
"frequency": {
"regularDayIntervals": 2
},
"startDate": "2023-12-07T08:00:00Z",
"times": [
{
"time": {
"hour": 8,
"minute": 0
},
"dosage": 5.0
},
{
"time": {
"hour": 15,
"minute": 0
},
"dosage": 5.0
}
]
}
"""
guard let dataWithTimes = withTimesJSON.data(using: .utf8) else {
XCTFail("Failed to encode JSON string to Data")
return
}
let withTimesSchedule = try jsonDecoder.decode(Schedule.self, from: dataWithTimes)
XCTAssertNotNil(withTimesSchedule.times)
}

// swiftlint:disable:next function_body_length
func testScheduleEncoding() throws {
let jsonEncoder = JSONEncoder()
Expand Down
Loading