Publish VCC Plus OSS source distribution for 3.6.2 build 60
This commit is contained in:
commit
c652a5276d
1192 files changed
+272368
No files matched your search
@@ -0,0 +1,181 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import XCTest
|
||||
import AppKit
|
||||
import ImageIO
|
||||
import UniformTypeIdentifiers
|
||||
import CryptoKit
|
||||
|
||||
final class SoftwareLibraryArtworkTests: XCTestCase {
|
||||
private func asset(url: String = "https://vccplus.brianholman.com/dl/software/CoCoLibrary/Artwork/Thumbnails/Manuals/Example.png", sha: String? = nil, size: Int64? = nil, kind: String = "replacement-label") -> SoftwareLibraryAsset {
|
||||
var value = SoftwareLibraryAsset(id: "art", name: "Example", kind: kind,
|
||||
sourceURL: URL(string: "https://colorcomputerarchive.com/repo/Documents/Manuals/Games/Example.pdf")!, sha256: nil,
|
||||
byteSize: nil, credit: "Example Artist — Color Computer Archive", matchStatus: "candidate", matchReason: "Title match")
|
||||
value.thumbnailURL = URL(string: url)
|
||||
value.thumbnailSHA256 = sha ?? SHA256.hash(data: LibraryArtworkFixture.payload).map { String(format: "%02x", $0) }.joined()
|
||||
value.thumbnailByteSize = size ?? Int64(LibraryArtworkFixture.payload.count)
|
||||
return value
|
||||
}
|
||||
private func png(width: Int = 1280, height: Int = 800) throws -> Data {
|
||||
let context = try XCTUnwrap(CGContext(data: nil, width: width, height: height, bitsPerComponent: 8,
|
||||
bytesPerRow: width * 4, space: CGColorSpaceCreateDeviceRGB(),
|
||||
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue))
|
||||
context.setFillColor(NSColor.systemGreen.cgColor)
|
||||
context.fill(CGRect(x: 0, y: 0, width: width, height: height))
|
||||
let data = NSMutableData()
|
||||
let destination = try XCTUnwrap(CGImageDestinationCreateWithData(data, UTType.png.identifier as CFString, 1, nil))
|
||||
CGImageDestinationAddImage(destination, try XCTUnwrap(context.makeImage()), nil)
|
||||
XCTAssertTrue(CGImageDestinationFinalize(destination))
|
||||
return data as Data
|
||||
}
|
||||
func testOnlyHostedHTTPSPNGThumbnailsAreAccepted() {
|
||||
XCTAssertTrue(SoftwareLibraryArtworkCache.accepts(asset().thumbnailURL!))
|
||||
for url in ["http://colorcomputerarchive.com/repo/Media/a.png", "https://colorcomputerarchive.com.evil.test/repo/a.png",
|
||||
"https://evil.test/repo/a.png", "https://colorcomputerarchive.com/repo/a.pdf",
|
||||
"https://colorcomputerarchive.com/repo/a.zip", "https://colorcomputerarchive.com/repo/a.png?redirect=evil",
|
||||
"https://user:[email protected]/repo/a.png", "file:///tmp/a.png"] {
|
||||
XCTAssertFalse(SoftwareLibraryArtworkCache.accepts(URL(string: url)!), url)
|
||||
}
|
||||
}
|
||||
func testThumbnailIsBoundedAndPreservesAspectRatio() throws {
|
||||
let input = try png()
|
||||
let hash = SHA256.hash(data: input).map { String(format: "%02x", $0) }.joined()
|
||||
let output = try SoftwareLibraryArtworkCache.downsample(input, expectedSHA256: hash)
|
||||
let image = try XCTUnwrap(SoftwareLibraryArtworkCache.image(from: output))
|
||||
XCTAssertEqual(image.width, 640)
|
||||
XCTAssertEqual(image.height, 400)
|
||||
XCTAssertLessThan(output.count, SoftwareLibraryArtworkCache.maximumThumbnailBytes)
|
||||
XCTAssertNil(SoftwareLibraryArtworkCache.image(from: input), "Full-size originals cannot masquerade as cached thumbnails")
|
||||
}
|
||||
func testInvalidChangedOrOversizedImagesAreRejected() throws {
|
||||
XCTAssertThrowsError(try SoftwareLibraryArtworkCache.downsample(Data("not an image".utf8), expectedSHA256: nil))
|
||||
XCTAssertThrowsError(try SoftwareLibraryArtworkCache.downsample(png(), expectedSHA256: String(repeating: "0", count: 64)))
|
||||
XCTAssertThrowsError(try SoftwareLibraryArtworkCache.downsample(Data(count: SoftwareLibraryArtworkCache.maximumSourceBytes + 1), expectedSHA256: nil))
|
||||
}
|
||||
func testCacheIdentityIncludesFingerprintAndUsesSafeFilename() {
|
||||
let a = SoftwareLibraryArtworkCache.cacheKey(for: asset())
|
||||
let b = SoftwareLibraryArtworkCache.cacheKey(for: asset(sha: String(repeating: "b", count: 64)))
|
||||
XCTAssertEqual(a.count, 64)
|
||||
XCTAssertTrue(a.allSatisfy { $0.isHexDigit })
|
||||
XCTAssertNotEqual(a, b)
|
||||
}
|
||||
func testValidCachedThumbnailWorksWithoutNetwork() async throws {
|
||||
let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
defer { try? FileManager.default.removeItem(at: directory) }
|
||||
let expected = LibraryArtworkFixture.payload
|
||||
let artwork = asset()
|
||||
try expected.write(to: directory.appendingPathComponent(SoftwareLibraryArtworkCache.cacheKey(for: artwork) + ".png"))
|
||||
let configuration = URLSessionConfiguration.ephemeral
|
||||
configuration.protocolClasses = [LibraryArtworkNoNetwork.self]
|
||||
let cache = SoftwareLibraryArtworkCache(session: URLSession(configuration: configuration))
|
||||
let found = try await cache.thumbnail(for: artwork, directory: directory)
|
||||
XCTAssertEqual(found, expected)
|
||||
}
|
||||
func testManualCoverAndZIPDerivedScreenshotUseHostedPNG() async throws {
|
||||
for kind in ["manual", "screenshot"] {
|
||||
let item = asset(kind: kind)
|
||||
XCTAssertTrue(SoftwareLibraryArtworkCache.canDisplay(item))
|
||||
XCTAssertFalse(SoftwareLibraryArtworkCache.accepts(item.sourceURL))
|
||||
}
|
||||
}
|
||||
func testCorruptCachedThumbnailIsReplacedByVerifiedDownload() async throws {
|
||||
let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
defer { try? FileManager.default.removeItem(at: directory) }
|
||||
let item = asset()
|
||||
let path = directory.appendingPathComponent(SoftwareLibraryArtworkCache.cacheKey(for: item) + ".png")
|
||||
try png(width: 16, height: 12).write(to: path)
|
||||
let config = URLSessionConfiguration.ephemeral; config.protocolClasses = [LibraryArtworkFixture.self]
|
||||
let data = try await SoftwareLibraryArtworkCache(session: URLSession(configuration: config)).thumbnail(for: item, directory: directory)
|
||||
XCTAssertEqual(data, LibraryArtworkFixture.payload)
|
||||
XCTAssertEqual(try Data(contentsOf: path), data)
|
||||
}
|
||||
func testCoverEligibilityRejectsUndisplayableAttachments() {
|
||||
XCTAssertTrue(SoftwareLibraryArtworkCache.canDisplay(asset()))
|
||||
XCTAssertTrue(SoftwareLibraryArtworkCache.canDisplay(asset(kind: "manual")))
|
||||
var missing = asset(); missing.thumbnailURL = nil
|
||||
XCTAssertFalse(SoftwareLibraryArtworkCache.canDisplay(missing))
|
||||
XCTAssertFalse(SoftwareLibraryArtworkCache.canDisplay(asset(url: "https://colorcomputerarchive.com/repo/Media/unbundled.zip")))
|
||||
XCTAssertFalse(SoftwareLibraryArtworkCache.canDisplay(asset(url: "https://colorcomputerarchive.com/repo/Media/Example.pdf")))
|
||||
}
|
||||
func testUnsupportedMediaAndKnownOversizeFailBeforeNetwork() async throws {
|
||||
let configuration = URLSessionConfiguration.ephemeral
|
||||
configuration.protocolClasses = [LibraryArtworkNoNetwork.self]
|
||||
let cache = SoftwareLibraryArtworkCache(session: URLSession(configuration: configuration))
|
||||
let directory = FileManager.default.temporaryDirectory
|
||||
for item in [asset(url: "https://colorcomputerarchive.com/repo/a.png"), asset(size: Int64(SoftwareLibraryArtworkCache.maximumSourceBytes + 1)), asset(url: "https://example.test/a.png")] {
|
||||
do {
|
||||
_ = try await cache.thumbnail(for: item, directory: directory)
|
||||
XCTFail("Unsupported art must be rejected")
|
||||
} catch is SoftwareLibraryArtworkCache.Failure { } catch { XCTFail("Unexpected network error: \(error)") }
|
||||
}
|
||||
}
|
||||
func testStreamedArtworkIsVerifiedDownsampledAndCached() async throws {
|
||||
let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||
defer { try? FileManager.default.removeItem(at: directory) }
|
||||
let configuration = URLSessionConfiguration.ephemeral
|
||||
configuration.protocolClasses = [LibraryArtworkFixture.self]
|
||||
let cache = SoftwareLibraryArtworkCache(session: URLSession(configuration: configuration))
|
||||
let hash = SHA256.hash(data: LibraryArtworkFixture.payload).map { String(format: "%02x", $0) }.joined()
|
||||
let artwork = asset(sha: hash)
|
||||
let result = try await cache.thumbnail(for: artwork, directory: directory)
|
||||
XCTAssertNotNil(SoftwareLibraryArtworkCache.image(from: result))
|
||||
let disk = directory.appendingPathComponent(SoftwareLibraryArtworkCache.cacheKey(for: artwork) + ".png")
|
||||
XCTAssertEqual(try Data(contentsOf: disk), result)
|
||||
XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath: directory.path).count, 1)
|
||||
}
|
||||
func testNetworkFailureLeavesNoPartialCache() async throws {
|
||||
let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||
let configuration = URLSessionConfiguration.ephemeral
|
||||
configuration.protocolClasses = [LibraryArtworkNoNetwork.self]
|
||||
let cache = SoftwareLibraryArtworkCache(session: URLSession(configuration: configuration))
|
||||
do { _ = try await cache.thumbnail(for: asset(), directory: directory); XCTFail("Expected network error") }
|
||||
catch { XCTAssertFalse(FileManager.default.fileExists(atPath: directory.path)) }
|
||||
}
|
||||
func testCancelledRequestDoesNotStartNetworkOrCreateCache() async throws {
|
||||
let configuration = URLSessionConfiguration.ephemeral
|
||||
configuration.protocolClasses = [LibraryArtworkNoNetwork.self]
|
||||
let cache = SoftwareLibraryArtworkCache(session: URLSession(configuration: configuration))
|
||||
let artwork = asset()
|
||||
let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||
let task = Task { () throws -> Data in
|
||||
withUnsafeCurrentTask { $0?.cancel() }
|
||||
return try await cache.thumbnail(for: artwork, directory: directory)
|
||||
}
|
||||
do { _ = try await task.value; XCTFail("Expected cancellation") }
|
||||
catch is CancellationError { }
|
||||
catch { XCTFail("Unexpected error: \(error)") }
|
||||
XCTAssertFalse(FileManager.default.fileExists(atPath: directory.path))
|
||||
}
|
||||
}
|
||||
|
||||
private final class LibraryArtworkNoNetwork: URLProtocol {
|
||||
override class func canInit(with request: URLRequest) -> Bool { true }
|
||||
override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
|
||||
override func startLoading() { client?.urlProtocol(self, didFailWithError: URLError(.notConnectedToInternet)) }
|
||||
override func stopLoading() { }
|
||||
}
|
||||
|
||||
private final class LibraryArtworkFixture: URLProtocol {
|
||||
static let payload: Data = {
|
||||
let context = CGContext(data: nil, width: 16, height: 12, bitsPerComponent: 8, bytesPerRow: 64,
|
||||
space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!
|
||||
context.setFillColor(CGColor(red: 0.2, green: 0.6, blue: 0.2, alpha: 1))
|
||||
context.fill(CGRect(x: 0, y: 0, width: 16, height: 12))
|
||||
let data = NSMutableData()
|
||||
let destination = CGImageDestinationCreateWithData(data, UTType.png.identifier as CFString, 1, nil)!
|
||||
CGImageDestinationAddImage(destination, context.makeImage()!, nil)
|
||||
precondition(CGImageDestinationFinalize(destination))
|
||||
return data as Data
|
||||
}()
|
||||
override class func canInit(with request: URLRequest) -> Bool { true }
|
||||
override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
|
||||
override func startLoading() {
|
||||
let response = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: "HTTP/1.1",
|
||||
headerFields: ["Content-Type": "image/png", "Content-Length": String(Self.payload.count)])!
|
||||
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
|
||||
client?.urlProtocol(self, didLoad: Self.payload)
|
||||
client?.urlProtocolDidFinishLoading(self)
|
||||
}
|
||||
override func stopLoading() { }
|
||||
}
|
||||
Reference in new issue
Block a user