-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathplugin_integration_test.py
More file actions
302 lines (248 loc) Β· 10.1 KB
/
plugin_integration_test.py
File metadata and controls
302 lines (248 loc) Β· 10.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
#!/usr/bin/env python3
"""
Integration test for the PyMapGIS QGIS plugin.
This test simulates plugin usage and demonstrates the identified bugs.
"""
import sys
import os
import tempfile
import traceback
from pathlib import Path
from unittest.mock import Mock, patch, MagicMock
import geopandas as gpd
import xarray as xr
import numpy as np
from shapely.geometry import Point
def test_plugin_import_handling():
"""Test how the plugin handles import scenarios."""
print("π Testing Plugin Import Handling")
print("-" * 40)
# Test 1: Normal import scenario
try:
import pymapgis
print("β
PyMapGIS is available")
# Test basic functionality
test_data = gpd.GeoDataFrame({
'geometry': [Point(0, 0)]
}, crs='EPSG:4326')
with tempfile.NamedTemporaryFile(suffix='.geojson', delete=False) as f:
test_data.to_file(f.name, driver='GeoJSON')
loaded_data = pymapgis.read(f.name)
assert isinstance(loaded_data, gpd.GeoDataFrame)
print("β
PyMapGIS read functionality works")
os.unlink(f.name)
except ImportError:
print("β PyMapGIS not available - plugin would fail")
return False
# Test 2: Simulate missing rioxarray
print("\nπ Testing rioxarray dependency")
try:
import rioxarray
print("β
rioxarray is available")
# Test raster functionality
da = xr.DataArray(np.random.rand(5, 5))
print(f"β
Can create DataArray: {da.shape}")
# Test if rio accessor is available
if hasattr(da, 'rio'):
print("β
Rio accessor is available")
else:
print("β Rio accessor not available - raster features would fail")
except ImportError:
print("β rioxarray not available - raster features would fail")
return True
def test_temporary_file_handling():
"""Test temporary file handling to demonstrate the cleanup bug."""
print("\nπ Testing Temporary File Handling")
print("-" * 40)
# Simulate the plugin's temporary file creation
temp_dirs_created = []
temp_files_created = []
try:
# This simulates what the plugin does (BUG-002)
for i in range(3):
temp_dir = tempfile.mkdtemp(prefix='pymapgis_qgis_')
temp_dirs_created.append(temp_dir)
# Create test data
gdf = gpd.GeoDataFrame({
'id': [1],
'geometry': [Point(0, 0)]
}, crs='EPSG:4326')
# Create temporary file (like the plugin does)
temp_file = os.path.join(temp_dir, f"test_{i}.gpkg")
gdf.to_file(temp_file, driver="GPKG")
temp_files_created.append(temp_file)
print(f" Created: {temp_file}")
print(f"β
Created {len(temp_dirs_created)} temporary directories")
print(f"β οΈ BUG DEMONSTRATION: These files are not automatically cleaned up!")
# Check if files exist
for temp_file in temp_files_created:
if os.path.exists(temp_file):
print(f" π Still exists: {temp_file}")
# Manual cleanup (what the plugin should do)
print("\nπ§Ή Manually cleaning up...")
for temp_dir in temp_dirs_created:
if os.path.exists(temp_dir):
import shutil
shutil.rmtree(temp_dir)
print(f" ποΈ Cleaned: {temp_dir}")
print("β
Cleanup completed")
except Exception as e:
print(f"β Error in temporary file test: {e}")
return False
return True
def test_signal_connection_simulation():
"""Simulate signal connection issues."""
print("\nπ Testing Signal Connection Management")
print("-" * 40)
# Mock Qt objects
class MockDialog:
def __init__(self):
self.finished = Mock()
self.finished.connect = Mock()
self.finished.disconnect = Mock()
self._connections = []
def connect_signal(self, callback):
self.finished.connect(callback)
self._connections.append(callback)
print(f" π‘ Connected signal (total: {len(self._connections)})")
def disconnect_signal(self, callback):
try:
self.finished.disconnect(callback)
if callback in self._connections:
self._connections.remove(callback)
print(f" π Disconnected signal (remaining: {len(self._connections)})")
except Exception as e:
print(f" β Failed to disconnect: {e}")
def cleanup(self):
print(f" π§Ή Cleaning up dialog with {len(self._connections)} remaining connections")
if self._connections:
print(" β οΈ BUG DEMONSTRATION: Signal connections not properly cleaned up!")
# Simulate plugin behavior
dialog_instances = []
# Create multiple dialog instances (simulating repeated usage)
for i in range(3):
dialog = MockDialog()
dialog.connect_signal(lambda: print("Dialog finished"))
dialog_instances.append(dialog)
print(f"β
Created dialog instance {i+1}")
# Simulate improper cleanup (current plugin behavior)
print("\nπ Simulating current plugin cleanup behavior:")
for i, dialog in enumerate(dialog_instances):
if i == 0:
# First dialog - proper cleanup
dialog.disconnect_signal(lambda: print("Dialog finished"))
dialog.cleanup()
else:
# Other dialogs - improper cleanup (demonstrates the bug)
dialog.cleanup()
print("β οΈ BUG DEMONSTRATION: Not all signal connections were properly disconnected!")
return True
def test_error_handling_scenarios():
"""Test various error scenarios."""
print("\nπ Testing Error Handling Scenarios")
print("-" * 40)
scenarios = [
{
"name": "Invalid URI",
"uri": "invalid://not/a/real/uri",
"expected_error": "Unsupported format or invalid URI"
},
{
"name": "Non-existent file",
"uri": "/path/that/does/not/exist.geojson",
"expected_error": "File not found"
},
{
"name": "Empty URI",
"uri": "",
"expected_error": "URI cannot be empty"
},
{
"name": "Malformed URI",
"uri": "census://acs/invalid?malformed=query",
"expected_error": "Invalid census query"
}
]
for scenario in scenarios:
print(f"\n π§ͺ Testing: {scenario['name']}")
print(f" URI: {scenario['uri']}")
try:
if scenario['uri'].strip() == "":
# Simulate plugin's URI validation
print(f" β
Caught empty URI (plugin handles this)")
else:
# Try to read with pymapgis
import pymapgis
data = pymapgis.read(scenario['uri'])
print(f" β Unexpected success - should have failed")
except Exception as e:
print(f" β
Caught expected error: {type(e).__name__}: {str(e)[:60]}...")
return True
def test_data_type_handling():
"""Test how the plugin handles different data types."""
print("\nπ Testing Data Type Handling")
print("-" * 40)
# Test GeoDataFrame handling
print(" π Testing GeoDataFrame handling...")
gdf = gpd.GeoDataFrame({
'id': [1, 2],
'geometry': [Point(0, 0), Point(1, 1)]
}, crs='EPSG:4326')
if isinstance(gdf, gpd.GeoDataFrame):
print(" β
GeoDataFrame detected correctly")
# Test xarray DataArray handling
print(" π Testing xarray DataArray handling...")
da = xr.DataArray(np.random.rand(5, 5))
if isinstance(da, xr.DataArray):
print(" β
DataArray detected correctly")
# Test CRS handling
if hasattr(da, 'rio'):
if da.rio.crs is None:
print(" β οΈ DataArray has no CRS - plugin would show warning")
else:
print(" β
DataArray has CRS")
else:
print(" β Rio accessor not available")
# Test unsupported data type
print(" π Testing unsupported data type...")
unsupported_data = {"type": "unsupported"}
if not isinstance(unsupported_data, (gpd.GeoDataFrame, xr.DataArray)):
print(" β
Unsupported data type detected - plugin would show warning")
return True
def main():
"""Run all integration tests."""
print("π§ͺ PyMapGIS QGIS Plugin Integration Tests")
print("=" * 50)
tests = [
test_plugin_import_handling,
test_temporary_file_handling,
test_signal_connection_simulation,
test_error_handling_scenarios,
test_data_type_handling
]
results = []
for test in tests:
try:
result = test()
results.append(result)
except Exception as e:
print(f"β Test {test.__name__} failed: {e}")
traceback.print_exc()
results.append(False)
print(f"\nπ Integration Test Results")
print("=" * 30)
print(f"Tests passed: {sum(results)}/{len(results)}")
if all(results):
print("π All integration tests passed!")
print("β οΈ However, several bugs were demonstrated during testing.")
else:
print("β οΈ Some integration tests failed.")
print(f"\nπ― Key Findings:")
print(" β’ Plugin core functionality works")
print(" β’ PyMapGIS integration is functional")
print(" β’ Several bugs exist that affect robustness")
print(" β’ Memory management needs improvement")
print(" β’ Error handling could be more user-friendly")
return 0 if all(results) else 1
if __name__ == "__main__":
sys.exit(main())