Skip to content

Commit

Permalink
Fix UnkeyedContainer crash for collections with nil (#200)
Browse files Browse the repository at this point in the history
  • Loading branch information
fananek authored Dec 16, 2021
1 parent c0359c4 commit ffff1a8
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
4 changes: 3 additions & 1 deletion Sources/Leaf/LeafEncoder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,9 @@ private final class UnkeyedContainer: UnkeyedEncodingContainer, _Container {
} else {
let encoder = _Encoder(codingPath: codingPath)
try value.encode(to: encoder)
self.array.append(encoder.container!.data!)
if let safeData = encoder.container!.data {
self.array.append(safeData)
}
}
}

Expand Down
35 changes: 35 additions & 0 deletions Tests/LeafTests/LeafTests.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import Leaf
import LeafKit
import XCTVapor
import Foundation

class LeafTests: XCTestCase {
func testApplication() throws {
Expand Down Expand Up @@ -258,6 +259,40 @@ class LeafTests: XCTestCase {
XCTAssertEqual(res.status, .internalServerError)
}
}

// Test for GH Issue #197
func testNoFatalErrorWhenAttemptingToUseArrayWithNil() throws {
var test = TestFiles()
test.files["/foo.leaf"] = """
#(value)
"""

let app = Application(.testing)
defer { app.shutdown() }
app.views.use(.leaf)
app.leaf.sources = .singleSource(test)

struct ArrayWithNils: Content {
let value:[UUID?]
}

let id1 = UUID.init()
let id2 = UUID.init()


app.get("noCrash") { req -> EventLoopFuture<View> in
let context = ArrayWithNils(value: [id1,nil,id2, nil])
return req.view.render("foo", context)
}

try app.test(.GET, "noCrash") { res in
// Expected result .ok
XCTAssertEqual(res.status, .ok)

// Rendered result should match to all non-nil values
XCTAssertEqual(res.body.string, "[\"\(id1)\", \"\(id2)\"]")
}
}
}

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

0 comments on commit ffff1a8

Please sign in to comment.