-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimport_csv.py
More file actions
330 lines (253 loc) · 10.1 KB
/
import_csv.py
File metadata and controls
330 lines (253 loc) · 10.1 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
"""
Import Test Cases into Testmo (example)
What this script does
- Reads a CSV file of test cases
- Creates the cases in a Testmo project via the Testmo API
- Uploads attachments for each created case
How to run
1) Install dependencies:
python -m pip install requests
2) Set your Testmo URL and API token as environment variables:
export TESTMO_URL="https://YOUR_WORKSPACE.testmo.net"
export TESTMO_TOKEN="testmo_api_..."
3) Run the importer:
python import_csv_optimized.py --csv test_cases.csv --project-id 2
CSV columns expected (case-insensitive)
- Name
- Description
- Expected Results
- State (Draft, Under Review, Rejected, Active, Retired)
- Estimate (Minutes)
- Priority (Low, Normal, High, Critical)
- Tags (comma-separated)
- Attachments (comma- or semicolon-separated file names, e.g. "a.txt; b.txt")
Attachments
- Put files in ./attachments by default (customize with --attachments-dir)
"""
from __future__ import annotations
import argparse
import csv
import os
from contextlib import ExitStack
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, Tuple
import requests
# ---- Mappings (labels -> API IDs) -----------------------------
STATE_IDS = {
"Draft": 1,
"Under Review": 2,
"Rejected": 3,
"Active": 4,
"Retired": 5,
}
PRIORITY_IDS = {
"Low": 3,
"Normal": 2,
"High": 1,
}
# ---- Config -----------------------------------------------------------------
@dataclass(frozen=True)
class Config:
base_url: str
api_token: str
project_id: int
attachments_dir: Path
dry_run: bool
# ---- Helpers ----------------------------------------------------------------
def normalize_key(key: str) -> str:
"""Normalize CSV column names to make matching more forgiving."""
return " ".join(key.strip().lower().split())
def split_list(value: Optional[str]) -> List[str]:
"""Split comma-separated values into a clean list."""
if not value:
return []
return [item.strip() for item in value.split(",") if item.strip()]
def split_attachments(value: Optional[str]) -> List[str]:
"""Split attachments by comma or semicolon."""
if not value:
return []
cleaned = value.replace(";", ",")
return [item.strip() for item in cleaned.split(",") if item.strip()]
def to_int(value: Any, *, default: int = 0) -> int:
try:
return int(str(value).strip())
except (TypeError, ValueError):
return default
def chunked(seq: List[Any], size: int) -> Iterable[List[Any]]:
for idx in range(0, len(seq), size):
yield seq[idx: idx + size]
# ---- CSV loading & transformation --------------------------------------------
def load_csv_rows(csv_path: Path) -> List[Dict[str, str]]:
if not csv_path.is_file():
raise FileNotFoundError(f"CSV file not found: {csv_path}")
with csv_path.open(mode="r", encoding="utf-8-sig", newline="") as f:
reader = csv.DictReader(f)
rows = []
for row in reader:
normalized = {normalize_key(k): (v or "").strip() for k, v in row.items()}
rows.append(normalized)
if not rows:
raise ValueError("CSV file contains no rows.")
return rows
def build_case_payload(row: Dict[str, str]) -> Tuple[Dict[str, Any], List[str]]:
"""
Convert one CSV row into:
- a Testmo API case payload (dict)
- a list of attachment file names (handled separately)
"""
name = row.get("name", "").strip()
if not name:
raise ValueError("Missing required field: Name")
# Estimate: by default we assume the CSV values are in minutes.
estimate = to_int(row.get("estimate"), default=0)
estimate = estimate * 60000000
state_label = row.get("state", "Active") or "Active"
priority_label = row.get("priority", "Normal") or "Normal"
state_id = STATE_IDS.get(state_label, STATE_IDS["Active"])
priority_id = PRIORITY_IDS.get(priority_label, PRIORITY_IDS["Normal"])
# These "custom_*" keys match the original example and custom fields will always have the "custom_" prefix.
# Adjust them to your workspace's custom fields if needed.
case_payload: Dict[str, Any] = {
"name": name,
"estimate": estimate,
"state": state_id,
"priority": priority_id,
"custom_description": row.get("description", ""),
"custom_expected_results": row.get("expected results", ""),
"custom_priority": priority_id,
"tags": split_list(row.get("tags")),
}
attachments = split_attachments(row.get("attachments"))
return case_payload, attachments
# ---- API calls ---------------------------------------------------------------
def make_session(api_token: str) -> requests.Session:
session = requests.Session()
session.headers.update(
{
"Authorization": f"Bearer {api_token}",
"Accept": "application/json",
}
)
return session
def create_cases(session: requests.Session, base_url: str, project_id: int, cases: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""
Create cases in bulk.
Returns the 'result' list from the API response, which typically contains created case objects.
"""
url = f"{base_url.rstrip('/')}/api/v1/projects/{project_id}/cases"
payload = {"cases": cases}
resp = session.post(url, json=payload, timeout=30)
# If Testmo returns a non-2xx response, show an error.
if not resp.ok:
raise RuntimeError(f"Create cases failed ({resp.status_code}): {resp.text}")
body = resp.json()
return body.get("result", [])
def upload_attachments(
session: requests.Session,
base_url: str,
case_id: int,
attachments: List[str],
attachments_dir: Path,
) -> None:
if not attachments:
return
url = f"{base_url.rstrip('/')}/api/v1/cases/{case_id}/attachments"
# Skip missing files with warning.
valid_files: List[Tuple[str, Path]] = []
for filename in attachments:
file_path = attachments_dir / filename
if not file_path.is_file():
print(f" - Warning: attachment not found, skipping: {file_path}")
continue
valid_files.append((filename, file_path))
if not valid_files:
return
# Upload in batches of maximum 20 attachments.
for batch in chunked(valid_files, size=20):
with ExitStack() as stack:
files_payload = []
for filename, path in batch:
handle = stack.enter_context(path.open("rb"))
files_payload.append(("files[]", (filename, handle)))
resp = session.post(url, files=files_payload, timeout=60)
if resp.status_code != 201 and not resp.ok:
print(f" - Error uploading attachments: ({resp.status_code}) {resp.text}")
else:
uploaded = resp.json().get("result", [])
print(f" - Uploaded {len(uploaded)} attachment(s).")
# ---- CLI --------------------------------------------------------------------
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Import test cases from a CSV into a Testmo project (with optional attachments)."
)
parser.add_argument("--csv", dest="csv_path", required=True, help="Path to the CSV file.")
parser.add_argument("--project-id", dest="project_id", type=int, required=True, help="Testmo project ID.")
parser.add_argument(
"--base-url",
dest="base_url",
default=os.getenv("TESTMO_URL", ""),
help='Testmo base URL (or set env var TESTMO_URL), e.g. "https://acme.testmo.net".',
)
parser.add_argument(
"--token",
dest="api_token",
default=os.getenv("TESTMO_TOKEN", ""),
help="Testmo API token (or set env var TESTMO_TOKEN).",
)
parser.add_argument(
"--attachments-dir",
dest="attachments_dir",
default="attachments",
help="Directory containing attachment files (default: ./attachments).",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Parse and validate the CSV but do not call the API.",
)
return parser.parse_args()
def main() -> None:
args = parse_args()
if not args.base_url:
raise SystemExit("Missing Testmo base URL. Provide --base-url or set TESTMO_URL.")
if not args.api_token:
raise SystemExit("Missing Testmo API token. Provide --token or set TESTMO_TOKEN.")
cfg = Config(
base_url=args.base_url,
api_token=args.api_token,
project_id=args.project_id,
attachments_dir=Path(args.attachments_dir).resolve(),
dry_run=args.dry_run,
)
csv_path = Path(args.csv_path).resolve()
rows = load_csv_rows(csv_path)
# Transform rows into API payloads + attachment lists (kept aligned by index).
cases: List[Dict[str, Any]] = []
attachments_by_index: List[List[str]] = []
for i, row in enumerate(rows, start=1):
try:
case_payload, attachments = build_case_payload(row)
cases.append(case_payload)
attachments_by_index.append(attachments)
except Exception as exc:
raise SystemExit(f"Row {i}: {exc}") from exc
print(f"Loaded {len(cases)} case(s) from: {csv_path}")
print(f"Attachments directory: {cfg.attachments_dir}")
if cfg.dry_run:
print("Dry run enabled: no API calls were made.")
return
session = make_session(cfg.api_token)
created = create_cases(session, cfg.base_url, cfg.project_id, cases)
print(f"Created {len(created)} case(s) in Testmo.")
# Upload attachments (if the API returns IDs in the same order as input, this stays aligned).
for idx, created_case in enumerate(created):
case_id = created_case.get("id")
if not case_id:
continue
attachments = attachments_by_index[idx] if idx < len(attachments_by_index) else []
if attachments:
print(f"Uploading attachments for case #{case_id}...")
upload_attachments(session, cfg.base_url, int(case_id), attachments, cfg.attachments_dir)
if __name__ == "__main__":
main()