codegraph-python 0.4.1

Python parser plugin for CodeGraph - extracts code entities and relationships from Python source files
Documentation
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
//! Unit tests specifically for parser_impl.rs
//! Testing the PythonParser implementation details

use codegraph::CodeGraph;
use codegraph_parser_api::{CodeParser, ParserConfig, ParserError};
use codegraph_python::PythonParser;
use std::path::Path;
use tempfile::TempDir;

// ====================
// Configuration Tests
// ====================

#[test]
fn test_parser_default_config() {
    let parser = PythonParser::new();
    let config = parser.config();
    assert!(!config.skip_private);
    assert!(!config.skip_tests);
}

#[test]
fn test_parser_custom_config() {
    let config = ParserConfig {
        skip_private: true,
        skip_tests: true,
        max_file_size: 5000,
        ..Default::default()
    };
    let parser = PythonParser::with_config(config.clone());

    assert!(parser.config().skip_private);
    assert!(parser.config().skip_tests);
    assert_eq!(parser.config().max_file_size, 5000);
}

// ====================
// Metrics Tests
// ====================

#[test]
fn test_metrics_initial_state() {
    let parser = PythonParser::new();
    let metrics = parser.metrics();

    assert_eq!(metrics.files_attempted, 0);
    assert_eq!(metrics.files_succeeded, 0);
    assert_eq!(metrics.files_failed, 0);
    assert_eq!(metrics.total_entities, 0);
    assert_eq!(metrics.total_relationships, 0);
}

#[test]
fn test_metrics_after_successful_parse() {
    let parser = PythonParser::new();
    let mut graph = CodeGraph::in_memory().unwrap();

    let source = "def foo(): pass";
    parser
        .parse_source(source, Path::new("test.py"), &mut graph)
        .unwrap();

    let metrics = parser.metrics();
    assert_eq!(metrics.files_attempted, 1);
    assert_eq!(metrics.files_succeeded, 1);
    assert_eq!(metrics.files_failed, 0);
    assert!(metrics.total_entities > 0);
}

#[test]
fn test_metrics_after_failed_parse() {
    let parser = PythonParser::new();
    let mut graph = CodeGraph::in_memory().unwrap();

    let source = "def broken(\n    incomplete";
    let _ = parser.parse_source(source, Path::new("test.py"), &mut graph);

    let metrics = parser.metrics();
    assert_eq!(metrics.files_attempted, 1);
    assert_eq!(metrics.files_failed, 1);
}

#[test]
fn test_metrics_accumulation() {
    let parser = PythonParser::new();
    let mut graph = CodeGraph::in_memory().unwrap();

    // Parse multiple files
    parser
        .parse_source("def foo(): pass", Path::new("test1.py"), &mut graph)
        .unwrap();
    parser
        .parse_source("def bar(): pass", Path::new("test2.py"), &mut graph)
        .unwrap();
    parser
        .parse_source("class Baz: pass", Path::new("test3.py"), &mut graph)
        .unwrap();

    let metrics = parser.metrics();
    assert_eq!(metrics.files_attempted, 3);
    assert_eq!(metrics.files_succeeded, 3);
    assert!(metrics.total_entities >= 3);
}

#[test]
fn test_metrics_reset() {
    let mut parser = PythonParser::new();
    let mut graph = CodeGraph::in_memory().unwrap();

    parser
        .parse_source("def foo(): pass", Path::new("test.py"), &mut graph)
        .unwrap();

    let metrics_before = parser.metrics();
    assert!(metrics_before.files_succeeded > 0);

    parser.reset_metrics();

    let metrics_after = parser.metrics();
    assert_eq!(metrics_after.files_attempted, 0);
    assert_eq!(metrics_after.files_succeeded, 0);
    assert_eq!(metrics_after.total_entities, 0);
}

// ====================
// Parsing Tests
// ====================

#[test]
fn test_parse_empty_source() {
    let parser = PythonParser::new();
    let mut graph = CodeGraph::in_memory().unwrap();

    let result = parser.parse_source("", Path::new("empty.py"), &mut graph);
    assert!(result.is_ok());

    let file_info = result.unwrap();
    assert_eq!(file_info.functions.len(), 0);
    assert_eq!(file_info.classes.len(), 0);
}

