diff --git a/Sources/LeafKit/LeafSerialize/LeafContext.swift b/Sources/LeafKit/LeafSerialize/LeafContext.swift index 60e512c..790654b 100644 --- a/Sources/LeafKit/LeafSerialize/LeafContext.swift +++ b/Sources/LeafKit/LeafSerialize/LeafContext.swift @@ -25,7 +25,7 @@ public struct LeafContext { /// Throws an error if this tag does not include a body. public func requireBody() throws -> [Syntax] { - guard let body = body else { + guard let body, !body.isEmpty else { throw "Missing body" } @@ -34,7 +34,7 @@ public struct LeafContext { /// Throws an error if this tag includes a body. public func requireNoBody() throws { - guard body == nil else { + if let body, !body.isEmpty { throw "Extraneous body" } } diff --git a/Tests/LeafKitTests/LeafKitTests.swift b/Tests/LeafKitTests/LeafKitTests.swift index 820078b..a41dd7d 100644 --- a/Tests/LeafKitTests/LeafKitTests.swift +++ b/Tests/LeafKitTests/LeafKitTests.swift @@ -630,4 +630,40 @@ final class LeafKitTests: XCTestCase { XCTAssert(error.localizedDescription.contains("No searchable sources exist")) } } + + func testBodyRequiring() async throws { + var test = TestFiles() + test.files["/body.leaf"] = "#bodytag:test#endbodytag" + test.files["/bodyError.leaf"] = "#bodytag:#endbodytag" + test.files["/nobody.leaf"] = "#nobodytag" + test.files["/nobodyError.leaf"] = "#nobodytag:test#endnobodytag" + + struct BodyRequiringTag: UnsafeUnescapedLeafTag { + func render(_ ctx: LeafContext) throws -> LeafData { + _ = try ctx.requireBody() + + return .string("Hello there") + } + } + + struct NoBodyRequiringTag: UnsafeUnescapedLeafTag { + func render(_ ctx: LeafContext) throws -> LeafData { + try ctx.requireNoBody() + + return .string("General Kenobi") + } + } + + let renderer = TestRenderer( + tags: [ + "bodytag": BodyRequiringTag(), + "nobodytag": NoBodyRequiringTag() + ], + sources: .singleSource(test) + ) + XCTAssertEqual(try renderer.render(path: "body", context: ["test":"ciao"]).wait().string, "Hello there") + XCTAssertThrowsError(try renderer.render(path: "bodyError", context: [:]).wait()) + XCTAssertEqual(try renderer.render(path: "nobody", context: [:]).wait().string, "General Kenobi") + XCTAssertThrowsError(try renderer.render(path: "nobodyError", context: [:]).wait()) + } }