Skip to content

Commit

Permalink
Prevent configuration decoding errors from being swallowed
Browse files Browse the repository at this point in the history
  • Loading branch information
mgutski committed Jan 29, 2024
1 parent 09ac417 commit 85c6967
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@ public struct Configuration: Equatable, Decodable {
let container = try decoder.container(keyedBy: CodingKeys.self)
self = .init(
algorithm: try container.decode([String].self, forKey: .algorithm)[...],
defaultAccessModifier: try? container.decodeIfPresent(String.self, forKey: .defaultAccessModifier),
defaultNamespace: try? container.decodeIfPresent(String.self, forKey: .defaultNamespace),
implementationOnlyImport: try? container.decodeIfPresent(Bool.self, forKey: .implementationOnlyImport),
defaultAccessModifier: try container.decodeIfPresent(String.self, forKey: .defaultAccessModifier),
defaultNamespace: try container.decodeIfPresent(String.self, forKey: .defaultNamespace),
implementationOnlyImport: try container.decodeIfPresent(Bool.self, forKey: .implementationOnlyImport),
secrets: try container.decode([Secret].self, forKey: .secrets)[...]
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,49 @@ final class ConfigurationTests: XCTestCase {
)
}

func test_givenInvalidJSONEncodedConfiguration_whenDecodeWithJSONDecoder_thenThrowsError() {
// given
let invalidConfigurations = [
"""
{
"algorithm": ["compress using lz4"]
}
""",
"""
{
"secrets": [{ "name": "secret", "value": "value" }]
}
""",
"""
{
"algorithm": ["compress using lz4"],
"defaultAccessModifier": [],
"secrets": [{ "name": "secret", "value": "value" }]
}
""",
"""
{
"algorithm": ["compress using lz4"],
"defaultNamespace": [],
"secrets": [{ "name": "secret", "value": "value" }]
}
""",
"""
{
"algorithm": ["compress using lz4"],
"implementationOnlyImport": 1,
"secrets": [{ "name": "secret", "value": "value" }]
}
"""
].map { ($0, $0.data(using: .utf8)!) }
let decoder = JSONDecoder()

// when & then
for (json, jsonData) in invalidConfigurations {
XCTAssertThrowsError(try decoder.decode(Configuration.self, from: jsonData), json)
}
}

func test_givenSecretSingleValue_whenJSONEncodeUnderlyingValue_thenResultEqualsJSONEncodedAssociatedValue() throws {
// given
let associatedValue = "test"
Expand Down

0 comments on commit 85c6967

Please sign in to comment.