summaryrefslogtreecommitdiffhomepage
path: root/ios/MullvadVPNUITests/Networking/TestRouterAPIClient.swift
blob: cfa75f6a3ec8db3cb1c6165a722d3c78116ee749 (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
//
//  TestRouterAPIClient.swift
//  MullvadVPN
//
//  Created by Niklas Berglund on 2024-12-18.
//  Copyright © 2025 Mullvad VPN AB. All rights reserved.
//

import XCTest

class TestRouterAPIClient {
    static let baseURL = URL(string: Bundle(for: FirewallClient.self).infoDictionary?["FirewallApiBaseURL"] as! String)!

    /// Gets the IP address of the device under test
    public func getDeviceIPAddress() throws -> String {
        let deviceIPURL = TestRouterAPIClient.baseURL.appendingPathComponent("own-ip")
        let request = URLRequest(url: deviceIPURL)
        let completionHandlerInvokedExpectation = XCTestExpectation(
            description: "Completion handler for the request is invoked"
        )
        nonisolated(unsafe) var deviceIPAddress = ""
        nonisolated(unsafe) var requestError: Error?

        let dataTask = URLSession.shared.dataTask(with: request) { data, _, _ in
            defer { completionHandlerInvokedExpectation.fulfill() }
            guard let data else {
                requestError = NetworkingError.internalError(reason: "Could not get device IP")
                return
            }

            deviceIPAddress = String(data: data, encoding: .utf8)!
        }

        dataTask.resume()

        let waitResult = XCTWaiter.wait(for: [completionHandlerInvokedExpectation], timeout: 30)
        if waitResult != .completed {
            XCTFail("Failed to get device IP address - timeout")
        }

        if let requestError {
            throw requestError
        }

        return deviceIPAddress
    }
}