Tests/OrgPresentationTests/RemoteImagesTests.swift
51 lines · 2478 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" as NSString
14 #expect(InlineImages.image(atLine: 0, in: text) == nil)
15 #expect(InlineImages.image(atLine: 0, in: text, remote: true)?.path == "https://example.com/a.png")
16 #expect(InlineImages.image(atLine: 30, in: text, remote: true) == nil)
17 #expect(InlineImages.image(atLine: 58, in: text, remote: true)?.path == "c.png")
18 }
19
20 @Test func downloadsOnceAndCaches() async throws {
21 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-remote-\(UUID().uuidString)")
22 defer { try? FileManager.default.removeItem(at: folder) }
23 let counter = Counter()
24 let images = RemoteImages(directory: folder) { url in
25 counter.calls += 1
26 if url.lastPathComponent == "missing.png" { throw URLError(.badServerResponse) }
27 return Data("image".utf8)
28 }
29 let url = URL(string: "https://example.com/a.png")!
30 #expect(images.data(for: url, mode: .skip) {} == nil)
31 var arrived = false
32 #expect(images.data(for: url, mode: .cache) { arrived = true } == nil)
33 #expect(images.data(for: url, mode: .cache) {} == nil)
34 while !arrived { try await Task.sleep(for: .milliseconds(10)) }
35 #expect(images.data(for: url, mode: .cache) {} == Data("image".utf8))
36 #expect(counter.calls == 1)
37 // A new run reads the cached copy.
38 let again = RemoteImages(directory: folder) { _ in Issue.record("fetched again"); return Data() }
39 #expect(again.data(for: url, mode: .cache) {} == Data("image".utf8))
40 #expect(again.data(for: url, mode: .download) {} == Data("image".utf8))
41
42 let missing = URL(string: "https://example.com/missing.png")!
43 var done = false
44 #expect(images.data(for: missing, mode: .download) { done = true } == nil)
45 while !done { try await Task.sleep(for: .milliseconds(10)) }
46 #expect(images.data(for: missing, mode: .download) {} == nil)
47 #expect(counter.calls == 2)
48 #expect(images.version == 2)
49 #expect(images.data(for: URL(string: "file:///tmp/a.png")!, mode: .cache) {} == nil)
50 }
51}