#[test]
fn test_parse_comments_only() {
    let parser = PythonParser::new();
    let mut graph = CodeGraph::in_memory().unwrap();

    let source = r#"
# This is a comment
# Another comment
    "#;

    let result = parser.parse_source(source, Path::new("comments.py"), &mut graph);
    assert!(result.is_ok());

    let file_info = result.unwrap();
    assert_eq!(file_info.functions.len(), 0);
    assert_eq!(file_info.classes.len(), 0);
}

#[test]
fn test_parse_docstring_only() {
    let parser = PythonParser::new();
    let mut graph = CodeGraph::in_memory().unwrap();

    let source = r#"
"""
This is a module docstring.
"""
    "#;

    let result = parser.parse_source(source, Path::new("docstring.py"), &mut graph);
    assert!(result.is_ok());
}

#[test]
fn test_parse_simple_function() {
    let parser = PythonParser::new();
    let mut graph = CodeGraph::in_memory().unwrap();

    let source = r#"
def greet(name):
    return f"Hello, {name}!"
    "#;

    let result = parser.parse_source(source, Path::new("greet.py"), &mut graph);
    assert!(result.is_ok());

    let file_info = result.unwrap();
    assert_eq!(file_info.functions.len(), 1);
    assert_eq!(file_info.classes.len(), 0);
}

#[test]
fn test_parse_async_function() {
    let parser = PythonParser::new();
    let mut graph = CodeGraph::in_memory().unwrap();

    let source = r#"
async def fetch_data():
    return await some_api()
    "#;

    let result = parser.parse_source(source, Path::new("async.py"), &mut graph);
    assert!(result.is_ok());

    let file_info = result.unwrap();
    assert_eq!(file_info.functions.len(), 1);
}

#[test]
fn test_parse_class_simple() {
    let parser = PythonParser::new();
    let mut graph = CodeGraph::in_memory().unwrap();

    let source = r#"
class Person:
    def __init__(self, name):
        self.name = name
    "#;

    let result = parser.parse_source(source, Path::new("person.py"), &mut graph);
    assert!(result.is_ok());

    let file_info = result.unwrap();
    assert_eq!(file_info.classes.len(), 1);
    assert_eq!(file_info.functions.len(), 1); // __init__ method
}

#[test]
fn test_parse_class_with_inheritance() {
    let parser = PythonParser::new();
    let mut graph = CodeGraph::in_memory().unwrap();

    let source = r#"
class Animal:
    pass

class Dog(Animal):
    def bark(self):
        print("Woof!")
    "#;

    let result = parser.parse_source(source, Path::new("animals.py"), &mut graph);
    assert!(result.is_ok());

    let file_info = result.unwrap();
    assert_eq!(file_info.classes.len(), 2);
}

#[test]
fn test_parse_multiple_imports() {
    let parser = PythonParser::new();
    let mut graph = CodeGraph::in_memory().unwrap();

    let source = r#"
import os
import sys
from pathlib import Path
from typing import List, Dict
import numpy as np
    "#;

    let result = parser.parse_source(source, Path::new("imports.py"), &mut graph);
    assert!(result.is_ok());

    let file_info = result.unwrap();
    assert_eq!(file_info.imports.len(), 5);
}

#[test]
fn test_parse_decorators() {
    let parser = PythonParser::new();
    let mut graph = CodeGraph::in_memory().unwrap();

    let source = r#"
@decorator
def func1():
    pass

class MyClass:
    @property
    def prop(self):
        return self._value

    @staticmethod
    def static_method():
        pass

    @classmethod
    def class_method(cls):
        pass
    "#;

    let result = parser.parse_source(source, Path::new("decorators.py"), &mut graph);
    assert!(result.is_ok());

    let file_info = result.unwrap();
    assert!(!file_info.functions.is_empty());
}

// ====================
// Error Handling Tests
// ====================

