Tests/OrgEditorAppKitTests/PasteMediaTests.swift
64 lines · 2429 bytes
5 symbols in this file
1import AppKit
2import OrgDocument
3import Testing
4@testable import OrgEditorAppKit
5
6@MainActor
7struct PasteMediaTests {
8 static func pasteboard() -> NSPasteboard {
9 let pasteboard = NSPasteboard(name: NSPasteboard.Name("orgstar-test-\(UUID().uuidString)"))
10 pasteboard.clearContents()
11 return pasteboard
12 }
13
14 static var tiff: Data {
15 let image = NSImage(size: NSSize(width: 2, height: 2))
16 image.lockFocus()
17 NSColor.red.setFill()
18 NSRect(x: 0, y: 0, width: 2, height: 2).fill()
19 image.unlockFocus()
20 return image.tiffRepresentation!
21 }
22
23 @Test func imagesWithoutTextArePastedAsImages() {
24 let png = Self.pasteboard()
25 png.setData(Data("PNG".utf8), forType: .png)
26 #expect(OrgTextView.image(on: png)?.ext == "png")
27 #expect(OrgTextView.image(on: png)?.data == Data("PNG".utf8))
28
29 let tiff = Self.pasteboard()
30 tiff.setData(Self.tiff, forType: .tiff)
31 let converted = OrgTextView.image(on: tiff)
32 #expect(converted?.ext == "png")
33 #expect((converted.flatMap { NSBitmapImageRep(data: $0.data) }?.pixelsWide ?? 0) >= 2)
34
35 let text = Self.pasteboard()
36 text.setData(Data("PNG".utf8), forType: .png)
37 text.setString("caption", forType: .string)
38 #expect(OrgTextView.image(on: text) == nil)
39 }
40
41 @Test func filesAreFiles() {
42 let pasteboard = Self.pasteboard()
43 let url = URL(fileURLWithPath: "/tmp/a.png")
44 pasteboard.writeObjects([url as NSURL])
45 #expect(OrgTextView.files(on: pasteboard) == [url])
46 #expect(OrgTextView.files(on: Self.pasteboard()) == nil)
47 }
48
49 @Test func theEditorTakesMediaOnlyInOrgWithAHandler() {
50 let harness = Harness("* a\n")
51 let view = harness.editor.textView as! OrgTextView
52 let pasteboard = Self.pasteboard()
53 pasteboard.setData(Data("PNG".utf8), forType: .png)
54 #expect(!view.takeMedia(from: pasteboard))
55 var got: (Data, String)?
56 harness.editor.onImage = { got = ($0, $1) }
57 #expect(view.takeMedia(from: pasteboard))
58 #expect(got?.1 == "png")
59
60 let plain = Harness(DocumentState(bytes: Array("x\n".utf8)), mode: .plain(language: nil))
61 plain.editor.onImage = { _, _ in Issue.record("a plain buffer took an image") }
62 #expect(!(plain.editor.textView as! OrgTextView).takeMedia(from: pasteboard))
63 }
64}