File size: 11,749 Bytes
ab07cb1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
End-to-End Tests for Eurus
===========================
These tests use REAL API calls to verify the complete workflow.
Requires valid API keys in .env file.

Run with: pytest tests/test_e2e.py -v -s
Use -s flag to see output from data retrieval.
"""

import os
import pytest
import tempfile
import shutil
from pathlib import Path
from datetime import datetime, timedelta
from dotenv import load_dotenv

# Load .env file
load_dotenv()


# ============================================================================
# FIXTURES
# ============================================================================

@pytest.fixture(scope="module")
def temp_data_dir():
    """Create temporary data directory for tests."""
    temp_dir = tempfile.mkdtemp(prefix="eurus_e2e_")
    yield temp_dir
    # Cleanup after all tests
    shutil.rmtree(temp_dir, ignore_errors=True)


@pytest.fixture(scope="module")
def has_arraylake_key():
    """Check if Arraylake API key is available."""
    key = os.environ.get("ARRAYLAKE_API_KEY")
    if not key:
        pytest.skip("ARRAYLAKE_API_KEY not found in environment")
    return True


# ============================================================================
# E2E: ERA5 DATA RETRIEVAL
# ============================================================================

class TestERA5Retrieval:
    """End-to-end tests for ERA5 data retrieval."""
    
    @pytest.mark.slow
    def test_retrieve_sst_temporal_small_region(self, has_arraylake_key, temp_data_dir):
        """
        E2E Test: Retrieve SST data for a small region and short time period.
        This tests the complete retrieval pipeline.
        """
        from eurus.retrieval import retrieve_era5_data
        from eurus.memory import reset_memory
        
        # Reset memory for clean state
        reset_memory()
        
        # Use a small request to minimize download time
        result = retrieve_era5_data(
            query_type="temporal",
            variable_id="sst",
            start_date="2023-01-01",
            end_date="2023-01-07",  # Just 1 week
            min_latitude=25.0,
            max_latitude=30.0,
            min_longitude=260.0,  # Gulf of Mexico
            max_longitude=265.0,
        )
        
        print(f"\n=== ERA5 Retrieval Result ===\n{result}\n")
        
        # Verify success
        assert "SUCCESS" in result or "CACHE HIT" in result
        assert "sst" in result.lower()
        assert ".zarr" in result
        
    @pytest.mark.slow
    def test_retrieve_t2m_spatial(self, has_arraylake_key, temp_data_dir):
        """
        E2E Test: Retrieve 2m temperature as spatial data.
        Tests spatial query type.
        """
        from eurus.retrieval import retrieve_era5_data
        from eurus.memory import reset_memory
        
        reset_memory()
        
        result = retrieve_era5_data(
            query_type="spatial",
            variable_id="t2",  # 2m temperature
            start_date="2023-06-01",
            end_date="2023-06-03",  # Just 3 days
            min_latitude=40.0,
            max_latitude=50.0,
            min_longitude=0.0,
            max_longitude=10.0,  # Western Europe
        )
        
        print(f"\n=== T2M Spatial Result ===\n{result}\n")
        
        assert "SUCCESS" in result or "CACHE HIT" in result
        
    @pytest.mark.slow
    def test_retrieve_and_load_dataset(self, has_arraylake_key, temp_data_dir):
        """
        E2E Test: Retrieve data and verify it can be loaded with xarray.
        Tests the full data integrity pipeline.
        """
        import xarray as xr
        from eurus.retrieval import retrieve_era5_data
        from eurus.memory import reset_memory, get_memory
        
        reset_memory()
        
        result = retrieve_era5_data(
            query_type="temporal",
            variable_id="sst",
            start_date="2023-02-01",
            end_date="2023-02-05",
            min_latitude=20.0,
            max_latitude=25.0,
            min_longitude=270.0,
            max_longitude=275.0,
        )
        
        assert "SUCCESS" in result or "CACHE HIT" in result
        
        # Extract path from result
        # Look for the path in the result string
        lines = result.split('\n')
        path = None
        for line in lines:
            if "Path:" in line:
                path = line.split("Path:")[-1].strip()
                break
            if ".zarr" in line and "Load with" not in line:
                # Try to find zarr path
                parts = line.split()
                for part in parts:
                    if ".zarr" in part:
                        path = part.strip()
                        break
        
        if path and os.path.exists(path):
            # Load and verify dataset
            ds = xr.open_dataset(path, engine='zarr')
            
            print(f"\n=== Loaded Dataset ===")
            print(f"Variables: {list(ds.data_vars)}")
            print(f"Dimensions: {dict(ds.dims)}")
            print(f"Time range: {ds.time.values[0]} to {ds.time.values[-1]}")
            
            assert 'sst' in ds.data_vars
            assert 'time' in ds.dims
            assert ds.dims['time'] > 0
            
            ds.close()


# ============================================================================
# E2E: PYTHON REPL ANALYSIS
# ============================================================================

class TestREPLAnalysis:
    """End-to-end tests for REPL-based data analysis."""
    
    def test_repl_numpy_computation(self):
        """
        E2E Test: Use REPL to perform numpy computation.
        """
        from eurus.tools.repl import PythonREPLTool
        
        repl = PythonREPLTool()
        
        code = """
