-
Notifications
You must be signed in to change notification settings - Fork 11
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Allow extracting recorded requests #29
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -29,59 +29,108 @@ final class MockBundle { | |
/// - Returns: The MockRequestResponse, if it can be loaded | ||
func loadResponse(for requestResponse: MockRequestResponse) -> Bool { | ||
guard let fileName = requestResponse.fileName(for: .request) else { return false } | ||
|
||
var targetURL: URL? | ||
var targetLoadingURL: URL? | ||
let request = requestResponse.request | ||
|
||
var loadedPath: String? | ||
var loadedResponse: MockResponse? | ||
if let response = checkRequestHandlers(for: request) { | ||
requestResponse.responseWrapper = response | ||
return true | ||
} else if | ||
let inputURL = loadingURL?.appendingPathComponent(fileName), | ||
FileManager.default.fileExists(atPath: inputURL.path) | ||
{ | ||
os_log("Loading request %@ from: %@", log: MockDuck.log, type: .debug, "\(request)", inputURL.path) | ||
targetURL = inputURL | ||
targetLoadingURL = loadingURL | ||
} else if | ||
let inputURL = recordingURL?.appendingPathComponent(fileName), | ||
FileManager.default.fileExists(atPath: inputURL.path) | ||
{ | ||
os_log("Loading request %@ from: %@", log: MockDuck.log, type: .debug, "\(request)", inputURL.path) | ||
targetURL = inputURL | ||
targetLoadingURL = recordingURL | ||
loadedResponse = response | ||
} else if let response = loadResponseFile(relativePath: fileName, baseURL: loadingURL) { | ||
loadedPath = loadingURL?.path ?? "" + fileName | ||
loadedResponse = response.responseWrapper | ||
} else if let response = loadResponseFile(relativePath: fileName, baseURL: recordingURL) { | ||
loadedPath = recordingURL?.path ?? "" + fileName | ||
loadedResponse = response.responseWrapper | ||
} else { | ||
os_log("Request %@ not found on disk. Expected file name: %@", log: MockDuck.log, type: .debug, "\(request)", fileName) | ||
} | ||
|
||
if | ||
let targetURL = targetURL, | ||
let targetLoadingURL = targetLoadingURL | ||
{ | ||
let decoder = JSONDecoder() | ||
|
||
do { | ||
let data = try Data(contentsOf: targetURL) | ||
|
||
let loaded = try decoder.decode(MockRequestResponse.self, from: data) | ||
requestResponse.responseWrapper = loaded.responseWrapper | ||
|
||
// Load the response data if the format is supported. | ||
// This should be the same filename with a different extension. | ||
if let dataFileName = requestResponse.fileName(for: .responseData) { | ||
let dataURL = targetLoadingURL.appendingPathComponent(dataFileName) | ||
requestResponse.responseData = try Data(contentsOf: dataURL) | ||
} | ||
|
||
return true | ||
} catch { | ||
os_log("Error decoding JSON: %@", log: MockDuck.log, type: .error, "\(error)") | ||
|
||
if let response = loadedResponse { | ||
requestResponse.responseWrapper = response | ||
if let path = loadedPath { | ||
os_log("Loading request %@ from: %@", | ||
log: MockDuck.log, | ||
type: .debug, | ||
"\(request)", | ||
path) | ||
} | ||
return true | ||
} | ||
|
||
return false | ||
} | ||
|
||
/// Takes a URL and attempts to parse the file at that location into a MockRequestResponse | ||
/// If the file doesn't exist, or isn't in the expected MockDuck format, nil is returned | ||
/// | ||
/// - Parameter targetURL: URL that should be loaded from file | ||
/// - Returns: MockRequestResponse if the request exists at that URL | ||
func loadResponseFile(relativePath: String, baseURL: URL?) -> MockRequestResponse? { | ||
guard let baseURL = baseURL else { return nil } | ||
let targetURL = baseURL.appendingPathComponent(relativePath) | ||
guard FileManager.default.fileExists(atPath: targetURL.path) else { return nil} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. A single
|
||
|
||
let decoder = JSONDecoder() | ||
|
||
do { | ||
let data = try Data(contentsOf: targetURL) | ||
|
||
let response = try decoder.decode(MockRequestResponse.self, from: data) | ||
|
||
// Load the response data if the format is supported. | ||
// This should be the same filename with a different extension. | ||
if let dataFileName = response.fileName(for: .responseData) { | ||
let dataURL = baseURL.appendingPathComponent(dataFileName) | ||
response.responseData = try? Data(contentsOf: dataURL) | ||
} | ||
|
||
return response | ||
} catch { | ||
os_log("Error decoding JSON: %@", log: MockDuck.log, type: .error, "\(error)") | ||
} | ||
return nil | ||
} | ||
|
||
/// Takes a passed in hostname and returns all the recorded mocks for that URL. | ||
/// If an empty string is passed in, all recordings will be returned. | ||
/// | ||
/// - Parameter hostname: String representing the hostname to load requests from. | ||
/// - Returns: An array of MockRequestResponse for each request under that domain | ||
func getResponses(for hostname: String) -> [MockRequestResponse] { | ||
guard let recordingURL = recordingURL else { return [] } | ||
|
||
let baseURL = recordingURL.resolvingSymlinksInPath() | ||
var responses = [MockRequestResponse]() | ||
let targetURL = baseURL.appendingPathComponent(hostname) | ||
|
||
let results = FileManager.default.enumerator( | ||
at: targetURL, | ||
includingPropertiesForKeys: [.isDirectoryKey], | ||
options: []) | ||
|
||
if let results = results { | ||
for case let item as URL in results { | ||
var isDir = ObjCBool(false) | ||
let itemURL = item.resolvingSymlinksInPath() | ||
|
||
/// Check if the item: | ||
/// 1) isn't a directory | ||
/// 2) doesn't end in '-response' (a sidecar file) | ||
/// If so, load it using loadResponseFile so any associated | ||
/// '-response' file is also loaded with the repsonse. | ||
if | ||
FileManager.default.fileExists(atPath: itemURL.path, isDirectory: &isDir), | ||
!isDir.boolValue, | ||
!itemURL.lastPathComponent.contains("-response"), | ||
let relativePath = itemURL.pathRelative(to: baseURL), | ||
let response = loadResponseFile(relativePath: relativePath, baseURL: recordingURL) | ||
{ | ||
responses.append(response) | ||
} | ||
} | ||
} | ||
|
||
return responses | ||
} | ||
|
||
/// If recording is enabled, this method saves the request to the filesystem. If the request | ||
/// body or the response data are of a certain type 'jpg/png/gif/json', the request is saved | ||
|
@@ -169,3 +218,24 @@ final class MockBundle { | |
} | ||
} | ||
} | ||
|
||
|
||
extension URL { | ||
func pathRelative(to url: URL) -> String? { | ||
guard | ||
host == url.host, | ||
scheme == url.scheme | ||
else { return nil } | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Minor nit: Whitespace |
||
|
||
let components = self.standardized.pathComponents | ||
let baseComponents = url.standardized.pathComponents | ||
|
||
if components.count < baseComponents.count { return nil } | ||
for (index, baseComponent) in baseComponents.enumerated() { | ||
let component = components[index] | ||
if component != baseComponent { return nil } | ||
} | ||
|
||
return components[baseComponents.count..<components.count].joined(separator: "/") | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -9,7 +9,7 @@ | |
import Foundation | ||
|
||
/// A basic container for holding a request, a response, and any associated data. | ||
final class MockRequestResponse: Codable { | ||
public final class MockRequestResponse: Codable, CustomDebugStringConvertible { | ||
|
||
enum MockFileTarget { | ||
case request | ||
|
@@ -19,7 +19,7 @@ final class MockRequestResponse: Codable { | |
|
||
// MARK: - Properties | ||
|
||
var request: URLRequest { | ||
public var request: URLRequest { | ||
get { | ||
return requestWrapper.request | ||
} | ||
|
@@ -28,11 +28,11 @@ final class MockRequestResponse: Codable { | |
} | ||
} | ||
|
||
var response: URLResponse? { | ||
public var response: URLResponse? { | ||
return responseWrapper?.response | ||
} | ||
|
||
var responseData: Data? { | ||
public var responseData: Data? { | ||
get { | ||
return responseWrapper?.responseData | ||
} | ||
|
@@ -107,6 +107,10 @@ final class MockRequestResponse: Codable { | |
hashData.append(body) | ||
} | ||
|
||
if let bodyData = normalizedRequest.httpBodyStreamData { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Will this break any existing recordings? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This will change the hash for the requests that have something in the .httpBodyStream and will break the recordings. We can tag and release a version for users that have some recordings already and then merge this and release a There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The better approach in my opinion is adding a delegate method that lets user compose the hash for each request based on their needs. We can keep the current hashing method as default to prevent broken recordings and we can expose a delegate so that people can compose the hash for each request based on their project needs. What do you think @scelis? If you agree with this approach we can merge this PR without the hashing change and I can open another PR to expose that delegate method. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Instead of bumping the version, what do you think about calculating multiple hashes for backwards compatibility? When loading, if the new/updated hash doesn't match anything on disk calculate the backwards-compatible hash and check for that file, too. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. My suggestion, as I explained in another comment, is keeping the hashing code as is, so don’t breaking the previous versions, and expose an optional delegate method for people to calculate hash based on their needs because I think each project has different requirements here. For one project the headers are not important for the other one the body of the request. Some project need to remove the headers or the body from the hash to get same response on a set of request. It completely depends on the project needs. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think that is a decent feature request, but that MockDuck should still provide basic hash-computation functionality that should work for the 95% use case. |
||
hashData.append(bodyData) | ||
} | ||
|
||
if !hashData.isEmpty { | ||
return String(CryptoUtils.md5(hashData).prefix(8)) | ||
} else { | ||
|
@@ -136,9 +140,32 @@ final class MockRequestResponse: Codable { | |
case responseWrapper = "response" | ||
} | ||
|
||
init(from decoder: Decoder) throws { | ||
public init(from decoder: Decoder) throws { | ||
let container = try decoder.container(keyedBy: CodingKeys.self) | ||
requestWrapper = try container.decode(MockRequest.self, forKey: .requestWrapper) | ||
responseWrapper = try container.decodeIfPresent(MockResponse.self, forKey: .responseWrapper) | ||
} | ||
|
||
// MARK: Debug | ||
|
||
public var debugDescription: String { | ||
var result = "\n" | ||
|
||
if let request = fileName(for: .request) { | ||
result.append("Request: \(request)\n") | ||
result.append("\t\(requestWrapper)\n") | ||
} | ||
if let requestBody = fileName(for: .requestBody) { | ||
result.append("Request Body: \(requestBody)\n") | ||
} | ||
if let responseData = fileName(for: .responseData) { | ||
result.append("Response Data: \(responseData)\n") | ||
|
||
if let response = responseWrapper { | ||
result.append("\t\(response)\n") | ||
} | ||
} | ||
|
||
return result | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looks like we could mark this
private