Coverage for scripts/tests/test_coco_txt.py: 100%
32 statements
« prev ^ index » next coverage.py v7.10.2, created at 2025-08-07 15:22 +0000
« prev ^ index » next coverage.py v7.10.2, created at 2025-08-07 15:22 +0000
1import os
2import json
3import tempfile
4from scripts.annotations.coco_txt import coco_to_txt # adjust import
6def make_coco_json(path):
7 coco = {
8 "images": [{"id": 1, "file_name": "img1.jpg", "width": 320, "height": 320}],
9 "annotations": [
10 {
11 "id": 1,
12 "image_id": 1,
13 "category_id": 0,
14 "segmentation": [[10,10, 50,10, 50,50, 10,50]],
15 "bbox": [10,10,40,40]
16 }
17 ],
18 "categories": [{"id":0, "name":"cat"}]
19 }
20 with open(path, 'w') as f:
21 json.dump(coco, f)
23def test_coco_to_txt_basic(tmp_path):
24 json_path = tmp_path / "test.json"
25 output_dir = tmp_path / "output"
26 output_dir.mkdir()
28 make_coco_json(json_path)
30 coco_to_txt(str(json_path), str(output_dir))
32 # Check output TXT file exists
33 txt_file = output_dir / "img1.txt"
34 assert txt_file.exists()
36 # Check contents: has class id and coordinates
37 with open(txt_file) as f:
38 lines = f.readlines()
39 assert len(lines) == 1
40 parts = lines[0].strip().split()
41 assert parts[0] == "0" # class id
42 coords = list(map(float, parts[1:]))
43 assert all(0.0 <= c <= 1.0 for c in coords)
45def test_coco_to_txt_no_annotations(tmp_path):
46 json_path = tmp_path / "test.json"
47 output_dir = tmp_path / "output"
48 output_dir.mkdir()
50 # COCO JSON with no annotations
51 coco = {
52 "images": [{"id": 1, "file_name": "img1.jpg", "width": 320, "height": 320}],
53 "annotations": [],
54 "categories": []
55 }
56 with open(json_path, 'w') as f:
57 json.dump(coco, f)
59 coco_to_txt(str(json_path), str(output_dir))
61 # No txt file should be created because no annotations
62 assert not any(output_dir.iterdir())
64# Add tests for invalid polygons, malformed JSON, etc.