Skip to content

Commit 1326540

Browse files
committed
+generate DynamoDB data generate_dynamo_data.py
1 parent befafb8 commit 1326540

1 file changed

Lines changed: 31 additions & 44 deletions

File tree

tests/e2e/data/generate_dynamo_data.py

Lines changed: 31 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -2,38 +2,35 @@
22
import logging
33
import os
44
import re
5-
from datetime import datetime, timedelta
5+
from datetime import datetime, timedelta, timezone
66
from pathlib import Path
77
from typing import Any
88

9-
# Constants
109
OUTPUT_ROOT = "out"
1110
DATE_FORMAT = "%Y%m%d"
1211
VAR_PATTERN = re.compile(r"<<([^<>]+)>>")
12+
REQUIRED_TOKEN_PARTS = 3
1313

14-
# Configure logging
14+
logger = logging.getLogger(__name__)
1515
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(message)s")
1616

1717

1818
class DateVariableResolver:
19-
"""Handles the logic for parsing and evaluating date-based variables."""
20-
21-
def __init__(self, today: datetime = None):
22-
self.today = today or datetime.today()
19+
def __init__(self, today: datetime | None = None):
20+
self.today = today or datetime.now(tz=timezone.UTC)
2321

2422
def resolve(self, token: str) -> str:
25-
logging.debug(f"Resolving variable: {token}")
23+
logger.debug("Resolving variable: %s", token)
2624
parts = token.split("_")
27-
if len(parts) < 3 or parts[0].upper() != "DATE":
28-
raise ValueError(f"Unsupported variable format: {token}")
29-
25+
if len(parts) < REQUIRED_TOKEN_PARTS or parts[0].upper() != "DATE":
26+
msg = f"Unsupported variable format: {token}"
27+
raise ValueError(msg)
3028
_, unit, value = parts[0], parts[1].lower(), parts[2]
31-
3229
try:
3330
offset = int(value)
34-
except ValueError:
35-
raise ValueError(f"Invalid offset value: {value}")
36-
31+
except ValueError as err:
32+
msg = f"Invalid offset value: {value}"
33+
raise ValueError(msg) from err
3734
if unit == "day":
3835
return (self.today + timedelta(days=offset)).strftime(DATE_FORMAT)
3936
if unit == "week":
@@ -44,15 +41,12 @@ def resolve(self, token: str) -> str:
4441
try:
4542
birth_date = self.today.replace(year=self.today.year - offset)
4643
except ValueError:
47-
# Handle February 29th
4844
birth_date = self.today.replace(month=2, day=28, year=self.today.year - offset)
4945
return birth_date.strftime(DATE_FORMAT)
50-
raise ValueError(f"Unsupported calculation unit: {unit}")
51-
46+
msg = f"Unsupported calculation unit: {unit}"
47+
raise ValueError(msg)
5248

5349
class JsonTestDataProcessor:
54-
"""Processes JSON test files by resolving placeholders in 'data' arrays."""
55-
5650
def __init__(self, input_dir: Path, output_dir: Path, resolver: DateVariableResolver):
5751
self.input_dir = input_dir
5852
self.output_dir = output_dir
@@ -71,56 +65,49 @@ def _replace_token(self, match: re.Match) -> str:
7165
token = match.group(1)
7266
try:
7367
return self.resolver.resolve(token)
74-
except Exception as e:
75-
logging.warning(f"Failed to resolve variable {token}: {e}")
68+
except ValueError:
69+
logger.warning("Failed to resolve variable: %s", token)
7670
return match.group(0)
7771

7872
def process_file(self, file_path: Path):
79-
logging.info(f"Processing file: {file_path}")
73+
logger.info("Processing file: %s", file_path)
8074
try:
81-
with open(file_path) as f:
75+
with file_path.open() as f:
8276
content = json.load(f)
83-
except Exception as e:
84-
logging.exception(f"Failed to read {file_path}: {e}")
77+
except Exception:
78+
logger.exception("Failed to read file: %s", file_path)
8579
return
86-
8780
try:
8881
resolved = self.resolve_placeholders(content)
89-
except Exception as e:
90-
logging.exception(f"Failed to resolve placeholders: {e}")
82+
except Exception:
83+
logger.exception("Failed to resolve placeholders in file: %s", file_path)
9184
return
92-
9385
if "data" not in resolved:
94-
logging.error(f"Missing 'data' key in {file_path}")
86+
logger.error("Missing 'data' key in file: %s", file_path)
9587
return
96-
9788
relative_path = file_path.relative_to(self.input_dir)
9889
output_path = self.output_dir / relative_path
9990
output_path.parent.mkdir(parents=True, exist_ok=True)
100-
10191
try:
102-
with open(output_path, "w") as f:
92+
with output_path.open("w") as f:
10393
json.dump(resolved["data"], f, indent=2)
104-
logging.info(f"Written resolved file: {output_path}")
105-
except Exception as e:
106-
logging.exception(f"Failed to write output: {e}")
107-
94+
logger.info("Written resolved file: %s", output_path)
95+
except Exception:
96+
logger.exception("Failed to write output to: %s", output_path)
10897

10998
def main():
11099
input_dir = Path()
111100
output_dir = Path(OUTPUT_ROOT)
112101
resolver = DateVariableResolver()
113-
114102
processor = JsonTestDataProcessor(input_dir, output_dir, resolver)
115-
116-
logging.info(f"Scanning for JSON files in {input_dir}")
103+
logger.info("Scanning for JSON files in directory: %s", input_dir)
117104
for root, _, files in os.walk(input_dir):
118105
for file in files:
106+
file_path = Path(root) / file
119107
if file.endswith(".json"):
120-
processor.process_file(Path(root) / file)
108+
processor.process_file(file_path)
121109
else:
122-
logging.debug(f"Skipping non-JSON file: {file}")
123-
110+
logger.debug("Skipping non-JSON file: %s", file)
124111

125112
if __name__ == "__main__":
126113
main()

0 commit comments

Comments
 (0)