Skip to content

Commit 7a13f0e

Browse files
jbalpertad-chaosnaveen521kk
authored
Migrate from os.path to pathlib in Testing Scripts (#2685)
* updated styling * final commit * fixed style * removed exist_ok=true * added parents=True * potentially .exists() is the problem * fixed style' * fixed style on revisions * style check processed * Update tests/helpers/graphical_units.py Co-authored-by: ad_chaos <[email protected]> * fixed changes * made get_dir_layout also accept path. * removed small auto import error Co-authored-by: ad_chaos <[email protected]> Co-authored-by: Naveen M K <[email protected]>
1 parent 32b714a commit 7a13f0e

File tree

6 files changed

+70
-80
lines changed

6 files changed

+70
-80
lines changed

manim/utils/commands.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
from __future__ import annotations
22

33
import json
4-
import os
4+
from pathlib import Path
55
from subprocess import run
6-
from typing import Any
6+
from typing import Generator
77

88
__all__ = [
99
"capture",
@@ -18,7 +18,7 @@ def capture(command, cwd=None, command_input=None):
1818
return out, err, p.returncode
1919

2020

21-
def get_video_metadata(path_to_video: str) -> dict[str, Any]:
21+
def get_video_metadata(path_to_video: str) -> dict[str]:
2222
command = [
2323
"ffprobe",
2424
"-v",
@@ -36,10 +36,10 @@ def get_video_metadata(path_to_video: str) -> dict[str, Any]:
3636
return json.loads(config)["streams"][0]
3737

3838

39-
def get_dir_layout(dirpath: str) -> list[str]:
39+
def get_dir_layout(dirpath: Path) -> Generator[str, None, None]:
4040
"""Get list of paths relative to dirpath of all files in dir and subdirs recursively."""
41-
index_files: list[str] = []
42-
for root, dirs, files in os.walk(dirpath):
43-
for file in files:
44-
index_files.append(f"{os.path.relpath(os.path.join(root, file), dirpath)}")
45-
return index_files
41+
for p in dirpath.iterdir():
42+
if p.is_dir():
43+
yield from get_dir_layout(p)
44+
continue
45+
yield str(p.relative_to(dirpath))

tests/helpers/graphical_units.py

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@
33

44
from __future__ import annotations
55

6-
import os
76
import tempfile
7+
from pathlib import Path
88

99
import numpy as np
1010

@@ -37,9 +37,9 @@ def set_test_scene(scene_object, module_name):
3737
config["frame_rate"] = 15
3838

3939
with tempfile.TemporaryDirectory() as tmpdir:
40-
os.makedirs(os.path.join(tmpdir, "tex"))
41-
config["text_dir"] = os.path.join(tmpdir, "text")
42-
config["tex_dir"] = os.path.join(tmpdir, "tex")
40+
temp_path = Path(tmpdir)
41+
config["text_dir"] = temp_path / "text"
42+
config["tex_dir"] = temp_path / "tex"
4343
scene = scene_object(skip_animations=True)
4444
scene.render()
4545
data = scene.renderer.get_frame()
@@ -48,14 +48,10 @@ def set_test_scene(scene_object, module_name):
4848
data == np.array([0, 0, 0, 255]),
4949
), f"Control data generated for {str(scene)} only contains empty pixels."
5050
assert data.shape == (480, 854, 4)
51-
tests_directory = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
52-
path_control_data = os.path.join(
53-
tests_directory,
54-
"control_data",
55-
"graphical_units_data",
56-
)
57-
path = os.path.join(path_control_data, module_name)
58-
if not os.path.isdir(path):
59-
os.makedirs(path)
60-
np.savez_compressed(os.path.join(path, str(scene)), frame_data=data)
51+
tests_directory = Path(__file__).absolute().parent.parent
52+
path_control_data = Path(tests_directory) / "control_data" / "graphical_units_data"
53+
path = Path(path_control_data) / module_name
54+
if not path.is_dir():
55+
path.mkdir(parents=True)
56+
np.savez_compressed(path / str(scene), frame_data=data)
6157
logger.info(f"Test data for {str(scene)} saved in {path}\n")

tests/helpers/video_utils.py

Lines changed: 17 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -3,31 +3,30 @@
33
from __future__ import annotations
44

55
import json
6-
import os
7-
import pathlib
6+
from pathlib import Path
87
from typing import Any
98

109
from manim import get_dir_layout, get_video_metadata, logger
1110

1211

13-
def get_section_dir_layout(dirpath: str) -> list[str]:
12+
def get_section_dir_layout(dirpath: Path) -> list[str]:
1413
"""Return a list of all files in the sections directory."""
1514
# test if sections have been created in the first place, doesn't work with multiple scene but this isn't an issue with tests
16-
if not os.path.isdir(dirpath):
15+
if not dirpath.is_dir():
1716
return []
18-
files = get_dir_layout(dirpath)
17+
files = list(get_dir_layout(dirpath))
1918
# indicate that the sections directory has been created
2019
files.append(".")
2120
return files
2221

2322

24-
def get_section_index(metapath: str) -> list[dict[str, Any]]:
23+
def get_section_index(metapath: Path) -> list[dict[str, Any]]:
2524
"""Return content of sections index file."""
26-
parent_folder = pathlib.Path(metapath).parent.absolute()
25+
parent_folder = metapath.parent.absolute()
2726
# test if sections have been created in the first place
28-
if not os.path.isdir(parent_folder):
27+
if not parent_folder.is_dir():
2928
return []
30-
with open(metapath) as file:
29+
with metapath.open() as file:
3130
index = json.load(file)
3231
return index
3332

@@ -51,28 +50,27 @@ def save_control_data_from_video(path_to_video: str, name: str) -> None:
5150
5251
See Also
5352
--------
53+
5454
tests/utils/video_tester.py : read control data and compare with output of test
5555
"""
56-
path_to_sections = os.path.join(
57-
pathlib.Path(path_to_video).parent.absolute(), "sections"
58-
)
59-
tests_directory = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
60-
path_control_data = os.path.join(tests_directory, "control_data", "videos_data")
56+
orig_path_to_sections = Path(path_to_video)
57+
path_to_sections = orig_path_to_sections.parent.absolute() / "sections"
58+
tests_directory = Path(__file__).absolute().parent.parent
59+
path_control_data = Path(tests_directory) / "control_data" / "videos_data"
6160
# this is the name of the section used in the test, not the name of the test itself, it can be found as a parameter of this function
62-
scene_name = "".join(os.path.basename(path_to_video).split(".")[:-1])
61+
scene_name = orig_path_to_sections.stem
6362

6463
movie_metadata = get_video_metadata(path_to_video)
6564
section_dir_layout = get_section_dir_layout(path_to_sections)
66-
section_index = get_section_index(
67-
os.path.join(path_to_sections, f"{scene_name}.json")
68-
)
65+
section_index = get_section_index(path_to_sections / f"{scene_name}.json")
66+
6967
data = {
7068
"name": name,
7169
"movie_metadata": movie_metadata,
7270
"section_dir_layout": section_dir_layout,
7371
"section_index": section_index,
7472
}
75-
path_saved = os.path.join(path_control_data, f"{name}.json")
73+
path_saved = Path(path_control_data) / f"{name}.json"
7674
with open(path_saved, "w") as f:
7775
json.dump(data, f, indent=4)
7876
logger.info(f"Data for {name} saved in {path_saved}")

tests/test_config.py

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -114,26 +114,24 @@ def test_custom_dirs(tmp_path):
114114
):
115115
scene = MyScene()
116116
scene.render()
117+
tmp_path = Path(tmp_path)
118+
assert_dir_filled(tmp_path / "test_sections")
119+
assert_file_exists(tmp_path / "test_sections/MyScene.json")
117120

118-
assert_dir_filled(os.path.join(tmp_path, "test_sections"))
119-
assert_file_exists(os.path.join(tmp_path, "test_sections", "MyScene.json"))
121+
assert_dir_filled(tmp_path / "test_video")
122+
assert_file_exists(tmp_path / "test_video/MyScene.mp4")
120123

121-
assert_dir_filled(os.path.join(tmp_path, "test_video"))
122-
assert_file_exists(os.path.join(tmp_path, "test_video", "MyScene.mp4"))
123-
124-
assert_dir_filled(os.path.join(tmp_path, "test_partial_movie_dir"))
124+
assert_dir_filled(tmp_path / "test_partial_movie_dir")
125125
assert_file_exists(
126-
os.path.join(
127-
tmp_path, "test_partial_movie_dir", "partial_movie_file_list.txt"
128-
)
126+
tmp_path / "test_partial_movie_dir/partial_movie_file_list.txt"
129127
)
130128

131129
# TODO: another example with image output would be nice
132-
assert_dir_exists(os.path.join(tmp_path, "test_images"))
130+
assert_dir_exists(tmp_path / "test_images")
133131

134-
assert_dir_filled(os.path.join(tmp_path, "test_text"))
135-
assert_dir_filled(os.path.join(tmp_path, "test_tex"))
136-
assert_dir_filled(os.path.join(tmp_path, "test_log"))
132+
assert_dir_filled(tmp_path / "test_text")
133+
assert_dir_filled(tmp_path / "test_tex")
134+
assert_dir_filled(tmp_path / "test_log")
137135

138136

139137
def test_frame_size(tmp_path):

tests/utils/GraphicalUnitTester.py

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import logging
44
import os
5+
from pathlib import Path
56

67
import numpy as np
78

@@ -34,27 +35,29 @@ class GraphicalUnitTester:
3435
def __init__(self, scene_class, module_tested, tmpdir, rgb_atol=0):
3536
# Disable the the logs, (--quiet is broken) TODO
3637
logging.disable(logging.CRITICAL)
37-
tests_directory = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
38-
self.path_tests_medias_cache = os.path.join(
39-
tmpdir,
40-
"test_graphical_units",
41-
"tests_cache",
42-
module_tested,
43-
scene_class.__name__,
38+
tests_directory = Path(__file__).absolute().parent.parent
39+
40+
self.path_tests_medias_cache = (
41+
Path(tmpdir)
42+
/ "test_graphical_units"
43+
/ "tests_cache"
44+
/ module_tested
45+
/ scene_class.__name__
4446
)
45-
self.path_control_data = os.path.join(
46-
tests_directory,
47-
"control_data",
48-
"graphical_units_data",
49-
module_tested,
47+
48+
self.path_control_data = (
49+
Path(tests_directory)
50+
/ "control_data"
51+
/ "graphical_units_data"
52+
/ module_tested
5053
)
5154
self.rgb_atol = rgb_atol
5255

5356
# IMPORTANT NOTE : The graphical units tests don't use for now any
5457
# custom manim.cfg, since it is impossible to manually select a
5558
# manim.cfg from a python file. (see issue #293)
56-
config["text_dir"] = os.path.join(self.path_tests_medias_cache, "Text")
57-
config["tex_dir"] = os.path.join(self.path_tests_medias_cache, "Tex")
59+
config["text_dir"] = Path(self.path_tests_medias_cache) / "Text"
60+
config["tex_dir"] = Path(self.path_tests_medias_cache) / "Tex"
5861

5962
config["disable_caching"] = True
6063
config["quality"] = "low_quality"
@@ -64,7 +67,7 @@ def __init__(self, scene_class, module_tested, tmpdir, rgb_atol=0):
6467
config["text_dir"],
6568
config["tex_dir"],
6669
]:
67-
os.makedirs(dir_temp)
70+
Path(dir_temp).mkdir(parents=True)
6871

6972
with tempconfig({"dry_run": True}):
7073
if config["renderer"] == "opengl":
@@ -81,9 +84,7 @@ def _load_data(self):
8184
:class:`numpy.array`
8285
The pre-rendered frame.
8386
"""
84-
frame_data_path = os.path.join(
85-
os.path.join(self.path_control_data, f"{self.scene}.npz"),
86-
)
87+
frame_data_path = Path(self.path_control_data) / f"{self.scene}.npz"
8788
return np.load(frame_data_path)["frame_data"]
8889

8990
def _show_diff_helper(self, frame_data, expected_frame_data):

tests/utils/video_tester.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@
22

33
import json
44
import os
5-
import pathlib
65
from functools import wraps
6+
from pathlib import Path
77

88
from manim import get_video_metadata
99

@@ -25,10 +25,7 @@ def check_video_data(path_control_data, path_video_gen):
2525
meta -> metadata
2626
"""
2727
# movie file specification
28-
path_sec_gen = os.path.join(
29-
pathlib.Path(path_video_gen).parent.absolute(),
30-
"sections",
31-
)
28+
path_sec_gen = Path(path_video_gen).parent.absolute() / "sections"
3229
control_data = load_control_data(path_control_data)
3330
movie_meta_gen = get_video_metadata(path_video_gen)
3431
movie_meta_exp = control_data["movie_metadata"]
@@ -51,8 +48,8 @@ def check_video_data(path_control_data, path_video_gen):
5148
raise AssertionError(f"Sections don't match:\n{mismatch}")
5249

5350
# sections index file
54-
scene_name = "".join(os.path.basename(path_video_gen).split(".")[:-1])
55-
path_sec_index_gen = os.path.join(path_sec_gen, f"{scene_name}.json")
51+
scene_name = Path(path_video_gen).stem
52+
path_sec_index_gen = path_sec_gen / f"{scene_name}.json"
5653
sec_index_gen = get_section_index(path_sec_index_gen)
5754
sec_index_exp = control_data["section_index"]
5855

0 commit comments

Comments
 (0)