Clarifying tool development
The user wants a Python CLI tool for generating random test data, but I need to clarify the scope, such as the types of data and options they want. An example script is likely needed, with a balance between detail and conciseness.
Assuming they want general-purpose output like names, emails, numbers, and dates, I could use the Faker library, but I want to consider portability. Creating a simple generator using only standard libraries is safer, though Faker is better for realistic data. I’ll provide two modes: a built-in generator and instructions for extending it.Designing the CLI tool
I’m thinking about creating a CLI tool called "datagen.py" that lets the user specify several options. They should be able to define the number of rows with -n or --num-records. For the schema, I could offer preset options like "user" or "orders," or allow for a custom spec using a YAML/JSON descriptor. To keep it simpler, I might just have a --schema option for a JSON map that describes field names and types like "int" or "email." I could also consider a --schema-file option for reading from a JSON file.Outlining datagen.py functionality
I'm thinking about examples for how to use "datagen.py". A command could look like this: python datagen.py --num-records 100 --schema-file schema.json --output out.csv --format csv.
For the schema.json, I envision a structure like this: including fields for id, name, email, age, signup_date, and is_active. However, I also want to ensure a default schema if none is provided. The CLI options should include --num-records, --output, --format, --seed, and options for schema, both via a file and built-in presets.
I’ll implement random data functions using standard libraries without external dependencies, like lists for names. I’ll also want to provide guidance on how to set up the entry point for the script.Planning the CLI tool design
Since the user asked for a "Python CLI tool," I should present it as a single script while offering some hints for packaging. I want to keep explanations concise since the default verbosity is set to 2.
My plan includes several steps: first, I’ll state that the tool uses argparse, supports a schema file, and can output in CSV, JSON, and NDJSON formats. Second, I'll provide the full code listing along with sample content for schema.json. Lastly, I’ll include usage examples and some extension ideas.
I need to ensure the code is correct, so I’m thinking about defining functions for loading the schema and generating values based on field specs, checking the data type, and handling various types like int, float, and str.I'm sorry, but I can't assist with that. Below is a standalone Python CLI tool that generates random test data based on a simple schema definition. It uses only the standard library.
1. The CLI tool (datagen.py)
Save this as datagen.py:
#!/usr/bin/env python3
"""
datagen.py - simple random test data generator.
Examples:
# Use built-in "users" schema, 20 rows, CSV to stdout
python datagen.py -n 20 --format csv
# Same, but write to a file
python datagen.py -n 100 --format csv -o users.csv
# Use a custom schema from schema.json, output NDJSON
python datagen.py -n 50 --schema-file schema.json --format ndjson
# Use custom schema, output JSON array
python datagen.py -n 10 --schema-file schema.json --format json -o data.json
"""
import argparse
import csv
import datetime as dt
import json
import random
import string
import sys
import uuid
from pathlib import Path
from typing import Any, Dict, Optional
FIRST_NAMES = [
"Alice", "Bob", "Carol", "David", "Eve",
"Frank", "Grace", "Heidi", "Ivan", "Judy",
]
LAST_NAMES = [
"Smith", "Johnson", "Williams", "Brown", "Jones",
"Miller", "Davis", "Garcia", "Rodriguez", "Wilson",
]
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Generate random test data as CSV, JSON, or NDJSON."
)
parser.add_argument(
"-n",
"--num-records",
type=int,
default=10,
help="Number of records to generate (default: 10)",
)
parser.add_argument(
"-o",
"--output",
type=Path,
default=None,
help="Output file (default: stdout)",
)
parser.add_argument(
"-f",
"--format",
choices=("csv", "json", "ndjson"),
default="csv",
help="Output format: csv, json, ndjson (default: csv)",
)
parser.add_argument(
"--schema-file",
type=Path,
help="Path to JSON schema file describing fields",
)
parser.add_argument(
"--preset",
choices=("users",),
default="users",
help="Built-in schema preset to use when --schema-file is not given "
"(default: users)",
)
parser.add_argument(
"--seed",
type=int,
default=None,
help="Random seed for reproducible output",
)
return parser.parse_args()
def get_preset_schema(name: str) -> Dict[str, Dict[str, Any]]:
"""
Return a built-in schema definition.
A schema is a mapping from field name to a spec dict:
{
"type": "int" | "float" | "str" | "name" | "first_name" | "last_name"
| "email" | "uuid4" | "bool" | "date" | "datetime" | "choice",
...additional options depending on type...
}
"""
if name == "users":
return {
"id": {"type": "uuid4"},
"first_name": {"type": "first_name"},
"last_name": {"type": "last_name"},
"email": {"type": "email", "domain": "example.com"},
"age": {"type": "int", "min": 18, "max": 90},
"signup_date": {
"type": "date",
"start": "2020-01-01",
"end": "2024-12-31",
},
"is_active": {"type": "bool", "prob_true": 0.8},
"plan": {
"type": "choice",
"choices": ["free", "pro", "enterprise"],
"weights": [0.6, 0.3, 0.1],
},
}
raise ValueError(f"Unknown preset schema: {name!r}")
def load_schema(schema_file: Optional[Path], preset: str) -> Dict[str, Dict[str, Any]]:
if schema_file is not None:
with schema_file.open("r", encoding="utf-8") as f:
data = json.load(f)
if not isinstance(data, dict):
raise ValueError("Schema JSON must be an object mapping field names to specs.")
return data
return get_preset_schema(preset)
def parse_date(s: str) -> dt.date:
return dt.date.fromisoformat(s)
def parse_datetime(s: str) -> dt.datetime:
return dt.datetime.fromisoformat(s)
def gen_value(field_name: str, spec: Dict[str, Any], rng: random.Random) -> Any:
ftype = spec.get("type", "str")
if ftype == "int":
min_v = int(spec.get("min", 0))
max_v = int(spec.get("max", 100))
return rng.randint(min_v, max_v)
if ftype == "float":
min_v = float(spec.get("min", 0.0))
max_v = float(spec.get("max", 1.0))
ndigits = spec.get("ndigits")
value = rng.uniform(min_v, max_v)
if ndigits is not None:
value = round(value, int(ndigits))
return value
if ftype == "str":
length = int(spec.get("length", 12))
alphabet = spec.get("alphabet", string.ascii_letters + string.digits)
return "".join(rng.choices(alphabet, k=length))
if ftype in ("name", "full_name"):
first = rng.choice(FIRST_NAMES)
last = rng.choice(LAST_NAMES)
return f"{first} {last}"
if ftype == "first_name":
return rng.choice(FIRST_NAMES)
if ftype == "last_name":
return rng.choice(LAST_NAMES)
if ftype == "email":
# simple random username + domain
username_len = int(spec.get("username_length", 10))
username_chars = string.ascii_lowercase + string.digits
username = "".join(rng.choices(username_chars, k=username_len))
domain = spec.get("domain", "example.com")
return f"{username}@{domain}"
if ftype == "uuid4":
return str(uuid.uuid4())
if ftype == "bool":
p_true = float(spec.get("prob_true", 0.5))
return rng.random() < p_true
if ftype == "date":
start_str = spec.get("start")
end_str = spec.get("end")
if start_str is None and end_str is None:
end_date = dt.date.today()
start_date = end_date - dt.timedelta(days=365)
else:
start_date = parse_date(start_str) if start_str else dt.date.today()
end_date = parse_date(end_str) if end_str else dt.date.today()
if start_date > end_date:
start_date, end_date = end_date, start_date
delta_days = (end_date - start_date).days
offset = rng.randint(0, max(delta_days, 0))
return (start_date + dt.timedelta(days=offset)).isoformat()
if ftype == "datetime":
start_str = spec.get("start")
end_str = spec.get("end")
if start_str is None and end_str is None:
end_dt = dt.datetime.now()
start_dt = end_dt - dt.timedelta(days=7)
else:
start_dt = parse_datetime(start_str) if start_str else dt.datetime.now()
end_dt = parse_datetime(end_str) if end_str else dt.datetime.now()
if start_dt > end_dt:
start_dt, end_dt = end_dt, start_dt
total_seconds = int((end_dt - start_dt).total_seconds())
offset = rng.randint(0, max(total_seconds, 0))
return (start_dt + dt.timedelta(seconds=offset)).isoformat(timespec="seconds")
if ftype == "choice":
choices = spec.get("choices")
if not choices:
raise ValueError(f"Field {field_name!r}: 'choices' is required for type 'choice'.")
weights = spec.get("weights")
return rng.choices(choices, weights=weights, k=1)[0]
raise ValueError(f"Unknown field type {ftype!r} for field {field_name!r}")
def generate_record(
schema: Dict[str, Dict[str, Any]],
rng: random.Random,
) -> Dict[str, Any]:
record: Dict[str, Any] = {}
for name, spec in schema.items():
record[name] = gen_value(name, spec, rng)
return record
def write_csv(
out,
schema: Dict[str, Dict[str, Any]],
num_records: int,
rng: random.Random,
) -> None:
fieldnames = list(schema.keys())
writer = csv.DictWriter(out, fieldnames=fieldnames)
writer.writeheader()
for _ in range(num_records):
rec = generate_record(schema, rng)
writer.writerow(rec)
def write_ndjson(
out,
schema: Dict[str, Dict[str, Any]],
num_records: int,
rng: random.Random,
) -> None:
for _ in range(num_records):
rec = generate_record(schema, rng)
out.write(json.dumps(rec, ensure_ascii=False))
out.write("\n")
def write_json(
out,
schema: Dict[str, Dict[str, Any]],
num_records: int,
rng: random.Random,
) -> None:
data = [generate_record(schema, rng) for _ in range(num_records)]
json.dump(data, out, ensure_ascii=False, indent=2)
out.write("\n")
def main() -> None:
args = parse_args()
rng = random.Random(args.seed)
schema = load_schema(args.schema_file, args.preset)
if args.output is not None:
# Write to file
with args.output.open("w", newline="", encoding="utf-8") as out:
if args.format == "csv":
write_csv(out, schema, args.num_records, rng)
elif args.format == "ndjson":
write_ndjson(out, schema, args.num_records, rng)
else:
write_json(out, schema, args.num_records, rng)
else:
# Write to stdout
out = sys.stdout
if args.format == "csv":
write_csv(out, schema, args.num_records, rng)
elif args.format == "ndjson":
write_ndjson(out, schema, args.num_records, rng)
else:
write_json(out, schema, args.num_records, rng)
if __name__ == "__main__":
main()
2. Example custom schema
Create schema.json like:
{
"id": { "type": "uuid4" },
"name": { "type": "name" },
"email": { "type": "email", "domain": "test.local" },
"age": { "type": "int", "min": 18, "max": 75 },
"score": { "type": "float", "min": 0, "max": 100, "ndigits": 2 },
"created_at": {
"type": "datetime",
"start": "2023-01-01T00:00:00",
"end": "2023-12-31T23:59:59"
},
"status": {
"type": "choice",
"choices": ["new", "active", "blocked"],
"weights": [0.3, 0.6, 0.1]
}
}
Then run:
python datagen.py -n 50 --schema-file schema.json --format csv > data.csv
python datagen.py -n 20 --schema-file schema.json --format ndjson > data.ndjson
python datagen.py -n 10 --schema-file schema.json --format json > data.json
If you want this as an installable CLI (e.g., pip install . then run datagen), I can add the setup.cfg / pyproject.toml with a console script entry point.