Skip to content

zorkdev/Hearken

Repository files navigation

Hearken

Swift SwiftPM Platforms Build

A simple Swift HTTP/1.1 server built on top of SwiftNIO.

The main goal of this package is to easily create mock servers for your Swift projects, for example when writing UI tests. The API has been kept very minimal as a consequence as Hearken is not intended to be a full-fledged web framework. It comes with a number of convenience APIs to make integration with XCTest even more of a breeze.

📦 Installation

Hearken is distributed using the Swift Package Manager. To install it into a project, add it as a dependency within your Package.swift manifest:

let package = Package(
    ...
    dependencies: [
        .package(url: "https://github.com/zorkdev/Hearken.git", from: "0.1.3")
    ],
    ...
)

🚀 Quickstart

An instance of Hearken can be easily created by initializing a Server:

import Hearken

let server = Server()

Simple routes with a response instance can be added by using a custom subscript on Server:

server[.GET, "/api/health"] = HTTPResponse(status: .ok)

You can also assign closures to routes by using another custom subscript on Server if you need more control over your route:

server[.POST, "/api/hello"] = { request in
    print(request)
    
    return .init(status: .ok,
                 headers: [.contentType(.json)],
                 body: """
                       {
                           "hello": "world"
                       }
                       """)
}

The Server can be started asynchronously by calling start() and stopped by calling stop():

try server.start()
try server.stop()

The Server can also be started synchronously using syncStart() if you want to block the current thread:

try server.syncStart()

ℹ️ Example Usage

Hearken comes with an example executable product to instantiate a Server if you want to quickly check out how it works. Just run HearkenExample after you've added Hearken as dependency or checked it out separately:

swift run HearkenExample

XCTest additions

Hearken has some added convenience APIs for XCTest in a separate HearkenTestKit library to make it easier to test network requests. If you intend to use this, don't forget to set the domains the tested application calls to localhost:8888.

Create your own subclass of HearkenTestCase in your tests:

import HearkenTestKit

class MyTestCase: HearkenTestCase {
    ...
}

Use the assert method to check that the tested application makes the correct request:

func testSomething() {
    assert(request: .init(method: .POST,
                          uri: "/api/test",
                          body: "Body",
           response: .init(status: .ok))
    ...
}

📖 Documentation

Documentation is available here.

🛠 Contributions

Use develop branch for development and master for release.

To run static analysis and tests on the project, use the test.sh script:

$ ./test.sh