-
Notifications
You must be signed in to change notification settings - Fork 198
Expand file tree
/
Copy pathlockfile_test.lua
More file actions
544 lines (490 loc) · 16 KB
/
Copy pathlockfile_test.lua
File metadata and controls
544 lines (490 loc) · 16 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
-- Tests for lockfile module
-- Load mock vim if needed
local real_vim = _G.vim
if not _G.vim then
-- Create a basic vim mock
_G.vim = { ---@type vim_global_api
schedule_wrap = function(fn)
return fn
end,
deepcopy = function(t) -- Basic deepcopy for testing
local copy = {}
for k, v in pairs(t) do
if type(v) == "table" then
copy[k] = _G.vim.deepcopy(v)
else
copy[k] = v
end
end
return copy
end,
cmd = function() end, ---@type fun(command: string):nil
api = {}, ---@type table
fs = { remove = function() end }, ---@type vim_fs_module
fn = { ---@type vim_fn_table
expand = function(path)
-- Use a temp directory that actually exists
local temp_dir = os.getenv("TMPDIR") or "/tmp"
return select(1, path:gsub("~", temp_dir .. "/claude_test"))
end,
-- Add other vim.fn mocks as needed by lockfile tests
-- For now, only adding what's explicitly used or causing major type issues
filereadable = function(path)
-- Check if file actually exists
local file = io.open(path, "r")
if file then
file:close()
return 1
else
return 0
end
end,
fnamemodify = function(fname, _)
return fname
end,
delete = function(_, _)
return 0
end,
mode = function()
return "n"
end,
buflisted = function(_)
return 0
end,
bufname = function(_)
return ""
end,
bufnr = function(_)
return 0
end,
win_getid = function()
return 0
end,
win_gotoid = function(_)
return false
end,
line = function(_)
return 0
end,
col = function(_)
return 0
end,
virtcol = function(_)
return 0
end,
getpos = function(_)
return { 0, 0, 0, 0 }
end,
setpos = function(_, _)
return false
end,
tempname = function()
return ""
end,
globpath = function(_, _)
return ""
end,
stdpath = function(_)
return ""
end,
json_encode = function(_)
return "{}"
end,
json_decode = function(_)
return {}
end,
-- getcwd is defined later in setup, so no need to mock it here initially
-- mkdir is defined later in setup
-- getpid is defined later in setup
getcwd = function()
return "/mock/cwd"
end,
mkdir = function()
return 1
end,
getpid = function()
return 12345
end,
termopen = function(_, _)
return 0
end,
},
notify = function(_, _, _) end,
log = {
levels = {
NONE = 0,
ERROR = 1,
WARN = 2,
INFO = 3,
DEBUG = 4,
TRACE = 5,
},
},
json = {
encode = function(obj)
-- Simple JSON encoding for testing
if type(obj) == "table" then
local pairs_array = {}
for k, v in pairs(obj) do
local key_str = '"' .. tostring(k) .. '"'
local val_str
if type(v) == "string" then
val_str = '"' .. v .. '"'
elseif type(v) == "number" then
val_str = tostring(v)
elseif type(v) == "table" then
-- Simple array encoding
local items = {}
for _, item in ipairs(v) do
table.insert(items, '"' .. tostring(item) .. '"')
end
val_str = "[" .. table.concat(items, ",") .. "]"
else
val_str = '"' .. tostring(v) .. '"'
end
table.insert(pairs_array, key_str .. ":" .. val_str)
end
return "{" .. table.concat(pairs_array, ",") .. "}"
else
return '"' .. tostring(obj) .. '"'
end
end,
decode = function(json_str)
-- Very basic JSON parsing for test purposes
if json_str:match("^%s*{.*}%s*$") then
local result = {}
-- Extract key-value pairs - this is very basic
for key, value in json_str:gmatch('"([^"]+)"%s*:%s*"([^"]*)"') do
result[key] = value
end
for key, value in json_str:gmatch('"([^"]+)"%s*:%s*(%d+)') do
result[key] = tonumber(value)
end
return result
end
return {}
end,
},
lsp = {}, -- Existing lsp mock part
o = { ---@type vim_options_table
columns = 80,
lines = 24,
},
bo = setmetatable({}, { -- Mock for vim.bo and vim.bo[bufnr]
__index = function(t, k)
if type(k) == "number" then
-- vim.bo[bufnr] accessed, return a new proxy table for this buffer
if not t[k] then
t[k] = {} ---@type vim_buffer_options_table
end
return t[k]
end
-- vim.bo.option_name (global buffer option)
return nil -- Return nil or a default mock value if needed
end, -- REMOVED COMMA from here (was after 'end')
-- __newindex can be added here if setting options is needed for tests
-- e.g., __newindex = function(t, k, v) rawset(t, k, v) end,
}), ---@type vim_bo_proxy
diagnostic = { ---@type vim_diagnostic_module
get = function()
return {}
end,
-- Add other vim.diagnostic functions as needed for tests
},
empty_dict = function()
return {}
end,
} -- This is the closing brace for _G.vim table
end
-- Track the most recent fs_open mode so permission-intent assertions can read it.
_G._test_last_fs_open_mode = nil
-- Track the most recent fs_chmod call (path, mode) so the directory-permission
-- assertion can verify an existing dir gets tightened to 0700 on upgrade.
_G._test_last_fs_chmod = nil
-- Provide a vim.loop mock with a CSPRNG and atomic-write file primitives.
-- The fs_* helpers write to real files so get_auth_token round-trips work.
if not _G.vim.loop then
_G.vim.loop = {}
end
do
local loop = _G.vim.loop
local open_files = {}
-- Deterministic-but-varying byte source: differs per call so successive
-- tokens are distinct (regression guard against the old seeded behavior).
local random_counter = 0
loop.random = function(n)
random_counter = random_counter + 1
local bytes = {}
for i = 1, n do
-- Mix the counter and index to vary bytes across calls and positions.
bytes[i] = string.char((random_counter * 31 + i * 7) % 256)
end
return table.concat(bytes)
end
loop.fs_open = function(path, _flags, mode)
_G._test_last_fs_open_mode = mode
local fh = io.open(path, "wb")
if not fh then
return nil
end
local fd = #open_files + 1
open_files[fd] = fh
return fd
end
-- Mirror libuv's signature: fs_write(fd, data, offset). The production code
-- now writes in a loop honoring the returned byte count and an offset, so
-- seek to the offset before writing and report the number of bytes written.
loop.fs_write = function(fd, data, offset)
local fh = open_files[fd]
if not fh then
return nil
end
if offset then
fh:seek("set", offset)
end
fh:write(data)
return #data
end
loop.fs_close = function(fd)
local fh = open_files[fd]
if fh then
fh:close()
open_files[fd] = nil
end
return true
end
loop.fs_unlink = function(path)
os.remove(path)
return true
end
-- Record chmod calls so tests can assert the lock dir is tightened to 0700.
loop.fs_chmod = function(path, mode)
_G._test_last_fs_chmod = { path = path, mode = mode }
return true
end
-- Monotonic-ish clock used to keep the temp-file path unique across calls.
local hrtime_counter = 0
loop.hrtime = function()
hrtime_counter = hrtime_counter + 1
return hrtime_counter
end
end
describe("Lockfile Module", function()
local lockfile
-- Save original vim functions/tables (not used in this test but kept for reference)
-- luacheck: ignore
local orig_vim = _G.vim
local orig_fn_getcwd = vim.fn.getcwd
local orig_lsp = vim.lsp
-- luacheck: no ignore
-- Create a mock for testing LSP client resolution
local create_mock_env = function(api_version)
-- Configure mock based on API version
local mock_lsp = {}
-- Test workspace folders data
local test_workspace_data = {
{
config = {
workspace_folders = {
{ uri = "file:///mock/folder1" },
{ uri = "file:///mock/folder2" },
},
},
},
}
if api_version == "current" then
-- Neovim 0.11+ API (get_clients)
mock_lsp.get_clients = function()
return test_workspace_data
end
elseif api_version == "legacy" then
-- Neovim 0.8-0.10 API (get_active_clients)
mock_lsp.get_active_clients = function()
return test_workspace_data
end
end
-- Apply mock
vim.lsp = mock_lsp
end
setup(function()
-- Mock required vim functions before loading the module
vim.fn.getcwd = function()
return "/mock/cwd"
end
-- Create test directory
local temp_dir = os.getenv("TMPDIR") or "/tmp"
local test_dir = temp_dir .. "/claude_test/.claude/ide"
os.execute("mkdir -p '" .. test_dir .. "'")
-- Load the lockfile module for all tests
package.loaded["claudecode.lockfile"] = nil -- Clear any previous requires
lockfile = require("claudecode.lockfile")
end)
teardown(function()
-- Clean up test files
local temp_dir = os.getenv("TMPDIR") or "/tmp"
local test_dir = temp_dir .. "/claude_test"
os.execute("rm -rf '" .. test_dir .. "'")
-- Restore original vim
if real_vim then
_G.vim = real_vim
end
end)
describe("get_workspace_folders()", function()
before_each(function()
-- Ensure consistent path
vim.fn.getcwd = function()
return "/mock/cwd"
end
end)
after_each(function()
-- Restore lsp table to clean state
vim.lsp = {}
end)
it("should include the current working directory", function()
local folders = lockfile.get_workspace_folders()
assert("/mock/cwd" == folders[1])
end)
it("should work with current Neovim API (get_clients)", function()
-- Set up the current API mock
create_mock_env("current")
-- Test the function
local folders = lockfile.get_workspace_folders()
-- Verify results
assert(3 == #folders) -- cwd + 2 workspace folders
assert("/mock/folder1" == folders[2])
assert("/mock/folder2" == folders[3])
end)
it("should work with legacy Neovim API (get_active_clients)", function()
-- Set up the legacy API mock
create_mock_env("legacy")
-- Test the function
local folders = lockfile.get_workspace_folders()
-- Verify results
assert(3 == #folders) -- cwd + 2 workspace folders
assert("/mock/folder1" == folders[2])
assert("/mock/folder2" == folders[3])
end)
it("should handle duplicate folder paths", function()
-- Set up a mock with duplicates
vim.lsp = {
get_clients = function()
return {
{
config = {
workspace_folders = {
{ uri = "file:///mock/cwd" }, -- Same as cwd
{ uri = "file:///mock/folder" },
{ uri = "file:///mock/folder" }, -- Duplicate
},
},
},
}
end,
}
-- Test the function
local folders = lockfile.get_workspace_folders()
-- Verify results
assert(2 == #folders) -- cwd + 1 unique workspace folder
end)
end)
describe("authentication token functionality", function()
it("should generate auth tokens", function()
local token1 = lockfile.generate_auth_token()
local token2 = lockfile.generate_auth_token()
-- Tokens should be strings
assert("string" == type(token1))
assert("string" == type(token2))
-- Tokens should be different (regression guard against the old
-- seed-once PRNG which produced identical tokens within a process)
assert(token1 ~= token2)
-- Tokens should be lowercase hex with at least 16 chars (32 for 16 bytes)
assert(token1:match("^[0-9a-f]+$"))
assert(token2:match("^[0-9a-f]+$"))
assert(#token1 >= 16)
assert(#token2 >= 16)
assert(32 == #token1)
assert(32 == #token2)
end)
it("should create lock files with auth tokens", function()
local port = 12345
local success, lock_path, auth_token = lockfile.create(port)
assert(success == true)
assert("string" == type(lock_path))
assert("string" == type(auth_token))
-- Should be able to read the auth token back
local read_success, read_token, read_error = lockfile.get_auth_token(port)
assert(read_success == true)
assert(auth_token == read_token)
assert(read_error == nil)
end)
it("should create lock files with pre-generated auth tokens", function()
local port = 12346
local preset_token = "test-auth-token-12345"
local success, lock_path, returned_token = lockfile.create(port, preset_token)
assert(success == true)
assert("string" == type(lock_path))
assert(preset_token == returned_token)
-- Should be able to read the preset token back
local read_success, read_token, read_error = lockfile.get_auth_token(port)
assert(read_success == true)
assert(preset_token == read_token)
assert(read_error == nil)
end)
it("should handle missing lock files when reading auth tokens", function()
local nonexistent_port = 99999
local success, token, error = lockfile.get_auth_token(nonexistent_port)
assert(success == false)
assert(token == nil)
assert("string" == type(error))
assert(error:find("Lock file does not exist"))
end)
it("should write the lock file with 0600 permissions", function()
_G._test_last_fs_open_mode = nil
local port = 12347
local success = lockfile.create(port)
assert(success == true)
-- The atomic write must request mode 0600 (octal 384) on the temp file.
assert(tonumber("600", 8) == _G._test_last_fs_open_mode)
end)
it("should create the lock directory with 0700 permissions", function()
local captured_mkdir_mode
local orig_mkdir = vim.fn.mkdir
vim.fn.mkdir = function(path, flags, mode)
captured_mkdir_mode = mode
return orig_mkdir(path, flags, mode)
end
_G._test_last_fs_chmod = nil
local port = 12348
local success = lockfile.create(port)
vim.fn.mkdir = orig_mkdir
assert(success == true)
-- New directories get 0700 from mkdir's mode argument, passed as an octal
-- number (tonumber("700", 8)); the string "0700" would be coerced to
-- decimal 700 and apply the wrong mode to freshly-created parents...
assert(tonumber("700", 8) == captured_mkdir_mode)
-- ...but mkdir's mode is a no-op for a pre-existing dir, so an explicit
-- chmod must also tighten the lock dir to 0700 on upgrade.
assert(_G._test_last_fs_chmod ~= nil)
assert(lockfile.lock_dir == _G._test_last_fs_chmod.path)
assert(tonumber("700", 8) == _G._test_last_fs_chmod.mode)
end)
it("should write the full lock file content when fs_write reports short writes", function()
-- Force fs_write to write at most one byte per call so the production
-- write loop has to iterate; the resulting lock file must be complete.
local loop = vim.loop
local orig_fs_write = loop.fs_write
loop.fs_write = function(fd, data, offset)
return orig_fs_write(fd, data:sub(1, 1), offset)
end
local port = 12349
local success, _, auth_token = lockfile.create(port)
loop.fs_write = orig_fs_write
assert(success == true)
assert("string" == type(auth_token))
-- The token must round-trip, proving the JSON was written in full.
local read_success, read_token = lockfile.get_auth_token(port)
assert(read_success == true)
assert(auth_token == read_token)
end)
end)
end)