|
| 1 | +// |
| 2 | +// APIErrorCacheFallbackCoreTests.swift |
| 3 | +// FlagsmithClientTests |
| 4 | +// |
| 5 | +// Core API error scenarios with cache fallback behavior |
| 6 | +// Customer requirement: "When fetching flags and we run into an error and have a valid cache we should return the cached flags" |
| 7 | +// |
| 8 | + |
| 9 | +@testable import FlagsmithClient |
| 10 | +import XCTest |
| 11 | + |
| 12 | +final class APIErrorCacheFallbackCoreTests: FlagsmithClientTestCase { |
| 13 | + var testCache: URLCache! |
| 14 | + |
| 15 | + override func setUp() { |
| 16 | + super.setUp() |
| 17 | + |
| 18 | + // Create isolated cache for testing |
| 19 | + testCache = URLCache(memoryCapacity: 8 * 1024 * 1024, diskCapacity: 64 * 1024 * 1024, directory: nil) |
| 20 | + |
| 21 | + // Reset Flagsmith to known state using TestConfig |
| 22 | + Flagsmith.shared.apiKey = TestConfig.hasRealApiKey ? TestConfig.apiKey : "mock-test-api-key" |
| 23 | + Flagsmith.shared.baseURL = TestConfig.baseURL |
| 24 | + Flagsmith.shared.enableRealtimeUpdates = false |
| 25 | + Flagsmith.shared.cacheConfig.useCache = true |
| 26 | + Flagsmith.shared.cacheConfig.skipAPI = false |
| 27 | + Flagsmith.shared.cacheConfig.cache = testCache |
| 28 | + Flagsmith.shared.cacheConfig.cacheTTL = 300 |
| 29 | + Flagsmith.shared.defaultFlags = [] |
| 30 | + } |
| 31 | + |
| 32 | + override func tearDown() { |
| 33 | + testCache.removeAllCachedResponses() |
| 34 | + Flagsmith.shared.cacheConfig.useCache = false |
| 35 | + Flagsmith.shared.cacheConfig.skipAPI = false |
| 36 | + Flagsmith.shared.apiKey = nil |
| 37 | + super.tearDown() |
| 38 | + } |
| 39 | + |
| 40 | + // MARK: - Test Helper Methods |
| 41 | + |
| 42 | + private func createMockCachedResponse(for request: URLRequest, with flags: [Flag]) throws -> CachedURLResponse { |
| 43 | + let jsonData = try JSONEncoder().encode(flags) |
| 44 | + let httpResponse = HTTPURLResponse( |
| 45 | + url: request.url!, |
| 46 | + statusCode: 200, |
| 47 | + httpVersion: "HTTP/1.1", |
| 48 | + headerFields: [ |
| 49 | + "Content-Type": "application/json", |
| 50 | + "Cache-Control": "max-age=300" |
| 51 | + ] |
| 52 | + )! |
| 53 | + return CachedURLResponse(response: httpResponse, data: jsonData) |
| 54 | + } |
| 55 | + |
| 56 | + // MARK: - Core API Error Cache Fallback Tests |
| 57 | + |
| 58 | + func testGetFeatureFlags_APIFailure_ReturnsCachedFlags() throws { |
| 59 | + // This test works with mock data, no real API key needed |
| 60 | + let expectation = expectation(description: "API failure with cache fallback") |
| 61 | + |
| 62 | + // Create mock flags for cache |
| 63 | + let cachedFlags = [ |
| 64 | + Flag(featureName: "cached_feature_1", value: .string("cached_value_1"), enabled: true, featureType: "FLAG"), |
| 65 | + Flag(featureName: "cached_feature_2", value: .string("cached_value_2"), enabled: false, featureType: "FLAG") |
| 66 | + ] |
| 67 | + |
| 68 | + // Pre-populate cache with successful response |
| 69 | + var mockRequest = URLRequest(url: TestConfig.baseURL.appendingPathComponent("flags/")) |
| 70 | + mockRequest.setValue(TestConfig.apiKey, forHTTPHeaderField: "X-Environment-Key") |
| 71 | + let cachedResponse = try createMockCachedResponse(for: mockRequest, with: cachedFlags) |
| 72 | + testCache.storeCachedResponse(cachedResponse, for: mockRequest) |
| 73 | + |
| 74 | + // Mock API failure by using invalid API key |
| 75 | + Flagsmith.shared.apiKey = "invalid-api-key" |
| 76 | + |
| 77 | + // Request should fail API call but return cached flags |
| 78 | + Flagsmith.shared.getFeatureFlags { result in |
| 79 | + switch result { |
| 80 | + case .success(let flags): |
| 81 | + // Should return cached flags |
| 82 | + XCTAssertEqual(flags.count, 2, "Should return cached flags") |
| 83 | + XCTAssertEqual(flags.first?.feature.name, "cached_feature_1", "Should return first cached flag") |
| 84 | + XCTAssertEqual(flags.last?.feature.name, "cached_feature_2", "Should return second cached flag") |
| 85 | + case .failure(let error): |
| 86 | + XCTFail("Should return cached flags instead of failing: \(error)") |
| 87 | + } |
| 88 | + expectation.fulfill() |
| 89 | + } |
| 90 | + |
| 91 | + wait(for: [expectation], timeout: 5.0) |
| 92 | + } |
| 93 | + |
| 94 | + func testGetFeatureFlags_APIFailure_NoCache_ReturnsDefaultFlags() throws { |
| 95 | + // This test works with mock data, no real API key needed |
| 96 | + let expectation = expectation(description: "API failure with no cache, default flags fallback") |
| 97 | + |
| 98 | + // Set up default flags |
| 99 | + let defaultFlags = [ |
| 100 | + Flag(featureName: "default_feature", value: .string("default_value"), enabled: true, featureType: "FLAG") |
| 101 | + ] |
| 102 | + Flagsmith.shared.defaultFlags = defaultFlags |
| 103 | + |
| 104 | + // Ensure no cache exists |
| 105 | + testCache.removeAllCachedResponses() |
| 106 | + |
| 107 | + // Mock API failure |
| 108 | + Flagsmith.shared.apiKey = "invalid-api-key" |
| 109 | + |
| 110 | + // Request should fail API call and return default flags |
| 111 | + Flagsmith.shared.getFeatureFlags { result in |
| 112 | + switch result { |
| 113 | + case .success(let flags): |
| 114 | + // Should return default flags |
| 115 | + XCTAssertEqual(flags.count, 1, "Should return default flags") |
| 116 | + XCTAssertEqual(flags.first?.feature.name, "default_feature", "Should return default flag") |
| 117 | + case .failure(let error): |
| 118 | + XCTFail("Should return default flags instead of failing: \(error)") |
| 119 | + } |
| 120 | + expectation.fulfill() |
| 121 | + } |
| 122 | + |
| 123 | + wait(for: [expectation], timeout: 5.0) |
| 124 | + } |
| 125 | + |
| 126 | + func testGetFeatureFlags_APIFailure_NoCacheNoDefaults_ReturnsError() throws { |
| 127 | + // This test works with mock data, no real API key needed |
| 128 | + let expectation = expectation(description: "API failure with no cache and no defaults") |
| 129 | + |
| 130 | + // Ensure no cache and no defaults |
| 131 | + testCache.removeAllCachedResponses() |
| 132 | + Flagsmith.shared.defaultFlags = [] |
| 133 | + |
| 134 | + // Mock API failure |
| 135 | + Flagsmith.shared.apiKey = "invalid-api-key" |
| 136 | + |
| 137 | + // Request should fail |
| 138 | + Flagsmith.shared.getFeatureFlags { result in |
| 139 | + switch result { |
| 140 | + case .success(_): |
| 141 | + XCTFail("Should fail when no cache and no defaults") |
| 142 | + case .failure(let error): |
| 143 | + // Should return the original API error |
| 144 | + XCTAssertTrue(error is FlagsmithError, "Should return FlagsmithError") |
| 145 | + } |
| 146 | + expectation.fulfill() |
| 147 | + } |
| 148 | + |
| 149 | + wait(for: [expectation], timeout: 5.0) |
| 150 | + } |
| 151 | +} |
0 commit comments