Skip to content
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
54 changes: 36 additions & 18 deletions Sources/HTTPMock/Models/MockResponse.swift
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,24 @@ extension MockResponse {
delivery: Delivery = .instant,
headers: [String: String] = [:],
jsonEncoder: JSONEncoder = .mockDefault
) throws -> MockResponse {
let data = try jsonEncoder.encode(payload)
return Self.init(
payload: .data(data, contentType: "application/json"),
status: status,
lifetime: lifetime,
delivery: delivery,
headers: headers
)
) -> MockResponse {
do {
let data = try jsonEncoder.encode(payload)
return Self.init(
payload: .data(data, contentType: "application/json"),
status: status,
lifetime: lifetime,
delivery: delivery,
headers: headers
)
} catch {
HTTPMockLog.error("""
Failed to encode payload to JSON data. Fallback to `.empty()`.
Payload: \(payload)
Error: \(error)
""")
return .empty()
}
}

public static func dictionary(
Expand All @@ -63,15 +72,24 @@ extension MockResponse {
lifetime: Lifetime = .single,
delivery: Delivery = .instant,
headers: [String: String] = [:]
) throws -> MockResponse {
let data = try JSONSerialization.data(withJSONObject: payload)
return Self.init(
payload: .data(data, contentType: "application/json"),
status: status,
lifetime: lifetime,
delivery: delivery,
headers: headers
)
) -> MockResponse {
do {
let data = try JSONSerialization.data(withJSONObject: payload)
return Self.init(
payload: .data(data, contentType: "application/json"),
status: status,
lifetime: lifetime,
delivery: delivery,
headers: headers
)
} catch {
HTTPMockLog.error("""
Failed to serialize payload to JSON data. Fallback to `.empty()`.
Payload: \(payload)
Error: \(error)
""")
return .empty()
}
}

public static func plaintext(
Expand Down
4 changes: 2 additions & 2 deletions Tests/HTTPMockTests/HTTPMockTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -157,13 +157,13 @@ struct HTTPMockTests {
}

@Test
func itSetsDefaultContentTypeAndAllowsOverride() throws {
func itSetsDefaultContentTypeAndAllowsOverride() {
// `plaintext` default
let plainText = MockResponse.plaintext("hi")
#expect(plainText.headers["Content-Type"] == "text/plain")

// `encodable` default
let encodable = try MockResponse.encodable(DummyData())
let encodable = MockResponse.encodable(DummyData())
#expect(encodable.headers["Content-Type"] == "application/json")

// Override content type via explicit headers
Expand Down