summaryrefslogtreecommitdiffhomepage
path: root/ios/MullvadVPNTests/MockFileCache.swift
blob: 0b07c788e281e9f780be2f3528e6e575e0e16875 (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
//
//  MockFileCache.swift
//  MullvadVPNTests
//
//  Created by pronebird on 13/06/2023.
//  Copyright © 2023 Mullvad VPN AB. All rights reserved.
//

import Foundation
import MullvadTypes

/// File cache implementation that simulates file state and uses internal lock to synchronize access to it.
final class MockFileCache<Content: Codable & Equatable>: FileCacheProtocol {
    private var state: State
    private let stateLock = NSLock()

    init(initialState: State = .fileNotFound) {
        state = initialState
    }

    /// Returns internal state.
    func getState() -> State {
        stateLock.lock()
        defer { stateLock.unlock() }

        return state
    }

    func read() throws -> Content {
        stateLock.lock()
        defer { stateLock.unlock() }

        switch state {
        case .fileNotFound:
            throw CocoaError(.fileReadNoSuchFile)
        case let .exists(content):
            return content
        }
    }

    func write(_ content: Content) throws {
        stateLock.lock()
        defer { stateLock.unlock() }

        state = .exists(content)
    }

    enum State: Equatable {
        /// File does not exist yet.
        case fileNotFound

        /// File exists with the given contents.
        case exists(Content)

        var isExists: Bool {
            if case .exists = self {
                return true
            } else {
                return false
            }
        }
    }
}