From d0ca4417166ef7868d28ad21bc77d36b8735a0fc Mon Sep 17 00:00:00 2001 From: Francesco Paolo Severino <96546612+fpseverino@users.noreply.github.com> Date: Tue, 3 Sep 2024 14:05:00 +0200 Subject: [PATCH] Fix and add tests for `requireBody()` and `requireNoBody()` (#133) --- .../LeafKit/LeafSerialize/LeafContext.swift | 4 +-- Tests/LeafKitTests/LeafKitTests.swift | 36 +++++++++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/Sources/LeafKit/LeafSerialize/LeafContext.swift b/Sources/LeafKit/LeafSerialize/LeafContext.swift index 60e512c6..790654bd 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 820078bc..a41dd7d6 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()) + } }