summaryrefslogtreecommitdiffhomepage
path: root/ios/OperationsTests/AsyncResultBlockOperationTests.swift
blob: d6361fe7065f7af71407d01e26367ef353ef8a0b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
//
//  AsyncResultBlockOperationTests.swift
//  OperationsTests
//
//  Created by pronebird on 26/04/2023.
//  Copyright © 2025 Mullvad VPN AB. All rights reserved.
//

import MullvadTypes
import Operations
import XCTest

@testable import MullvadMockData

final class AsyncResultBlockOperationTests: XCTestCase {
    let operationQueue = AsyncOperationQueue()

    func testBlockOperation() async {
        let expectation = expectation(description: "Should finish")

        let operation = ResultBlockOperation<Bool> { finish in
            finish(.success(true))
        }

        operation.onFinish { op, _ in
            XCTAssertEqual(op.result?.value, true)
            expectation.fulfill()
        }

        operationQueue.addOperation(operation)

        await fulfillment(of: [expectation], timeout: .UnitTest.timeout)
    }

    func testThrowingBlockOperation() async {
        let expectation = expectation(description: "Should finish")

        let operation = ResultBlockOperation {
            throw URLError(.badURL)
        }

        operation.onFinish { op, error in
            XCTAssertEqual(op.result?.error as? URLError, URLError(.badURL))
            XCTAssertEqual(error as? URLError, URLError(.badURL))

            expectation.fulfill()
        }

        operationQueue.addOperation(operation)

        await fulfillment(of: [expectation], timeout: .UnitTest.timeout)
    }

    func testCancellableTaskOperation() async {
        let expectation = expectation(description: "Should finish")

        let operation = ResultBlockOperation<Bool> { finish -> Cancellable in
            AnyCancellable {
                finish(.failure(URLError(.cancelled)))
            }
        }

        operation.onStart { op in
            op.cancel()
        }

        operation.onFinish { op, error in
            XCTAssertEqual(op.result?.error as? URLError, URLError(.cancelled))
            XCTAssertEqual(error as? URLError, URLError(.cancelled))
            expectation.fulfill()
        }

        operationQueue.addOperation(operation)

        await fulfillment(of: [expectation], timeout: .UnitTest.timeout)
    }
}