[ad_1]
Writing assessments utilizing XCTVapor
In my earlier article I confirmed you learn how to construct a kind secure RESTful API utilizing Vapor. This time we’ll prolong that venture a bit and write some assessments utilizing the Vapor testing software to find the underlying points within the API layer. First we’ll use XCTVapor library, then we migrate to a light-weight declarative testing framework (Spec) constructed on prime of that.
Earlier than we begin testing our software, we’ve got to ensure that if the app runs in testing mode we register an inMemory database as a substitute of our native SQLite file. We are able to merely alter the configuration and test the atmosphere and set the db driver based mostly on it.
import Vapor
import Fluent
import FluentSQLiteDriver
public func configure(_ app: Utility) throws {
if app.atmosphere == .testing {
app.databases.use(.sqlite(.reminiscence), as: .sqlite, isDefault: true)
}
else {
app.databases.use(.sqlite(.file("Assets/db.sqlite")), as: .sqlite)
}
app.migrations.add(TodoMigration())
strive app.autoMigrate().wait()
strive TodoRouter().boot(routes: app.routes)
}
Now we’re able to create our very first unit check utilizing the XCTVapor testing framework. The official docs are brief, however fairly helpful to be taught in regards to the fundamentals of testing Vapor endpoints. Sadly it will not let you know a lot about testing web sites or advanced API calls. ✅
We’ll make a easy check that checks the return kind for our Todo checklist endpoint.
@testable import App
import TodoApi
import Fluent
import XCTVapor
closing class AppTests: XCTestCase {
func testTodoList() throws {
let app = Utility(.testing)
defer { app.shutdown() }
strive configure(app)
strive app.check(.GET, "/todos/", afterResponse: { res in
XCTAssertEqual(res.standing, .okay)
XCTAssertEqual(res.headers.contentType, .json)
_ = strive res.content material.decode(Web page<TodoListObject>.self)
})
}
}
As you possibly can see first we setup & configure our software, then we ship a GET request to the /todos/
endpoint. After we’ve got a response we will test the standing code, the content material kind and we will attempt to decode the response physique as a legitimate paginated todo checklist merchandise object.
This check case was fairly easy, now let’s write a brand new unit check for the todo merchandise creation.
@testable import App
import TodoApi
import Fluent
import XCTVapor
closing class AppTests: XCTestCase {
func testCreateTodo() throws {
let app = Utility(.testing)
defer { app.shutdown() }
strive configure(app)
let title = "Write a todo tutorial"
strive app.check(.POST, "/todos/", beforeRequest: { req in
let enter = TodoCreateObject(title: title)
strive req.content material.encode(enter)
}, afterResponse: { res in
XCTAssertEqual(res.standing, .created)
let todo = strive res.content material.decode(TodoGetObject.self)
XCTAssertEqual(todo.title, title)
XCTAssertEqual(todo.accomplished, false)
XCTAssertEqual(todo.order, nil)
})
}
}
This time we would wish to submit a brand new TodoCreateObject as a POST information, luckily XCTVapor may also help us with the beforeRequest block. We are able to merely encode the enter object as a content material, then within the response handler we will test the HTTP standing code (it ought to be created) decode the anticipated response object (TodoGetObject) and validate the sphere values.
I additionally up to date the TodoCreateObject, because it doesn’t make an excessive amount of sense to have an optionally available Bool subject and we will use a default nil worth for the customized order. 🤓
public struct TodoCreateObject: Codable {
public let title: String
public let accomplished: Bool
public let order: Int?
public init(title: String, accomplished: Bool = false, order: Int? = nil) {
self.title = title
self.accomplished = accomplished
self.order = order
}
}
The check will nonetheless fail, as a result of we’re returning an .okay
standing as a substitute of a .created
worth. We are able to simply repair this within the create technique of the TodoController Swift file.
import Vapor
import Fluent
import TodoApi
struct TodoController {
func create(req: Request) throws -> EventLoopFuture<Response> {
let enter = strive req.content material.decode(TodoCreateObject.self)
let todo = TodoModel()
todo.create(enter)
return todo
.create(on: req.db)
.map { todo.mapGet() }
.encodeResponse(standing: .created, for: req)
}
}
Now we must always attempt to create an invalid todo merchandise and see what occurs…
func testCreateInvalidTodo() throws {
let app = Utility(.testing)
defer { app.shutdown() }
strive configure(app)
let title = ""
strive app.check(.POST, "/todos/", beforeRequest: { req in
let enter = TodoCreateObject(title: title)
strive req.content material.encode(enter)
}, afterResponse: { res in
XCTAssertEqual(res.standing, .created)
let todo = strive res.content material.decode(TodoGetObject.self)
XCTAssertEqual(todo.title, title)
XCTAssertEqual(todo.accomplished, false)
XCTAssertEqual(todo.order, nil)
})
}
Properly, that is unhealthy, we should not have the ability to create a todo merchandise and not using a title. We may use the built-in validation API to test consumer enter, however truthfully talking that is not one of the best strategy.
My situation with validation is that to begin with you possibly can’t return customized error messages and the opposite predominant purpose is that validation in Vapor will not be async by default. Ultimately you may face a state of affairs when you have to validate an object based mostly on a db name, then you possibly can’t match that a part of the item validation course of into different non-async subject validation. IMHO, this ought to be unified. 🥲
Fort the sake of simplicity we’ll begin with a customized validation technique, this time with none async logic concerned, afterward I will present you learn how to construct a generic validation & error reporting mechanism to your JSON-based RESTful API.
import Vapor
import TodoApi
extension TodoModel {
func create(_ enter: TodoCreateObject) {
title = enter.title
accomplished = enter.accomplished
order = enter.order
}
static func validateCreate(_ enter: TodoCreateObject) throws {
guard !enter.title.isEmpty else {
throw Abort(.badRequest, purpose: "Title is required")
}
}
}
Within the create controller we will merely name the throwing validateCreate operate, if one thing goes unsuitable the Abort error might be returned as a response. It is usually doable to make use of an async technique (return with an EventLoopFuture
) then await (flatMap
) the decision and return our newly created todo if the whole lot was fantastic.
func create(req: Request) throws -> EventLoopFuture<Response> {
let enter = strive req.content material.decode(TodoCreateObject.self)
strive TodoModel.validateCreate(enter)
let todo = TodoModel()
todo.create(enter)
return todo
.create(on: req.db)
.map { todo.mapGet() }
.encodeResponse(standing: .created, for: req)
}
The very last thing that we’ve got to do is to replace our check case and test for an error response.
struct ErrorResponse: Content material {
let error: Bool
let purpose: String
}
func testCreateInvalidTodo() throws {
let app = Utility(.testing)
defer { app.shutdown() }
strive configure(app)
strive app.check(.POST, "/todos/", beforeRequest: { req in
let enter = TodoCreateObject(title: "")
strive req.content material.encode(enter)
}, afterResponse: { res in
XCTAssertEqual(res.standing, .badRequest)
let error = strive res.content material.decode(ErrorResponse.self)
XCTAssertEqual(error.purpose, "Title is required")
})
}
Writing assessments is an effective way to debug our server facet Swift code and double test our API endpoints. My solely situation with this strategy is that the code is not an excessive amount of self-explaining.
Declarative unit assessments utilizing Spec XCTVapor and all the check framework works simply nice, however I had a small drawback with it. Should you ever labored with JavaScript or TypeScript you might need heard in regards to the SuperTest library. This little npm
package deal offers us a declarative syntactical sugar for testing HTTP requests, which I favored method an excessive amount of to return to common XCTVapor-based check instances.
That is the explanation why I’ve created the Spec “micro-framework”, which is actually one file with with an additional skinny layer round Vapor’s unit testing framework to offer a declarative API. Let me present you the way this works in observe, utilizing a real-world instance. 🙃
import PackageDescription
let package deal = Package deal(
title: "myProject",
platforms: [
.macOS(.v10_15)
],
merchandise: [
.library(name: "TodoApi", targets: ["TodoApi"]),
],
dependencies: [
.package(url: "https://github.com/vapor/vapor", from: "4.44.0"),
.package(url: "https://github.com/vapor/fluent", from: "4.0.0"),
.package(url: "https://github.com/vapor/fluent-sqlite-driver", from: "4.0.0"),
.package(url: "https://github.com/binarybirds/spec", from: "1.0.0"),
],
targets: [
.target(name: "TodoApi"),
.target(
name: "App",
dependencies: [
.product(name: "Fluent", package: "fluent"),
.product(name: "FluentSQLiteDriver", package: "fluent-sqlite-driver"),
.product(name: "Vapor", package: "vapor"),
.target(name: "TodoApi")
],
swiftSettings: [
.unsafeFlags(["-cross-module-optimization"], .when(configuration: .launch))
]
),
.goal(title: "Run", dependencies: [.target(name: "App")]),
.testTarget(title: "AppTests", dependencies: [
.target(name: "App"),
.product(name: "XCTVapor", package: "vapor"),
.product(name: "Spec", package: "spec"),
])
]
)
We had some expectations for the earlier calls, proper? How ought to we check the replace todo endpoint? Properly, we will create a brand new merchandise, then replace it and test if the outcomes are legitimate.
import Spec
func testUpdateTodo() throws {
let app = Utility(.testing)
defer { app.shutdown() }
strive configure(app)
var existingTodo: TodoGetObject?
strive app
.describe("A sound todo object ought to exists after creation")
.submit("/todos/")
.physique(TodoCreateObject(title: "pattern"))
.count on(.created)
.count on(.json)
.count on(TodoGetObject.self) { existingTodo = $0 }
.check()
XCTAssertNotNil(existingTodo)
let updatedTitle = "Merchandise is completed"
strive app
.describe("Todo ought to be up to date")
.put("/todos/" + existingTodo!.id.uuidString)
.physique(TodoUpdateObject(title: updatedTitle, accomplished: true, order: 2))
.count on(.okay)
.count on(.json)
.count on(TodoGetObject.self) { todo in
XCTAssertEqual(todo.title, updatedTitle)
XCTAssertTrue(todo.accomplished)
XCTAssertEqual(todo.order, 2)
}
.check()
}
The very first a part of the code expects that we had been capable of create a todo object, it’s the very same create expectation as we used to write down with the assistance of the XCTVapor framework.
IMHO the general code high quality is method higher than it was within the earlier instance. We described the check state of affairs then we set our expectations and eventually we run our check. With this format it should be extra easy to grasp check instances. Should you evaluate the 2 variations the create case the second is trivial to grasp, however within the first one you really need to take a deeper have a look at every line to grasp what is going on on.
Okay, yet another check earlier than we cease, let me present you learn how to describe the delete endpoint. We’ll refactor our code a bit, since there are some duplications already.
@testable import App
import TodoApi
import Fluent
import Spec
closing class AppTests: XCTestCase {
personal struct ErrorResponse: Content material {
let error: Bool
let purpose: String
}
@discardableResult
personal func createTodo(app: Utility, enter: TodoCreateObject) throws -> TodoGetObject {
var existingTodo: TodoGetObject?
strive app
.describe("A sound todo object ought to exists after creation")
.submit("/todos/")
.physique(enter)
.count on(.created)
.count on(.json)
.count on(TodoGetObject.self) { existingTodo = $0 }
.check()
XCTAssertNotNil(existingTodo)
return existingTodo!
}
func testTodoList() throws {
let app = Utility(.testing)
defer { app.shutdown() }
strive configure(app)
strive app
.describe("A sound todo checklist web page ought to be returned.")
.get("/todos/")
.count on(.okay)
.count on(.json)
.count on(Web page<TodoListObject>.self)
.check()
}
func testCreateTodo() throws {
let app = Utility(.testing)
defer { app.shutdown() }
strive configure(app)
strive createTodo(app: app, enter: TodoCreateObject(title: "Write a todo tutorial"))
}
func testCreateInvalidTodo() throws {
let app = Utility(.testing)
defer { app.shutdown() }
strive configure(app)
strive app
.describe("An invalid title response ought to be returned")
.submit("/todos/")
.physique(TodoCreateObject(title: ""))
.count on(.badRequest)
.count on(.json)
.count on(ErrorResponse.self) { error in
XCTAssertEqual(error.purpose, "Title is required")
}
.check()
}
func testUpdateTodo() throws {
let app = Utility(.testing)
defer { app.shutdown() }
strive configure(app)
let todo: TodoGetObject? = strive createTodo(app: app, enter: TodoCreateObject(title: "Write a todo tutorial"))
let updatedTitle = "Merchandise is completed"
strive app
.describe("Todo ought to be up to date")
.put("/todos/" + todo!.id.uuidString)
.count on(.okay)
.count on(.json)
.physique(TodoUpdateObject(title: updatedTitle, accomplished: true, order: 2))
.count on(TodoGetObject.self) { todo in
XCTAssertEqual(todo.title, updatedTitle)
XCTAssertTrue(todo.accomplished)
XCTAssertEqual(todo.order, 2)
}
.check()
}
func testDeleteTodo() throws {
let app = Utility(.testing)
defer { app.shutdown() }
strive configure(app)
let todo: TodoGetObject? = strive createTodo(app: app, enter: TodoCreateObject(title: "Write a todo tutorial"))
strive app
.describe("Todo ought to be up to date")
.delete("/todos/" + todo!.id.uuidString)
.count on(.okay)
.check()
}
}
That is how one can create an entire unit check state of affairs for a REST API endpoint utilizing the Spec library. After all there are a dozen different points that we may repair, resembling higher enter object validation, unit check for the patch endpoint, higher assessments for edge instances. Properly, subsequent time. 😅
Through the use of Spec you possibly can construct your expectations by describing the use case, then you possibly can place your expectations on the described “specification” run the hooked up validators. The great factor about this declarative strategy is the clear self-explaining format that you may perceive with out taking an excessive amount of time on investigating the underlying Swift / Vapor code.
I consider that Spec is a enjoyable little software that lets you write higher assessments to your Swift backend apps. It has a really light-weight footprint, and the API is easy and simple to make use of. 💪
[ad_2]