Repository navigation
Expand file tree
/
Copy pathtest_lua_environment.py
More file actions
531 lines (433 loc) · 13.3 KB
/
Copy pathtest_lua_environment.py
File metadata and controls
531 lines (433 loc) · 13.3 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
from pathlib import Path
from unittest.mock import MagicMock
from codebase_rag.graph_updater import GraphUpdater
from codebase_rag.parser_loader import load_parsers
def test_global_environment_access(temp_repo: Path, mock_ingestor: MagicMock) -> None:
"""Test global environment access patterns with user-defined functions."""
project = temp_repo / "lua_global_env"
project.mkdir()
(project / "globals.lua").write_text("""
local env_manager = {}
function env_manager.backup_global(name)
-- Simulate backing up a global value
local backup = {}
backup[name] = _G[name]
return backup
end
function env_manager.restore_global(backup, name)
-- Simulate restoring a global value
if backup[name] ~= nil then
_G[name] = backup[name]
else
_G[name] = nil
end
return true
end
function manage_globals()
-- Call our user-defined functions to manage globals
local old_print_backup = env_manager.backup_global("print")
_G.print = function(...)
-- Custom print implementation (stdlib call not tracked)
old_print_backup.print("LOG:", ...)
end
_G.custom_global = "Hello from global"
local global_value = _G.custom_global
_G["dynamic_key"] = "Dynamic value"
local dynamic_value = _G["dynamic_key"]
-- Use our restore function
env_manager.restore_global(old_print_backup, "print")
return {
global_val = global_value,
dynamic_val = dynamic_value
}
end
function list_globals()
local globals = {}
for key, value in pairs(_G) do
if type(value) ~= "function" then
globals[key] = tostring(value)
end
end
return globals
end
-- Create user-defined functions
_G.shared_data = {counter = 0}
_G.increment = function()
_G.shared_data.counter = _G.shared_data.counter + 1
end
return env_manager
""")
parsers, queries = load_parsers()
updater = GraphUpdater(
ingestor=mock_ingestor, repo_path=project, parsers=parsers, queries=queries
)
updater.run()
# Verify DEFINES relationships
defines_rels = [
c
for c in mock_ingestor.ensure_relationship_batch.call_args_list
if c.args[1] == "DEFINES"
]
# Verify CALLS relationships
calls_rels = [
c
for c in mock_ingestor.ensure_relationship_batch.call_args_list
if c.args[1] == "CALLS"
]
# Should have function definitions for user-defined functions
assert len(defines_rels) >= 4, (
f"Expected at least 4 DEFINES relationships, got {len(defines_rels)}"
)
# Should have calls to user-defined functions (env_manager functions)
assert len(calls_rels) >= 2, (
f"Expected at least 2 CALLS relationships, got {len(calls_rels)}"
)
def test_environment_manipulation(temp_repo: Path, mock_ingestor: MagicMock) -> None:
"""Test environment manipulation with user-defined helper functions."""
project = temp_repo / "lua_env_manipulation"
project.mkdir()
(project / "env_manip.lua").write_text("""
local env_utils = {}
function env_utils.create_safe_env()
-- Create a safe environment table
return {
print = print,
tostring = tostring,
tonumber = tonumber,
type = type,
pairs = pairs,
ipairs = ipairs,
math = math,
string = string,
table = table
}
end
function env_utils.execute_with_env(code, env)
-- Execute code in a given environment
local chunk = loadstring(code)
if chunk then
setfenv(chunk, env)
local result = chunk()
return result
end
return nil
end
function create_sandbox()
local sandbox_env = env_utils.create_safe_env()
local safe_code = [[
local x = 10
local y = 20
return x + y
]]
return env_utils.execute_with_env(safe_code, sandbox_env)
end
function get_current_env()
local env = getfenv(1)
local env_type = type(env)
local func_env = getfenv(print)
return {
current = env,
env_type = env_type,
print_env = func_env
}
end
function modify_function_env(func)
local new_env = env_utils.create_safe_env()
-- Override print in the new environment
new_env.print = function(...)
print("MODIFIED:", ...)
end
setfenv(func, new_env)
return func
end
-- Use our helper functions
local chunk = loadstring("return 42")
local safe_env = env_utils.create_safe_env()
setfenv(chunk, safe_env)
local result = chunk()
return env_utils
""")
parsers, queries = load_parsers()
updater = GraphUpdater(
ingestor=mock_ingestor, repo_path=project, parsers=parsers, queries=queries
)
updater.run()
# Verify DEFINES relationships
defines_rels = [
c
for c in mock_ingestor.ensure_relationship_batch.call_args_list
if c.args[1] == "DEFINES"
]
# Verify CALLS relationships
calls_rels = [
c
for c in mock_ingestor.ensure_relationship_batch.call_args_list
if c.args[1] == "CALLS"
]
# Should have function definitions for user-defined functions
assert len(defines_rels) >= 5, (
f"Expected at least 5 DEFINES relationships, got {len(defines_rels)}"
)
# Should have calls to user-defined helper functions
assert len(calls_rels) >= 2, (
f"Expected at least 2 CALLS relationships, got {len(calls_rels)}"
)
def test_module_environment_patterns(temp_repo: Path, mock_ingestor: MagicMock) -> None:
"""Test module environment patterns with user-defined functions."""
project = temp_repo / "lua_module_env"
project.mkdir()
(project / "module_env.lua").write_text("""
local M = {}
local env_helpers = {}
function env_helpers.setup_metatable(env, default_value_generator)
setmetatable(env, {
__index = function(t, k)
return default_value_generator(k)
end
})
return env
end
function env_helpers.create_logging_metatable()
return {
__index = _G,
__newindex = function(t, k, v)
print("Setting isolated:", k, v)
rawset(t, k, v)
end
}
end
function M.setup_module_env()
local env = getfenv(1)
env.MODULE_NAME = "MyModule"
env.VERSION = "1.0.0"
local generator = function(k)
return "DEFAULT_" .. tostring(k)
end
return env_helpers.setup_metatable(env, generator)
end
function M.create_isolated_env()
local isolated = {}
local logging_mt = env_helpers.create_logging_metatable()
setmetatable(isolated, logging_mt)
return isolated
end
function M.load_in_environment(code, env)
local chunk = loadstring(code)
if chunk then
setfenv(chunk, env or getfenv(1))
return pcall(chunk)
end
return false, "Failed to load code"
end
-- Test our helper functions
local test_env = M.setup_module_env()
local isolated = M.create_isolated_env()
setfenv(1, {
print = print,
require = require,
M = M,
env_helpers = env_helpers
})
return M
""")
parsers, queries = load_parsers()
updater = GraphUpdater(
ingestor=mock_ingestor, repo_path=project, parsers=parsers, queries=queries
)
updater.run()
# Verify DEFINES relationships
defines_rels = [
c
for c in mock_ingestor.ensure_relationship_batch.call_args_list
if c.args[1] == "DEFINES"
]
# Verify CALLS relationships
calls_rels = [
c
for c in mock_ingestor.ensure_relationship_batch.call_args_list
if c.args[1] == "CALLS"
]
# Should have module function definitions (M.* and env_helpers.*)
assert len(defines_rels) >= 5, (
f"Expected at least 5 DEFINES relationships, got {len(defines_rels)}"
)
# Should have calls to helper functions
assert len(calls_rels) >= 2, (
f"Expected at least 2 CALLS relationships, got {len(calls_rels)}"
)
def test_dynamic_code_execution(temp_repo: Path, mock_ingestor: MagicMock) -> None:
"""Test dynamic code execution patterns with user-defined helpers."""
project = temp_repo / "lua_dynamic_exec"
project.mkdir()
(project / "dynamic_exec.lua").write_text("""
local code_executor = {}
function code_executor.create_safe_env()
return {
math = math,
string = string,
table = table,
print = print,
tostring = tostring,
tonumber = tonumber,
type = type
}
end
function code_executor.substitute_template(template, params)
return string.gsub(template, "%$(%w+)", params)
end
function code_executor.execute_in_env(code, env)
local chunk = loadstring(code)
if chunk then
setfenv(chunk, env)
local success, result = pcall(chunk)
if success then
return result
else
error("Execution failed: " .. result)
end
else
error("Compilation failed")
end
end
function execute_dynamic_code(code_str, params)
local template = code_executor.substitute_template(code_str, params)
local safe_env = code_executor.create_safe_env()
return code_executor.execute_in_env(template, safe_env)
end
function load_config_file(filename)
local file = io.open(filename, "r")
if file then
local content = file:read("*all")
file:close()
local config_chunk = loadstring("return " .. content)
if config_chunk then
local config_env = code_executor.create_safe_env()
-- Add specific os functions
config_env.os = {time = os.time, date = os.date}
return code_executor.execute_in_env("return " .. content, config_env)
end
end
return {}
end
-- Test our functions
local code = "return math.pi * 2"
local safe_env = code_executor.create_safe_env()
local result = code_executor.execute_in_env(code, safe_env)
return code_executor
""")
parsers, queries = load_parsers()
updater = GraphUpdater(
ingestor=mock_ingestor, repo_path=project, parsers=parsers, queries=queries
)
updater.run()
# Verify DEFINES relationships
defines_rels = [
c
for c in mock_ingestor.ensure_relationship_batch.call_args_list
if c.args[1] == "DEFINES"
]
# Verify CALLS relationships
calls_rels = [
c
for c in mock_ingestor.ensure_relationship_batch.call_args_list
if c.args[1] == "CALLS"
]
# Should have function definitions for user-defined functions
assert len(defines_rels) >= 5, (
f"Expected at least 5 DEFINES relationships, got {len(defines_rels)}"
)
# Should have calls to our helper functions
assert len(calls_rels) >= 3, (
f"Expected at least 3 CALLS relationships, got {len(calls_rels)}"
)
def test_global_variable_management(temp_repo: Path, mock_ingestor: MagicMock) -> None:
"""Test global variable management patterns with user-defined functions."""
project = temp_repo / "lua_global_mgmt"
project.mkdir()
(project / "global_mgmt.lua").write_text("""
local global_manager = {}
local globals_backup = {}
function global_manager.backup_value(name)
globals_backup[name] = _G[name]
return globals_backup[name]
end
function global_manager.restore_value(name)
if globals_backup[name] ~= nil then
_G[name] = globals_backup[name]
else
_G[name] = nil
end
return _G[name]
end
function global_manager.find_matching_keys(pattern)
local matches = {}
for key, _ in pairs(_G) do
if type(key) == "string" and string.match(key, pattern) then
table.insert(matches, key)
end
end
return matches
end
function save_globals(names)
for _, name in ipairs(names) do
global_manager.backup_value(name)
end
end
function restore_globals(names)
for _, name in ipairs(names) do
global_manager.restore_value(name)
end
end
function clear_globals(pattern)
local to_remove = global_manager.find_matching_keys(pattern)
for _, key in ipairs(to_remove) do
_G[key] = nil
end
return #to_remove
end
function set_global_readonly(name, value)
_G[name] = value
local mt = getmetatable(_G) or {}
local protected = mt.__protected or {}
protected[name] = true
mt.__protected = protected
mt.__newindex = function(t, k, v)
if protected[k] then
error("Attempt to modify read-only global: " .. k)
else
rawset(t, k, v)
end
end
setmetatable(_G, mt)
end
-- Use our functions
save_globals({"print", "require"})
_G.test_global = "test_value"
restore_globals({"print", "require"})
return global_manager
""")
parsers, queries = load_parsers()
updater = GraphUpdater(
ingestor=mock_ingestor, repo_path=project, parsers=parsers, queries=queries
)
updater.run()
# Verify DEFINES relationships
defines_rels = [
c
for c in mock_ingestor.ensure_relationship_batch.call_args_list
if c.args[1] == "DEFINES"
]
# Verify CALLS relationships
calls_rels = [
c
for c in mock_ingestor.ensure_relationship_batch.call_args_list
if c.args[1] == "CALLS"
]
# Should have function definitions for user-defined functions
assert len(defines_rels) >= 7, (
f"Expected at least 7 DEFINES relationships, got {len(defines_rels)}"
)
# Should have calls to our helper functions
assert len(calls_rels) >= 3, (
f"Expected at least 3 CALLS relationships, got {len(calls_rels)}"
)