Repository navigation
Expand file tree
/
Copy pathtest_cpp_smart_pointers.py
More file actions
1653 lines (1321 loc) · 45.9 KB
/
Copy pathtest_cpp_smart_pointers.py
File metadata and controls
1653 lines (1321 loc) · 45.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
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
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Comprehensive C++ smart pointers testing.
Tests unique_ptr, shared_ptr, weak_ptr, custom deleters, and various memory management patterns.
"""
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_smart_pointers_project(temp_repo: Path) -> Path:
"""Create a comprehensive C++ project with smart pointer patterns."""
project_path = temp_repo / "cpp_smart_pointers_test"
project_path.mkdir()
# Create basic structure
(project_path / "src").mkdir()
(project_path / "include").mkdir()
return project_path
def test_unique_ptr_patterns(
cpp_smart_pointers_project: Path,
mock_ingestor: MagicMock,
) -> None:
"""Test unique_ptr usage patterns and ownership semantics."""
test_file = cpp_smart_pointers_project / "unique_ptr_patterns.cpp"
test_file.write_text(
"""
#include <iostream>
#include <memory>
#include <vector>
#include <string>
#include <utility>
// Simple resource class
class Resource {
private:
std::string name_;
int value_;
public:
Resource(const std::string& name, int value)
: name_(name), value_(value) {
std::cout << "Resource " << name_ << " created" << std::endl;
}
~Resource() {
std::cout << "Resource " << name_ << " destroyed" << std::endl;
}
// Delete copy operations
Resource(const Resource&) = delete;
Resource& operator=(const Resource&) = delete;
// Allow move operations
Resource(Resource&& other) noexcept
: name_(std::move(other.name_)), value_(other.value_) {
other.value_ = 0;
}
Resource& operator=(Resource&& other) noexcept {
if (this != &other) {
name_ = std::move(other.name_);
value_ = other.value_;
other.value_ = 0;
}
return *this;
}
void use() const {
std::cout << "Using resource " << name_ << " with value " << value_ << std::endl;
}
const std::string& getName() const { return name_; }
int getValue() const { return value_; }
};
// Factory function returning unique_ptr
std::unique_ptr<Resource> createResource(const std::string& name, int value) {
return std::make_unique<Resource>(name, value);
}
// Function taking ownership
void takeOwnership(std::unique_ptr<Resource> resource) {
std::cout << "Taking ownership of " << resource->getName() << std::endl;
resource->use();
// Resource will be destroyed when function exits
}
// Function borrowing resource
void borrowResource(const Resource* resource) {
if (resource) {
std::cout << "Borrowing " << resource->getName() << std::endl;
resource->use();
}
}
// Container managing unique_ptr collection
class ResourceManager {
private:
std::vector<std::unique_ptr<Resource>> resources_;
public:
void addResource(std::unique_ptr<Resource> resource) {
resources_.push_back(std::move(resource));
}
void addResource(const std::string& name, int value) {
resources_.push_back(std::make_unique<Resource>(name, value));
}
Resource* getResource(size_t index) {
if (index < resources_.size()) {
return resources_[index].get();
}
return nullptr;
}
std::unique_ptr<Resource> releaseResource(size_t index) {
if (index < resources_.size()) {
auto resource = std::move(resources_[index]);
resources_.erase(resources_.begin() + index);
return resource;
}
return nullptr;
}
void clearAll() {
resources_.clear();
}
size_t size() const { return resources_.size(); }
void useAll() const {
for (const auto& resource : resources_) {
if (resource) {
resource->use();
}
}
}
};
// Custom deleter example
struct FileDeleter {
void operator()(FILE* file) const {
if (file) {
std::cout << "Closing file with custom deleter" << std::endl;
fclose(file);
}
}
};
// Array deleter
template<typename T>
struct ArrayDeleter {
void operator()(T* array) const {
std::cout << "Deleting array with custom deleter" << std::endl;
delete[] array;
}
};
// Smart pointer wrapper for legacy APIs
class LegacyResourceWrapper {
private:
std::unique_ptr<void, std::function<void(void*)>> resource_;
public:
LegacyResourceWrapper(void* resource, std::function<void(void*)> deleter)
: resource_(resource, deleter) {}
void* get() const { return resource_.get(); }
void* release() { return resource_.release(); }
};
void demonstrateUniquePtrBasics() {
std::cout << "=== Unique Pointer Basics ===" << std::endl;
// Basic creation and destruction
{
auto resource = std::make_unique<Resource>("Basic", 100);
resource->use();
} // Resource destroyed here
// Moving ownership
auto resource1 = std::make_unique<Resource>("Movable", 200);
auto resource2 = std::move(resource1);
// resource1 is now empty
if (!resource1) {
std::cout << "resource1 is empty after move" << std::endl;
}
resource2->use();
// Factory pattern
auto factoryResource = createResource("Factory", 300);
factoryResource->use();
// Passing ownership
auto transferResource = std::make_unique<Resource>("Transfer", 400);
takeOwnership(std::move(transferResource));
// transferResource is now empty
// Borrowing without ownership
auto borrowedResource = std::make_unique<Resource>("Borrowed", 500);
borrowResource(borrowedResource.get());
// borrowedResource still owns the resource
// Reset and release
auto resetResource = std::make_unique<Resource>("Reset", 600);
resetResource.reset(); // Destroys current resource
resetResource = std::make_unique<Resource>("New", 700);
Resource* rawPtr = resetResource.release(); // Releases ownership
delete rawPtr; // Manual cleanup required
}
void demonstrateUniquePtrContainers() {
std::cout << "=== Unique Pointer Containers ===" << std::endl;
ResourceManager manager;
// Add resources
manager.addResource(std::make_unique<Resource>("First", 1));
manager.addResource("Second", 2);
manager.addResource(createResource("Third", 3));
// Use resources
manager.useAll();
// Borrow a resource
if (auto* resource = manager.getResource(1)) {
borrowResource(resource);
}
// Transfer ownership out
auto extracted = manager.releaseResource(0);
if (extracted) {
std::cout << "Extracted: ";
extracted->use();
}
std::cout << "Remaining resources: " << manager.size() << std::endl;
manager.useAll();
// Clear all
manager.clearAll();
std::cout << "After clear: " << manager.size() << " resources" << std::endl;
}
void demonstrateCustomDeleters() {
std::cout << "=== Custom Deleters ===" << std::endl;
// File with custom deleter
{
std::unique_ptr<FILE, FileDeleter> file(
fopen("test.txt", "w"),
FileDeleter()
);
if (file) {
fprintf(file.get(), "Hello from unique_ptr\n");
}
} // File automatically closed
// Array with custom deleter
{
std::unique_ptr<int, ArrayDeleter<int>> array(
new int[5]{1, 2, 3, 4, 5},
ArrayDeleter<int>()
);
for (int i = 0; i < 5; ++i) {
std::cout << "Array[" << i << "] = " << array.get()[i] << std::endl;
}
} // Array deleted with custom deleter
// Lambda deleter
{
auto deleter = [](Resource* r) {
std::cout << "Lambda deleter for " << r->getName() << std::endl;
delete r;
};
std::unique_ptr<Resource, decltype(deleter)> resource(
new Resource("Lambda", 800),
deleter
);
resource->use();
}
// Function deleter
{
auto customFree = [](void* ptr) {
std::cout << "Custom free function" << std::endl;
free(ptr);
};
std::unique_ptr<char, decltype(customFree)> buffer(
static_cast<char*>(malloc(100)),
customFree
);
if (buffer) {
strcpy(buffer.get(), "Hello");
std::cout << "Buffer: " << buffer.get() << std::endl;
}
}
}
// Polymorphic unique_ptr
class Base {
public:
virtual ~Base() = default;
virtual void process() const = 0;
};
class DerivedA : public Base {
public:
void process() const override {
std::cout << "DerivedA processing" << std::endl;
}
};
class DerivedB : public Base {
public:
void process() const override {
std::cout << "DerivedB processing" << std::endl;
}
};
std::unique_ptr<Base> createPolymorphic(char type) {
switch (type) {
case 'A':
return std::make_unique<DerivedA>();
case 'B':
return std::make_unique<DerivedB>();
default:
return nullptr;
}
}
void demonstratePolymorphicUniquePtr() {
std::cout << "=== Polymorphic Unique Pointers ===" << std::endl;
std::vector<std::unique_ptr<Base>> polymorphic;
polymorphic.push_back(createPolymorphic('A'));
polymorphic.push_back(createPolymorphic('B'));
polymorphic.push_back(std::make_unique<DerivedA>());
for (const auto& ptr : polymorphic) {
if (ptr) {
ptr->process();
}
}
}
"""
)
parsers, queries = load_parsers()
updater = GraphUpdater(
ingestor=mock_ingestor,
repo_path=cpp_smart_pointers_project,
parsers=parsers,
queries=queries,
)
updater.run()
project_name = cpp_smart_pointers_project.name
# Expected unique_ptr related classes and functions
expected_entities = [
f"{project_name}.unique_ptr_patterns.Resource",
f"{project_name}.unique_ptr_patterns.ResourceManager",
f"{project_name}.unique_ptr_patterns.FileDeleter",
f"{project_name}.unique_ptr_patterns.createResource",
f"{project_name}.unique_ptr_patterns.demonstrateUniquePtrBasics",
]
# Get all node creation calls
all_calls = mock_ingestor.ensure_node_batch.call_args_list
class_calls = [call for call in all_calls if call[0][0] == "Class"]
function_calls = [call for call in all_calls if call[0][0] == "Function"]
created_entities = {
call[0][1]["qualified_name"] for call in class_calls + function_calls
}
# Verify expected entities were created
found_entities = [
entity for entity in expected_entities if entity in created_entities
]
assert len(found_entities) >= 4, (
f"Expected at least 4 unique_ptr entities, found {len(found_entities)}: {found_entities}"
)
def test_shared_ptr_patterns(
cpp_smart_pointers_project: Path,
mock_ingestor: MagicMock,
) -> None:
"""Test shared_ptr usage patterns and reference counting."""
test_file = cpp_smart_pointers_project / "shared_ptr_patterns.cpp"
test_file.write_text(
"""
#include <iostream>
#include <memory>
#include <vector>
#include <map>
#include <thread>
#include <mutex>
// Node for circular reference demonstration
class Node {
private:
std::string name_;
std::shared_ptr<Node> next_;
std::weak_ptr<Node> parent_; // Use weak_ptr to avoid cycles
public:
Node(const std::string& name) : name_(name) {
std::cout << "Node " << name_ << " created" << std::endl;
}
~Node() {
std::cout << "Node " << name_ << " destroyed" << std::endl;
}
void setNext(std::shared_ptr<Node> node) {
next_ = node;
}
void setParent(std::shared_ptr<Node> node) {
parent_ = node;
}
std::shared_ptr<Node> getNext() const { return next_; }
std::shared_ptr<Node> getParent() const {
return parent_.lock(); // Convert weak_ptr to shared_ptr
}
const std::string& getName() const { return name_; }
void printChain() const {
std::cout << name_;
if (next_) {
std::cout << " -> ";
next_->printChain();
} else {
std::cout << std::endl;
}
}
};
// Observer pattern with weak_ptr
class Subject;
class Observer {
public:
virtual ~Observer() = default;
virtual void update(const Subject* subject) = 0;
};
class Subject {
private:
std::vector<std::weak_ptr<Observer>> observers_;
std::string state_;
mutable std::mutex mutex_;
public:
void attach(std::shared_ptr<Observer> observer) {
std::lock_guard<std::mutex> lock(mutex_);
observers_.push_back(observer);
}
void setState(const std::string& state) {
{
std::lock_guard<std::mutex> lock(mutex_);
state_ = state;
}
notify();
}
std::string getState() const {
std::lock_guard<std::mutex> lock(mutex_);
return state_;
}
private:
void notify() {
std::lock_guard<std::mutex> lock(mutex_);
// Remove expired observers
observers_.erase(
std::remove_if(observers_.begin(), observers_.end(),
[](const std::weak_ptr<Observer>& wp) { return wp.expired(); }),
observers_.end()
);
// Notify remaining observers
for (const auto& wp : observers_) {
if (auto observer = wp.lock()) {
observer->update(this);
}
}
}
};
class ConcreteObserver : public Observer,
public std::enable_shared_from_this<ConcreteObserver> {
private:
std::string name_;
public:
ConcreteObserver(const std::string& name) : name_(name) {}
void update(const Subject* subject) override {
std::cout << name_ << " received update: " << subject->getState() << std::endl;
}
void registerWith(std::shared_ptr<Subject> subject) {
subject->attach(shared_from_this());
}
};
// Cache with shared_ptr
template<typename Key, typename Value>
class Cache {
private:
mutable std::map<Key, std::shared_ptr<Value>> cache_;
mutable std::mutex mutex_;
size_t max_size_;
public:
Cache(size_t max_size = 100) : max_size_(max_size) {}
void put(const Key& key, std::shared_ptr<Value> value) {
std::lock_guard<std::mutex> lock(mutex_);
if (cache_.size() >= max_size_ && cache_.find(key) == cache_.end()) {
// Remove oldest entry (simplified - just remove first)
cache_.erase(cache_.begin());
}
cache_[key] = value;
}
std::shared_ptr<Value> get(const Key& key) const {
std::lock_guard<std::mutex> lock(mutex_);
auto it = cache_.find(key);
if (it != cache_.end()) {
return it->second;
}
return nullptr;
}
size_t size() const {
std::lock_guard<std::mutex> lock(mutex_);
return cache_.size();
}
void clear() {
std::lock_guard<std::mutex> lock(mutex_);
cache_.clear();
}
};
// Thread-safe reference counting
class ThreadSafeResource {
private:
std::string data_;
mutable std::mutex mutex_;
public:
ThreadSafeResource(const std::string& data) : data_(data) {
std::cout << "ThreadSafeResource created: " << data_ << std::endl;
}
~ThreadSafeResource() {
std::cout << "ThreadSafeResource destroyed: " << data_ << std::endl;
}
void modify(const std::string& newData) {
std::lock_guard<std::mutex> lock(mutex_);
data_ = newData;
}
std::string read() const {
std::lock_guard<std::mutex> lock(mutex_);
return data_;
}
};
void demonstrateSharedPtrBasics() {
std::cout << "=== Shared Pointer Basics ===" << std::endl;
// Basic creation
auto shared1 = std::make_shared<Node>("First");
std::cout << "Reference count: " << shared1.use_count() << std::endl;
// Copy increases reference count
{
auto shared2 = shared1;
std::cout << "Reference count after copy: " << shared1.use_count() << std::endl;
auto shared3 = shared1;
std::cout << "Reference count with 3 pointers: " << shared1.use_count() << std::endl;
} // shared2 and shared3 destroyed, count decreases
std::cout << "Reference count after scope: " << shared1.use_count() << std::endl;
// Move doesn't increase count
auto shared4 = std::make_shared<Node>("Second");
auto shared5 = std::move(shared4);
if (!shared4) {
std::cout << "shared4 is empty after move" << std::endl;
}
std::cout << "shared5 count: " << shared5.use_count() << std::endl;
// Reset
shared1.reset(); // Decreases count, may destroy object
std::cout << "After reset, shared1 is " << (shared1 ? "valid" : "empty") << std::endl;
}
void demonstrateCircularReferences() {
std::cout << "=== Circular References ===" << std::endl;
// Problem: circular reference with shared_ptr
{
auto node1 = std::make_shared<Node>("Circular1");
auto node2 = std::make_shared<Node>("Circular2");
// This would create a circular reference if next_ was shared_ptr for both
// node1->setNext(node2);
// node2->setNext(node1); // Memory leak!
// Solution: use weak_ptr for one direction
node1->setNext(node2);
node2->setParent(node1); // parent_ is weak_ptr
std::cout << "node1 count: " << node1.use_count() << std::endl;
std::cout << "node2 count: " << node2.use_count() << std::endl;
} // Both nodes properly destroyed
// Linked list with proper cleanup
{
auto head = std::make_shared<Node>("Head");
auto middle = std::make_shared<Node>("Middle");
auto tail = std::make_shared<Node>("Tail");
head->setNext(middle);
middle->setNext(tail);
// Set parents using weak_ptr
middle->setParent(head);
tail->setParent(middle);
head->printChain();
} // All nodes properly destroyed
}
void demonstrateObserverPattern() {
std::cout << "=== Observer Pattern with weak_ptr ===" << std::endl;
auto subject = std::make_shared<Subject>();
{
auto observer1 = std::make_shared<ConcreteObserver>("Observer1");
auto observer2 = std::make_shared<ConcreteObserver>("Observer2");
observer1->registerWith(subject);
observer2->registerWith(subject);
subject->setState("State A");
{
auto observer3 = std::make_shared<ConcreteObserver>("Observer3");
observer3->registerWith(subject);
subject->setState("State B");
} // observer3 destroyed
subject->setState("State C"); // observer3 automatically removed
} // observer1 and observer2 destroyed
subject->setState("State D"); // No observers, but no crash
}
void demonstrateThreadSafety() {
std::cout << "=== Thread Safety with shared_ptr ===" << std::endl;
auto resource = std::make_shared<ThreadSafeResource>("Shared Data");
std::vector<std::thread> threads;
// Multiple threads sharing the resource
for (int i = 0; i < 5; ++i) {
threads.emplace_back([resource, i]() {
// Each thread has its own shared_ptr copy
std::cout << "Thread " << i << " count: " << resource.use_count() << std::endl;
resource->modify("Modified by thread " + std::to_string(i));
std::this_thread::sleep_for(std::chrono::milliseconds(10));
std::cout << "Thread " << i << " read: " << resource->read() << std::endl;
});
}
for (auto& t : threads) {
t.join();
}
std::cout << "Final count: " << resource.use_count() << std::endl;
}
void demonstrateCaching() {
std::cout << "=== Caching with shared_ptr ===" << std::endl;
Cache<std::string, Node> cache(3);
// Add items to cache
cache.put("node1", std::make_shared<Node>("Cached1"));
cache.put("node2", std::make_shared<Node>("Cached2"));
cache.put("node3", std::make_shared<Node>("Cached3"));
// Retrieve from cache
if (auto node = cache.get("node2")) {
std::cout << "Retrieved from cache: " << node->getName() << std::endl;
std::cout << "Reference count: " << node.use_count() << std::endl;
}
// Add more items (causes eviction)
cache.put("node4", std::make_shared<Node>("Cached4"));
// Try to get evicted item
if (!cache.get("node1")) {
std::cout << "node1 was evicted from cache" << std::endl;
}
std::cout << "Cache size: " << cache.size() << std::endl;
// Clear cache
cache.clear();
std::cout << "Cache size after clear: " << cache.size() << std::endl;
}
// Custom allocator
template<typename T>
struct CustomAllocator {
using value_type = T;
T* allocate(std::size_t n) {
std::cout << "Custom allocating " << n << " objects" << std::endl;
return static_cast<T*>(::operator new(n * sizeof(T)));
}
void deallocate(T* p, std::size_t n) {
std::cout << "Custom deallocating " << n << " objects" << std::endl;
::operator delete(p);
}
};
void demonstrateAllocators() {
std::cout << "=== Custom Allocators ===" << std::endl;
// Allocate shared
auto ptr1 = std::allocate_shared<Node>(CustomAllocator<Node>(), "AllocatedNode");
ptr1->printChain();
// Array allocation
auto array = std::shared_ptr<int[]>(new int[5]{1, 2, 3, 4, 5});
for (int i = 0; i < 5; ++i) {
std::cout << "Array[" << i << "] = " << array[i] << std::endl;
}
}
"""
)
parsers, queries = load_parsers()
updater = GraphUpdater(
ingestor=mock_ingestor,
repo_path=cpp_smart_pointers_project,
parsers=parsers,
queries=queries,
)
updater.run()
project_name = cpp_smart_pointers_project.name
# Expected shared_ptr related classes
expected_classes = [
f"{project_name}.shared_ptr_patterns.Node",
f"{project_name}.shared_ptr_patterns.Observer",
f"{project_name}.shared_ptr_patterns.Subject",
f"{project_name}.shared_ptr_patterns.ConcreteObserver",
f"{project_name}.shared_ptr_patterns.Cache",
]
# 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 expected classes were created
found_classes = [cls for cls in expected_classes if cls in created_classes]
assert len(found_classes) >= 4, (
f"Expected at least 4 shared_ptr classes, found {len(found_classes)}: {found_classes}"
)
def test_weak_ptr_and_advanced_patterns(
cpp_smart_pointers_project: Path,
mock_ingestor: MagicMock,
) -> None:
"""Test weak_ptr usage and advanced smart pointer patterns."""
test_file = cpp_smart_pointers_project / "weak_ptr_advanced.cpp"
test_file.write_text(
"""
#include <iostream>
#include <memory>
#include <vector>
#include <unordered_map>
#include <functional>
// Tree structure with parent-child relationships
class TreeNode : public std::enable_shared_from_this<TreeNode> {
private:
std::string name_;
std::weak_ptr<TreeNode> parent_;
std::vector<std::shared_ptr<TreeNode>> children_;
public:
TreeNode(const std::string& name) : name_(name) {
std::cout << "TreeNode " << name_ << " created" << std::endl;
}
~TreeNode() {
std::cout << "TreeNode " << name_ << " destroyed" << std::endl;
}
void addChild(std::shared_ptr<TreeNode> child) {
children_.push_back(child);
child->parent_ = weak_from_this();
}
std::shared_ptr<TreeNode> getParent() const {
return parent_.lock();
}
const std::vector<std::shared_ptr<TreeNode>>& getChildren() const {
return children_;
}
std::string getPath() const {
if (auto p = parent_.lock()) {
return p->getPath() + "/" + name_;
}
return "/" + name_;
}
void printTree(int depth = 0) const {
std::string indent(depth * 2, ' ');
std::cout << indent << name_ << std::endl;
for (const auto& child : children_) {
child->printTree(depth + 1);
}
}
// Safe self-reference
std::shared_ptr<TreeNode> getSharedPtr() {
return shared_from_this();
}
// Weak self-reference
std::weak_ptr<TreeNode> weak_from_this() {
return shared_from_this();
}
};
// Event system with weak callbacks
class EventManager {
private:
using Callback = std::function<void(const std::string&)>;
using WeakCallback = std::pair<std::weak_ptr<void>, Callback>;
std::unordered_map<std::string, std::vector<WeakCallback>> listeners_;
public:
void subscribe(const std::string& event,
std::shared_ptr<void> owner,
Callback callback) {
listeners_[event].emplace_back(owner, callback);
}
void emit(const std::string& event, const std::string& data) {
auto it = listeners_.find(event);
if (it == listeners_.end()) return;
// Clean up expired listeners while emitting
auto& callbacks = it->second;
callbacks.erase(
std::remove_if(callbacks.begin(), callbacks.end(),
[&data](WeakCallback& wc) {
if (auto owner = wc.first.lock()) {
wc.second(data);
return false;
}
return true; // Remove expired
}),
callbacks.end()
);
}
size_t getListenerCount(const std::string& event) const {
auto it = listeners_.find(event);
if (it != listeners_.end()) {
return it->second.size();
}
return 0;
}
};
// Resource pool with weak references
template<typename T>
class ResourcePool {
private:
std::vector<std::weak_ptr<T>> available_;
std::vector<std::shared_ptr<T>> all_resources_;
std::function<std::shared_ptr<T>()> factory_;
public:
ResourcePool(std::function<std::shared_ptr<T>()> factory)
: factory_(factory) {}
std::shared_ptr<T> acquire() {
// Try to find an available resource
for (auto it = available_.begin(); it != available_.end(); ) {
if (auto resource = it->lock()) {
available_.erase(it);
return resource;
} else {
// Remove expired weak_ptr
it = available_.erase(it);
}
}
// Create new resource if none available
auto resource = factory_();
all_resources_.push_back(resource);
return resource;
}
void release(std::shared_ptr<T> resource) {
available_.push_back(resource);
}
size_t totalSize() const { return all_resources_.size(); }
size_t availableSize() const { return available_.size(); }
void cleanup() {
// Remove expired resources
available_.erase(
std::remove_if(available_.begin(), available_.end(),
[](const std::weak_ptr<T>& wp) { return wp.expired(); }),
available_.end()
);
all_resources_.erase(
std::remove_if(all_resources_.begin(), all_resources_.end(),
[](const std::shared_ptr<T>& sp) { return sp.use_count() == 1; }),
all_resources_.end()
);
}
};
// Cycle detection using weak_ptr
class GraphNode {
private:
std::string name_;
std::vector<std::shared_ptr<GraphNode>> strong_edges_;
std::vector<std::weak_ptr<GraphNode>> weak_edges_;
public:
GraphNode(const std::string& name) : name_(name) {}