Files

74 lines
3.1 KiB
Python
Executable File

#!/usr/bin/env python3
# fakedata - generate fake CSV data (names, ages, cities) for testing
# Usage: fakedata [-n ROWS] [--columns name,age,city] [--seed N] [-o FILE]
import argparse, csv, random, sys
FIRST = ["Ada", "Alan", "Grace", "Linus", "Margaret", "Dennis", "Barbara", "Ken",
"Dorothy", "John", "Mary", "James", "Patricia", "Robert", "Linda", "Michael"]
LAST = ["Lovelace", "Turing", "Hopper", "Torvalds", "Hamilton", "Ritchie", "Liskov",
"Thompson", "Smith", "Johnson", "Williams", "Brown", "Jones", "Garcia"]
CITIES = ["Springfield", "Rivertown", "Lakeside", "Fairview", "Brookfield",
"Hillcrest", "Meadowbrook", "Sunnyvale", "Oakdale", "Cedar Falls"]
DEPTS = ["engineering", "sales", "marketing", "support", "finance", "operations"]
COLUMNS = ["id", "name", "email", "age", "city", "department", "salary", "score"]
def row(rng, i, cols):
first, last = rng.choice(FIRST), rng.choice(LAST)
vals = {
"id": i,
"name": f"{first} {last}",
"email": f"{first.lower()}.{last.lower()}@example.com",
"age": rng.randint(18, 75),
"city": rng.choice(CITIES),
"department": rng.choice(DEPTS),
"salary": rng.randint(35000, 150000),
"score": round(rng.uniform(0, 100), 1),
}
return [vals[c] for c in cols]
def generate(n, cols, seed=None):
rng = random.Random(seed)
return [row(rng, i + 1, cols) for i in range(n)]
def selftest():
cols = ["id", "name", "age", "city"]
rows = generate(3, cols, seed=5)
assert len(rows) == 3 and all(len(r) == 4 for r in rows)
assert rows[0][0] == 1 and 18 <= rows[0][2] <= 75
assert generate(3, cols, seed=5) == rows
import io
buf = io.StringIO()
w = csv.writer(buf); w.writerow(cols); w.writerows(rows)
assert buf.getvalue().count("\n") == 4
print(buf.getvalue(), end="")
print("fakedata selftest OK")
def main():
p = argparse.ArgumentParser(description="Generate fake CSV data (names, ages, cities) for testing.")
p.add_argument("-n", "--rows", type=int, default=10, help="number of rows (default 10)")
p.add_argument("--columns", default="id,name,email,age,city",
help="comma-separated columns (default id,name,email,age,city)")
p.add_argument("--seed", type=int, default=None, help="seed for deterministic output")
p.add_argument("-o", "--output", default=None, help="output file (default: stdout)")
p.add_argument("--selftest", action="store_true", help="run a built-in self-test and exit")
a = p.parse_args()
if a.selftest:
selftest(); return 0
cols = [c.strip() for c in a.columns.split(",") if c.strip()]
bad = [c for c in cols if c not in COLUMNS]
if bad:
p.error(f"unknown columns: {', '.join(bad)} (available: {', '.join(COLUMNS)})")
rows = generate(max(1, a.rows), cols, a.seed)
out = open(a.output, "w", newline="") if a.output else sys.stdout
try:
w = csv.writer(out)
w.writerow(cols)
w.writerows(rows)
finally:
if a.output:
out.close()
return 0
if __name__ == "__main__":
sys.exit(main())