-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_diagram_integration.py
More file actions
executable file
Β·212 lines (179 loc) Β· 7.75 KB
/
Copy pathtest_diagram_integration.py
File metadata and controls
executable file
Β·212 lines (179 loc) Β· 7.75 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
#!/usr/bin/env python3
"""
Simple test script to verify the new diagram generation functionality.
This script tests the integration of diagram generation into the NetBird client.
"""
import os
import sys
import tempfile
from pathlib import Path
# Add the src directory to the path for local development
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))
from netbird import APIClient
from netbird.exceptions import NetBirdAPIError
def test_diagram_functionality():
"""Test the diagram generation functionality."""
print("π§ͺ Testing NetBird Client Diagram Generation")
print("=" * 50)
# Check environment variables
host = os.getenv("NETBIRD_HOST", "api.netbird.io")
token = os.getenv("NETBIRD_API_TOKEN")
if not token:
print("β NETBIRD_API_TOKEN environment variable is required")
print(" Set it with: export NETBIRD_API_TOKEN='your-token-here'")
return False
print(f"π Connecting to: {host}")
print(f"π Token: {token[:10]}...")
try:
# Create client
client = APIClient(host=host, api_token=token)
print("β
Client created successfully")
# Test 1: Check if generate_diagram method exists
print("\nπ Test 1: Method availability")
if hasattr(client, 'generate_diagram'):
print("β
generate_diagram method found")
else:
print("β generate_diagram method not found")
return False
# Test 2: Generate Mermaid diagram (no file output)
print("\nπ Test 2: Mermaid diagram generation")
try:
mermaid_content = client.generate_diagram(format="mermaid")
if mermaid_content:
print(f"β
Mermaid diagram generated ({len(mermaid_content)} chars)")
print(f" Preview: {mermaid_content[:100]}...")
else:
print("β οΈ No mermaid content returned (no networks?)")
except Exception as e:
print(f"β Mermaid generation failed: {e}")
return False
# Test 3: Generate with file output
print("\nπ Test 3: File output generation")
try:
with tempfile.TemporaryDirectory() as temp_dir:
output_path = os.path.join(temp_dir, "test_diagram")
result = client.generate_diagram(
format="mermaid",
output_file=output_path,
include_routers=True,
include_policies=True,
include_resources=True
)
if result:
print("β
Diagram generated with file output")
# Check if files were created
mermaid_file = f"{output_path}.mmd"
markdown_file = f"{output_path}.md"
if os.path.exists(mermaid_file):
print("β
Mermaid file created")
with open(mermaid_file, 'r') as f:
content = f.read()
print(f" File size: {len(content)} chars")
else:
print("β Mermaid file not found")
if os.path.exists(markdown_file):
print("β
Markdown file created")
else:
print("β Markdown file not found")
else:
print("β οΈ No result returned from file generation")
except Exception as e:
print(f"β File generation failed: {e}")
return False
# Test 4: Test different options
print("\nπ Test 4: Different include options")
try:
# Test with resources only
result = client.generate_diagram(
format="mermaid",
include_routers=False,
include_policies=False,
include_resources=True
)
print("β
Resources-only diagram generated")
# Test with all options disabled except one
result = client.generate_diagram(
format="mermaid",
include_routers=True,
include_policies=False,
include_resources=False
)
print("β
Routers-only diagram generated")
except Exception as e:
print(f"β Options test failed: {e}")
return False
# Test 5: Test invalid format (should raise ValueError)
print("\nπ Test 5: Invalid format handling")
try:
client.generate_diagram(format="invalid_format")
print("β Should have raised ValueError for invalid format")
return False
except ValueError as e:
if "Unsupported format" in str(e):
print("β
Invalid format properly rejected")
else:
print(f"β Unexpected ValueError: {e}")
return False
except Exception as e:
print(f"β Unexpected exception for invalid format: {e}")
return False
# Test 6: Test helper methods
print("\nπ Test 6: Helper methods")
try:
# Test color generation
colors = client._get_source_group_colors(['group1', 'group2', 'group3'])
if len(colors) == 3:
print("β
Color generation works")
else:
print(f"β Color generation returned {len(colors)} colors, expected 3")
# Test policy label formatting
label = client._format_policy_label(['policy1', 'policy2'], "Test")
if "Test:" in label and ("policy1" in label or "policy2" in label):
print("β
Policy label formatting works")
else:
print(f"β Policy label formatting failed: {label}")
# Test ID sanitization
sanitized = client._sanitize_id("test-group.name/with spaces")
if sanitized == "test_group_name_with_spaces":
print("β
ID sanitization works")
else:
print(f"β ID sanitization failed: {sanitized}")
except Exception as e:
print(f"β Helper methods test failed: {e}")
return False
print("\nπ All tests passed!")
return True
except NetBirdAPIError as e:
print(f"β NetBird API Error: {e}")
return False
except Exception as e:
print(f"β Unexpected error: {e}")
return False
finally:
try:
client.close()
print("π Client connection closed")
except:
pass
def main():
"""Main function."""
print("NetBird Python Client - Diagram Generation Test")
print("This script tests the integrated diagram generation functionality.\n")
success = test_diagram_functionality()
print("\n" + "=" * 50)
if success:
print("β
All diagram functionality tests PASSED!")
print("\nπ‘ Next steps:")
print(" - Try generating diagrams with your networks")
print(" - Experiment with different formats (mermaid, graphviz, diagrams)")
print(" - Use diagrams in your documentation")
sys.exit(0)
else:
print("β Some tests FAILED!")
print("\nπ§ Troubleshooting:")
print(" - Check your API token and NetBird server connection")
print(" - Ensure you have networks configured in NetBird")
print(" - Try running tests individually for more details")
sys.exit(1)
if __name__ == "__main__":
main()