Skip to content

Commit

Permalink
Basic tests for PictureCache (#19)
Browse files Browse the repository at this point in the history
* update: move PictureCache to another file

* update: add couple of tests for PictureCache

* update: remove playground

* resolve: review threads
  • Loading branch information
devahmedshendy authored Oct 20, 2023
1 parent 06531d5 commit 85e0d9b
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 22 deletions.
23 changes: 23 additions & 0 deletions Sources/Picture/Public/PictureCache.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import SwiftUI

public class PictureCache {
private var cache: [URL: Image]
private var lock: NSLock

public init() {
cache = [:]
lock = NSLock()
}

public func `get`(url: URL) -> Image? {
lock.lock(); defer { lock.unlock() }

return cache[url]
}

public func `set`(value: Image?, for url: URL) {
lock.lock(); defer { lock.unlock() }

cache[url] = value
}
}
22 changes: 0 additions & 22 deletions Sources/Picture/Public/PictureSource.swift
Original file line number Diff line number Diff line change
@@ -1,27 +1,5 @@
import SwiftUI

public class PictureCache {
private var cache: [URL: Image]
private var lock: NSLock

public init() {
cache = [:]
lock = NSLock()
}

public func `get`(url: URL) -> Image? {
lock.lock(); defer { lock.unlock() }

return cache[url]
}

public func `set`(value: Image?, for url: URL) {
lock.lock(); defer { lock.unlock() }

cache[url] = value
}
}

public enum PictureSource {
public private(set) static var cache: PictureCache = PictureCache()

Expand Down
27 changes: 27 additions & 0 deletions Tests/PictureTests/PictureCacheTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import XCTest
import SwiftUI
@testable import Picture

final class PictureCacheTests: XCTestCase {
private let faviconURL: URL = .init(string: "https://openbytes.com/favicon.png")!

internal func testNotFoundImageForSpecifiedURL() {
let cache = PictureCache()

let image = cache.get(url: faviconURL)

XCTAssertNil(image)
}

internal func testFoundImageForSpecifiedURL() {
let cache = PictureCache()

let expectedImage = Image("house")

cache.set(value: expectedImage, for: faviconURL)

let actualImage = cache.get(url: faviconURL)

XCTAssertEqual(actualImage, expectedImage)
}
}

0 comments on commit 85e0d9b

Please sign in to comment.