Skip to content

Commit

Permalink
Fix and add tests for requireBody() and requireNoBody() (#133)
Browse files Browse the repository at this point in the history
  • Loading branch information
fpseverino committed Sep 3, 2024
1 parent c04e547 commit d0ca441
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
4 changes: 2 additions & 2 deletions Sources/LeafKit/LeafSerialize/LeafContext.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}

Expand All @@ -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"
}
}
Expand Down
36 changes: 36 additions & 0 deletions Tests/LeafKitTests/LeafKitTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
}

0 comments on commit d0ca441

Please sign in to comment.