|
| 1 | +// |
| 2 | +// Created by Marko Justinek on 5/8/2023. |
| 3 | +// Copyright © 2023 Marko Justinek. All rights reserved. |
| 4 | +// |
| 5 | +// Permission to use, copy, modify, and/or distribute this software for any |
| 6 | +// purpose with or without fee is hereby granted, provided that the above |
| 7 | +// copyright notice and this permission notice appear in all copies. |
| 8 | +// |
| 9 | +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES |
| 10 | +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF |
| 11 | +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY |
| 12 | +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES |
| 13 | +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN |
| 14 | +// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR |
| 15 | +// IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. |
| 16 | +// |
| 17 | + |
| 18 | +import Foundation |
| 19 | + |
| 20 | +#if canImport(_Concurrency) && compiler(>=5.7) |
| 21 | +@_implementationOnly import PactSwiftMockServer |
| 22 | + |
| 23 | +public extension MockService { |
| 24 | + |
| 25 | + /// Runs the Pact test against the code making the API request |
| 26 | + /// |
| 27 | + /// - Parameters: |
| 28 | + /// - file: The file to report the failing test in |
| 29 | + /// - line: The line on which to report the failing test |
| 30 | + /// - verify: An array of specific `Interaction`s to verify. If none provided, the latest defined interaction is used |
| 31 | + /// - timeout: Time before the test times out. Default is 10 seconds |
| 32 | + /// - testFunction: Your async code making the API request |
| 33 | + /// |
| 34 | + /// The `testFunction` closure is passed a `String` representing the url of the active Mock Server. |
| 35 | + /// |
| 36 | + /// ``` |
| 37 | + /// try await mockService.run { baseURL in |
| 38 | + /// // async code making the request with provided `baseURL` |
| 39 | + /// // assert response can be processed |
| 40 | + /// } |
| 41 | + /// ``` |
| 42 | + /// |
| 43 | + @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) |
| 44 | + func run(_ file: FileString? = #file, line: UInt? = #line, verify interactions: [Interaction]? = nil, timeout: TimeInterval? = nil, testFunction: @escaping @Sendable (_ baseURL: String) async throws -> Void) async throws { |
| 45 | + // Use the provided set or if not provided only the current interaction |
| 46 | + pact.interactions = interactions ?? [currentInteraction] |
| 47 | + |
| 48 | + if checkForInvalidInteractions(pact.interactions, file: file, line: line) { |
| 49 | + // Remove interactions with errors |
| 50 | + pact.interactions.removeAll { $0.encodingErrors.isEmpty == false } |
| 51 | + self.interactions.removeAll() |
| 52 | + } else { |
| 53 | + // Prepare a brand spanking new MockServer (Mock Provider) on its own port |
| 54 | + let mockServer = MockServer() |
| 55 | + |
| 56 | + // Set the expectations so we don't wait for this async magic indefinitely |
| 57 | + try await setupPactInteraction(timeout: timeout ?? Constants.kTimeout, file: file, line: line, mockServer: mockServer, testFunction: testFunction) |
| 58 | + |
| 59 | + // At the same time start listening to verification that Mock Server received the expected request |
| 60 | + try await verifyPactInteraction(timeout: timeout ?? Constants.kTimeout, file: file, line: line, mockServer: mockServer) |
| 61 | + } |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +// MARK: - Internal |
| 66 | + |
| 67 | +extension MockService { |
| 68 | + |
| 69 | + @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) |
| 70 | + func setupPactInteraction(timeout: TimeInterval, file: FileString?, line: UInt?, mockServer: MockServer, testFunction: @escaping @Sendable (String) async throws -> Void) async throws { |
| 71 | + Logger.log(message: "Setting up pact test", data: pact.data) |
| 72 | + do { |
| 73 | + // Set up a Mock Server with Pact data and on desired http protocol |
| 74 | + try await mockServer.setup(pact: pact.data!, protocol: transferProtocolScheme) |
| 75 | + |
| 76 | + // If Mock Server spun up, run the test function |
| 77 | + let task = Task(timeout: timeout) { |
| 78 | + try await testFunction(mockServer.baseUrl) |
| 79 | + } |
| 80 | + // await task completion (value is Void) |
| 81 | + try await task.value |
| 82 | + } catch { |
| 83 | + // Failed to spin up a Mock Server. This could be due to bad Pact data. Most likely to Pact data. |
| 84 | + failWith((error as? MockServerError)?.description ?? error.localizedDescription, file: file, line: line) |
| 85 | + throw error |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) |
| 90 | + func verifyPactInteraction(timeout: TimeInterval, file: FileString?, line: UInt?, mockServer: MockServer) async throws { |
| 91 | + do { |
| 92 | + let task = Task(timeout: timeout) { |
| 93 | + try await mockServer.verify() |
| 94 | + } |
| 95 | + // await task completion (value is discarded) |
| 96 | + _ = try await task.value |
| 97 | + |
| 98 | + // If the comsumer (in testFunction:) made the promised request to Mock Server, go and finalize the test. |
| 99 | + // Only finalize when running in simulator or macOS. Running on a physical iOS device makes little sense due to |
| 100 | + // writing a pact file to device's disk. `libpact_ffi` does the actual file writing it writes it onto the |
| 101 | + // disk of the device it is being run on. |
| 102 | + #if targetEnvironment(simulator) || os(macOS) |
| 103 | + let message = try await finalize(file: file, line: line) |
| 104 | + Logger.log(message: message, data: self.pact.data) |
| 105 | + #else |
| 106 | + print("[INFO]: Running on an iOS device. Writing Pact interaction into a contract skipped.") |
| 107 | + #endif |
| 108 | + } catch { |
| 109 | + failWith((error as? MockServerError)?.description ?? error.localizedDescription, file: file, line: line) |
| 110 | + throw error |
| 111 | + } |
| 112 | + } |
| 113 | + |
| 114 | + /// Writes a Pact contract file in JSON format |
| 115 | + /// |
| 116 | + /// By default Pact contracts are written to `/tmp/pacts` folder. |
| 117 | + /// Set `PACT_OUTPUT_DIR` to `$(PATH)/to/desired/dir/` in `Build` phase of your `Scheme` to change the location. |
| 118 | + /// |
| 119 | + @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) |
| 120 | + func finalize(file: FileString? = nil, line: UInt? = nil) async throws -> String { |
| 121 | + // Spin up a fresh Mock Server with a directory to write to |
| 122 | + let mockServer = MockServer(directory: pactsDirectory, merge: self.merge) |
| 123 | + |
| 124 | + // Gather all the interactions this MockService has received to set up and prepare Pact data with them all |
| 125 | + pact.interactions = interactions.filter { $0.encodingErrors.isEmpty } |
| 126 | + |
| 127 | + // Validate the Pact `Data` is hunky dory |
| 128 | + guard let pactData = pact.data else { |
| 129 | + throw MockServerError.nullPointer |
| 130 | + } |
| 131 | + |
| 132 | + // Ask Mock Server to do the actual Pact file writing to disk |
| 133 | + do { |
| 134 | + return try await mockServer.finalize(pact: pactData) |
| 135 | + } catch { |
| 136 | + failWith((error as? MockServerError)?.description ?? error.localizedDescription, file: file, line: line) |
| 137 | + throw error |
| 138 | + } |
| 139 | + } |
| 140 | +} |
| 141 | +#endif |
0 commit comments