Skip to content

Commit

Permalink
Make ImageDownloader mockable (#161)
Browse files Browse the repository at this point in the history
Summary
In order to write downloading tests without needing access to the internet, it is necessary to be able to mock an ImageDownloader.

Implementation
This PR makes a protocol `ImageDownloaderType` that can then mock an ImageDownloader. This requires making the Response struct to have a public init as well.
  • Loading branch information
plflanagan authored Jun 29, 2021
1 parent c940f57 commit 805e7f4
Showing 1 changed file with 21 additions and 1 deletion.
22 changes: 21 additions & 1 deletion Sources/Conduit/Networking/Images/ImageDownloader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,13 @@ public enum ImageDownloaderError: Error {
case invalidRequest
}

public protocol ImageDownloaderType {
func downloadImage(for request: URLRequest, completion: @escaping (ImageDownloader.Response) -> Void) -> SessionTaskProxyType?
}

/// Utilizes Conduit to download and safely cache/retrieve
/// images across multiple threads
public final class ImageDownloader {
public final class ImageDownloader: ImageDownloaderType {

/// Represents a network or cached image response
public struct Response {
Expand All @@ -37,6 +41,22 @@ public final class ImageDownloader {
public let urlResponse: HTTPURLResponse?
/// Signifies if the image was retrieved directly from the cache
public let isFromCache: Bool

#if canImport(AppKit)
public init(image: NSImage?, error: Error?, urlResponse: HTTPURLResponse?, isFromCache: Bool) {
self.image = image
self.error = error
self.urlResponse = urlResponse
self.isFromCache = isFromCache
}
#elseif os(iOS) || os(tvOS) || os(watchOS)
public init(image: UIImage?, error: Error?, urlResponse: HTTPURLResponse?, isFromCache: Bool) {
self.image = image
self.error = error
self.urlResponse = urlResponse
self.isFromCache = isFromCache
}
#endif
}

/// A closure that fires upon image fetch success/failure
Expand Down

0 comments on commit 805e7f4

Please sign in to comment.