summaryrefslogtreecommitdiffhomepage
path: root/ios/OperationsTests/OperationObserverTests.swift
blob: 69b9bf81f98f7800eacd1a746c76ad6ba7504567 (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
//
//  OperationObserverTests.swift
//  MullvadVPNTests
//
//  Created by pronebird on 02/06/2022.
//  Copyright © 2025 Mullvad VPN AB. All rights reserved.
//

@testable import MullvadMockData
import Operations
import XCTest

class OperationObserverTests: XCTestCase {
    func testBlockObserver() throws {
        let expectDidAttach = expectation(description: "didAttach handler")
        let expectDidStart = expectation(description: "didStart handler")
        let expectDidCancel = expectation(description: "didCancel handler")
        expectDidCancel.isInverted = true
        let expectDidFinish = expectation(description: "didAttach handler")

        let operation = AsyncBlockOperation {}
        operation.addBlockObserver(OperationBlockObserver(
            didAttach: { _ in
                expectDidAttach.fulfill()
            }, didStart: { _ in
                expectDidStart.fulfill()
            }, didCancel: { _ in
                expectDidCancel.fulfill()
            }, didFinish: { _, _ in
                expectDidFinish.fulfill()
            }
        ))

        let operationQueue = AsyncOperationQueue()
        operationQueue.addOperation(operation)

        wait(for: [expectDidCancel], timeout: .UnitTest.invertedTimeout)
        wait(for: [expectDidAttach, expectDidStart, expectDidFinish], timeout: .UnitTest.timeout, enforceOrder: true)
    }

    func testBlockObserverWithCancelledOperation() {
        let expectDidAttach = expectation(description: "didAttach handler")
        let expectDidStart = expectation(description: "didStart handler")
        expectDidStart.isInverted = true
        let expectDidCancel = expectation(description: "didCancel handler")
        let expectDidFinish = expectation(description: "didAttach handler")

        let operation = AsyncBlockOperation {}
        operation.addBlockObserver(OperationBlockObserver(
            didAttach: { _ in
                expectDidAttach.fulfill()
            }, didStart: { _ in
                expectDidStart.fulfill()
            }, didCancel: { _ in
                expectDidCancel.fulfill()
            }, didFinish: { _, _ in
                expectDidFinish.fulfill()
            }
        ))
        operation.cancel()

        let operationQueue = AsyncOperationQueue()
        operationQueue.addOperation(operation)

        wait(for: [expectDidStart], timeout: .UnitTest.invertedTimeout)
        wait(for: [expectDidAttach, expectDidCancel, expectDidFinish], timeout: .UnitTest.timeout, enforceOrder: true)
    }
}