summaryrefslogtreecommitdiff
path: root/tests/target_policy_test.lua
blob: 4ce9b982881ed1a0ec430d026b28dbca2921ba33 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
local entry_path = "yazi-enter.yazi/main.lua"

local file = assert(io.open(entry_path, "rb"))
local source = assert(file:read("*a"))
file:close()

local instrumented_source, replacement_count = source:gsub(
	"\nlocal commit = ya%.sync",
	"\ncapture_target_policy(decide_target)\n\nlocal commit = ya.sync",
	1
)
assert(replacement_count == 1, "target policy capture point must occur once")

local target_policy
local sync_calls = 0
local environment = {
	error = error,
	pairs = pairs,
	type = type,
	capture_target_policy = function(policy)
		assert(type(policy) == "function", "target policy must be a function")
		target_policy = policy
	end,
	ya = {
		sync = function(callback)
			sync_calls = sync_calls + 1
			return callback
		end,
		emit = function()
			error("target policy called ya.emit", 0)
		end,
		exec = function()
			error("target policy called ya.exec", 0)
		end,
		input = function()
			error("target policy called ya.input", 0)
		end,
	},
}

local chunk = assert(load(instrumented_source, "@" .. entry_path, "t", environment))
chunk()

assert(type(target_policy) == "function", "target policy was not captured")
assert(sync_calls == 1, "plugin load must create only the commit shell")

local function pack_values(...)
	return { n = select("#", ...), ... }
end

local function assert_equal(actual, expected, label)
	assert(actual == expected, ("%s: expected %s, got %s"):format(label, tostring(expected), tostring(actual)))
end

local decisions = {
	{ label = "directory mode with directory", mode = "directory", is_dir = true, expected = "enter" },
	{ label = "directory mode with file", mode = "directory", is_dir = false, expected = "none" },
	{ label = "file mode with directory", mode = "file", is_dir = true, expected = "none" },
	{ label = "file mode with file", mode = "file", is_dir = false, expected = "open-hovered" },
	{ label = "either mode with directory", mode = "either", is_dir = true, expected = "enter" },
	{ label = "either mode with file", mode = "either", is_dir = false, expected = "open-hovered" },
}

assert_equal(#decisions, 6, "decision fixture count")

for _, case in ipairs(decisions) do
	local calls_before = sync_calls
	local result = pack_values(target_policy(case.mode, case.is_dir))
	assert_equal(result.n, 1, case.label .. " return count")
	assert_equal(result[1], case.expected, case.label .. " decision")
	assert_equal(sync_calls, calls_before, case.label .. " host call count")
end

print("target policy checks passed")