#[test]
fn test_syntax_error_handling() {
    let parser = PythonParser::new();
    let mut graph = CodeGraph::in_memory().unwrap();

    let source = r#"
def broken(
    # Missing closing paren
    "#;

    let result = parser.parse_source(source, Path::new("broken.py"), &mut graph);
    assert!(result.is_err());

    match result {
        Err(ParserError::ParseError(path, msg)) => {
            assert_eq!(path, Path::new("broken.py"));
            assert!(!msg.is_empty());
        }
        _ => panic!("Expected ParseError"),
    }
}

#[test]
fn test_file_size_limit_in_parse_source() {
    let config = ParserConfig::default().with_max_file_size(50);
    let parser = PythonParser::with_config(config);
    let mut graph = CodeGraph::in_memory().unwrap();

    // Create source larger than 50 bytes
    let source = "# ".repeat(100); // 200 bytes

    let result = parser.parse_source(&source, Path::new("large.py"), &mut graph);
    assert!(result.is_err());

    match result {
        Err(ParserError::FileTooLarge(path, size)) => {
            assert_eq!(path, Path::new("large.py"));
            assert!(size > 50);
        }
        _ => panic!("Expected FileTooLarge error"),
    }
}

#[test]
fn test_invalid_file_extension() {
    let parser = PythonParser::new();
    let mut graph = CodeGraph::in_memory().unwrap();

    let temp_dir = TempDir::new().unwrap();
    let file_path = temp_dir.path().join("test.txt");
    std::fs::write(&file_path, "def foo(): pass").unwrap();

    let result = parser.parse_file(&file_path, &mut graph);
    assert!(result.is_err());
}

// ====================
// File Operations Tests
// ====================

#[test]
fn test_parse_file_success() {
    let parser = PythonParser::new();
    let mut graph = CodeGraph::in_memory().unwrap();

    let temp_dir = TempDir::new().unwrap();
    let file_path = temp_dir.path().join("test.py");
    std::fs::write(&file_path, "def foo(): pass").unwrap();

    let result = parser.parse_file(&file_path, &mut graph);
    assert!(result.is_ok());

    let file_info = result.unwrap();
    assert_eq!(file_info.functions.len(), 1);
    assert!(file_info.byte_count > 0);
}

#[test]
fn test_parse_file_not_found() {
    let parser = PythonParser::new();
    let mut graph = CodeGraph::in_memory().unwrap();

    let result = parser.parse_file(Path::new("/nonexistent/file.py"), &mut graph);
    assert!(result.is_err());

    match result {
        Err(ParserError::IoError(_, _)) => (),
        _ => panic!("Expected IoError"),
    }
}

#[test]
fn test_parse_file_too_large() {
    let config = ParserConfig::default().with_max_file_size(10);
    let parser = PythonParser::with_config(config);
    let mut graph = CodeGraph::in_memory().unwrap();

    let temp_dir = TempDir::new().unwrap();
    let file_path = temp_dir.path().join("large.py");
    std::fs::write(&file_path, "# This is more than 10 bytes").unwrap();

    let result = parser.parse_file(&file_path, &mut graph);
    assert!(result.is_err());

    match result {
        Err(ParserError::FileTooLarge(_, _)) => (),
        _ => panic!("Expected FileTooLarge error"),
    }
}

// ====================
// Multiple Files Tests
// ====================

#[test]
fn test_parse_files_all_success() {
    let parser = PythonParser::new();
    let mut graph = CodeGraph::in_memory().unwrap();

    let temp_dir = TempDir::new().unwrap();
    let file1 = temp_dir.path().join("file1.py");
    let file2 = temp_dir.path().join("file2.py");
    let file3 = temp_dir.path().join("file3.py");

    std::fs::write(&file1, "def foo(): pass").unwrap();
    std::fs::write(&file2, "class Bar: pass").unwrap();
    std::fs::write(&file3, "import os").unwrap();

    let paths = vec![file1, file2, file3];
    let result = parser.parse_files(&paths, &mut graph);

    assert!(result.is_ok());
    let project_info = result.unwrap();
    assert_eq!(project_info.files.len(), 3);
    assert_eq!(project_info.failed_files.len(), 0);
    assert_eq!(project_info.total_functions, 1);
    assert_eq!(project_info.total_classes, 1);
}

#[test]
fn test_parse_files_partial_failure() {
    let parser = PythonParser::new();
    let mut graph = CodeGraph::in_memory().unwrap();

    let temp_dir = TempDir::new().unwrap();
    let file1 = temp_dir.path().join("good.py");
    let file2 = temp_dir.path().join("bad.py");

    std::fs::write(&file1, "def foo(): pass").unwrap();
    std::fs::write(&file2, "def broken(\n    incomplete").unwrap();

    let paths = vec![file1, file2];
    let result = parser.parse_files(&paths, &mut graph);

    assert!(result.is_ok());
    let project_info = result.unwrap();
    assert_eq!(project_info.files.len(), 1);
    assert_eq!(project_info.failed_files.len(), 1);
}

#[test]
fn test_parse_directory_recursive() {
    let parser = PythonParser::new();
    let mut graph = CodeGraph::in_memory().unwrap();

    let temp_dir = TempDir::new().unwrap();

    // Create files in root
    std::fs::write(temp_dir.path().join("file1.py"), "def foo(): pass").unwrap();

    // Create subdirectory with files
    let subdir = temp_dir.path().join("subdir");
    std::fs::create_dir(&subdir).unwrap();
    std::fs::write(subdir.join("file2.py"), "def bar(): pass").unwrap();

    // Create nested subdirectory
    let nested = subdir.join("nested");
    std::fs::create_dir(&nested).unwrap();
    std::fs::write(nested.join("file3.py"), "def baz(): pass").unwrap();

    let result = parser.parse_directory(temp_dir.path(), &mut graph);
    assert!(result.is_ok());

    let project_info = result.unwrap();
    assert_eq!(project_info.files.len(), 3);
}

#[test]
fn test_parse_directory_empty() {
    let parser = PythonParser::new();
    let mut graph = CodeGraph::in_memory().unwrap();

    let temp_dir = TempDir::new().unwrap();

    let result = parser.parse_directory(temp_dir.path(), &mut graph);
    assert!(result.is_ok());

    let project_info = result.unwrap();
    assert_eq!(project_info.files.len(), 0);
}

// ====================
// Special Cases Tests
// ====================

#[test]
fn test_parse_private_functions_included() {
    let parser = PythonParser::new();
    let mut graph = CodeGraph::in_memory().unwrap();

    let source = r#"
def public_func():
    pass

def _private_func():
    pass

def __very_private():
    pass
    "#;

    let result = parser.parse_source(source, Path::new("test.py"), &mut graph);
    assert!(result.is_ok());

    let file_info = result.unwrap();
    assert_eq!(file_info.functions.len(), 3); // All functions included by default
}

#[test]
fn test_parse_private_functions_excluded() {
    let config = ParserConfig {
        skip_private: true,
        ..Default::default()
    };
    let parser = PythonParser::with_config(config);
    let mut graph = CodeGraph::in_memory().unwrap();

    let source = r#"
def public_func():
    pass

def _private_func():
    pass
    "#;

    let result = parser.parse_source(source, Path::new("test.py"), &mut graph);
    assert!(result.is_ok());

    let file_info = result.unwrap();
    assert_eq!(file_info.functions.len(), 1); // Only public function
}

#[test]
fn test_parse_test_functions_included() {
    let parser = PythonParser::new();
    let mut graph = CodeGraph::in_memory().unwrap();

    let source = r#"
def test_something():
    assert True

def regular_function():
    pass
    "#;

    let result = parser.parse_source(source, Path::new("test.py"), &mut graph);
    assert!(result.is_ok());

    let file_info = result.unwrap();
    assert_eq!(file_info.functions.len(), 2); // Both included by default
}

#[test]
fn test_parse_test_functions_excluded() {
    let config = ParserConfig {
        skip_tests: true,
        ..Default::default()
    };
    let parser = PythonParser::with_config(config);
    let mut graph = CodeGraph::in_memory().unwrap();

    let source = r#"
def test_something():
    assert True

def regular_function():
    pass
    "#;

    let result = parser.parse_source(source, Path::new("test.py"), &mut graph);
    assert!(result.is_ok());

    let file_info = result.unwrap();
    assert_eq!(file_info.functions.len(), 1); // Test function excluded
}

#[test]
fn test_complex_nested_structures() {
    let parser = PythonParser::new();
    let mut graph = CodeGraph::in_memory().unwrap();

    let source = r#"
class Outer:
    class Inner:
        def inner_method(self):
            def nested_function():
                pass
            return nested_function

    def outer_method(self):
        pass
    "#;

    let result = parser.parse_source(source, Path::new("nested.py"), &mut graph);
    assert!(result.is_ok());

    // The parser should handle nested structures
    let file_info = result.unwrap();
    assert!(!file_info.classes.is_empty());
}