Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix and add tests for requireBody() and requireNoBody() #133

Merged
merged 1 commit into from
Sep 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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())
}
}