Repository navigation
Expand file tree
/
Copy pathtest_cpp_namespaces.py
More file actions
918 lines (748 loc) · 24.1 KB
/
Copy pathtest_cpp_namespaces.py
File metadata and controls
918 lines (748 loc) · 24.1 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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
"""
Comprehensive C++ namespace parsing and qualified name testing.
Tests namespace definitions, using directives, nested namespaces, and qualified name resolution.
"""
from pathlib import Path
from typing import cast
from unittest.mock import MagicMock
import pytest
from codebase_rag.graph_updater import GraphUpdater
from codebase_rag.parser_loader import load_parsers
@pytest.fixture
def cpp_namespaces_project(temp_repo: Path) -> Path:
"""Create a comprehensive C++ project with namespace patterns."""
project_path = temp_repo / "cpp_namespaces_test"
project_path.mkdir()
# Create basic structure
(project_path / "src").mkdir()
(project_path / "include").mkdir()
return project_path
def test_basic_namespaces(
cpp_namespaces_project: Path,
mock_ingestor: MagicMock,
) -> None:
"""Test basic namespace declarations and usage."""
test_file = cpp_namespaces_project / "basic_namespaces.cpp"
test_file.write_text(
"""
#include <iostream>
#include <string>
// Global namespace function
void globalFunction() {
std::cout << "Global function called" << std::endl;
}
// Basic namespace
namespace utils {
void printMessage(const std::string& message) {
std::cout << "Utils: " << message << std::endl;
}
class Logger {
public:
static void log(const std::string& message) {
std::cout << "[LOG] " << message << std::endl;
}
void info(const std::string& message) {
std::cout << "[INFO] " << message << std::endl;
}
void error(const std::string& message) {
std::cout << "[ERROR] " << message << std::endl;
}
};
const int MAX_BUFFER_SIZE = 1024;
double calculateArea(double radius) {
const double PI = 3.14159;
return PI * radius * radius;
}
}
// Another namespace
namespace graphics {
struct Point {
double x, y;
Point(double x = 0, double y = 0) : x(x), y(y) {}
};
struct Color {
int r, g, b;
Color(int r = 0, int g = 0, int b = 0) : r(r), g(g), b(b) {}
};
class Shape {
public:
Shape(const Point& pos, const Color& col) : position_(pos), color_(col) {}
virtual ~Shape() = default;
virtual void draw() const = 0;
virtual double area() const = 0;
Point getPosition() const { return position_; }
Color getColor() const { return color_; }
protected:
Point position_;
Color color_;
};
class Circle : public Shape {
private:
double radius_;
public:
Circle(const Point& pos, const Color& col, double radius)
: Shape(pos, col), radius_(radius) {}
void draw() const override {
std::cout << "Drawing circle at (" << position_.x << ", " << position_.y
<< ") with radius " << radius_ << std::endl;
}
double area() const override {
return utils::calculateArea(radius_); // Cross-namespace call
}
double getRadius() const { return radius_; }
};
}
// Math utilities namespace
namespace math {
namespace constants {
const double PI = 3.141592653589793;
const double E = 2.718281828459045;
}
double add(double a, double b) {
return a + b;
}
double multiply(double a, double b) {
return a * b;
}
class Calculator {
public:
static double compute(double a, double b, char op) {
switch (op) {
case '+': return add(a, b);
case '*': return multiply(a, b);
default: return 0.0;
}
}
double power(double base, int exponent) {
double result = 1.0;
for (int i = 0; i < exponent; ++i) {
result = multiply(result, base);
}
return result;
}
};
}
void demonstrateBasicNamespaces() {
// Global function call
globalFunction();
// Qualified namespace calls
utils::printMessage("Hello from utils namespace");
utils::Logger::log("Static method call");
utils::Logger logger;
logger.info("Instance method call");
logger.error("Error message");
// Cross-namespace usage
graphics::Point origin(0, 0);
graphics::Color red(255, 0, 0);
graphics::Circle circle(origin, red, 5.0);
circle.draw();
double area = circle.area(); // This calls utils::calculateArea internally
std::cout << "Circle area: " << area << std::endl;
// Math namespace usage
double sum = math::add(10.0, 20.0);
double product = math::multiply(5.0, 6.0);
math::Calculator calc;
double power = calc.power(2.0, 8);
double computed = math::Calculator::compute(15.0, 3.0, '+');
std::cout << "Sum: " << sum << std::endl;
std::cout << "Product: " << product << std::endl;
std::cout << "2^8 = " << power << std::endl;
std::cout << "Computed: " << computed << std::endl;
// Access nested namespace
std::cout << "PI from math::constants: " << math::constants::PI << std::endl;
std::cout << "E from math::constants: " << math::constants::E << std::endl;
}
"""
)
parsers, queries = load_parsers()
updater = GraphUpdater(
ingestor=mock_ingestor,
repo_path=cpp_namespaces_project,
parsers=parsers,
queries=queries,
)
updater.run()
project_name = cpp_namespaces_project.name
# Expected namespaced classes
expected_classes = [
f"{project_name}.basic_namespaces.utils.Logger",
f"{project_name}.basic_namespaces.graphics.Point",
f"{project_name}.basic_namespaces.graphics.Shape",
f"{project_name}.basic_namespaces.graphics.Circle",
f"{project_name}.basic_namespaces.math.Calculator",
]
# Get all Class node creation calls
class_calls = [
call
for call in mock_ingestor.ensure_node_batch.call_args_list
if call[0][0] == "Class"
]
created_classes = {call[0][1]["qualified_name"] for call in class_calls}
# Verify at least some namespaced classes were created
missing_classes = set(expected_classes) - created_classes
assert not missing_classes, (
f"Missing expected classes: {sorted(list(missing_classes))}"
)
# Expected namespaced functions
expected_functions = [
f"{project_name}.basic_namespaces.globalFunction",
f"{project_name}.basic_namespaces.utils.printMessage",
f"{project_name}.basic_namespaces.utils.calculateArea",
f"{project_name}.basic_namespaces.math.add",
f"{project_name}.basic_namespaces.math.multiply",
]
# Get all Function node creation calls
function_calls = [
call
for call in mock_ingestor.ensure_node_batch.call_args_list
if call[0][0] == "Function"
]
created_functions = {call[0][1]["qualified_name"] for call in function_calls}
# Verify namespaced functions were created
missing_functions = set(expected_functions) - created_functions
assert not missing_functions, (
f"Missing expected functions: {sorted(list(missing_functions))}"
)
def test_using_directives(
cpp_namespaces_project: Path,
mock_ingestor: MagicMock,
) -> None:
"""Test using directives and namespace aliases."""
test_file = cpp_namespaces_project / "using_directives.cpp"
test_file.write_text(
"""
#include <iostream>
#include <string>
#include <vector>
namespace company {
namespace project {
namespace module {
class DataProcessor {
public:
void process(const std::string& data) {
std::cout << "Processing: " << data << std::endl;
}
std::vector<std::string> split(const std::string& input, char delimiter) {
std::vector<std::string> result;
// Simplified split implementation
result.push_back(input);
return result;
}
};
void utility_function() {
std::cout << "Utility function called" << std::endl;
}
const int VERSION = 1;
}
}
}
namespace utils {
void helper() {
std::cout << "Helper function" << std::endl;
}
class StringUtils {
public:
static std::string uppercase(const std::string& str) {
std::string result = str;
// Simplified uppercase implementation
return result;
}
static bool isEmpty(const std::string& str) {
return str.empty();
}
};
}
// Using namespace directive
using namespace std;
// Using specific declarations
using utils::helper;
using utils::StringUtils;
// Namespace alias
namespace cpm = company::project::module;
void demonstrateUsingDirectives() {
// Can use std types without std:: prefix due to "using namespace std"
string message = "Hello, World!";
vector<int> numbers = {1, 2, 3, 4, 5};
cout << "Message: " << message << endl;
cout << "Numbers count: " << numbers.size() << endl;
// Use function brought into scope with using declaration
helper(); // Instead of utils::helper()
// Use class brought into scope with using declaration
string upper = StringUtils::uppercase("hello"); // Instead of utils::StringUtils::uppercase
bool empty = StringUtils::isEmpty("");
cout << "Uppercase: " << upper << endl;
cout << "Is empty: " << (empty ? "yes" : "no") << endl;
// Use namespace alias
cpm::DataProcessor processor; // Instead of company::project::module::DataProcessor
processor.process("test data");
auto parts = processor.split("a,b,c", ',');
cout << "Split result count: " << parts.size() << endl;
cpm::utility_function(); // Instead of company::project::module::utility_function
cout << "Version: " << cpm::VERSION << endl;
// Still can use fully qualified names
company::project::module::DataProcessor fullProcessor;
fullProcessor.process("fully qualified");
}
// Scoped using directives
void scopedUsingExample() {
{
using namespace utils;
// Within this scope, can use utils members directly
helper();
string result = StringUtils::uppercase("scoped");
cout << "Scoped result: " << result << endl;
}
// Outside the scope, need qualification again
utils::helper();
utils::StringUtils stringUtils;
}
// Using directive in function
void functionScopedUsing() {
using company::project::module::DataProcessor;
using company::project::module::utility_function;
DataProcessor processor;
processor.process("function scoped");
utility_function();
}
// Class with using declarations
class MyClass {
public:
using ProcessorType = company::project::module::DataProcessor;
using StringType = std::string;
void useTypes() {
ProcessorType processor;
StringType data = "class scoped types";
processor.process(data);
}
private:
ProcessorType processor_;
StringType name_;
};
void demonstrateClassUsing() {
MyClass obj;
obj.useTypes();
}
// Template with using
template<typename T>
class Container {
public:
using value_type = T;
using size_type = size_t;
void add(const value_type& item) {
// Add implementation
cout << "Adding item to container" << endl;
}
size_type size() const {
return 0; // Simplified
}
};
void demonstrateTemplateUsing() {
Container<string> stringContainer;
Container<string>::value_type item = "test";
stringContainer.add(item);
Container<string>::size_type count = stringContainer.size();
cout << "Container size: " << count << endl;
}
"""
)
parsers, queries = load_parsers()
updater = GraphUpdater(
ingestor=mock_ingestor,
repo_path=cpp_namespaces_project,
parsers=parsers,
queries=queries,
)
updater.run()
project_name = cpp_namespaces_project.name
# Verify deeply nested namespace classes
expected_nested_classes = [
f"{project_name}.using_directives.company.project.module.DataProcessor",
f"{project_name}.using_directives.utils.StringUtils",
f"{project_name}.using_directives.MyClass",
f"{project_name}.using_directives.Container",
]
# Get all Class node creation calls
class_calls = [
call
for call in mock_ingestor.ensure_node_batch.call_args_list
if call[0][0] == "Class"
]
created_classes = {call[0][1]["qualified_name"] for call in class_calls}
# Verify nested namespace classes
found_nested_classes = [
cls for cls in expected_nested_classes if cls in created_classes
]
assert len(found_nested_classes) >= 2, (
f"Expected at least 2 nested namespace classes, found {len(found_nested_classes)}: {found_nested_classes}"
)
# Verify function calls that use qualified names
call_relationships = [
c
for c in cast(MagicMock, mock_ingestor.ensure_relationship_batch).call_args_list
if c.args[1] == "CALLS"
]
namespace_calls = [
call
for call in call_relationships
if "using_directives" in call.args[0][2]
and any(
name in call.args[2][2]
for name in ["helper", "process", "utility_function", "uppercase"]
)
]
assert len(namespace_calls) >= 4, (
f"Expected at least 4 namespace-related calls, found {len(namespace_calls)}"
)
def test_anonymous_namespaces(
cpp_namespaces_project: Path,
mock_ingestor: MagicMock,
) -> None:
"""Test anonymous namespaces and internal linkage."""
test_file = cpp_namespaces_project / "anonymous_namespaces.cpp"
test_file.write_text(
"""
#include <iostream>
#include <string>
// Anonymous namespace (internal linkage)
namespace {
void internal_function() {
std::cout << "Internal function called" << std::endl;
}
class InternalClass {
public:
void method() {
std::cout << "InternalClass method called" << std::endl;
}
static void static_method() {
std::cout << "InternalClass static method called" << std::endl;
}
};
const int INTERNAL_CONSTANT = 42;
// Nested anonymous namespace
namespace {
void deeply_internal() {
std::cout << "Deeply internal function" << std::endl;
}
}
}
// Named namespace with anonymous namespace inside
namespace outer {
namespace {
void outer_internal() {
std::cout << "Outer internal function" << std::endl;
}
class OuterInternalClass {
public:
void process() {
std::cout << "OuterInternalClass processing" << std::endl;
}
};
}
void public_function() {
std::cout << "Outer public function" << std::endl;
outer_internal(); // Can call anonymous namespace function
}
class PublicClass {
public:
void use_internal() {
OuterInternalClass internal;
internal.process();
}
};
}
// Another file-level anonymous namespace
namespace {
class AnotherInternalClass {
public:
void work() {
std::cout << "AnotherInternalClass working" << std::endl;
}
};
void another_internal_function() {
std::cout << "Another internal function" << std::endl;
}
}
void demonstrateAnonymousNamespaces() {
// Can use anonymous namespace members directly
internal_function();
deeply_internal();
another_internal_function();
InternalClass internal;
internal.method();
InternalClass::static_method();
AnotherInternalClass another;
another.work();
std::cout << "Internal constant: " << INTERNAL_CONSTANT << std::endl;
// Use named namespace with internal anonymous members
outer::public_function(); // This calls outer_internal() internally
outer::PublicClass publicObj;
publicObj.use_internal(); // This uses OuterInternalClass internally
}
// Template in anonymous namespace
namespace {
template<typename T>
class InternalTemplate {
public:
void process(const T& value) {
std::cout << "Processing internal template with value" << std::endl;
}
};
template<typename T>
T internal_max(T a, T b) {
return (a > b) ? a : b;
}
}
void demonstrateInternalTemplates() {
InternalTemplate<int> intTemplate;
intTemplate.process(42);
InternalTemplate<std::string> stringTemplate;
stringTemplate.process("hello");
int max_int = internal_max(10, 20);
double max_double = internal_max(3.14, 2.71);
std::cout << "Max int: " << max_int << std::endl;
std::cout << "Max double: " << max_double << std::endl;
}
// Static vs anonymous namespace comparison
static void static_function() {
std::cout << "Static function (C-style internal linkage)" << std::endl;
}
namespace {
void modern_internal_function() {
std::cout << "Anonymous namespace function (C++ style internal linkage)" << std::endl;
}
}
void compareLinkageStyles() {
static_function(); // C-style internal linkage
modern_internal_function(); // C++ style internal linkage
}
"""
)
parsers, queries = load_parsers()
updater = GraphUpdater(
ingestor=mock_ingestor,
repo_path=cpp_namespaces_project,
parsers=parsers,
queries=queries,
)
updater.run()
# Expected anonymous namespace classes (may have unique qualified names)
expected_internal_classes = [
"InternalClass",
"OuterInternalClass",
"AnotherInternalClass",
"InternalTemplate",
]
# Get all Class node creation calls
class_calls = [
call
for call in mock_ingestor.ensure_node_batch.call_args_list
if call[0][0] == "Class"
]
created_classes = {call[0][1]["qualified_name"] for call in class_calls}
# Verify anonymous namespace classes were created (they might have special naming)
found_internal_classes = [
cls
for cls in created_classes
if any(internal_name in cls for internal_name in expected_internal_classes)
]
assert len(found_internal_classes) >= 2, (
f"Expected at least 2 anonymous namespace classes, found {len(found_internal_classes)}: {found_internal_classes}"
)
# Expected internal functions
expected_internal_functions = [
"internal_function",
"deeply_internal",
"outer_internal",
"another_internal_function",
"static_function",
"modern_internal_function",
]
# Get all Function node creation calls
function_calls = [
call
for call in mock_ingestor.ensure_node_batch.call_args_list
if call[0][0] == "Function"
]
created_functions = {call[0][1]["qualified_name"] for call in function_calls}
# Verify internal functions were created
found_internal_functions = [
func
for func in created_functions
if any(internal_name in func for internal_name in expected_internal_functions)
]
assert len(found_internal_functions) >= 4, (
f"Expected at least 4 internal functions, found {len(found_internal_functions)}: {found_internal_functions}"
)
def test_cpp_namespaces_comprehensive(
cpp_namespaces_project: Path,
mock_ingestor: MagicMock,
) -> None:
"""Comprehensive test ensuring all namespace patterns create proper relationships."""
test_file = cpp_namespaces_project / "comprehensive_namespaces.cpp"
test_file.write_text(
"""
// Every C++ namespace pattern in one file
#include <iostream>
#include <string>
// Global namespace
void global_func() {
std::cout << "Global function" << std::endl;
}
// Basic namespace
namespace basic {
void func() {
std::cout << "Basic namespace function" << std::endl;
}
class Class {
public:
void method() {
std::cout << "Basic namespace class method" << std::endl;
}
};
}
// Nested namespaces
namespace outer {
namespace inner {
void nested_func() {
std::cout << "Nested namespace function" << std::endl;
}
class NestedClass {
public:
void process() {
std::cout << "Nested class processing" << std::endl;
}
};
}
void outer_func() {
inner::nested_func(); // Cross-namespace call
}
}
// Anonymous namespace
namespace {
void internal_func() {
std::cout << "Internal function" << std::endl;
}
class InternalClass {
public:
void work() {
std::cout << "Internal class working" << std::endl;
}
};
}
// Using directives
using namespace std;
using basic::Class;
namespace alias = outer::inner;
void demonstrateComprehensiveNamespaces() {
// Global namespace
global_func();
// Basic namespace - qualified calls
basic::func();
basic::Class basicObj;
basicObj.method();
// Nested namespace - qualified calls
outer::inner::nested_func();
outer::inner::NestedClass nestedObj;
nestedObj.process();
// Cross-namespace call
outer::outer_func(); // This calls inner::nested_func internally
// Anonymous namespace - direct calls
internal_func();
InternalClass internalObj;
internalObj.work();
// Using declarations
Class usingObj; // Uses basic::Class
usingObj.method();
// Namespace alias
alias::NestedClass aliasObj;
aliasObj.process();
// std namespace usage (from using namespace std)
string text = "Hello";
cout << text << endl;
}
// Template in namespace
namespace templates {
template<typename T>
class Container {
public:
void store(const T& item) {
cout << "Storing item in namespace template" << endl;
}
};
template<typename T>
T max_value(T a, T b) {
return (a > b) ? a : b;
}
}
// Namespace reopening
namespace basic {
void additional_func() {
cout << "Additional function in reopened namespace" << endl;
}
class AnotherClass {
public:
void work() {
cout << "Another class in reopened namespace" << endl;
}
};
}
void testNamespaceFeatures() {
// Template namespace usage
templates::Container<int> container;
container.store(42);
int max_val = templates::max_value(10, 20);
cout << "Max value: " << max_val << endl;
// Reopened namespace
basic::additional_func();
basic::AnotherClass another;
another.work();
// All namespace types together
basic::func(); // Basic namespace
outer::inner::nested_func(); // Nested namespace
internal_func(); // Anonymous namespace
global_func(); // Global namespace
}
"""
)
parsers, queries = load_parsers()
updater = GraphUpdater(
ingestor=mock_ingestor,
repo_path=cpp_namespaces_project,
parsers=parsers,
queries=queries,
)
updater.run()
# Verify all relationship types exist
all_relationships = cast(
MagicMock, mock_ingestor.ensure_relationship_batch
).call_args_list
call_relationships = [c for c in all_relationships if c.args[1] == "CALLS"]
defines_relationships = [c for c in all_relationships if c.args[1] == "DEFINES"]
# Should have comprehensive namespace coverage
comprehensive_calls = [
call
for call in call_relationships
if "comprehensive_namespaces" in call.args[0][2]
]
assert len(comprehensive_calls) >= 12, (
f"Expected at least 12 comprehensive namespace calls, found {len(comprehensive_calls)}"
)
# Verify cross-namespace calls
cross_namespace_calls = [
call
for call in comprehensive_calls
if any(
namespace_func in call.args[2][2]
for namespace_func in [
"basic.func",
"inner.nested_func",
"internal_func",
"global_func",
]
)
]
assert len(cross_namespace_calls) >= 4, (
f"Expected at least 4 cross-namespace calls, found {len(cross_namespace_calls)}"
)
# Test that namespace parsing doesn't interfere with other relationships
assert defines_relationships, "Should still have DEFINES relationships"