|
| 1 | +// |
| 2 | +// CustomHeadersTests.swift |
| 3 | +// FlagsmithClientTests |
| 4 | +// |
| 5 | + |
| 6 | +@testable import FlagsmithClient |
| 7 | +import XCTest |
| 8 | + |
| 9 | +final class CustomHeadersTests: FlagsmithClientTestCase { |
| 10 | + override func tearDown() { |
| 11 | + super.tearDown() |
| 12 | + Flagsmith.shared.customHeaders = nil |
| 13 | + } |
| 14 | + |
| 15 | + /// Verify the `customHeaders` closure is invoked when a request is made. |
| 16 | + func testCustomHeadersClosureIsInvoked() throws { |
| 17 | + let closureInvoked = expectation(description: "customHeaders closure invoked") |
| 18 | + |
| 19 | + Flagsmith.shared.customHeaders = { |
| 20 | + closureInvoked.fulfill() |
| 21 | + return ["X-Test-Header": "value"] |
| 22 | + } |
| 23 | + Flagsmith.shared.apiKey = "mock-test-api-key" |
| 24 | + // Force a quick failure so the request doesn't hang |
| 25 | + Flagsmith.shared.baseURL = URL(fileURLWithPath: "/dev/null") |
| 26 | + |
| 27 | + Flagsmith.shared.getFeatureFlags { _ in } |
| 28 | + |
| 29 | + wait(for: [closureInvoked], timeout: 1.0) |
| 30 | + } |
| 31 | + |
| 32 | + /// Verify that when `customHeaders` is nil, requests still work normally. |
| 33 | + func testNilCustomHeadersDoesNotCrash() throws { |
| 34 | + Flagsmith.shared.customHeaders = nil |
| 35 | + Flagsmith.shared.apiKey = "mock-test-api-key" |
| 36 | + Flagsmith.shared.baseURL = URL(fileURLWithPath: "/dev/null") |
| 37 | + |
| 38 | + let requestFinished = expectation(description: "Request finished without crash") |
| 39 | + |
| 40 | + Flagsmith.shared.getFeatureFlags { _ in |
| 41 | + requestFinished.fulfill() |
| 42 | + } |
| 43 | + |
| 44 | + wait(for: [requestFinished], timeout: 1.0) |
| 45 | + } |
| 46 | + |
| 47 | + /// Verify the closure is invoked on every request (not cached). |
| 48 | + func testCustomHeadersClosureInvokedEveryRequest() throws { |
| 49 | + var invocationCount = 0 |
| 50 | + Flagsmith.shared.customHeaders = { |
| 51 | + invocationCount += 1 |
| 52 | + return [:] |
| 53 | + } |
| 54 | + Flagsmith.shared.apiKey = "mock-test-api-key" |
| 55 | + Flagsmith.shared.baseURL = URL(fileURLWithPath: "/dev/null") |
| 56 | + |
| 57 | + let firstRequest = expectation(description: "First request") |
| 58 | + let secondRequest = expectation(description: "Second request") |
| 59 | + |
| 60 | + Flagsmith.shared.getFeatureFlags { _ in firstRequest.fulfill() } |
| 61 | + Flagsmith.shared.getFeatureFlags { _ in secondRequest.fulfill() } |
| 62 | + |
| 63 | + wait(for: [firstRequest, secondRequest], timeout: 2.0) |
| 64 | + XCTAssertEqual(invocationCount, 2, "customHeaders should be invoked for every request") |
| 65 | + } |
| 66 | +} |
0 commit comments