import numpy as np
data = np.random.randn(100)
mean = np.mean(data)
std = np.std(data)
print(f"Mean: {mean:.4f}, Std: {std:.4f}")
"""
        result = repl._run(code)
        print(f"\n=== REPL Result ===\n{result}\n")
        
        assert "Mean:" in result
        assert "Std:" in result
        assert "Error" not in result
        
    def test_repl_pandas_dataframe(self):
        """
        E2E Test: Use REPL to create and manipulate pandas DataFrame.
        """
        from eurus.tools.repl import PythonREPLTool
        
        repl = PythonREPLTool()
        
        code = """
import pandas as pd
import numpy as np

df = pd.DataFrame({
    'date': pd.date_range('2023-01-01', periods=10),
    'temperature': np.random.randn(10) * 5 + 20,
    'humidity': np.random.randn(10) * 10 + 60
})

print("DataFrame created:")
print(df.head())
print(f"\\nStats: Mean temp = {df['temperature'].mean():.2f}")
"""
        result = repl._run(code)
        print(f"\n=== Pandas Result ===\n{result}\n")
        
        assert "DataFrame created" in result
        assert "temperature" in result
        assert "Error" not in result
        
    @pytest.mark.slow
    def test_repl_load_and_analyze_data(self, has_arraylake_key):
        """
        E2E Test: Retrieve ERA5 data, then analyze it in REPL.
        Full workflow test.
        """
        from eurus.retrieval import retrieve_era5_data
        from eurus.tools.repl import PythonREPLTool
        from eurus.memory import reset_memory
        import xarray as xr
        
        reset_memory()
        
        # Step 1: Retrieve data
        result = retrieve_era5_data(
            query_type="temporal",
            variable_id="sst",
            start_date="2023-03-01",
            end_date="2023-03-05",
            min_latitude=25.0,
            max_latitude=28.0,
            min_longitude=265.0,
            max_longitude=268.0,
        )
        
        assert "SUCCESS" in result or "CACHE HIT" in result
        
        # Extract path
        path = None
        for line in result.split('\n'):
            if "Path:" in line:
                path = line.split("Path:")[-1].strip()
                break
                
        if not path or not os.path.exists(path):
            pytest.skip("Could not extract data path")
            
        # Step 2: Analyze in REPL
        repl = PythonREPLTool()
        
        analysis_code = f"""
import xarray as xr
import numpy as np

# Load the dataset
ds = xr.open_dataset('{path}', engine='zarr')
data = ds['sst']

# Calculate statistics
spatial_mean = data.mean(dim=['latitude', 'longitude'])
time_mean = data.mean(dim='time')

print("=== SST Analysis ===")
print(f"Time points: {{len(data.time)}}")
print(f"Spatial shape: {{data.shape}}")
print(f"Overall mean: {{float(data.mean()):.2f}} K")
print(f"Overall std: {{float(data.std()):.2f}} K")
print(f"Min: {{float(data.min()):.2f}} K, Max: {{float(data.max()):.2f}} K")
"""
        analysis_result = repl._run(analysis_code)
        print(f"\n=== Analysis Result ===\n{analysis_result}\n")
        
        assert "SST Analysis" in analysis_result
        assert "Error" not in analysis_result or "Security" not in analysis_result




# ============================================================================
# E2E: MEMORY PERSISTENCE
# ============================================================================

class TestMemoryPersistence:
    """End-to-end tests for memory and dataset tracking."""
    
    @pytest.mark.slow
    def test_memory_tracks_downloaded_data(self, has_arraylake_key):
        """
        E2E Test: Verify memory tracks downloaded datasets.
        """
        from eurus.retrieval import retrieve_era5_data
        from eurus.memory import reset_memory, get_memory
        
        reset_memory()
        memory = get_memory()
        
        # Initial state - no datasets
        initial_datasets = memory.list_datasets()
        
        # Download data
        result = retrieve_era5_data(
            query_type="temporal",
            variable_id="sst",
            start_date="2023-04-01",
            end_date="2023-04-03",
            min_latitude=30.0,
            max_latitude=32.0,
            min_longitude=275.0,
            max_longitude=278.0,
        )
        
        # Check memory registered the dataset
        datasets = memory.list_datasets()
        print(f"\n=== Registered Datasets ===\n{datasets}\n")
        
        # Should have at least one dataset now
        if "SUCCESS" in result:
            assert len(datasets) > len(initial_datasets)


# ============================================================================
# E2E: ROUTING (if scgraph installed)
# ============================================================================

class TestRouting:
    """End-to-end tests for maritime routing."""
    
    def test_routing_without_deps(self):
        """
        E2E Test: Verify routing handles missing dependencies gracefully.
        """
        from eurus.tools.routing import HAS_ROUTING_DEPS, calculate_maritime_route
        
        if not HAS_ROUTING_DEPS:
            # Should return helpful error message
            result = calculate_maritime_route(
                origin_lat=53.5,
                origin_lon=8.5,
                dest_lat=52.4,
                dest_lon=4.9,
                month=6
            )
            print(f"\n=== Routing (no deps) ===\n{result}\n")
            assert "scgraph" in result.lower() or "install" in result.lower()
        else:
            pytest.skip("scgraph is installed, skipping no-deps test")


# ============================================================================
# RUN WITH: pytest tests/test_e2e.py -v -s --tb=short
# Add -m "not slow" to skip slow tests
# ============================================================================

if __name__ == "__main__":
    pytest.main([__file__, "-v", "-s", "--tb=short"])