summaryrefslogtreecommitdiffhomepage
path: root/ios/OperationsTests/OperationInputInjectionTests.swift
blob: 828afd2643d45d6ef036c7550d1bdb21a1d5217c (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
//
//  OperationInputInjectionTests.swift
//  MullvadVPNTests
//
//  Created by pronebird on 09/06/2022.
//  Copyright © 2022 Mullvad VPN AB. All rights reserved.
//

import Operations
import XCTest

class OperationInputInjectionTests: XCTestCase {
    func testInject() throws {
        let provider = ResultBlockOperation<Int, Error> {
            return 1
        }

        let consumer = TransformOperation<Int, Int, Error> { input in
            return input + 1
        }

        consumer.inject(from: provider)

        let operationQueue = AsyncOperationQueue()

        operationQueue.addOperations([provider, consumer], waitUntilFinished: true)

        XCTAssertEqual(consumer.output, 2)
    }

    func testInjectVia() throws {
        let provider = ResultBlockOperation<Int, Error> {
            return 1
        }

        let consumer = TransformOperation<String, Int, Error> { input in
            return Int(input)!
        }

        consumer.inject(from: provider) { output in
            return "\(output)"
        }

        let operationQueue = AsyncOperationQueue()

        operationQueue.addOperations([provider, consumer], waitUntilFinished: true)

        XCTAssertEqual(consumer.output, 1)
    }

    func testInjectMany() throws {
        struct Context: OperationInputContext {
            var a: Int?
            var b: Int?

            func reduce() -> Int? {
                guard let a = a, let b = b else { return nil }

                return a + b
            }
        }

        let operationQueue = AsyncOperationQueue()

        let providerA = ResultBlockOperation<Int, Error> {
            return 1
        }

        let providerB = ResultBlockOperation<Int, Error> {
            return 2
        }

        let consumer = TransformOperation<Int, String, Error> { input in
            return "\(input)"
        }

        consumer.injectMany(context: Context())
            .inject(from: providerA, assignOutputTo: \.a)
            .inject(from: providerB, assignOutputTo: \.b)
            .reduce()

        operationQueue.addOperations(
            [providerA, providerB, consumer],
            waitUntilFinished: true
        )

        XCTAssertEqual(consumer.output, "3")
    }
}