Repository navigation
Expand file tree
/
Copy pathcli.py
More file actions
331 lines (283 loc) · 11.8 KB
/
Copy pathcli.py
File metadata and controls
331 lines (283 loc) · 11.8 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
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
"""Command-line interface for the QA API Automation Framework.
Usage:
python cli.py --help
python cli.py health
python cli.py customers list
python cli.py customers get CUST-001
python cli.py customers create --first-name Alice --last-name Smith --email a@example.com
python cli.py orders list
python cli.py orders get ORD-001
python cli.py orders create --customer-id CUST-001 --order-type NEW --amount 100
python cli.py billing invoices
python cli.py billing get-invoice INV-001
python cli.py billing event --customer-id CUST-001 --order-id ORD-001 --amount 250
python cli.py test
python cli.py serve
"""
import os
import subprocess
import sys
from typing import Optional
import requests
import typer
from rich import box
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich.text import Text
app = typer.Typer(
name="qa-framework",
help="CLI for the QA API Automation Framework - manage customers, orders, billing, and run tests.",
no_args_is_help=True,
rich_markup_mode="rich",
)
customers_app = typer.Typer(help="Manage customers.", no_args_is_help=True)
orders_app = typer.Typer(help="Manage orders.", no_args_is_help=True)
billing_app = typer.Typer(help="Manage billing and invoices.", no_args_is_help=True)
app.add_typer(customers_app, name="customers")
app.add_typer(orders_app, name="orders")
app.add_typer(billing_app, name="billing")
console = Console()
STATUS_STYLE = {
"ACTIVE": "bold green",
"SUSPENDED": "bold yellow",
"CLOSED": "bold red",
"SUBMITTED": "bold blue",
"PROCESSING": "bold magenta",
"COMPLETED": "bold green",
"FAILED": "bold red",
"OPEN": "bold blue",
"PAID": "bold green",
"DISPUTED": "bold yellow",
"VOID": "dim",
}
def _base_url() -> str:
return os.getenv("API_BASE_URL", "http://localhost:8000").rstrip("/")
def _get(path: str) -> dict:
url = f"{_base_url()}{path}"
try:
r = requests.get(url, timeout=8)
r.raise_for_status()
return r.json()
except requests.exceptions.ConnectionError:
console.print(f"[bold red]Error:[/] Cannot connect to API at {_base_url()}. Is the server running?")
raise typer.Exit(1)
except requests.exceptions.HTTPError as e:
console.print(f"[bold red]HTTP {e.response.status_code}:[/] {e.response.json().get('detail', e)}")
raise typer.Exit(1)
def _post(path: str, payload: dict) -> dict:
url = f"{_base_url()}{path}"
try:
r = requests.post(url, json=payload, timeout=8)
r.raise_for_status()
return r.json()
except requests.exceptions.ConnectionError:
console.print(f"[bold red]Error:[/] Cannot connect to API at {_base_url()}. Is the server running?")
raise typer.Exit(1)
except requests.exceptions.HTTPError as e:
detail = e.response.json().get("detail", e)
console.print(f"[bold red]HTTP {e.response.status_code}:[/] {detail}")
raise typer.Exit(1)
def _status_text(value: str) -> Text:
return Text(value, style=STATUS_STYLE.get(value, ""))
# ---------------------------------------------------------------------------
# health
# ---------------------------------------------------------------------------
@app.command()
def health():
"""Check the API health endpoint."""
data = _get("/health")
console.print(Panel(
f"[bold green]OK[/] [bold]{data['service']}[/] is [bold green]online[/]",
title="Health Check", border_style="green",
))
# ---------------------------------------------------------------------------
# customers
# ---------------------------------------------------------------------------
@customers_app.command("list")
def customers_list():
"""List all customers."""
data = _get("/customers")
t = Table(box=box.ROUNDED, show_header=True, header_style="bold dim")
t.add_column("ID", style="dim")
t.add_column("Name", style="bold")
t.add_column("Email")
t.add_column("Status")
t.add_column("Created", style="dim")
for c in data:
t.add_row(
c["customer_id"],
f"{c['first_name']} {c['last_name']}",
c["email"],
_status_text(c["status"]),
c["created_date"],
)
console.print(t)
console.print(f"[dim]{len(data)} customer(s)[/]")
@customers_app.command("get")
def customers_get(customer_id: str = typer.Argument(..., help="Customer ID e.g. CUST-001")):
"""Get a single customer by ID."""
c = _get(f"/customers/{customer_id}")
console.print(Panel(
f"[bold]{c['first_name']} {c['last_name']}[/]\n"
f"[dim]ID:[/] {c['customer_id']}\n"
f"[dim]Email:[/] {c['email']}\n"
f"[dim]Status:[/] {_status_text(c['status'])}\n"
f"[dim]Created:[/] {c['created_date']}",
title=f"Customer - {c['customer_id']}",
border_style="blue",
))
@customers_app.command("create")
def customers_create(
first_name: str = typer.Option(..., "--first-name", "-f", help="First name"),
last_name: str = typer.Option(..., "--last-name", "-l", help="Last name"),
email: str = typer.Option(..., "--email", "-e", help="Email address"),
status: str = typer.Option("ACTIVE", "--status", "-s", help="ACTIVE | SUSPENDED | CLOSED"),
):
"""Create a new customer."""
data = _post("/customers", {"first_name": first_name, "last_name": last_name, "email": email, "status": status})
console.print(f"[bold green]OK[/] Created customer [bold]{data['customer_id']}[/] - {data['first_name']} {data['last_name']}")
# ---------------------------------------------------------------------------
# orders
# ---------------------------------------------------------------------------
@orders_app.command("list")
def orders_list():
"""List all orders."""
data = _get("/orders")
t = Table(box=box.ROUNDED, show_header=True, header_style="bold dim")
t.add_column("ID", style="dim")
t.add_column("Customer", style="dim")
t.add_column("Type")
t.add_column("Amount", justify="right")
t.add_column("Status")
t.add_column("Created", style="dim")
for o in data:
t.add_row(
o["order_id"],
o["customer_id"],
o["order_type"],
f"${o['amount']:,.2f}",
_status_text(o["status"]),
o["created_date"],
)
console.print(t)
console.print(f"[dim]{len(data)} order(s)[/]")
@orders_app.command("get")
def orders_get(order_id: str = typer.Argument(..., help="Order ID e.g. ORD-001")):
"""Get a single order by ID."""
o = _get(f"/orders/{order_id}")
console.print(Panel(
f"[dim]Order ID:[/] {o['order_id']}\n"
f"[dim]Customer:[/] {o['customer_id']}\n"
f"[dim]Type:[/] {o['order_type']}\n"
f"[dim]Amount:[/] ${o['amount']:,.2f}\n"
f"[dim]Status:[/] {_status_text(o['status'])}\n"
f"[dim]Created:[/] {o['created_date']}",
title=f"Order - {o['order_id']}",
border_style="blue",
))
@orders_app.command("create")
def orders_create(
customer_id: str = typer.Option(..., "--customer-id", "-c", help="Customer ID"),
order_type: str = typer.Option("NEW", "--order-type", "-t", help="NEW | CHANGE | CANCEL"),
amount: float = typer.Option(..., "--amount", "-a", help="Order amount (USD)"),
):
"""Create a new order."""
data = _post("/orders", {"customer_id": customer_id, "order_type": order_type, "amount": amount})
console.print(f"[bold green]OK[/] Created order [bold]{data['order_id']}[/] for customer {data['customer_id']} - ${data['amount']:,.2f}")
# ---------------------------------------------------------------------------
# billing
# ---------------------------------------------------------------------------
@billing_app.command("invoices")
def billing_invoices():
"""List all invoices."""
data = _get("/billing/invoices")
t = Table(box=box.ROUNDED, show_header=True, header_style="bold dim")
t.add_column("ID", style="dim")
t.add_column("Customer", style="dim")
t.add_column("Order", style="dim")
t.add_column("Amount", justify="right")
t.add_column("Status")
t.add_column("Due Date", style="dim")
for inv in data:
t.add_row(
inv["invoice_id"],
inv["customer_id"],
inv["order_id"],
f"${inv['amount']:,.2f}",
_status_text(inv["status"]),
inv["due_date"],
)
console.print(t)
console.print(f"[dim]{len(data)} invoice(s)[/]")
@billing_app.command("get-invoice")
def billing_get_invoice(invoice_id: str = typer.Argument(..., help="Invoice ID e.g. INV-001")):
"""Get a single invoice by ID."""
inv = _get(f"/billing/invoices/{invoice_id}")
console.print(Panel(
f"[dim]Invoice ID:[/] {inv['invoice_id']}\n"
f"[dim]Customer:[/] {inv['customer_id']}\n"
f"[dim]Order:[/] {inv['order_id']}\n"
f"[dim]Amount:[/] ${inv['amount']:,.2f}\n"
f"[dim]Status:[/] {_status_text(inv['status'])}\n"
f"[dim]Due Date:[/] {inv['due_date']}",
title=f"Invoice - {inv['invoice_id']}",
border_style="blue",
))
@billing_app.command("event")
def billing_event(
customer_id: str = typer.Option(..., "--customer-id", "-c", help="Customer ID"),
order_id: str = typer.Option(..., "--order-id", "-o", help="Order ID"),
amount: float = typer.Option(..., "--amount", "-a", help="Billing amount (USD)"),
):
"""Post a billing event and create an invoice."""
data = _post("/billing/events", {"customer_id": customer_id, "order_id": order_id, "amount": amount})
console.print(f"[bold green]OK[/] Invoice [bold]{data['invoice_id']}[/] created - ${data['amount']:,.2f} due {data['due_date']}")
# ---------------------------------------------------------------------------
# test runner
# ---------------------------------------------------------------------------
@app.command()
def test(
verbose: bool = typer.Option(True, "--verbose/--quiet", "-v/-q", help="Verbose or quiet output"),
file: Optional[str] = typer.Option(None, "--file", "-f", help="Run a specific test file, e.g. test_customers"),
cov: bool = typer.Option(False, "--cov", help="Include coverage report"),
):
"""Run the automated pytest suite."""
cmd = [sys.executable, "-m", "pytest"]
if verbose:
cmd.append("-v")
else:
cmd.append("-q")
if file:
cmd.append(f"tests/{file}.py" if not file.endswith(".py") else f"tests/{file}")
if cov:
cmd += ["--cov=app", "--cov-report=term-missing"]
console.print(f"[bold]Running:[/] {' '.join(cmd)}\n")
result = subprocess.run(cmd)
raise typer.Exit(result.returncode)
# ---------------------------------------------------------------------------
# serve
# ---------------------------------------------------------------------------
@app.command()
def serve(
host: str = typer.Option("0.0.0.0", "--host", "-H", help="Bind host"),
port: int = typer.Option(8000, "--port", "-p", help="Bind port"),
reload: bool = typer.Option(True, "--reload/--no-reload", help="Auto-reload on code changes"),
):
"""Start the FastAPI server with uvicorn."""
console.print(Panel(
f"Starting server at [bold]http://{host}:{port}[/]\n"
f"Dashboard: [bold]http://localhost:{port}/ui/[/]\n"
f"API Docs: [bold]http://localhost:{port}/docs[/]",
title="QA API Automation Framework", border_style="blue",
))
cmd = [
sys.executable, "-m", "uvicorn", "app.main:app",
"--host", host,
"--port", str(port),
]
if reload:
cmd.append("--reload")
subprocess.run(cmd)
if __name__ == "__main__":
app()