Repository navigation
Expand file tree
/
Copy pathtest_lua_oop_patterns.py
More file actions
629 lines (504 loc) · 15.9 KB
/
Copy pathtest_lua_oop_patterns.py
File metadata and controls
629 lines (504 loc) · 15.9 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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
"""Tests for Lua OOP patterns using tables and metatables."""
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_lua_class_pattern_basic(temp_repo: Path, mock_ingestor: MagicMock) -> None:
"""Test basic Lua class pattern with constructor and methods."""
project = temp_repo / "lua_oop_test"
project.mkdir()
# Create a Person "class" with constructor and methods
(project / "person.lua").write_text("""
-- Define a Person "class"
local Person = {}
Person.__index = Person
function Person:new(name, age)
local obj = setmetatable({}, Person)
obj.name = name
obj.age = age
return obj
end
function Person:greet()
print("Hello, my name is " .. self.name)
end
function Person:getAge()
return self.age
end
return Person
""")
# Create a file that uses the Person class
(project / "main.lua").write_text("""
local Person = require('person')
local alice = Person:new("Alice", 30)
alice:greet()
local age = alice:getAge()
local bob = Person:new("Bob", 25)
bob:greet()
""")
parsers, queries = load_parsers()
updater = GraphUpdater(
ingestor=mock_ingestor, repo_path=project, parsers=parsers, queries=queries
)
updater.run()
# Check that Person class methods were detected
person_qn = f"{project.name}.person"
main_qn = f"{project.name}.main"
# Verify DEFINES relationships (Module defines functions)
defines_rels = [
c
for c in mock_ingestor.ensure_relationship_batch.call_args_list
if c.args[1] == "DEFINES"
]
# Verify CALLS relationships (Functions call other functions)
calls_rels = [
c
for c in mock_ingestor.ensure_relationship_batch.call_args_list
if c.args[1] == "CALLS"
]
# Verify IMPORTS relationships
imports_rels = [
c
for c in mock_ingestor.ensure_relationship_batch.call_args_list
if c.args[1] == "IMPORTS"
]
# Should have module defining functions
assert len(defines_rels) >= 3, (
f"Expected at least 3 DEFINES relationships, got {len(defines_rels)}"
)
# Should have method calls (Person:new calls)
assert len(calls_rels) >= 2, (
f"Expected at least 2 CALLS relationships, got {len(calls_rels)}"
)
# Should have import relationship (main imports person)
assert len(imports_rels) >= 1, (
f"Expected at least 1 IMPORTS relationship, got {len(imports_rels)}"
)
# Verify import was detected
import_map = updater.factory.import_processor.import_mapping.get(main_qn, {})
assert "Person" in import_map
assert import_map["Person"] == person_qn
def test_lua_inheritance_pattern(temp_repo: Path, mock_ingestor: MagicMock) -> None:
"""Test Lua inheritance pattern using metatables."""
project = temp_repo / "lua_inheritance_test"
project.mkdir()
# Base class
(project / "animal.lua").write_text("""
local Animal = {}
Animal.__index = Animal
function Animal:new(name)
local obj = setmetatable({}, Animal)
obj.name = name
return obj
end
function Animal:speak()
print(self.name .. " makes a sound")
end
function Animal:getName()
return self.name
end
return Animal
""")
# Derived class
(project / "dog.lua").write_text("""
local Animal = require('animal')
local Dog = {}
Dog.__index = Dog
setmetatable(Dog, {__index = Animal}) -- Inheritance
function Dog:new(name, breed)
local obj = Animal.new(self, name) -- Call parent constructor
setmetatable(obj, Dog)
obj.breed = breed
return obj
end
function Dog:speak()
print(self.name .. " barks!")
end
function Dog:getBreed()
return self.breed
end
return Dog
""")
# Usage
(project / "main.lua").write_text("""
local Dog = require('dog')
local myDog = Dog:new("Buddy", "Golden Retriever")
myDog:speak() -- Should call Dog's speak
local name = myDog:getName() -- Should call inherited Animal's getName
local breed = myDog:getBreed() -- Should call Dog's getBreed
""")
parsers, queries = load_parsers()
updater = GraphUpdater(
ingestor=mock_ingestor, repo_path=project, parsers=parsers, queries=queries
)
updater.run()
# Check class definitions
animal_qn = f"{project.name}.animal"
dog_qn = f"{project.name}.dog"
main_qn = f"{project.name}.main"
# Get created functions
created_functions = [
c
for c in mock_ingestor.ensure_node_batch.call_args_list
if c[0][0] == "Function"
]
fn_qns = {c[0][1]["qualified_name"] for c in created_functions}
# Verify Animal methods
assert f"{animal_qn}.Animal:new" in fn_qns or f"{animal_qn}.Animal.new" in fn_qns
assert (
f"{animal_qn}.Animal:speak" in fn_qns or f"{animal_qn}.Animal.speak" in fn_qns
)
assert (
f"{animal_qn}.Animal:getName" in fn_qns
or f"{animal_qn}.Animal.getName" in fn_qns
)
# Verify Dog methods
assert f"{dog_qn}.Dog:new" in fn_qns or f"{dog_qn}.Dog.new" in fn_qns
assert f"{dog_qn}.Dog:speak" in fn_qns or f"{dog_qn}.Dog.speak" in fn_qns
assert f"{dog_qn}.Dog:getBreed" in fn_qns or f"{dog_qn}.Dog.getBreed" in fn_qns
# Verify imports
dog_imports = updater.factory.import_processor.import_mapping.get(dog_qn, {})
assert "Animal" in dog_imports
main_imports = updater.factory.import_processor.import_mapping.get(main_qn, {})
assert "Dog" in main_imports
def test_lua_module_pattern(temp_repo: Path, mock_ingestor: MagicMock) -> None:
"""Test Lua module pattern with encapsulation."""
project = temp_repo / "lua_module_test"
project.mkdir()
# Module with private and public functions
(project / "calculator.lua").write_text("""
local Calculator = {}
-- Private function (local)
local function validate(x, y)
if type(x) ~= "number" or type(y) ~= "number" then
error("Arguments must be numbers")
end
end
-- Public functions
function Calculator.add(x, y)
validate(x, y)
return x + y
end
function Calculator.subtract(x, y)
validate(x, y)
return x - y
end
function Calculator.multiply(x, y)
validate(x, y)
return x * y
end
-- Another way to define methods
Calculator.divide = function(x, y)
validate(x, y)
if y == 0 then
error("Division by zero")
end
return x / y
end
return Calculator
""")
(project / "main.lua").write_text("""
local calc = require('calculator')
local sum = calc.add(5, 3)
local diff = calc.subtract(10, 4)
local product = calc.multiply(6, 7)
local quotient = calc.divide(20, 5)
""")
parsers, queries = load_parsers()
updater = GraphUpdater(
ingestor=mock_ingestor, repo_path=project, parsers=parsers, queries=queries
)
updater.run()
calc_qn = f"{project.name}.calculator"
main_qn = f"{project.name}.main"
# Get created functions
created_functions = [
c
for c in mock_ingestor.ensure_node_batch.call_args_list
if c[0][0] == "Function"
]
fn_qns = {c[0][1]["qualified_name"] for c in created_functions}
# Verify module methods
assert f"{calc_qn}.Calculator.add" in fn_qns
assert f"{calc_qn}.Calculator.subtract" in fn_qns
assert f"{calc_qn}.Calculator.multiply" in fn_qns
assert (
f"{calc_qn}.Calculator.divide" in fn_qns
) # Assignment pattern should now be detected
# Private function should also be detected (but as a local function)
assert f"{calc_qn}.validate" in fn_qns
# Verify import
import_map = updater.factory.import_processor.import_mapping.get(main_qn, {})
assert "calc" in import_map
def test_lua_prototype_pattern(temp_repo: Path, mock_ingestor: MagicMock) -> None:
"""Test Lua prototype-based OOP pattern."""
project = temp_repo / "lua_prototype_test"
project.mkdir()
(project / "shape.lua").write_text("""
-- Prototype object
local ShapePrototype = {
x = 0,
y = 0
}
function ShapePrototype:clone()
local obj = {}
for k, v in pairs(self) do
obj[k] = v
end
setmetatable(obj, {__index = self})
return obj
end
function ShapePrototype:moveTo(newX, newY)
self.x = newX
self.y = newY
end
function ShapePrototype:getPosition()
return self.x, self.y
end
-- Factory function
local function createCircle(x, y, radius)
local circle = ShapePrototype:clone()
circle.x = x
circle.y = y
circle.radius = radius
function circle:getArea()
return math.pi * self.radius * self.radius
end
return circle
end
-- Export
return {
ShapePrototype = ShapePrototype,
createCircle = createCircle
}
""")
(project / "main.lua").write_text("""
local shapes = require('shape')
local circle1 = shapes.createCircle(10, 20, 5)
circle1:moveTo(30, 40)
local area = circle1:getArea()
local x, y = circle1:getPosition()
local circle2 = shapes.createCircle(0, 0, 10)
""")
parsers, queries = load_parsers()
updater = GraphUpdater(
ingestor=mock_ingestor, repo_path=project, parsers=parsers, queries=queries
)
updater.run()
shape_qn = f"{project.name}.shape"
main_qn = f"{project.name}.main"
# Get created functions
created_functions = [
c
for c in mock_ingestor.ensure_node_batch.call_args_list
if c[0][0] == "Function"
]
fn_qns = {c[0][1]["qualified_name"] for c in created_functions}
# Verify prototype methods
assert (
f"{shape_qn}.ShapePrototype:clone" in fn_qns
or f"{shape_qn}.ShapePrototype.clone" in fn_qns
)
assert (
f"{shape_qn}.ShapePrototype:moveTo" in fn_qns
or f"{shape_qn}.ShapePrototype.moveTo" in fn_qns
)
assert (
f"{shape_qn}.ShapePrototype:getPosition" in fn_qns
or f"{shape_qn}.ShapePrototype.getPosition" in fn_qns
)
# Verify factory function
assert f"{shape_qn}.createCircle" in fn_qns
# Note: The dynamically created circle:getArea might not be detected
# as it's defined inside a function
# Verify import
import_map = updater.factory.import_processor.import_mapping.get(main_qn, {})
assert "shapes" in import_map
def test_lua_mixin_pattern(temp_repo: Path, mock_ingestor: MagicMock) -> None:
"""Test Lua mixin pattern for multiple inheritance."""
project = temp_repo / "lua_mixin_test"
project.mkdir()
# Mixin 1
(project / "printable.lua").write_text("""
local Printable = {}
function Printable:toString()
local str = "{"
for k, v in pairs(self) do
if type(v) ~= "function" then
str = str .. k .. "=" .. tostring(v) .. ", "
end
end
return str .. "}"
end
function Printable:print()
print(self:toString())
end
return Printable
""")
# Mixin 2
(project / "serializable.lua").write_text("""
local Serializable = {}
function Serializable:serialize()
-- Simple JSON-like serialization
local result = {}
for k, v in pairs(self) do
if type(v) ~= "function" then
table.insert(result, '"' .. k .. '":"' .. tostring(v) .. '"')
end
end
return "{" .. table.concat(result, ",") .. "}"
end
function Serializable:deserialize(data)
-- Simplified deserialization
-- In real code, you'd parse the JSON properly
return data
end
return Serializable
""")
# Class using mixins
(project / "user.lua").write_text("""
local Printable = require('printable')
local Serializable = require('serializable')
local User = {}
User.__index = User
-- Apply mixins
for k, v in pairs(Printable) do
User[k] = v
end
for k, v in pairs(Serializable) do
User[k] = v
end
function User:new(name, email)
local obj = setmetatable({}, User)
obj.name = name
obj.email = email
return obj
end
function User:getName()
return self.name
end
function User:getEmail()
return self.email
end
return User
""")
(project / "main.lua").write_text("""
local User = require('user')
local user = User:new("John Doe", "[email protected]")
user:print() -- From Printable mixin
local json = user:serialize() -- From Serializable mixin
local name = user:getName() -- From User itself
""")
parsers, queries = load_parsers()
updater = GraphUpdater(
ingestor=mock_ingestor, repo_path=project, parsers=parsers, queries=queries
)
updater.run()
printable_qn = f"{project.name}.printable"
serializable_qn = f"{project.name}.serializable"
user_qn = f"{project.name}.user"
main_qn = f"{project.name}.main"
# Get created functions
created_functions = [
c
for c in mock_ingestor.ensure_node_batch.call_args_list
if c[0][0] == "Function"
]
fn_qns = {c[0][1]["qualified_name"] for c in created_functions}
# Verify mixin methods
assert (
f"{printable_qn}.Printable:toString" in fn_qns
or f"{printable_qn}.Printable.toString" in fn_qns
)
assert (
f"{printable_qn}.Printable:print" in fn_qns
or f"{printable_qn}.Printable.print" in fn_qns
)
assert (
f"{serializable_qn}.Serializable:serialize" in fn_qns
or f"{serializable_qn}.Serializable.serialize" in fn_qns
)
assert (
f"{serializable_qn}.Serializable:deserialize" in fn_qns
or f"{serializable_qn}.Serializable.deserialize" in fn_qns
)
# Verify User methods
assert f"{user_qn}.User:new" in fn_qns or f"{user_qn}.User.new" in fn_qns
assert f"{user_qn}.User:getName" in fn_qns or f"{user_qn}.User.getName" in fn_qns
assert f"{user_qn}.User:getEmail" in fn_qns or f"{user_qn}.User.getEmail" in fn_qns
# Verify imports
user_imports = updater.factory.import_processor.import_mapping.get(user_qn, {})
assert "Printable" in user_imports
assert "Serializable" in user_imports
main_imports = updater.factory.import_processor.import_mapping.get(main_qn, {})
assert "User" in main_imports
def test_lua_singleton_pattern(temp_repo: Path, mock_ingestor: MagicMock) -> None:
"""Test Lua singleton pattern."""
project = temp_repo / "lua_singleton_test"
project.mkdir()
(project / "config.lua").write_text("""
-- Singleton pattern
local Config = {}
local instance = nil
function Config:getInstance()
if not instance then
instance = {}
setmetatable(instance, {__index = Config})
-- Initialize with default values
instance.settings = {
debug = false,
logLevel = "info",
maxConnections = 100
}
end
return instance
end
function Config:get(key)
return self.settings[key]
end
function Config:set(key, value)
self.settings[key] = value
end
function Config:reset()
self.settings = {
debug = false,
logLevel = "info",
maxConnections = 100
}
end
return Config
""")
(project / "main.lua").write_text("""
local Config = require('config')
local config1 = Config:getInstance()
config1:set("debug", true)
local config2 = Config:getInstance()
local debug = config2:get("debug") -- Should be true (same instance)
config2:reset()
""")
parsers, queries = load_parsers()
updater = GraphUpdater(
ingestor=mock_ingestor, repo_path=project, parsers=parsers, queries=queries
)
updater.run()
config_qn = f"{project.name}.config"
main_qn = f"{project.name}.main"
# Get created functions
created_functions = [
c
for c in mock_ingestor.ensure_node_batch.call_args_list
if c[0][0] == "Function"
]
fn_qns = {c[0][1]["qualified_name"] for c in created_functions}
# Verify singleton methods
assert (
f"{config_qn}.Config:getInstance" in fn_qns
or f"{config_qn}.Config.getInstance" in fn_qns
)
assert f"{config_qn}.Config:get" in fn_qns or f"{config_qn}.Config.get" in fn_qns
assert f"{config_qn}.Config:set" in fn_qns or f"{config_qn}.Config.set" in fn_qns
assert (
f"{config_qn}.Config:reset" in fn_qns or f"{config_qn}.Config.reset" in fn_qns
)
# Verify import
import_map = updater.factory.import_processor.import_mapping.get(main_qn, {})
assert "Config" in import_map