Tests/OrgPresentationTests/RemoteImagesTests.swift
50 lines · 2380 bytes
1import Foundation
2import OrgCore
3@testable import OrgPresentation
4import Testing
5
6@MainActor
7struct RemoteImagesTests {
8 final class Counter: @unchecked Sendable {
9 var calls = 0
10 }
11
12 @Test func linksNeedTheSetting() {
13 let text = "[[https://example.com/a.png]]\n[[ftp://example.com/b.png]]\n[[file:c.png]]\n"
14 let tree = OrgParser.parse(text)
15 #expect(InlineImages.links(tree, in: 0..<75).map(\.image.path) == ["c.png"])
16 #expect(InlineImages.links(tree, in: 0..<75, remote: true).map(\.image.path) == ["https://example.com/a.png", "c.png"])
17 }
18
19 @Test func downloadsOnceAndCaches() async throws {
20 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-remote-\(UUID().uuidString)")
21 defer { try? FileManager.default.removeItem(at: folder) }
22 let counter = Counter()
23 let images = RemoteImages(directory: folder) { url in
24 counter.calls += 1
25 if url.lastPathComponent == "missing.png" { throw URLError(.badServerResponse) }
26 return Data("image".utf8)
27 }
28 let url = URL(string: "https://example.com/a.png")!
29 #expect(images.data(for: url, mode: .skip) {} == nil)
30 var arrived = false
31 #expect(images.data(for: url, mode: .cache) { arrived = true } == nil)
32 #expect(images.data(for: url, mode: .cache) {} == nil)
33 while !arrived { try await Task.sleep(for: .milliseconds(10)) }
34 #expect(images.data(for: url, mode: .cache) {} == Data("image".utf8))
35 #expect(counter.calls == 1)
36 // A new run reads the cached copy.
37 let again = RemoteImages(directory: folder) { _ in Issue.record("fetched again"); return Data() }
38 #expect(again.data(for: url, mode: .cache) {} == Data("image".utf8))
39 #expect(again.data(for: url, mode: .download) {} == Data("image".utf8))
40
41 let missing = URL(string: "https://example.com/missing.png")!
42 var done = false
43 #expect(images.data(for: missing, mode: .download) { done = true } == nil)
44 while !done { try await Task.sleep(for: .milliseconds(10)) }
45 #expect(images.data(for: missing, mode: .download) {} == nil)
46 #expect(counter.calls == 2)
47 #expect(images.version == 2)
48 #expect(images.data(for: URL(string: "file:///tmp/a.png")!, mode: .cache) {} == nil)
49 }
50}