summaryrefslogtreecommitdiffhomepage
path: root/ios/OperationsTests/TransformOperationTests.swift
blob: c16bcd3be13571de35824018d7c26fd935c66f1a (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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
//
//  TransformOperationTests.swift
//  OperationsTests
//
//  Created by pronebird on 26/04/2023.
//  Copyright © 2023 Mullvad VPN AB. All rights reserved.
//

import MullvadTypes
import Operations
import XCTest

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

    func testBlockTransformOperation() {
        let finishExpectation = expectation(description: "Should finish")

        let transform = TransformOperation(input: Int.zero) { input, finish in
            finish(.success(input + 1))
        }

        transform.onFinish { op, error in
            XCTAssertEqual(op.result?.value, 1)

            finishExpectation.fulfill()
        }

        operationQueue.addOperation(transform)

        waitForExpectations(timeout: 1)
    }

    func testThrowingBlockTransformOperation() {
        let finishExpectation = expectation(description: "Should finish")

        let transform = TransformOperation(input: Int.zero) { value in
            throw URLError(.badURL)
        }

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

            finishExpectation.fulfill()
        }

        operationQueue.addOperation(transform)

        waitForExpectations(timeout: 1)
    }

    func testCancellableTaskBlockTransformOperation() {
        let finishExpectation = expectation(description: "Should finish")

        let transform = TransformOperation<Int, Int>(input: Int.zero) { _, finish -> Cancellable in
            return AnyCancellable {
                finish(.failure(URLError(.cancelled)))
            }
        }

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

        transform.onFinish { op, error in
            XCTAssertEqual(error as? URLError, URLError(.cancelled))

            finishExpectation.fulfill()
        }

        operationQueue.addOperation(transform)

        waitForExpectations(timeout: 1)
    }

    func testShouldFailWithUnsatisfiedRequirement() {
        let finishExpectation = expectation(description: "Should finish")

        let transform = TransformOperation<Int, Int> { input, finish in
            finish(.success(input))
        }

        transform.onFinish { _, error in
            XCTAssertEqual(error as? OperationError, .unsatisfiedRequirement)

            finishExpectation.fulfill()
        }

        operationQueue.addOperation(transform)

        waitForExpectations(timeout: 1)
    }
}