-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_integration_cratedb.py
More file actions
256 lines (230 loc) · 10 KB
/
test_integration_cratedb.py
File metadata and controls
256 lines (230 loc) · 10 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
#!/usr/bin/env python3
"""
Integration tests for pfc-export-cratedb — requires live CrateDB.
Run on the server:
python3 test_integration_cratedb.py
CrateDB: localhost:5433 (Docker container crate-test)
"""
import json
import os
import subprocess
import sys
import tempfile
import unittest
from datetime import datetime, timezone, timedelta
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent))
CRATE_HOST = "localhost"
CRATE_PORT = 5433
CRATE_USER = "crate"
CRATE_PASS = ""
CRATE_DB = "doc"
PFC_BINARY = "/usr/local/bin/pfc_jsonl"
try:
import psycopg2
import psycopg2.extras
HAS_PSYCOPG2 = True
except ImportError:
HAS_PSYCOPG2 = False
def get_conn():
return psycopg2.connect(
host=CRATE_HOST, port=CRATE_PORT,
user=CRATE_USER, password=CRATE_PASS,
dbname=CRATE_DB, connect_timeout=10,
)
def pfc_binary_available():
return os.path.isfile(PFC_BINARY) and os.access(PFC_BINARY, os.X_OK)
@unittest.skipUnless(HAS_PSYCOPG2, "psycopg2 not installed")
class TestCrateDBIntegration(unittest.TestCase):
TABLE = "pfc_export_integration_test"
@classmethod
def setUpClass(cls):
cls.conn = get_conn()
cls.conn.autocommit = True
cur = cls.conn.cursor()
cur.execute(f'DROP TABLE IF EXISTS "{cls.TABLE}"')
cur.execute(f"""
CREATE TABLE "{cls.TABLE}" (
id INTEGER,
ts TIMESTAMP WITH TIME ZONE,
level TEXT,
message TEXT,
value DOUBLE PRECISION
)
""")
# Insert 200 rows spanning 10 days
base = datetime(2024, 1, 1, tzinfo=timezone.utc)
rows = []
for i in range(200):
ts = base + timedelta(hours=i)
level = ["INFO", "WARN", "ERROR"][i % 3]
rows.append((i, ts.isoformat(), level, f"log message {i}", float(i) * 1.5))
cur.executemany(
f'INSERT INTO "{cls.TABLE}" (id, ts, level, message, value) VALUES (%s, %s, %s, %s, %s)',
rows,
)
# CrateDB needs a refresh before SELECT sees new rows
cur.execute(f'REFRESH TABLE "{cls.TABLE}"')
cur.close()
@classmethod
def tearDownClass(cls):
cur = cls.conn.cursor()
cur.execute(f'DROP TABLE IF EXISTS "{cls.TABLE}"')
cur.close()
cls.conn.close()
# ------------------------------------------------------------------
# 1. Basic export — all rows
# ------------------------------------------------------------------
def test_basic_export_row_count(self):
from pfc_export_cratedb import export_to_pfc
with tempfile.TemporaryDirectory() as tmp:
out = Path(tmp) / "test_basic.pfc"
result = export_to_pfc(
host=CRATE_HOST, port=CRATE_PORT,
user=CRATE_USER, password=CRATE_PASS,
dbname=CRATE_DB, schema=None,
table=self.TABLE, output_path=out,
pfc_binary=PFC_BINARY,
)
self.assertEqual(result["rows"], 200, f"Expected 200 rows, got {result['rows']}")
self.assertTrue(out.exists(), ".pfc file not created")
# ------------------------------------------------------------------
# 2. .bidx file is created alongside .pfc
# ------------------------------------------------------------------
@unittest.skipUnless(pfc_binary_available(), "pfc_jsonl binary not found")
def test_bidx_created(self):
from pfc_export_cratedb import export_to_pfc
with tempfile.TemporaryDirectory() as tmp:
out = Path(tmp) / "test_bidx.pfc"
export_to_pfc(
host=CRATE_HOST, port=CRATE_PORT,
user=CRATE_USER, password=CRATE_PASS,
dbname=CRATE_DB, schema=None,
table=self.TABLE, output_path=out,
pfc_binary=PFC_BINARY, ts_column="ts",
)
bidx = Path(str(out) + ".bidx")
self.assertTrue(bidx.exists(), ".pfc.bidx not created")
# ------------------------------------------------------------------
# 3. Time-range filter — only rows in range
# ------------------------------------------------------------------
def test_time_range_filter(self):
from pfc_export_cratedb import export_to_pfc
with tempfile.TemporaryDirectory() as tmp:
out = Path(tmp) / "test_range.pfc"
# First 48 hours = rows 0..47 = 48 rows
result = export_to_pfc(
host=CRATE_HOST, port=CRATE_PORT,
user=CRATE_USER, password=CRATE_PASS,
dbname=CRATE_DB, schema=None,
table=self.TABLE, output_path=out,
pfc_binary=PFC_BINARY, ts_column="ts",
from_ts="2024-01-01T00:00:00",
to_ts="2024-01-03T00:00:00",
)
self.assertEqual(result["rows"], 48, f"Expected 48 rows, got {result['rows']}")
# ------------------------------------------------------------------
# 4. JSONL content — fields are preserved correctly
# ------------------------------------------------------------------
@unittest.skipUnless(pfc_binary_available(), "pfc_jsonl binary not found")
def test_field_integrity(self):
from pfc_export_cratedb import export_to_pfc
with tempfile.TemporaryDirectory() as tmp:
out = Path(tmp) / "test_fields.pfc"
export_to_pfc(
host=CRATE_HOST, port=CRATE_PORT,
user=CRATE_USER, password=CRATE_PASS,
dbname=CRATE_DB, schema=None,
table=self.TABLE, output_path=out,
pfc_binary=PFC_BINARY,
from_ts="2024-01-01T00:00:00",
to_ts="2024-01-01T01:00:00",
ts_column="ts",
)
# Decompress and check first record
result = subprocess.run(
[PFC_BINARY, "decompress", str(out), "-"],
capture_output=True, text=True,
)
lines = [l for l in result.stdout.splitlines() if l.startswith("{")]
self.assertGreater(len(lines), 0, "No JSON lines in decompress output")
record = json.loads(lines[0])
self.assertIn("id", record)
self.assertIn("level", record)
self.assertIn("message", record)
self.assertIn("value", record)
# ------------------------------------------------------------------
# 5. .pfc file is non-empty and decompresses without error
# ------------------------------------------------------------------
@unittest.skipUnless(pfc_binary_available(), "pfc_jsonl binary not found")
def test_pfc_decompresses_cleanly(self):
from pfc_export_cratedb import export_to_pfc
with tempfile.TemporaryDirectory() as tmp:
out = Path(tmp) / "test_decomp.pfc"
result = export_to_pfc(
host=CRATE_HOST, port=CRATE_PORT,
user=CRATE_USER, password=CRATE_PASS,
dbname=CRATE_DB, schema=None,
table=self.TABLE, output_path=out,
pfc_binary=PFC_BINARY,
)
self.assertGreater(os.path.getsize(out), 0, ".pfc file is empty")
# Decompress must exit cleanly
proc = subprocess.run(
[PFC_BINARY, "decompress", str(out), "-"],
capture_output=True,
)
self.assertEqual(proc.returncode, 0, f"decompress failed: {proc.stderr.decode()[:200]}")
# ------------------------------------------------------------------
# 6. Empty result — no rows in range
# ------------------------------------------------------------------
def test_empty_range_no_crash(self):
from pfc_export_cratedb import export_to_pfc
with tempfile.TemporaryDirectory() as tmp:
out = Path(tmp) / "test_empty.pfc"
result = export_to_pfc(
host=CRATE_HOST, port=CRATE_PORT,
user=CRATE_USER, password=CRATE_PASS,
dbname=CRATE_DB, schema=None,
table=self.TABLE, output_path=out,
pfc_binary=PFC_BINARY, ts_column="ts",
from_ts="2030-01-01T00:00:00",
to_ts="2030-01-02T00:00:00",
)
self.assertEqual(result["rows"], 0)
# ------------------------------------------------------------------
# 7. Bad credentials — clean error
# ------------------------------------------------------------------
def test_bad_credentials_raises(self):
from pfc_export_cratedb import export_to_pfc
with tempfile.TemporaryDirectory() as tmp:
out = Path(tmp) / "test_bad.pfc"
with self.assertRaises(Exception):
export_to_pfc(
host=CRATE_HOST, port=CRATE_PORT,
user="wrong_user", password="wrong_pass",
dbname=CRATE_DB, schema=None,
table=self.TABLE, output_path=out,
pfc_binary=PFC_BINARY,
)
# ------------------------------------------------------------------
# 8. Batch streaming — large batches work
# ------------------------------------------------------------------
def test_large_batch_size(self):
from pfc_export_cratedb import export_to_pfc
with tempfile.TemporaryDirectory() as tmp:
out = Path(tmp) / "test_batch.pfc"
result = export_to_pfc(
host=CRATE_HOST, port=CRATE_PORT,
user=CRATE_USER, password=CRATE_PASS,
dbname=CRATE_DB, schema=None,
table=self.TABLE, output_path=out,
pfc_binary=PFC_BINARY,
batch_size=500, # larger than row count — single fetch
)
self.assertEqual(result["rows"], 200)
if __name__ == "__main__":
print(f"CrateDB Integration Tests — {CRATE_HOST}:{CRATE_PORT}")
print(f"pfc_jsonl binary: {'found' if pfc_binary_available() else 'NOT FOUND — binary tests will skip'}")
print("-" * 60)
unittest.main(verbosity=2)