Using #require to unwrap an optional fails to compile

Hi all, I'm trying to to write some tests using the new swift-testing library and am running into an issue with using #require to unwrap optionals. Here's my test:

import FluentKit
import NIOEmbedded
import Testing
import XCTFluent

@Suite
struct CreateObjectTests {
    @Test func testCreateObject() async throws {
        // Given
        var mockDB = DummyDatabase()
        mockDB.context = .init(
            configuration: DummyDatabaseConfiguration(middleware: []),
            logger: .init(label: "codes.vapor.test"),
            eventLoop: EmbeddedEventLoop(),
            history: QueryHistory()
        )

        // When
        // Create the object...

        // Then
        let queries = #require(mockDB.history?.queries)

        #expect(queries.count == 1)
        let onlyQuery = #require(queries.first)

        print(onlyQuery.input)
    }
}

Based on what I know, this seems like a valid usage of this #require overload. Am I missing or misunderstanding something?

I think I might have spotted a small oversight in your code. It seems like you're just missing the try keyword before your #require macros. I belive your code should look something like this:

-let queries = #require(mockDB.history?.queries)
+let queries = try #require(mockDB.history?.queries)

#expect(queries.count == 1)
-let onlyQuery = #require(queries.first)
+let onlyQuery = try #require(queries.first)
1 Like

Ah, thank you! I was expecting the macro to handle that all for me but this makes sense.

Our documentation should consistently show try before #require(). If any of our documentation is missing try, please let us know so we can fix it.

1 Like

Should the macro declaration have throws?

Effect keywords are not valid on macro declarations, which is why you don't see any on the declarations for #require(). @Douglas_Gregor can provide more information.

1 Like