Skip to content

Commit

Permalink
fix Test
Browse files Browse the repository at this point in the history
  • Loading branch information
zunda-pixel committed Nov 30, 2024
1 parent 0967834 commit 02fd09b
Show file tree
Hide file tree
Showing 32 changed files with 323 additions and 309 deletions.
28 changes: 15 additions & 13 deletions Sources/TestHelpers/HTTPClientMock.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,16 @@ import ConcurrencyExtras
import Foundation
import Helpers
import XCTestDynamicOverlay
import HTTPTypes

package actor HTTPClientMock: HTTPClientType {

package struct MockNotFound: Error {}

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

/// Requests received by this client in order.
package var receivedRequests: [HTTPRequest] = []
package var receivedRequests: [(HTTPRequest, Data?)] = []

/// Responses returned by this client in order.
package var returnedResponses: [Result<HTTPResponse, any Error>] = []
Expand All @@ -25,12 +27,12 @@ package actor HTTPClientMock: HTTPClientType {

@discardableResult
package func when(
_ request: @escaping @Sendable (HTTPRequest) -> Bool,
return response: @escaping @Sendable (HTTPRequest) async throws -> HTTPResponse
_ request: @escaping @Sendable (HTTPRequest, Data?) -> Bool,
return response: @escaping @Sendable (HTTPRequest, Data?) async throws -> (Data, HTTPResponse)
) -> Self {
mocks.append { r in
if request(r) {
return try await response(r)
mocks.append { r, b in
if request(r, b) {
return try await response(r, b)
}
return nil
}
Expand All @@ -39,19 +41,19 @@ package actor HTTPClientMock: HTTPClientType {

@discardableResult
package func any(
_ response: @escaping @Sendable (HTTPRequest) async throws -> HTTPResponse
_ response: @escaping @Sendable (HTTPRequest, Data?) async throws -> (Data, HTTPResponse)
) -> Self {
when({ _ in true }, return: response)
when({ _, _ in true }, return: response)
}

package func send(_ request: HTTPRequest) async throws -> HTTPResponse {
receivedRequests.append(request)
package func send(_ request: HTTPRequest, _ bodyData: Data?) async throws -> (Data, HTTPResponse) {
receivedRequests.append((request, bodyData))

for mock in mocks {
do {
if let response = try await mock(request) {
if let (data, response) = try await mock(request, bodyData) {
returnedResponses.append(.success(response))
return response
return (data, response)
}
} catch {
returnedResponses.append(.failure(error))
Expand Down
3 changes: 2 additions & 1 deletion Tests/AuthTests/AuthClientMultipleInstancesTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@
// Created by Guilherme Souza on 05/07/24.
//

@testable import Auth
import TestHelpers
import XCTest

@testable import Auth

final class AuthClientMultipleInstancesTests: XCTestCase {
func testMultipleAuthClientInstances() {
let url = URL(string: "http://localhost:54321/auth")!
Expand Down
126 changes: 58 additions & 68 deletions Tests/AuthTests/AuthClientTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import ConcurrencyExtras
import CustomDump
import HTTPTypes
import InlineSnapshotTesting
import TestHelpers
import XCTest
Expand Down Expand Up @@ -80,8 +81,8 @@ final class AuthClientTests: XCTestCase {
}

func testSignOut() async throws {
sut = makeSUT { _ in
.stub()
sut = makeSUT { _, _ in
TestStub.stub()
}

Dependencies[sut.clientID].sessionStorage.store(.validSession)
Expand Down Expand Up @@ -109,8 +110,8 @@ final class AuthClientTests: XCTestCase {
}

func testSignOutWithOthersScopeShouldNotRemoveLocalSession() async throws {
sut = makeSUT { _ in
.stub()
sut = makeSUT { _, _ in
TestStub.stub()
}

Dependencies[sut.clientID].sessionStorage.store(.validSession)
Expand All @@ -122,14 +123,12 @@ final class AuthClientTests: XCTestCase {
}

func testSignOutShouldRemoveSessionIfUserIsNotFound() async throws {
sut = makeSUT { _ in
sut = makeSUT { _, _ in
throw AuthError.api(
message: "",
errorCode: .unknown,
underlyingData: Data(),
underlyingResponse: HTTPURLResponse(
url: URL(string: "http://localhost")!, statusCode: 404, httpVersion: nil,
headerFields: nil)!
data: Data(),
response: HTTPResponse(status: .init(code: 404))
)
}

Expand All @@ -155,14 +154,12 @@ final class AuthClientTests: XCTestCase {
}

func testSignOutShouldRemoveSessionIfJWTIsInvalid() async throws {
sut = makeSUT { _ in
sut = makeSUT { _, _ in
throw AuthError.api(
message: "",
errorCode: .invalidCredentials,
underlyingData: Data(),
underlyingResponse: HTTPURLResponse(
url: URL(string: "http://localhost")!, statusCode: 401, httpVersion: nil,
headerFields: nil)!
data: Data(),
response: HTTPResponse(status: .init(code: 401))
)
}

Expand All @@ -188,14 +185,12 @@ final class AuthClientTests: XCTestCase {
}

func testSignOutShouldRemoveSessionIf403Returned() async throws {
sut = makeSUT { _ in
sut = makeSUT { _, _ in
throw AuthError.api(
message: "",
errorCode: .invalidCredentials,
underlyingData: Data(),
underlyingResponse: HTTPURLResponse(
url: URL(string: "http://localhost")!, statusCode: 403, httpVersion: nil,
headerFields: nil)!
data: Data(),
response: HTTPResponse(status: .init(code: 403))
)
}

Expand Down Expand Up @@ -223,8 +218,8 @@ final class AuthClientTests: XCTestCase {
func testSignInAnonymously() async throws {
let session = Session(fromMockNamed: "anonymous-sign-in-response")

let sut = makeSUT { _ in
.stub(fromFileName: "anonymous-sign-in-response")
let sut = makeSUT { _, _ in
TestStub.stub(fromFileName: "anonymous-sign-in-response")
}

let eventsTask = Task {
Expand All @@ -243,8 +238,8 @@ final class AuthClientTests: XCTestCase {
}

func testSignInWithOAuth() async throws {
let sut = makeSUT { _ in
.stub(fromFileName: "session")
let sut = makeSUT { _, _ in
TestStub.stub(fromFileName: "session")
}

let eventsTask = Task {
Expand All @@ -266,8 +261,8 @@ final class AuthClientTests: XCTestCase {
}

func testGetLinkIdentityURL() async throws {
let sut = makeSUT { _ in
.stub(
let sut = makeSUT { _, _ in
TestStub.stub(
"""
{
"url" : "https://github.com/login/oauth/authorize?client_id=1234&redirect_to=com.supabase.swift-examples://&redirect_uri=http://127.0.0.1:54321/auth/v1/callback&response_type=code&scope=user:email&skip_http_redirect=true&state=jwt"
Expand Down Expand Up @@ -295,8 +290,8 @@ final class AuthClientTests: XCTestCase {
func testLinkIdentity() async throws {
let url =
"https://github.com/login/oauth/authorize?client_id=1234&redirect_to=com.supabase.swift-examples://&redirect_uri=http://127.0.0.1:54321/auth/v1/callback&response_type=code&scope=user:email&skip_http_redirect=true&state=jwt"
let sut = makeSUT { _ in
.stub(
let sut = makeSUT { _, _ in
TestStub.stub(
"""
{
"url" : "\(url)"
Expand All @@ -318,12 +313,12 @@ final class AuthClientTests: XCTestCase {
}

func testAdminListUsers() async throws {
let sut = makeSUT { _ in
.stub(
let sut = makeSUT { _, _ in
TestStub.stub(
fromFileName: "list-users-response",
headers: [
"X-Total-Count": "669",
"Link":
.xTotalCount: "669",
.link:
"</admin/users?page=2&per_page=>; rel=\"next\", </admin/users?page=14&per_page=>; rel=\"last\"",
]
)
Expand All @@ -336,12 +331,12 @@ final class AuthClientTests: XCTestCase {
}

func testAdminListUsers_noNextPage() async throws {
let sut = makeSUT { _ in
.stub(
let sut = makeSUT { _, _ in
TestStub.stub(
fromFileName: "list-users-response",
headers: [
"X-Total-Count": "669",
"Link": "</admin/users?page=14&per_page=>; rel=\"last\"",
.xTotalCount: "669",
.link: "</admin/users?page=14&per_page=>; rel=\"last\"",
]
)
}
Expand Down Expand Up @@ -378,20 +373,20 @@ final class AuthClientTests: XCTestCase {
}

private func makeSUT(
fetch: ((URLRequest) async throws -> HTTPResponse)? = nil
fetch: ((HTTPRequest, Data?) async throws -> (Data, HTTPResponse))? = nil
) -> AuthClient {
let configuration = AuthClient.Configuration(
url: clientURL,
headers: ["Apikey": "dummy.api.key"],
headers: [.apiKey: "dummy.api.key"],
localStorage: storage,
logger: nil,
fetch: { request in
fetch: { request, body in
guard let fetch else {
throw UnimplementedError()
}

let response = try await fetch(request)
return (response.data, response.underlyingResponse)
let (data, response) = try await fetch(request, body)
return (data, response)
}
)

Expand All @@ -401,52 +396,47 @@ final class AuthClientTests: XCTestCase {
}
}

extension HTTPResponse {
struct TestStub {
static func stub(
_ body: String = "",
code: Int = 200,
headers: [String: String]? = nil
) -> HTTPResponse {
HTTPResponse(
data: body.data(using: .utf8)!,
response: HTTPURLResponse(
url: clientURL,
statusCode: code,
httpVersion: nil,
headers: HTTPFields = [:]
) -> (Data, HTTPResponse) {
(
Data(body.utf8),
HTTPResponse(
status: .init(code: code),
headerFields: headers
)!
)
)
}

static func stub(
fromFileName fileName: String,
code: Int = 200,
headers: [String: String]? = nil
) -> HTTPResponse {
HTTPResponse(
data: json(named: fileName),
response: HTTPURLResponse(
url: clientURL,
statusCode: code,
httpVersion: nil,
headers: HTTPFields = [:]
) -> (Data, HTTPResponse) {
(
json(named: fileName),
HTTPResponse(
status: .init(code: code),
headerFields: headers
)!
)
)
}

static func stub(
_ value: some Encodable,
code: Int = 200,
headers: [String: String]? = nil
) -> HTTPResponse {
HTTPResponse(
data: try! AuthClient.Configuration.jsonEncoder.encode(value),
response: HTTPURLResponse(
url: clientURL,
statusCode: code,
httpVersion: nil,
headers: HTTPFields = [:]
) -> (Data, HTTPResponse) {
(
try! AuthClient.Configuration.jsonEncoder.encode(value),
HTTPResponse(
status: .init(code: code),
headerFields: headers
)!
)
)

}
}
14 changes: 10 additions & 4 deletions Tests/AuthTests/AuthErrorTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@
// Created by Guilherme Souza on 29/08/24.
//

@testable import Auth
import HTTPTypes
import XCTest

@testable import Auth

#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
Expand All @@ -25,13 +27,17 @@ final class AuthErrorTests: XCTestCase {
let api = AuthError.api(
message: "API Error",
errorCode: .emailConflictIdentityNotDeletable,
underlyingData: Data(),
underlyingResponse: HTTPURLResponse(url: URL(string: "http://localhost")!, statusCode: 400, httpVersion: nil, headerFields: nil)!
data: Data(),
response: HTTPResponse(status: .init(code: 400))
)
XCTAssertEqual(api.errorCode, .emailConflictIdentityNotDeletable)
XCTAssertEqual(api.message, "API Error")

let pkceGrantCodeExchange = AuthError.pkceGrantCodeExchange(message: "PKCE failure", error: nil, code: nil)
let pkceGrantCodeExchange = AuthError.pkceGrantCodeExchange(
message: "PKCE failure",
error: nil,
code: nil
)
XCTAssertEqual(pkceGrantCodeExchange.errorCode, .unknown)
XCTAssertEqual(pkceGrantCodeExchange.message, "PKCE failure")

Expand Down
3 changes: 2 additions & 1 deletion Tests/AuthTests/ExtractParamsTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@
// Created by Guilherme Souza on 23/12/23.
//

@testable import Auth
import XCTest

@testable import Auth

final class ExtractParamsTests: XCTestCase {
func testExtractParamsInQuery() {
let code = UUID().uuidString
Expand Down
Loading

0 comments on commit 02fd09b

Please sign in to comment.