Configure first WebSocket test

This commit is contained in:
Christoph Hagen 2022-01-23 20:49:06 +01:00
parent 8722d21e9b
commit 145f68268a
5 changed files with 93 additions and 0 deletions

31
Package.swift Normal file
View File

@ -0,0 +1,31 @@
// swift-tools-version:5.5
import PackageDescription
let package = Package(
name: "SesameServer",
platforms: [
.macOS(.v10_15)
],
dependencies: [
.package(url: "https://github.com/vapor/vapor.git", from: "4.0.0"),
],
targets: [
.target(
name: "App",
dependencies: [
.product(name: "Vapor", package: "vapor")
],
swiftSettings: [
// Enable better optimizations when building in Release configuration. Despite the use of
// the `.unsafeFlags` construct required by SwiftPM, this flag is recommended for Release
// builds. See <https://github.com/swift-server/guides/blob/main/docs/building.md#building-for-production> for details.
.unsafeFlags(["-cross-module-optimization"], .when(configuration: .release))
]
),
.executableTarget(name: "Run", dependencies: [.target(name: "App")]),
.testTarget(name: "AppTests", dependencies: [
.target(name: "App"),
.product(name: "XCTVapor", package: "vapor"),
])
]
)

7
Sources/App/configure.swift Executable file
View File

@ -0,0 +1,7 @@
import Vapor
// configures your application
public func configure(_ app: Application) throws {
app.http.server.configuration.port = 10000
try routes(app)
}

31
Sources/App/routes.swift Executable file
View File

@ -0,0 +1,31 @@
import Vapor
var connection: WebSocket?
func routes(_ app: Application) throws {
app.get { req in
return "It works!"
}
/**
Start a new websocket connection for the client to receive table updates from the server
- Returns: Nothing
- Note: The first (and only) message from the client over the connection must be a valid session token.
*/
app.webSocket("listen") { req, socket in
socket.onBinary { socket, data in
print("\(data)")
}
socket.onText { socket, text in
print(text)
}
_ = socket.onClose.always { result in
connection = nil
print("Socket closed")
}
connection = socket
print("Socket connected")
}
}

9
Sources/Run/main.swift Normal file
View File

@ -0,0 +1,9 @@
import App
import Vapor
var env = try Environment.detect()
try LoggingSystem.bootstrap(from: &env)
let app = Application(env)
defer { app.shutdown() }
try configure(app)
try app.run()

View File

@ -0,0 +1,15 @@
@testable import App
import XCTVapor
final class AppTests: XCTestCase {
func testHelloWorld() throws {
let app = Application(.testing)
defer { app.shutdown() }
try configure(app)
try app.test(.GET, "hello", afterResponse: { res in
XCTAssertEqual(res.status, .ok)
XCTAssertEqual(res.body.string, "Hello, world!")
})
}
}