-
Notifications
You must be signed in to change notification settings - Fork 2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
chore: extract CoderSDK to framework #19
Merged
+787
−325
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
11 changes: 1 addition & 10 deletions
11
...Desktop/Coder Desktop.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
29 changes: 0 additions & 29 deletions
29
Coder Desktop/Coder Desktop/Preview Content/PreviewClient.swift
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,6 @@ | ||
@testable import Coder_Desktop | ||
@testable import CoderSDK | ||
import Mocker | ||
import SwiftUI | ||
import Testing | ||
import ViewInspector | ||
|
@@ -7,12 +9,12 @@ import ViewInspector | |
@Suite(.timeLimit(.minutes(1))) | ||
struct LoginTests { | ||
let session: MockSession | ||
let sut: LoginForm<MockClient, MockSession> | ||
let sut: LoginForm<MockSession> | ||
let view: any View | ||
|
||
init() { | ||
session = MockSession() | ||
sut = LoginForm<MockClient, MockSession>() | ||
sut = LoginForm<MockSession>() | ||
view = sut.environmentObject(session) | ||
} | ||
|
||
|
@@ -68,14 +70,16 @@ struct LoginTests { | |
|
||
@Test | ||
func testFailedAuthentication() async throws { | ||
let login = LoginForm<MockErrorClient, MockSession>() | ||
let login = LoginForm<MockSession>() | ||
let url = URL(string: "https://testFailedAuthentication.com")! | ||
Mock(url: url.appendingPathComponent("/api/v2/users/me"), statusCode: 401, data: [.get: Data()]).register() | ||
|
||
try await ViewHosting.host(login.environmentObject(session)) { | ||
try await login.inspection.inspect { view in | ||
try view.find(ViewType.TextField.self).setInput("https://coder.example.com") | ||
try view.find(ViewType.TextField.self).setInput(url.absoluteString) | ||
try view.find(button: "Next").tap() | ||
#expect(throws: Never.self) { try view.find(text: "Session Token") } | ||
try view.find(ViewType.SecureField.self).setInput("valid-token") | ||
try view.find(ViewType.SecureField.self).setInput("invalid-token") | ||
try await view.actualView().submit() | ||
#expect(throws: Never.self) { try view.find(ViewType.Alert.self) } | ||
} | ||
|
@@ -84,9 +88,33 @@ struct LoginTests { | |
|
||
@Test | ||
func testSuccessfulLogin() async throws { | ||
let url = URL(string: "https://testSuccessfulLogin.com")! | ||
|
||
let user = User( | ||
id: UUID(), | ||
username: "admin", | ||
avatar_url: "", | ||
name: "admin", | ||
email: "[email protected]", | ||
created_at: Date.now, | ||
updated_at: Date.now, | ||
last_seen_at: Date.now, | ||
status: "active", | ||
login_type: "none", | ||
theme_preference: "dark", | ||
organization_ids: [], | ||
roles: [] | ||
) | ||
|
||
try Mock( | ||
url: url.appendingPathComponent("/api/v2/users/me"), | ||
statusCode: 200, | ||
data: [.get: Client.encoder.encode(user)] | ||
).register() | ||
|
||
try await ViewHosting.host(view) { | ||
try await sut.inspection.inspect { view in | ||
try view.find(ViewType.TextField.self).setInput("https://coder.example.com") | ||
try view.find(ViewType.TextField.self).setInput(url.absoluteString) | ||
try view.find(button: "Next").tap() | ||
try view.find(ViewType.SecureField.self).setInput("valid-token") | ||
try await view.actualView().submit() | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,137 @@ | ||
import Foundation | ||
|
||
public struct Client { | ||
public let url: URL | ||
public var token: String? | ||
public var headers: [HTTPHeader] | ||
|
||
public init(url: URL, token: String? = nil, headers: [HTTPHeader] = []) { | ||
self.url = url | ||
self.token = token | ||
self.headers = headers | ||
} | ||
|
||
static let decoder: JSONDecoder = { | ||
var dec = JSONDecoder() | ||
dec.dateDecodingStrategy = .iso8601withOptionalFractionalSeconds | ||
return dec | ||
}() | ||
|
||
static let encoder: JSONEncoder = { | ||
var enc = JSONEncoder() | ||
enc.dateEncodingStrategy = .iso8601withFractionalSeconds | ||
return enc | ||
}() | ||
|
||
private func doRequest( | ||
path: String, | ||
method: HTTPMethod, | ||
body: Data? = nil | ||
) async throws(ClientError) -> HTTPResponse { | ||
let url = self.url.appendingPathComponent(path) | ||
var req = URLRequest(url: url) | ||
if let token { req.addValue(token, forHTTPHeaderField: Headers.sessionToken) } | ||
req.httpMethod = method.rawValue | ||
for header in headers { | ||
req.addValue(header.value, forHTTPHeaderField: header.header) | ||
} | ||
req.httpBody = body | ||
let data: Data | ||
let resp: URLResponse | ||
do { | ||
(data, resp) = try await URLSession.shared.data(for: req) | ||
} catch { | ||
throw .network(error) | ||
} | ||
guard let httpResponse = resp as? HTTPURLResponse else { | ||
throw .unexpectedResponse(data) | ||
} | ||
return HTTPResponse(resp: httpResponse, data: data, req: req) | ||
} | ||
|
||
func request<T: Encodable & Sendable>( | ||
_ path: String, | ||
method: HTTPMethod, | ||
body: T | ||
) async throws(ClientError) -> HTTPResponse { | ||
let encodedBody: Data? | ||
do { | ||
encodedBody = try Client.encoder.encode(body) | ||
} catch { | ||
throw .encodeFailure(error) | ||
} | ||
return try await doRequest(path: path, method: method, body: encodedBody) | ||
} | ||
|
||
func request( | ||
_ path: String, | ||
method: HTTPMethod | ||
) async throws(ClientError) -> HTTPResponse { | ||
return try await doRequest(path: path, method: method) | ||
} | ||
|
||
func responseAsError(_ resp: HTTPResponse) -> ClientError { | ||
do { | ||
let body = try Client.decoder.decode(Response.self, from: resp.data) | ||
let out = APIError( | ||
response: body, | ||
statusCode: resp.resp.statusCode, | ||
method: resp.req.httpMethod!, | ||
url: resp.req.url! | ||
) | ||
return .api(out) | ||
} catch { | ||
return .unexpectedResponse(resp.data.prefix(1024)) | ||
} | ||
} | ||
} | ||
|
||
public struct APIError: Decodable { | ||
let response: Response | ||
let statusCode: Int | ||
let method: String | ||
let url: URL | ||
|
||
var description: String { | ||
var components = ["\(method) \(url.absoluteString)\nUnexpected status code \(statusCode):\n\(response.message)"] | ||
if let detail = response.detail { | ||
components.append("\tError: \(detail)") | ||
} | ||
if let validations = response.validations, !validations.isEmpty { | ||
let validationMessages = validations.map { "\t\($0.field): \($0.detail)" } | ||
components.append(contentsOf: validationMessages) | ||
} | ||
return components.joined(separator: "\n") | ||
} | ||
} | ||
|
||
public struct Response: Decodable { | ||
let message: String | ||
let detail: String? | ||
let validations: [FieldValidation]? | ||
} | ||
|
||
public struct FieldValidation: Decodable { | ||
let field: String | ||
let detail: String | ||
} | ||
|
||
public enum ClientError: Error { | ||
case api(APIError) | ||
case network(any Error) | ||
case unexpectedResponse(Data) | ||
case encodeFailure(any Error) | ||
|
||
public var description: String { | ||
switch self { | ||
case let .api(error): | ||
return error.description | ||
case let .network(error): | ||
return error.localizedDescription | ||
case let .unexpectedResponse(data): | ||
return "Unexpected or non HTTP response: \(data)" | ||
case let .encodeFailure(error): | ||
return "Failed to encode body: \(error)" | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
#import <Foundation/Foundation.h> | ||
|
||
//! Project version number for CoderSDK. | ||
FOUNDATION_EXPORT double CoderSDKVersionNumber; | ||
|
||
//! Project version string for CoderSDK. | ||
FOUNDATION_EXPORT const unsigned char CoderSDKVersionString[]; | ||
|
||
// In this header, you should import all the public headers of your framework using statements like #import <CoderSDK/PublicHeader.h> | ||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
public extension Client { | ||
func buildInfo() async throws(ClientError) -> BuildInfoResponse { | ||
let res = try await request("/api/v2/buildinfo", method: .get) | ||
guard res.resp.statusCode == 200 else { | ||
throw responseAsError(res) | ||
} | ||
do { | ||
return try Client.decoder.decode(BuildInfoResponse.self, from: res.data) | ||
} catch { | ||
throw .unexpectedResponse(res.data.prefix(1024)) | ||
} | ||
} | ||
} | ||
|
||
public struct BuildInfoResponse: Encodable, Decodable, Equatable, Sendable { | ||
public let external_url: String | ||
public let version: String | ||
public let dashboard_url: String | ||
public let telemetry: Bool | ||
public let workspace_proxy: Bool | ||
public let agent_api_version: String | ||
public let provisioner_api_version: String | ||
public let upgrade_message: String | ||
public let deployment_id: String | ||
|
||
// `version` in the form `[0-9]+.[0-9]+.[0-9]+` | ||
public var semver: String? { | ||
return try? NSRegularExpression(pattern: #"v(\d+\.\d+\.\d+)"#) | ||
.firstMatch(in: version, range: NSRange(version.startIndex ..< version.endIndex, in: version)) | ||
.flatMap { Range($0.range(at: 1), in: version).map { String(version[$0]) } } | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
public struct HTTPResponse { | ||
let resp: HTTPURLResponse | ||
let data: Data | ||
let req: URLRequest | ||
} | ||
|
||
public struct HTTPHeader: Sendable { | ||
public let header: String | ||
public let value: String | ||
public init(header: String, value: String) { | ||
self.header = header | ||
self.value = value | ||
} | ||
} | ||
|
||
enum HTTPMethod: String, Equatable, Hashable, Sendable { | ||
case get = "GET" | ||
case post = "POST" | ||
case delete = "DELETE" | ||
case put = "PUT" | ||
case head = "HEAD" | ||
} | ||
|
||
enum Headers { | ||
static let sessionToken = "Coder-Session-Token" | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
import Foundation | ||
|
||
public extension Client { | ||
func user(_ ident: String) async throws(ClientError) -> User { | ||
let res = try await request("/api/v2/users/\(ident)", method: .get) | ||
guard res.resp.statusCode == 200 else { | ||
throw responseAsError(res) | ||
} | ||
do { | ||
return try Client.decoder.decode(User.self, from: res.data) | ||
} catch { | ||
throw .unexpectedResponse(res.data.prefix(1024)) | ||
} | ||
} | ||
} | ||
|
||
public struct User: Encodable, Decodable, Equatable, Sendable { | ||
public let id: UUID | ||
public let username: String | ||
public let avatar_url: String | ||
public let name: String | ||
public let email: String | ||
public let created_at: Date | ||
public let updated_at: Date | ||
public let last_seen_at: Date | ||
public let status: String | ||
public let login_type: String | ||
public let theme_preference: String | ||
public let organization_ids: [UUID] | ||
public let roles: [Role] | ||
|
||
public init( | ||
id: UUID, | ||
username: String, | ||
avatar_url: String, | ||
name: String, | ||
email: String, | ||
created_at: Date, | ||
updated_at: Date, | ||
last_seen_at: Date, | ||
status: String, | ||
login_type: String, | ||
theme_preference: String, | ||
organization_ids: [UUID], | ||
roles: [Role] | ||
) { | ||
self.id = id | ||
self.username = username | ||
self.avatar_url = avatar_url | ||
self.name = name | ||
self.email = email | ||
self.created_at = created_at | ||
self.updated_at = updated_at | ||
self.last_seen_at = last_seen_at | ||
self.status = status | ||
self.login_type = login_type | ||
self.theme_preference = theme_preference | ||
self.organization_ids = organization_ids | ||
self.roles = roles | ||
} | ||
} | ||
|
||
public struct Role: Encodable, Decodable, Equatable, Sendable { | ||
public let name: String | ||
public let display_name: String | ||
public let organization_id: UUID? | ||
|
||
public init(name: String, display_name: String, organization_id: UUID?) { | ||
self.name = name | ||
self.display_name = display_name | ||
self.organization_id = organization_id | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
@testable import CoderSDK | ||
import Mocker | ||
import Testing | ||
|
||
@Suite(.timeLimit(.minutes(1))) | ||
struct CoderSDKTests { | ||
@Test | ||
func user() async throws { | ||
let now = Date.now | ||
let user = User( | ||
id: UUID(), | ||
username: "johndoe", | ||
avatar_url: "https://example.com/img.png", | ||
name: "John Doe", | ||
email: "john.doe@example.com", | ||
created_at: now, | ||
updated_at: now, | ||
last_seen_at: now, | ||
status: "active", | ||
login_type: "email", | ||
theme_preference: "dark", | ||
organization_ids: [UUID()], | ||
roles: [ | ||
Role(name: "user", display_name: "User", organization_id: UUID()), | ||
] | ||
) | ||
|
||
let url = URL(string: "https://example.com")! | ||
let token = "fake-token" | ||
let client = Client(url: url, token: token, headers: [.init(header: "X-Test-Header", value: "foo")]) | ||
var mock = try Mock( | ||
url: url.appending(path: "api/v2/users/johndoe"), | ||
contentType: .json, | ||
statusCode: 200, | ||
data: [.get: Client.encoder.encode(user)] | ||
) | ||
var correctHeaders = false | ||
mock.onRequestHandler = OnRequestHandler { req in | ||
correctHeaders = req.value(forHTTPHeaderField: Headers.sessionToken) == token && | ||
req.value(forHTTPHeaderField: "X-Test-Header") == "foo" | ||
} | ||
mock.register() | ||
|
||
let retUser = try await client.user(user.username) | ||
#expect(user == retUser) | ||
#expect(correctHeaders) | ||
} | ||
|
||
@Test | ||
func buildInfo() async throws { | ||
let buildInfo = BuildInfoResponse( | ||
external_url: "https://example.com", | ||
version: "v2.18.2-devel+630fd7c0a", | ||
dashboard_url: "https://example.com/dashboard", | ||
telemetry: true, | ||
workspace_proxy: false, | ||
agent_api_version: "1.0", | ||
provisioner_api_version: "1.2", | ||
upgrade_message: "foo", | ||
deployment_id: UUID().uuidString | ||
) | ||
|
||
let url = URL(string: "https://example.com")! | ||
let client = Client(url: url) | ||
try Mock( | ||
url: url.appending(path: "api/v2/buildinfo"), | ||
contentType: .json, | ||
statusCode: 200, | ||
data: [.get: Client.encoder.encode(buildInfo)] | ||
).register() | ||
|
||
let retBuildInfo = try await client.buildInfo() | ||
#expect(buildInfo == retBuildInfo) | ||
#expect(retBuildInfo.semver == "2.18.2") | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I much prefer using the
Mocker
mocks over plastering a generic type throughout the actual implementation.