Skip to content

Commit ffff1a8

Browse files
authored
Fix UnkeyedContainer crash for collections with nil (#200)
1 parent c0359c4 commit ffff1a8

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

Sources/Leaf/LeafEncoder.swift

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,9 @@ private final class UnkeyedContainer: UnkeyedEncodingContainer, _Container {
189189
} else {
190190
let encoder = _Encoder(codingPath: codingPath)
191191
try value.encode(to: encoder)
192-
self.array.append(encoder.container!.data!)
192+
if let safeData = encoder.container!.data {
193+
self.array.append(safeData)
194+
}
193195
}
194196
}
195197

Tests/LeafTests/LeafTests.swift

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import Leaf
22
import LeafKit
33
import XCTVapor
4+
import Foundation
45

56
class LeafTests: XCTestCase {
67
func testApplication() throws {
@@ -258,6 +259,40 @@ class LeafTests: XCTestCase {
258259
XCTAssertEqual(res.status, .internalServerError)
259260
}
260261
}
262+
263+
// Test for GH Issue #197
264+
func testNoFatalErrorWhenAttemptingToUseArrayWithNil() throws {
265+
var test = TestFiles()
266+
test.files["/foo.leaf"] = """
267+
#(value)
268+
"""
269+
270+
let app = Application(.testing)
271+
defer { app.shutdown() }
272+
app.views.use(.leaf)
273+
app.leaf.sources = .singleSource(test)
274+
275+
struct ArrayWithNils: Content {
276+
let value:[UUID?]
277+
}
278+
279+
let id1 = UUID.init()
280+
let id2 = UUID.init()
281+
282+
283+
app.get("noCrash") { req -> EventLoopFuture<View> in
284+
let context = ArrayWithNils(value: [id1,nil,id2, nil])
285+
return req.view.render("foo", context)
286+
}
287+
288+
try app.test(.GET, "noCrash") { res in
289+
// Expected result .ok
290+
XCTAssertEqual(res.status, .ok)
291+
292+
// Rendered result should match to all non-nil values
293+
XCTAssertEqual(res.body.string, "[\"\(id1)\", \"\(id2)\"]")
294+
}
295+
}
261296
}
262297

263298
/// Helper `LeafFiles` struct providing an in-memory thread-safe map of "file names" to "file data"

0 commit comments

Comments
 (0)