From 7d4f41fc81d054c6c758bdaa206cfbe5e694ae2d Mon Sep 17 00:00:00 2001 From: Fabrizio Demaria Date: Tue, 10 Dec 2024 08:46:16 +0100 Subject: [PATCH] test: putContextAndWait and awaitReconciliation --- Tests/ConfidenceTests/ConfidenceTest.swift | 62 ++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/Tests/ConfidenceTests/ConfidenceTest.swift b/Tests/ConfidenceTests/ConfidenceTest.swift index 0d56378e..f3fa2c82 100644 --- a/Tests/ConfidenceTests/ConfidenceTest.swift +++ b/Tests/ConfidenceTests/ConfidenceTest.swift @@ -548,6 +548,68 @@ class ConfidenceTest: XCTestCase { XCTAssertEqual(flagApplier.applyCallCount, 1) } + func testAwaitReconciliationFailingTaskAwait() async throws { + class FakeClient: XCTestCase, ConfidenceResolveClient { + var resolveStats: Int = 0 + var resolvedValues: [ResolvedValue] = [] + + func resolve(ctx: ConfidenceStruct) async throws -> ResolvesResult { + self.resolveStats += 1 + if resolveStats == 1 { + // Delay to ensure the second putContext cancels this Task + try await Task.sleep(nanoseconds: 2000000) + XCTFail("This line shouldn't be reached as task is expected to be cancelled") + return .init(resolvedValues: [], resolveToken: "token") + } else { + if ctx["hello"] == .init(string: "world") { + return .init(resolvedValues: resolvedValues, resolveToken: "token") + } else { + return .init(resolvedValues: [], resolveToken: "token") + } + } + } + } + + let client = FakeClient() + client.resolvedValues = [ + ResolvedValue( + variant: "control", + value: .init(structure: ["size": .init(integer: 3)]), + flag: "flag", + resolveReason: .match) + ] + + let confidence = Confidence.Builder(clientSecret: "test") + .withContext(initialContext: ["targeting_key": .init(string: "user2")]) + .withFlagResolverClient(flagResolver: client) + .withFlagApplier(flagApplier: flagApplier) + .withStorage(storage: storage) + .build() + + Task { + await confidence.putContextAndWait(context: ["hello": .init(string: "not-world")]) + } + try await Task.sleep(nanoseconds: 1000000) + Task { + await confidence.putContextAndWait(context: ["hello": .init(string: "world")]) + } + try await Task.sleep(nanoseconds: 1000000) + await confidence.awaitReconciliation() + let evaluation = confidence.getEvaluation( + key: "flag.size", + defaultValue: 0 + ) + + XCTAssertEqual(client.resolveStats, 2) + XCTAssertEqual(evaluation.value, 3) + XCTAssertNil(evaluation.errorCode) + XCTAssertNil(evaluation.errorMessage) + XCTAssertEqual(evaluation.reason, .match) + XCTAssertEqual(evaluation.variant, "control") + await fulfillment(of: [flagApplier.applyExpectation], timeout: 1) + XCTAssertEqual(flagApplier.applyCallCount, 1) + } + func testResolveBooleanFlag() async throws { class FakeClient: ConfidenceResolveClient { var resolveStats: Int = 0