-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_abstract_inheritance.py
More file actions
executable file
·463 lines (383 loc) · 11.1 KB
/
test_abstract_inheritance.py
File metadata and controls
executable file
·463 lines (383 loc) · 11.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
#!/usr/bin/env python3
"""
Comprehensive test suite for abstract method inheritance tracking feature.
This script creates various test scenarios to validate:
1. Abstract methods can document Returns/Raises/Yields without errors
2. Cross-file inheritance tracking works correctly
3. Implementations are validated against abstract contracts
4. D070/D071/D072 error codes are properly triggered
"""
import os
import subprocess
import tempfile
import shutil
from pathlib import Path
class TestRunner:
"""Helper class to run vipyrdocs tests."""
def __init__(self, vipyrdocs_path):
self.vipyrdocs_path = vipyrdocs_path
self.test_results = []
def run_test(self, test_name, files_dict, expected_errors):
"""
Run a test case.
Args:
test_name: Name of the test
files_dict: Dict of filename -> content
expected_errors: List of expected error codes (e.g., ['D070', 'D030'])
"""
print(f"\n{'='*60}")
print(f"Test: {test_name}")
print(f"{'='*60}")
# Create temp directory
with tempfile.TemporaryDirectory() as tmpdir:
# Write files
for filename, content in files_dict.items():
filepath = Path(tmpdir) / filename
filepath.write_text(content)
print(f"Created: {filename}")
# Run vipyrdocs
result = subprocess.run(
[self.vipyrdocs_path, tmpdir],
capture_output=True,
text=True
)
print(f"\nExit code: {result.returncode}")
print(f"\nOutput:\n{result.stdout}")
if result.stderr:
print(f"\nErrors:\n{result.stderr}")
# Check for expected errors
found_errors = []
for error_code in expected_errors:
if error_code in result.stdout:
found_errors.append(error_code)
print(f"✓ Found expected error: {error_code}")
else:
print(f"✗ Missing expected error: {error_code}")
# Check for unexpected errors
all_error_codes = ['D010', 'D020', 'D030', 'D031', 'D040', 'D041',
'D050', 'D051', 'D060', 'D070', 'D071', 'D072']
unexpected = [code for code in all_error_codes
if code in result.stdout and code not in expected_errors]
if unexpected:
print(f"✗ Unexpected errors: {unexpected}")
success = (set(found_errors) == set(expected_errors) and
len(unexpected) == 0)
self.test_results.append({
'name': test_name,
'success': success,
'found': found_errors,
'expected': expected_errors,
'unexpected': unexpected
})
return success
def print_summary(self):
"""Print test summary."""
print(f"\n{'='*60}")
print("TEST SUMMARY")
print(f"{'='*60}")
passed = sum(1 for t in self.test_results if t['success'])
total = len(self.test_results)
for result in self.test_results:
status = "✓ PASS" if result['success'] else "✗ FAIL"
print(f"{status}: {result['name']}")
if not result['success']:
print(f" Expected: {result['expected']}")
print(f" Found: {result['found']}")
if result['unexpected']:
print(f" Unexpected: {result['unexpected']}")
print(f"\nTotal: {passed}/{total} passed")
return passed == total
def main():
# Find vipyrdocs binary
vipyrdocs_paths = [
'./target/release/vipyrdocs',
'./target/x86_64-unknown-linux-gnu/release/vipyrdocs',
'../target/release/vipyrdocs',
]
vipyrdocs_path = None
for path in vipyrdocs_paths:
if os.path.exists(path):
vipyrdocs_path = path
break
if not vipyrdocs_path:
print("Error: Could not find vipyrdocs binary")
print("Please build it first: cargo build --release")
return 1
print(f"Using vipyrdocs: {vipyrdocs_path}")
runner = TestRunner(vipyrdocs_path)
# Test 1: Abstract method with Returns - should NOT error
runner.run_test(
"Abstract method with Returns section",
{
'base.py': '''
from abc import ABC, abstractmethod
class Base(ABC):
@abstractmethod
def process(self, data):
"""Process data.
Args:
data: Input data.
Returns:
dict: Processed result.
"""
pass
'''
},
[] # No errors expected
)
# Test 2: Abstract method with Raises - should NOT error
runner.run_test(
"Abstract method with Raises section",
{
'base.py': '''
from abc import ABC, abstractmethod
class Base(ABC):
@abstractmethod
def validate(self, data):
"""Validate data.
Args:
data: Data to validate.
Raises:
ValueError: If invalid.
"""
pass
'''
},
[] # No errors expected
)
# Test 3: Implementation missing Returns - should error with D030 and D070
runner.run_test(
"Implementation missing Returns section",
{
'base.py': '''
from abc import ABC, abstractmethod
class Base(ABC):
@abstractmethod
def process(self, data):
"""Process data.
Returns:
dict: Result.
"""
pass
''',
'impl.py': '''
from base import Base
class Impl(Base):
def process(self, data):
"""Process implementation.
Args:
data: Input.
"""
return {"result": data}
'''
},
['D030', 'D070'] # Both regular and inheritance errors
)
# Test 4: Implementation missing Raises - should error with D050 and D071
runner.run_test(
"Implementation missing Raises section",
{
'base.py': '''
from abc import ABC, abstractmethod
class Base(ABC):
@abstractmethod
def validate(self, data):
"""Validate.
Raises:
ValueError: If invalid.
"""
pass
''',
'impl.py': '''
from base import Base
class Impl(Base):
def validate(self, data):
"""Validate implementation."""
if not data:
raise ValueError("Invalid")
'''
},
['D050', 'D071'] # Both regular and inheritance errors
)
# Test 5: Good implementation - should have NO errors
runner.run_test(
"Proper implementation with all sections",
{
'base.py': '''
from abc import ABC, abstractmethod
class Base(ABC):
@abstractmethod
def process(self, data):
"""Process data.
Returns:
dict: Result.
Raises:
ValueError: If error.
"""
pass
''',
'impl.py': '''
from base import Base
class Impl(Base):
def process(self, data):
"""Process implementation.
Args:
data: Input.
Returns:
dict: Result.
Raises:
ValueError: If error.
"""
if not data:
raise ValueError("Error")
return {"result": data}
'''
},
[] # No errors
)
# Test 6: Multiple implementations in different files
runner.run_test(
"Multiple implementations across files",
{
'base.py': '''
from abc import ABC, abstractmethod
class Processor(ABC):
@abstractmethod
def process(self, data):
"""Process data.
Returns:
str: Result.
"""
pass
''',
'impl_good.py': '''
from base import Processor
class GoodImpl(Processor):
def process(self, data):
"""Good implementation.
Returns:
str: Result.
"""
return str(data)
''',
'impl_bad.py': '''
from base import Processor
class BadImpl(Processor):
def process(self, data):
"""Bad implementation missing Returns."""
return str(data)
'''
},
['D030', 'D070'] # Only bad implementation should error
)
# Test 7: Yields section
runner.run_test(
"Abstract method with Yields section",
{
'base.py': '''
from abc import ABC, abstractmethod
class Base(ABC):
@abstractmethod
def generate(self):
"""Generate values.
Yields:
int: Generated value.
"""
pass
''',
'impl.py': '''
from base import Base
class Impl(Base):
def generate(self):
"""Generate implementation."""
for i in range(10):
yield i
'''
},
['D040', 'D072'] # Missing yields documentation
)
# Test 8: Abstract method with abc.abstractmethod style
runner.run_test(
"Abstract method with abc.abstractmethod decorator",
{
'base.py': '''
import abc
class Base(abc.ABC):
@abc.abstractmethod
def process(self, data):
"""Process data.
Returns:
str: Result.
"""
pass
'''
},
[] # No errors for abstract method
)
# Test 9: Multiple base classes
runner.run_test(
"Implementation with multiple base classes",
{
'base_a.py': '''
from abc import ABC, abstractmethod
class BaseA(ABC):
@abstractmethod
def method_a(self):
"""Method A.
Returns:
int: Value.
"""
pass
''',
'base_b.py': '''
from abc import ABC, abstractmethod
class BaseB(ABC):
@abstractmethod
def method_b(self):
"""Method B.
Raises:
RuntimeError: On error.
"""
pass
''',
'impl.py': '''
from base_a import BaseA
from base_b import BaseB
class Impl(BaseA, BaseB):
def method_a(self):
"""Implementation A."""
return 42
def method_b(self):
"""Implementation B."""
raise RuntimeError("Error")
'''
},
['D030', 'D070', 'D050', 'D071'] # Missing docs for both methods
)
# Test 10: Single file with abstract and implementation
runner.run_test(
"Abstract and implementation in same file",
{
'combined.py': '''
from abc import ABC, abstractmethod
class Base(ABC):
@abstractmethod
def process(self):
"""Process.
Returns:
str: Result.
"""
pass
class Impl(Base):
def process(self):
"""Implementation missing Returns."""
return "done"
'''
},
['D030', 'D070']
)
# Print summary
all_passed = runner.print_summary()
return 0 if all_passed else 1
if __name__ == '__main__':
exit(main())