Working and testing async Vapor instructions

Working and testing async Vapor instructions


The best way to run async instructions in Vapor?

The async / await function is comparatively new in Swift and a few framework authors have not transformed every little thing to reap the benefits of these new key phrases. Presently, that is the state of affairs with the Command API in Vapor 4. You’ll be able to already outline async instructions, however there is no method to register them utilizing the Vapor framework. Luckily, there’s a comparatively easy workaround that you should utilize if you wish to execute instructions utilizing an asynchronous context. 🔀

First we will outline a helper protocol and create an asyncRun perform. We’re going to prolong the unique Command protocol and supply a default implementation for the run technique.

import Vapor

public protocol AsyncCommand: Command {
    
    func asyncRun(
        utilizing context: CommandContext,
        signature: Signature
    ) async throws
}

public extension AsyncCommand {

    func run(
        utilizing context: CommandContext,
        signature: Signature
    ) throws {
        let promise = context
            .software
            .eventLoopGroup
            .subsequent()
            .makePromise(of: Void.self)
        
        promise.completeWithTask {
            attempt await asyncRun(
                utilizing: context,
                signature: signature
            )
        }
        attempt promise.futureResult.wait()
    }
}

This fashion it is best to have the ability to create a brand new async command and it is best to implement the asyncRun technique if you wish to name some asynchronous Swift code.

import Vapor

remaining class MyAsyncCommand: AsyncCommand {
    
    static let identify = "async"
    
    let assist = "This command run asynchronously."

    struct Signature: CommandSignature {}

    func asyncRun(
        utilizing context: CommandContext,
        signature: Signature
    ) async throws {
        context.console.information("That is async.")
    }
}

It’s potential to register the command utilizing the configure technique, you’ll be able to do this out by operating the swift run Run async snippet if you’re utilizing the usual Vapor template. 💧

import Vapor

public func configure(
    _ app: Utility
) throws {

    app.instructions.use(
        MyAsyncCommand(),
        as: MyAsyncCommand.identify
    )

    attempt routes(app)
}

As you’ll be able to see it is a fairly neat trick, it is also talked about on GitHub, however hopefully we do not want this workaround for too lengthy and correct async command help will arrive in Vapor 4.x.

Unit testing Vapor instructions

This subject has actually zero documentation, so I believed it could be good to inform you a bit about unit check scripts created by way of ConsoleKit. Initially we want a TestConsole that we are able to use to gather the output of our instructions. It is a shameless ripoff from ConsoleKit. 😅

import Vapor

remaining class TestConsole: Console {

    var testInputQueue: [String]
    var testOutputQueue: [String]
    var userInfo: [AnyHashable : Any]

    init() {
        self.testInputQueue = []
        self.testOutputQueue = []
        self.userInfo = [:]
    }

    func enter(isSecure: Bool) -> String {
        testInputQueue.popLast() ?? ""
    }

    func output(_ textual content: ConsoleText, newLine: Bool) {
        let line = textual content.description + (newLine ? "n" : "")
        testOutputQueue.insert(line, at: 0)
    }

    func report(error: String, newLine: Bool) {
        
    }

    func clear(_ sort: ConsoleClear) {
        
    }

    var dimension: (width: Int, top: Int) {
        (0, 0)
    }
}

Now contained in the check suite, it is best to create a brand new software occasion utilizing the check atmosphere and configure it for testing functions. Then it is best to provoke the command that you just’d like to check and run it utilizing the check console. You simply must create a brand new context and a correct enter with the required arguments and the console.run perform will maintain every little thing else.

@testable import App
import XCTVapor

remaining class AppTests: XCTestCase {
    
    func testCommand() throws {
        let app = Utility(.testing)
        defer { app.shutdown() }
        attempt configure(app)
        
        let command = MyAsyncCommand()
        let arguments = ["async"]
        
        let console = TestConsole()
        let enter = CommandInput(arguments: arguments)
        var context = CommandContext(
            console: console,
            enter: enter
        )
        context.software = app
        
        attempt console.run(command, with: context)

        let output = console
            .testOutputQueue
            .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
        
        let expectation = [
            "This is async."
        ]
        XCTAssertEqual(output, expectation)
    }
}

The great factor about this answer is that the ConsoleKit framework will robotically parse the arguments, choices and the flags. You’ll be able to present these as standalone array components utilizing the enter arguments array (e.g. ["arg1", "--option1", "value1", "--flag1"]).

It’s potential to check command teams, you simply have so as to add the precise command identify as the primary argument that you just’d prefer to run from the group and you’ll merely examine the output by means of the check console if you’re in search of the precise command outcomes. 💪

Leave a Reply

Your email address will not be published. Required fields are marked *