Skip to content

Commit 02fd09b

Browse files
committed
fix Test
1 parent 0967834 commit 02fd09b

32 files changed

+323
-309
lines changed

Sources/TestHelpers/HTTPClientMock.swift

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,16 @@ import ConcurrencyExtras
99
import Foundation
1010
import Helpers
1111
import XCTestDynamicOverlay
12+
import HTTPTypes
1213

1314
package actor HTTPClientMock: HTTPClientType {
15+
1416
package struct MockNotFound: Error {}
1517

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

1820
/// Requests received by this client in order.
19-
package var receivedRequests: [HTTPRequest] = []
21+
package var receivedRequests: [(HTTPRequest, Data?)] = []
2022

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

2628
@discardableResult
2729
package func when(
28-
_ request: @escaping @Sendable (HTTPRequest) -> Bool,
29-
return response: @escaping @Sendable (HTTPRequest) async throws -> HTTPResponse
30+
_ request: @escaping @Sendable (HTTPRequest, Data?) -> Bool,
31+
return response: @escaping @Sendable (HTTPRequest, Data?) async throws -> (Data, HTTPResponse)
3032
) -> Self {
31-
mocks.append { r in
32-
if request(r) {
33-
return try await response(r)
33+
mocks.append { r, b in
34+
if request(r, b) {
35+
return try await response(r, b)
3436
}
3537
return nil
3638
}
@@ -39,19 +41,19 @@ package actor HTTPClientMock: HTTPClientType {
3941

4042
@discardableResult
4143
package func any(
42-
_ response: @escaping @Sendable (HTTPRequest) async throws -> HTTPResponse
44+
_ response: @escaping @Sendable (HTTPRequest, Data?) async throws -> (Data, HTTPResponse)
4345
) -> Self {
44-
when({ _ in true }, return: response)
46+
when({ _, _ in true }, return: response)
4547
}
4648

47-
package func send(_ request: HTTPRequest) async throws -> HTTPResponse {
48-
receivedRequests.append(request)
49+
package func send(_ request: HTTPRequest, _ bodyData: Data?) async throws -> (Data, HTTPResponse) {
50+
receivedRequests.append((request, bodyData))
4951

5052
for mock in mocks {
5153
do {
52-
if let response = try await mock(request) {
54+
if let (data, response) = try await mock(request, bodyData) {
5355
returnedResponses.append(.success(response))
54-
return response
56+
return (data, response)
5557
}
5658
} catch {
5759
returnedResponses.append(.failure(error))

Tests/AuthTests/AuthClientMultipleInstancesTests.swift

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,11 @@
55
// Created by Guilherme Souza on 05/07/24.
66
//
77

8-
@testable import Auth
98
import TestHelpers
109
import XCTest
1110

11+
@testable import Auth
12+
1213
final class AuthClientMultipleInstancesTests: XCTestCase {
1314
func testMultipleAuthClientInstances() {
1415
let url = URL(string: "http://localhost:54321/auth")!

Tests/AuthTests/AuthClientTests.swift

Lines changed: 58 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
import ConcurrencyExtras
99
import CustomDump
10+
import HTTPTypes
1011
import InlineSnapshotTesting
1112
import TestHelpers
1213
import XCTest
@@ -80,8 +81,8 @@ final class AuthClientTests: XCTestCase {
8081
}
8182

8283
func testSignOut() async throws {
83-
sut = makeSUT { _ in
84-
.stub()
84+
sut = makeSUT { _, _ in
85+
TestStub.stub()
8586
}
8687

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

111112
func testSignOutWithOthersScopeShouldNotRemoveLocalSession() async throws {
112-
sut = makeSUT { _ in
113-
.stub()
113+
sut = makeSUT { _, _ in
114+
TestStub.stub()
114115
}
115116

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

124125
func testSignOutShouldRemoveSessionIfUserIsNotFound() async throws {
125-
sut = makeSUT { _ in
126+
sut = makeSUT { _, _ in
126127
throw AuthError.api(
127128
message: "",
128129
errorCode: .unknown,
129-
underlyingData: Data(),
130-
underlyingResponse: HTTPURLResponse(
131-
url: URL(string: "http://localhost")!, statusCode: 404, httpVersion: nil,
132-
headerFields: nil)!
130+
data: Data(),
131+
response: HTTPResponse(status: .init(code: 404))
133132
)
134133
}
135134

@@ -155,14 +154,12 @@ final class AuthClientTests: XCTestCase {
155154
}
156155

157156
func testSignOutShouldRemoveSessionIfJWTIsInvalid() async throws {
158-
sut = makeSUT { _ in
157+
sut = makeSUT { _, _ in
159158
throw AuthError.api(
160159
message: "",
161160
errorCode: .invalidCredentials,
162-
underlyingData: Data(),
163-
underlyingResponse: HTTPURLResponse(
164-
url: URL(string: "http://localhost")!, statusCode: 401, httpVersion: nil,
165-
headerFields: nil)!
161+
data: Data(),
162+
response: HTTPResponse(status: .init(code: 401))
166163
)
167164
}
168165

@@ -188,14 +185,12 @@ final class AuthClientTests: XCTestCase {
188185
}
189186

190187
func testSignOutShouldRemoveSessionIf403Returned() async throws {
191-
sut = makeSUT { _ in
188+
sut = makeSUT { _, _ in
192189
throw AuthError.api(
193190
message: "",
194191
errorCode: .invalidCredentials,
195-
underlyingData: Data(),
196-
underlyingResponse: HTTPURLResponse(
197-
url: URL(string: "http://localhost")!, statusCode: 403, httpVersion: nil,
198-
headerFields: nil)!
192+
data: Data(),
193+
response: HTTPResponse(status: .init(code: 403))
199194
)
200195
}
201196

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

226-
let sut = makeSUT { _ in
227-
.stub(fromFileName: "anonymous-sign-in-response")
221+
let sut = makeSUT { _, _ in
222+
TestStub.stub(fromFileName: "anonymous-sign-in-response")
228223
}
229224

230225
let eventsTask = Task {
@@ -243,8 +238,8 @@ final class AuthClientTests: XCTestCase {
243238
}
244239

245240
func testSignInWithOAuth() async throws {
246-
let sut = makeSUT { _ in
247-
.stub(fromFileName: "session")
241+
let sut = makeSUT { _, _ in
242+
TestStub.stub(fromFileName: "session")
248243
}
249244

250245
let eventsTask = Task {
@@ -266,8 +261,8 @@ final class AuthClientTests: XCTestCase {
266261
}
267262

268263
func testGetLinkIdentityURL() async throws {
269-
let sut = makeSUT { _ in
270-
.stub(
264+
let sut = makeSUT { _, _ in
265+
TestStub.stub(
271266
"""
272267
{
273268
"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"
@@ -295,8 +290,8 @@ final class AuthClientTests: XCTestCase {
295290
func testLinkIdentity() async throws {
296291
let url =
297292
"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"
298-
let sut = makeSUT { _ in
299-
.stub(
293+
let sut = makeSUT { _, _ in
294+
TestStub.stub(
300295
"""
301296
{
302297
"url" : "\(url)"
@@ -318,12 +313,12 @@ final class AuthClientTests: XCTestCase {
318313
}
319314

320315
func testAdminListUsers() async throws {
321-
let sut = makeSUT { _ in
322-
.stub(
316+
let sut = makeSUT { _, _ in
317+
TestStub.stub(
323318
fromFileName: "list-users-response",
324319
headers: [
325-
"X-Total-Count": "669",
326-
"Link":
320+
.xTotalCount: "669",
321+
.link:
327322
"</admin/users?page=2&per_page=>; rel=\"next\", </admin/users?page=14&per_page=>; rel=\"last\"",
328323
]
329324
)
@@ -336,12 +331,12 @@ final class AuthClientTests: XCTestCase {
336331
}
337332

338333
func testAdminListUsers_noNextPage() async throws {
339-
let sut = makeSUT { _ in
340-
.stub(
334+
let sut = makeSUT { _, _ in
335+
TestStub.stub(
341336
fromFileName: "list-users-response",
342337
headers: [
343-
"X-Total-Count": "669",
344-
"Link": "</admin/users?page=14&per_page=>; rel=\"last\"",
338+
.xTotalCount: "669",
339+
.link: "</admin/users?page=14&per_page=>; rel=\"last\"",
345340
]
346341
)
347342
}
@@ -378,20 +373,20 @@ final class AuthClientTests: XCTestCase {
378373
}
379374

380375
private func makeSUT(
381-
fetch: ((URLRequest) async throws -> HTTPResponse)? = nil
376+
fetch: ((HTTPRequest, Data?) async throws -> (Data, HTTPResponse))? = nil
382377
) -> AuthClient {
383378
let configuration = AuthClient.Configuration(
384379
url: clientURL,
385-
headers: ["Apikey": "dummy.api.key"],
380+
headers: [.apiKey: "dummy.api.key"],
386381
localStorage: storage,
387382
logger: nil,
388-
fetch: { request in
383+
fetch: { request, body in
389384
guard let fetch else {
390385
throw UnimplementedError()
391386
}
392387

393-
let response = try await fetch(request)
394-
return (response.data, response.underlyingResponse)
388+
let (data, response) = try await fetch(request, body)
389+
return (data, response)
395390
}
396391
)
397392

@@ -401,52 +396,47 @@ final class AuthClientTests: XCTestCase {
401396
}
402397
}
403398

404-
extension HTTPResponse {
399+
struct TestStub {
405400
static func stub(
406401
_ body: String = "",
407402
code: Int = 200,
408-
headers: [String: String]? = nil
409-
) -> HTTPResponse {
410-
HTTPResponse(
411-
data: body.data(using: .utf8)!,
412-
response: HTTPURLResponse(
413-
url: clientURL,
414-
statusCode: code,
415-
httpVersion: nil,
403+
headers: HTTPFields = [:]
404+
) -> (Data, HTTPResponse) {
405+
(
406+
Data(body.utf8),
407+
HTTPResponse(
408+
status: .init(code: code),
416409
headerFields: headers
417-
)!
410+
)
418411
)
419412
}
420413

421414
static func stub(
422415
fromFileName fileName: String,
423416
code: Int = 200,
424-
headers: [String: String]? = nil
425-
) -> HTTPResponse {
426-
HTTPResponse(
427-
data: json(named: fileName),
428-
response: HTTPURLResponse(
429-
url: clientURL,
430-
statusCode: code,
431-
httpVersion: nil,
417+
headers: HTTPFields = [:]
418+
) -> (Data, HTTPResponse) {
419+
(
420+
json(named: fileName),
421+
HTTPResponse(
422+
status: .init(code: code),
432423
headerFields: headers
433-
)!
424+
)
434425
)
435426
}
436427

437428
static func stub(
438429
_ value: some Encodable,
439430
code: Int = 200,
440-
headers: [String: String]? = nil
441-
) -> HTTPResponse {
442-
HTTPResponse(
443-
data: try! AuthClient.Configuration.jsonEncoder.encode(value),
444-
response: HTTPURLResponse(
445-
url: clientURL,
446-
statusCode: code,
447-
httpVersion: nil,
431+
headers: HTTPFields = [:]
432+
) -> (Data, HTTPResponse) {
433+
(
434+
try! AuthClient.Configuration.jsonEncoder.encode(value),
435+
HTTPResponse(
436+
status: .init(code: code),
448437
headerFields: headers
449-
)!
438+
)
450439
)
440+
451441
}
452442
}

Tests/AuthTests/AuthErrorTests.swift

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,11 @@
55
// Created by Guilherme Souza on 29/08/24.
66
//
77

8-
@testable import Auth
8+
import HTTPTypes
99
import XCTest
1010

11+
@testable import Auth
12+
1113
#if canImport(FoundationNetworking)
1214
import FoundationNetworking
1315
#endif
@@ -25,13 +27,17 @@ final class AuthErrorTests: XCTestCase {
2527
let api = AuthError.api(
2628
message: "API Error",
2729
errorCode: .emailConflictIdentityNotDeletable,
28-
underlyingData: Data(),
29-
underlyingResponse: HTTPURLResponse(url: URL(string: "http://localhost")!, statusCode: 400, httpVersion: nil, headerFields: nil)!
30+
data: Data(),
31+
response: HTTPResponse(status: .init(code: 400))
3032
)
3133
XCTAssertEqual(api.errorCode, .emailConflictIdentityNotDeletable)
3234
XCTAssertEqual(api.message, "API Error")
3335

34-
let pkceGrantCodeExchange = AuthError.pkceGrantCodeExchange(message: "PKCE failure", error: nil, code: nil)
36+
let pkceGrantCodeExchange = AuthError.pkceGrantCodeExchange(
37+
message: "PKCE failure",
38+
error: nil,
39+
code: nil
40+
)
3541
XCTAssertEqual(pkceGrantCodeExchange.errorCode, .unknown)
3642
XCTAssertEqual(pkceGrantCodeExchange.message, "PKCE failure")
3743

Tests/AuthTests/ExtractParamsTests.swift

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,10 @@
55
// Created by Guilherme Souza on 23/12/23.
66
//
77

8-
@testable import Auth
98
import XCTest
109

10+
@testable import Auth
11+
1112
final class ExtractParamsTests: XCTestCase {
1213
func testExtractParamsInQuery() {
1314
let code = UUID().uuidString

0 commit comments

Comments
 (0)