Skip to content

Commit

Permalink
test: fix failing tests (#467)
Browse files Browse the repository at this point in the history
  • Loading branch information
grdsdev authored Jul 16, 2024
1 parent e92e43e commit b8f8164
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 46 deletions.
39 changes: 13 additions & 26 deletions Sources/TestHelpers/HTTPClientMock.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,16 @@ import Foundation
import Helpers
import XCTestDynamicOverlay

package final class HTTPClientMock: HTTPClientType {
package actor HTTPClientMock: HTTPClientType {
package struct MockNotFound: Error {}

private let mocks: LockIsolated < [@Sendable (HTTPRequest) async throws -> HTTPResponse?]> = .init([])
private let _receivedRequests = LockIsolated<[HTTPRequest]>([])
private let _returnedResponses = LockIsolated<[Result<HTTPResponse, any Error>]>([])

private var mocks = [@Sendable (HTTPRequest) async throws -> HTTPResponse?]()

/// Requests received by this client in order.
package var receivedRequests: [HTTPRequest] {
_receivedRequests.value
}
package var receivedRequests: [HTTPRequest] = []

/// Responses returned by this client in order.
package var returnedResponses: [Result<HTTPResponse, any Error>] {
_returnedResponses.value
}
package var returnedResponses: [Result<HTTPResponse, any Error>] = []

package init() {}

Expand All @@ -34,14 +28,11 @@ package final class HTTPClientMock: HTTPClientType {
_ request: @escaping @Sendable (HTTPRequest) -> Bool,
return response: @escaping @Sendable (HTTPRequest) async throws -> HTTPResponse
) -> Self {
mocks.withValue {
$0.append { r in
if request(r) {
return try await response(r)
}

return nil
mocks.append { r in
if request(r) {
return try await response(r)
}
return nil
}
return self
}
Expand All @@ -54,20 +45,16 @@ package final class HTTPClientMock: HTTPClientType {
}

package func send(_ request: HTTPRequest) async throws -> HTTPResponse {
_receivedRequests.withValue { $0.append(request) }
receivedRequests.append(request)

for mock in mocks.value {
for mock in mocks{
do {
if let response = try await mock(request) {
_returnedResponses.withValue {
$0.append(.success(response))
}
returnedResponses.append(.success(response))
return response
}
} catch {
_returnedResponses.withValue {
$0.append(.failure(error))
}
returnedResponses.append(.failure(error))
throw error
}
}
Expand Down
12 changes: 9 additions & 3 deletions Tests/AuthTests/SessionManagerTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ final class SessionManagerTests: XCTestCase {
configuration: .init(
url: clientURL,
localStorage: InMemoryLocalStorage(),
logger: nil,
logger: TestLogger(),
autoRefreshToken: false
),
http: http,
Expand Down Expand Up @@ -72,7 +72,7 @@ final class SessionManagerTests: XCTestCase {

let (refreshSessionStream, refreshSessionContinuation) = AsyncStream<Session>.makeStream()

http.when(
await http.when(
{ $0.url.path.contains("/token") },
return: { _ in
refreshSessionCallCount.withValue { $0 += 1 }
Expand All @@ -83,7 +83,7 @@ final class SessionManagerTests: XCTestCase {

// Fire N tasks and call sut.session()
let tasks = (0 ..< 10).map { _ in
Task.detached { [weak self] in
Task { [weak self] in
try await self?.sut.session()
}
}
Expand All @@ -106,3 +106,9 @@ final class SessionManagerTests: XCTestCase {
}
}
}

struct TestLogger: SupabaseLogger {
func log(message: SupabaseLogMessage) {
print(message.description)
}
}
35 changes: 18 additions & 17 deletions Tests/FunctionsTests/FunctionsClientTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ final class FunctionsClientTests: XCTestCase {
func testInvoke() async throws {
let url = URL(string: "http://localhost:5432/functions/v1/hello_world")!

let http = HTTPClientMock()
let http = await HTTPClientMock()
.when {
$0.url.pathComponents.contains("hello_world")
} return: { _ in
Expand All @@ -49,7 +49,7 @@ final class FunctionsClientTests: XCTestCase {
options: .init(headers: ["X-Custom-Key": "value"], body: body)
)

let request = http.receivedRequests.last
let request = await http.receivedRequests.last

XCTAssertEqual(request?.url, url)
XCTAssertEqual(request?.method, .post)
Expand All @@ -59,7 +59,7 @@ final class FunctionsClientTests: XCTestCase {
}

func testInvokeWithCustomMethod() async throws {
let http = HTTPClientMock().any { _ in try .stub(body: Empty()) }
let http = await HTTPClientMock().any { _ in try .stub(body: Empty()) }

let sut = FunctionsClient(
url: url,
Expand All @@ -70,12 +70,12 @@ final class FunctionsClientTests: XCTestCase {

try await sut.invoke("hello-world", options: .init(method: .delete))

let request = http.receivedRequests.last
let request = await http.receivedRequests.last
XCTAssertEqual(request?.method, .delete)
}

func testInvokeWithQuery() async throws {
let http = HTTPClientMock().any { _ in try .stub(body: Empty()) }
let http = await HTTPClientMock().any { _ in try .stub(body: Empty()) }

let sut = FunctionsClient(
url: url,
Expand All @@ -91,12 +91,12 @@ final class FunctionsClientTests: XCTestCase {
)
)

let request = http.receivedRequests.last
let request = await http.receivedRequests.last
XCTAssertEqual(request?.urlRequest.url?.query, "key=value")
}

func testInvokeWithRegionDefinedInClient() async throws {
let http = HTTPClientMock()
let http = await HTTPClientMock()
.any { _ in try .stub(body: Empty()) }

let sut = FunctionsClient(
Expand All @@ -108,11 +108,12 @@ final class FunctionsClientTests: XCTestCase {

try await sut.invoke("hello-world")

XCTAssertEqual(http.receivedRequests.last?.headers["x-region"], "ca-central-1")
let request = await http.receivedRequests.last
XCTAssertEqual(request?.headers["x-region"], "ca-central-1")
}

func testInvokeWithRegion() async throws {
let http = HTTPClientMock()
let http = await HTTPClientMock()
.any { _ in try .stub(body: Empty()) }

let sut = FunctionsClient(
Expand All @@ -124,11 +125,12 @@ final class FunctionsClientTests: XCTestCase {

try await sut.invoke("hello-world", options: .init(region: .caCentral1))

XCTAssertEqual(http.receivedRequests.last?.headers["x-region"], "ca-central-1")
let request = await http.receivedRequests.last
XCTAssertEqual(request?.headers["x-region"], "ca-central-1")
}

func testInvokeWithoutRegion() async throws {
let http = HTTPClientMock()
let http = await HTTPClientMock()
.any { _ in try .stub(body: Empty()) }

let sut = FunctionsClient(
Expand All @@ -140,11 +142,12 @@ final class FunctionsClientTests: XCTestCase {

try await sut.invoke("hello-world")

XCTAssertNil(http.receivedRequests.last?.headers["x-region"])
let request = await http.receivedRequests.last
XCTAssertNil(request?.headers["x-region"])
}

func testInvoke_shouldThrow_URLError_badServerResponse() async {
let sut = FunctionsClient(
let sut = await FunctionsClient(
url: url,
headers: ["Apikey": apiKey],
region: nil,
Expand All @@ -162,7 +165,7 @@ final class FunctionsClientTests: XCTestCase {
}

func testInvoke_shouldThrow_FunctionsError_httpError() async {
let sut = FunctionsClient(
let sut = await FunctionsClient(
url: url,
headers: ["Apikey": apiKey],
region: nil,
Expand All @@ -180,9 +183,7 @@ final class FunctionsClientTests: XCTestCase {
}

func testInvoke_shouldThrow_FunctionsError_relayError() async {
let url = URL(string: "http://localhost:5432/functions/v1/hello_world")!

let sut = FunctionsClient(
let sut = await FunctionsClient(
url: self.url,
headers: ["Apikey": apiKey],
region: nil,
Expand Down

0 comments on commit b8f8164

Please sign in to comment.