text
stringlengths
2.1k
15.6k
check that config is correctly restored for k, v in original.items(): if isinstance(v, np.ndarray): np.testing.assert_allclose(config[k], v) else: assert config[k] == v @pytest.mark.parametrize( ("format", "expected_file_extension"), [ ("mp4", ".mp4"), ("webm", ".webm"), ("mov", ".mov"), ("gif", ".mp4"), ], ) def test_resolve_file_extensions(config, format, expected_file_extension): config.format = format assert config.movie_file_extension == expected_file_extension class MyScene(Scene): def construct(self): self.add(Square()) self.add(Text("Prepare for unforeseen consequencesλ")) self.add(Tex(r"$\lambda$")) self.wait(1) def test_transparent(config): """Test the 'transparent' config option.""" config.verbosity = "ERROR" config.dry_run = True scene = MyScene() scene.render() frame = scene.renderr.get_frame() np.testing.assert_allclose(frame[0, 0], [0, 0, 0, 255]) config.transparent = True scene = MyScene() scene.render() frame = scene.renderer.get_frame() np.testing.assert_allclose(frame[0, 0], [0, 0, 0, 0]) def test_transparent_by_background_opacity(config, dry_run): config.background_opacity = 0.5 assert config.transparent is True scene = MyScene() scene.render() frame = scene.renderer.get_frame() np.testing.assert_allclose(frame[0, 0], [0, 0, 0, 127]) assert config.movie_file_extension == ".mov" assert config.transparent is True def test_background_color(config): """Test the 'background_color' config option.""" config.background_color = WHITE config.verbosity = "ERROR" config.dry_run = True scene = MyScene() scene.render() frame = scene.renderer.get_frame() np.testing.assert_allclose(frame[0, 0], [255, 255, 255, 255]) def test_digest_file(tmp_path, config): """Test that a config file can be digested programmatically.""" with tempfile.NamedTemporaryFile("w", dir=tmp_path, delete=False) as tmp_cfg: tmp_cfg.write( """ [CLI] media_dir = this_is_my_favorite_path video_dir = {media_dir}/videos sections_dir = {media_dir}/{scene_name}/prepare_for_unforeseen_consequences frame_height = 10 """, ) config.digest_file(tmp_cfg.name) assert config.get_dir("media_dir") == Path("this_is_my_favorite_path") assert config.get_dir("video_dir") == Path("this_is_my_favorite_path/videos") assert config.get_dir("sections_dir", scene_name="test") == Path( "this_is_my_favorite_path/test/prepare_for_unforeseen_consequences" ) def test_custom_dirs(tmp_path, config): config.media_dir = tmp_path config.save_sections = True config.log_to_file = True config.frame_rate = 15 config.pixel_height = 854 config.pixel_width = 480 config.sections_dir = "{media_dir}/test_sections" config.video_dir = "{media_dir}/test_video" config.partial_movie_dir = "{media_dir}/test_partial_movie_dir" config.images_dir = "{media_dir}/test_images" config.text_dir = "{media_dir}/test_text" config.tex_dir = "{media_dir}/test_tex" config.log_dir = "{media_dir}/test_log" scene = MyScene() scene.render() tmp_path = Path(tmp_path) assert_dir_filled(tmp_path / "test_sections") assert_file_exists(tmp_path / "test_sections/MyScene.json") assert_dir_filled(tmp_path / "test_video") assert_file_exists(tmp_path / "test_video/MyScene.mp4") assert_dir_filled(tmp_path / "test_partial_movie_dir") assert_file_exists(tmp_path / "test_partial_movie_dir/partial_movie_file_list.txt") # TODO: another example with image output would be nice assert_dir_exists(tmp_path / "test_images") assert_dir_filled(tmp_path / "test_text") assert_dir_filled(tmp_path / "test_tex") assert_dir_filled(tmp_path / "test_log") def test_pixel_dimensions(tmp_path, config): with tempfile.NamedTemporaryFile("w", dir=tmp_path, delete=False) as tmp_cfg: tmp_cfg.write( """ [CLI] pixel_height = 10 pixel_width = 10 """, ) config.digest_file(tmp_cfg.name) # aspect ratio is set using pixel measurements np.testing.assert_allclose(config.aspect_ratio, 1.0) # if not specified in the cfg file, frame_width is set using the aspect ratio np.testing.assert_allclose(config.frame_height, 8.0) np.testing.assert_allclose(config.frame_width, 8.0) def test_frame_size(tmp_path, config): """Test that the frame size can be set via config file.""" np.testing.assert_allclose( config.aspect_ratio, config.pixel_width / config.pixel_height ) np.testing.assert_allclose(config.frame_height, 8.0) with tempfile.NamedTemporaryFile("w", dir=tmp_path, delete=False) as tmp_cfg: tmp_cfg.write( """ [CLI] pixel_height = 10 pixel_width = 10 frame_height = 10 frame_width = 10 """, ) config.digest_file(tmp_cfg.name) np.testing.assert_allclose(config.aspect_ratio, 1.0) # if both are specified in the cfg file, the aspect ratio is ignored np.testing.assert_allclose(config.frame_height, 10.0) np.testing.assert_allclose(config.frame_width, 10.0) def test_temporary_dry_run(config): """Test that tempconfig correctly restores after setting dry_run.""" assert config["write_to_movie"] assert not config["save_last_frame"] with tempconfig({"dry_run": True}): assert not config["write_to_movie"] assert not config["save_last_frame"] assert config["write_to_movie"] assert not config["save_last_frame"] def test_dry_run_with_png_format(config, dry_run): """Test that there are no exceptions when running a png without output""" config.write_to_movie = False config.disable_caching = True assert config.dry_run is True scene = MyScene() scene.render() def test_dry_run_with_png_format_skipped_animations(config, dry_run): """Test that there are no exceptions when running a png without output and skipped animations""" config.write_to_movie = False config.disable_caching = True assert config["dry_run"] is
are no exceptions when running a png without output""" config.write_to_movie = False config.disable_caching = True assert config.dry_run is True scene = MyScene() scene.render() def test_dry_run_with_png_format_skipped_animations(config, dry_run): """Test that there are no exceptions when running a png without output and skipped animations""" config.write_to_movie = False config.disable_caching = True assert config["dry_run"] is True scene = MyScene(skip_animations=True) scene.render() def test_tex_template_file(tmp_path): """Test that a custom tex template file can be set from a config file.""" tex_file = Path(tmp_path / "my_template.tex") tex_file.write_text("Hello World!") with tempfile.NamedTemporaryFile("w", dir=tmp_path, delete=False) as tmp_cfg: tmp_cfg.write( f""" [CLI] tex_template_file = {tex_file} """, ) custom_config = ManimConfig().digest_file(tmp_cfg.name) assert Path(custom_config.tex_template_file) == tex_file assert custom_config.tex_template.body == "Hello World!" def test_from_to_animations_only_first_animation(config): config: ManimConfig config.from_animation_number = 0 config.upto_animation_number = 0 class SceneWithTwoAnimations(Scene): def construct(self): self.after_first_animation = False s = Square() self.add(s) self.play(s.animate.scale(2)) self.renderer.update_skipping_status() self.after_first_animation = True self.play(s.animate.scale(2)) scene = SceneWithTwoAnimations() scene.render() assert scene.after_first_animation is False ================================================ FILE: tests/test_ipython_magic.py ================================================ from __future__ import annotations import re from manim.utils.ipython_magic import _generate_file_name def test_jupyter_file_naming(config): """Check the format of file names for jupyter""" scene_name = "SimpleScene" expected_pattern = r"[0-9a-zA-Z_]+[@_-]\d\d\d\d-\d\d-\d\d[@_-]\d\d-\d\d-\d\d" config.scene_names = [scene_name] file_name = _generate_file_name() match = re.match(expected_pattern, file_name) assert scene_name in file_name, ( "Expected file to contain " + scene_name + " but got " + file_name ) assert match, "file name does not match expected pattern " + expected_pattern def test_jupyter_file_output(tmp_path, config): """Check the jupyter file naming is valid and can be created""" scene_name = "SimpleScene" config.scene_names = [scene_name] file_name = _generate_file_name() actual_path = tmp_path.with_name(file_name) with actual_path.open("w") as outfile: outfile.write("") assert actual_path.exists() assert actual_path.is_file() ================================================ FILE: tests/test_linear_transformation_scene.py ================================================ from manim import RIGHT, UP, LinearTransformationScene, Vector, VGroup __module_test__ = "vector_space_scene" def test_ghost_vectors_len_and_types(): scene = LinearTransformationScene() scene.leave_ghost_vectors = True # prepare vectors (they require a vmobject as their target) v1, v2 = Vector(RIGHT), Vector(RIGHT) v1.target, v2.target = Vector(UP), Vector(UP) # ghost_vector addition is in this method scene.get_piece_movement((v1, v2)) ghosts = scene.get_ghost_vectors() assert len(ghosts) == 1 # check if there are two vectors in the ghost vector VGroup assert len(ghosts[0]) == 2 # check types of ghost vectors assert isinstance(ghosts, VGroup) assert isinstance(ghosts[0], VGroup) assert all(isinstance(x, Vector) for x in ghosts[0]) ================================================ FILE: tests/control_data/logs_data/bad_tex_scene_BadTex.txt ================================================ {"levelname": "INFO", "module": "logger_utils", "message": "Log file will be saved in <>"} {"levelname": "INFO", "module": "tex_file_writing", "message": "Writing <> to <>"} {"levelname": "ERROR", "module": "tex_file_writing", "message": "LaTeX compilation error: LaTeX Error: File `notapackage.sty' not found.\n"} {"levelname": "ERROR", "module": "tex_file_writing", "message": "Context of error: \n\\documentclass[preview]{standalone}\n-> \\usepackage{notapackage}\n\\begin{document}\n\\begin{center}\n\\frac{1}{0}\n"} {"levelname": "INFO", "module": "tex_file_writing", "message": "You do not have package notapackage.sty installed."} {"levelname": "INFO", "module": "tex_file_writing", "message": "Install notapackage.sty it using your LaTeX package manager, or check for typos."} {"levelname": "ERROR", "module": "tex_file_writing", "message": "LaTeX compilation error: Emergency stop.\n"} {"levelname": "ERROR", "module": "tex_file_writing", "message": "Context of error: \n\\documentclass[preview]{standalone}\n-> \\usepackage{notapackage}\n\\begin{document}\n\\begin{center}\n\\frac{1}{0}\n"} ================================================ FILE: tests/control_data/logs_data/BasicSceneLoggingTest.txt ================================================ {"levelname": "INFO", "module": "logger_utils", "message": "Log file will be saved in <>"} {"levelname": "DEBUG", "module": "hashing", "message": "Hashing ..."} {"levelname": "DEBUG", "module": "hashing", "message": "Hashing done in <> s."} {"levelname": "DEBUG", "module": "hashing", "message": "Hash generated : <>"} {"levelname": "DEBUG", "module": "cairo_renderer", "message": "List of the first few animation hashes of the scene: <>"} {"levelname": "INFO", "module": "scene_file_writer",
be saved in <>"} {"levelname": "DEBUG", "module": "hashing", "message": "Hashing ..."} {"levelname": "DEBUG", "module": "hashing", "message": "Hashing done in <> s."} {"levelname": "DEBUG", "module": "hashing", "message": "Hash generated : <>"} {"levelname": "DEBUG", "module": "cairo_renderer", "message": "List of the first few animation hashes of the scene: <>"} {"levelname": "INFO", "module": "scene_file_writer", "message": "Animation 0 : Partial movie file written in <>"} {"levelname": "INFO", "module": "scene_file_writer", "message": "Combining to Movie file."} {"levelname": "DEBUG", "module": "scene_file_writer", "message": "Partial movie files to combine (1 files): <>"} {"levelname": "INFO", "module": "scene_file_writer", "message": "\nFile ready at <>\n"} {"levelname": "INFO", "module": "scene", "message": "Rendered SquareToCircle\nPlayed 1 animations"} ================================================ FILE: tests/control_data/videos_data/InputFileViaCfg.json ================================================ { "name": "InputFileViaCfg", "movie_metadata": { "codec_name": "h264", "width": 854, "height": 480, "avg_frame_rate": "15/1", "duration": "1.000000", "nb_frames": "15", "pix_fmt": "yuv420p" }, "section_dir_layout": [], "section_index": [] } ================================================ FILE: tests/control_data/videos_data/SceneWithDisabledSections.json ================================================ { "name": "SceneWithDisabledSections", "movie_metadata": { "codec_name": "h264", "width": 854, "height": 480, "avg_frame_rate": "15/1", "duration": "1.000000", "nb_frames": "15", "pix_fmt": "yuv420p" }, "section_dir_layout": [], "section_index": [] } ================================================ FILE: tests/control_data/videos_data/SceneWithEnabledSections.json ================================================ { "name": "SceneWithEnabledSections", "movie_metadata": { "codec_name": "h264", "width": 854, "height": 480, "avg_frame_rate": "15/1", "duration": "1.000000", "nb_frames": "15", "pix_fmt": "yuv420p" }, "section_dir_layout": [ "SquareToCircle.json", "SquareToCircle_0000_autocreated.mp4", "." ], "section_index": [ { "name": "autocreated", "type": "default.normal", "video": "SquareToCircle_0000_autocreated.mp4", "codec_name": "h264", "width": 854, "height": 480, "avg_frame_rate": "15/1", "duration": "1.000000", "nb_frames": "15", "pix_fmt": "yuv420p" } ] } ================================================ FILE: tests/control_data/videos_data/SceneWithMultipleCallsWithNFlag.json ================================================ { "name": "SceneWithMultipleCallsWithNFlag", "movie_metadata": { "codec_name": "h264", "width": 854, "height": 480, "avg_frame_rate": "15/1", "duration": "4.000000", "nb_frames": "60", "pix_fmt": "yuv420p" }, "section_dir_layout": [], "section_index": [] } ================================================ FILE: tests/control_data/videos_data/SceneWithMultiplePlayCallsWithNFlag.json ================================================ { "name": "SceneWithMultiplePlayCallsWithNFlag", "movie_metadata": { "codec_name": "h264", "width": 854, "height": 480, "avg_frame_rate": "15/1", "duration": "7.000000", "nb_frames": "105", "pix_fmt": "yuv420p" }, "section_dir_layout": [], "section_index": [] } ================================================ FILE: tests/control_data/videos_data/SceneWithMultipleWaitCallsWithNFlag.json ================================================ { "name": "SceneWithMultipleWaitCallsWithNFlag", "movie_metadata": { "codec_name": "h264", "width": 854, "height": 480, "avg_frame_rate": "15/1", "duration": "5.000000", "nb_frames": "75", "pix_fmt": "yuv420p" }, "section_dir_layout": [], "section_index": [] } ================================================ FILE: tests/control_data/videos_data/SceneWithSections.json ================================================ { "name": "SceneWithSections", "movie_metadata": { "codec_name": "h264", "width": 854, "height": 480, "avg_frame_rate": "15/1", "duration": "7.000000", "nb_frames": "105", "pix_fmt": "yuv420p" }, "section_dir_layout": [ "SceneWithSections.json", "SceneWithSections_0004_unnamed.mp4", "SceneWithSections_0003_Prepare For Unforeseen Consequences..mp4", "SceneWithSections_0002_test.mp4", "SceneWithSections_0001_unnamed.mp4", "SceneWithSections_0000_autocreated.mp4", "." ], "section_index": [ { "name": "autocreated", "type": "default.normal", "video": "SceneWithSections_0000_autocreated.mp4", "codec_name": "h264", "width": 854, "height": 480, "avg_frame_rate": "15/1", "duration": "1.000000", "nb_frames": "15", "pix_fmt": "yuv420p" }, { "name": "unnamed", "type": "default.normal", "video": "SceneWithSections_0001_unnamed.mp4", "codec_name": "h264", "width": 854, "height": 480, "avg_frame_rate": "15/1", "duration": "2.000000", "nb_frames": "30", "pix_fmt": "yuv420p" }, { "name": "test", "type": "default.normal", "video": "SceneWithSections_0002_test.mp4", "codec_name": "h264", "width": 854, "height": 480, "avg_frame_rate": "15/1", "duration": "1.000000", "nb_frames": "15", "pix_fmt": "yuv420p" }, { "name": "Prepare For Unforeseen Consequences.", "type": "default.normal", "video": "SceneWithSections_0003_Prepare For Unforeseen Consequences..mp4", "codec_name": "h264", "width": 854, "height": 480, "avg_frame_rate": "15/1", "duration": "2.000000", "nb_frames": "30", "pix_fmt": "yuv420p" }, { "name": "unnamed", "type": "presentation.skip", "video": "SceneWithSections_0004_unnamed.mp4", "codec_name": "h264", "width": 854, "height": 480, "avg_frame_rate": "15/1", "duration": "1.000000", "nb_frames": "15", "pix_fmt": "yuv420p" } ] } ================================================ FILE: tests/control_data/videos_data/SceneWithSkipAnimations.json ================================================ { "name": "SceneWithSkipAnimations", "movie_metadata": { "codec_name": "h264", "width": 854, "height": 480, "avg_frame_rate": "15/1", "duration": "6.000000", "nb_frames": "90", "pix_fmt": "yuv420p" }, "section_dir_layout": [ "ElaborateSceneWithSections.json", "ElaborateSceneWithSections_0003_fade out.mp4", "ElaborateSceneWithSections_0001_transform to circle.mp4", "ElaborateSceneWithSections_0000_create square.mp4", "." ], "section_index": [ { "name": "create square",
"1.000000", "nb_frames": "15", "pix_fmt": "yuv420p" } ] } ================================================ FILE: tests/control_data/videos_data/SceneWithSkipAnimations.json ================================================ { "name": "SceneWithSkipAnimations", "movie_metadata": { "codec_name": "h264", "width": 854, "height": 480, "avg_frame_rate": "15/1", "duration": "6.000000", "nb_frames": "90", "pix_fmt": "yuv420p" }, "section_dir_layout": [ "ElaborateSceneWithSections.json", "ElaborateSceneWithSections_0003_fade out.mp4", "ElaborateSceneWithSections_0001_transform to circle.mp4", "ElaborateSceneWithSections_0000_create square.mp4", "." ], "section_index": [ { "name": "create square", "type": "default.normal", "video": "ElaborateSceneWithSections_0000_create square.mp4", "codec_name": "h264", "width": 854, "height": 480, "avg_frame_rate": "15/1", "duration": "2.000000", "nb_frames": "30", "pix_fmt": "yuv420p" }, { "name": "transform to circle", "type": "default.normal", "video": "ElaborateSceneWithSections_0001_transform to circle.mp4", "codec_name": "h264", "width": 854, "height": 480, "avg_frame_rate": "15/1", "duration": "2.000000", "nb_frames": "30", "pix_fmt": "yuv420p" }, { "name": "fade out", "type": "default.normal", "video": "ElaborateSceneWithSections_0003_fade out.mp4", "codec_name": "h264", "width": 854, "height": 480, "avg_frame_rate": "15/1", "duration": "2.000000", "nb_frames": "30", "pix_fmt": "yuv420p" } ] } ================================================ FILE: tests/control_data/videos_data/SquareToCircleWithDefaultValues.json ================================================ { "name": "SquareToCircleWithDefaultValues", "movie_metadata": { "codec_name": "h264", "width": 1920, "height": 1080, "avg_frame_rate": "60/1", "duration": "1.000000", "nb_frames": "60", "pix_fmt": "yuv420p" }, "section_dir_layout": [], "section_index": [] } ================================================ FILE: tests/control_data/videos_data/SquareToCircleWithlFlag.json ================================================ { "name": "SquareToCircleWithlFlag", "movie_metadata": { "codec_name": "h264", "width": 854, "height": 480, "avg_frame_rate": "15/1", "duration": "1.000000", "nb_frames": "15", "pix_fmt": "yuv420p" }, "section_dir_layout": [], "section_index": [] } ================================================ FILE: tests/helpers/__init__.py ================================================ [Empty file] ================================================ FILE: tests/helpers/graphical_units.py ================================================ """Helpers functions for devs to set up new graphical-units data.""" from __future__ import annotations import logging import tempfile from pathlib import Path import numpy as np from manim.scene.scene import Scene logger = logging.getLogger("manim") def set_test_scene(scene_object: type[Scene], module_name: str, config): """Function used to set up the test data for a new feature. This will basically set up a pre-rendered frame for a scene. This is meant to be used only when setting up tests. Please refer to the wiki. Parameters ---------- scene_object The scene with which we want to set up a new test. module_name The name of the module in which the functionality tested is contained. For example, ``Write`` is contained in the module ``creation``. This will be used in the folder architecture of ``/tests_data``. Examples -------- Normal usage:: set_test_scene(DotTest, "geometry") """ config["write_to_movie"] = False config["disable_caching"] = True config["format"] = "png" config["pixel_height"] = 480 config["pixel_width"] = 854 config["frame_rate"] = 15 with tempfile.TemporaryDirectory() as tmpdir: temp_path = Path(tmpdir) config["text_dir"] = temp_path / "text" config["tex_dir"] = temp_path / "tex" scene = scene_object(skip_animations=True) scene.render() data = scene.renderer.get_frame() assert not np.all( data == np.array([0, 0, 0, 255]), ), f"Control data generated for {scene!s} only contains empty pixels." assert data.shape == (480, 854, 4) tests_directory = Path(__file__).absolute().parent.parent path_control_data = Path(tests_directory) / "control_data" / "graphical_units_data" path = Path(path_control_data) / module_name if not path.is_dir(): path.mkdir(parents=True) np.savez_compressed(path / str(scene), frame_data=data) logger.info(f"Test data for {str(scene)} saved in {path}\n") ================================================ FILE: tests/helpers/path_utils.py ================================================ from __future__ import annotations from pathlib import Path def get_project_root() -> Path: return Path(__file__).parent.parent.parent def get_svg_resource(filename): return str( get_project_root() / "tests/test_graphical_units/img_svg_resources" / filename, ) ================================================ FILE: tests/helpers/video_utils.py ================================================ """Helpers for dev to set up new tests that use videos.""" from __future__ import annotations import json from pathlib import Path from typing import Any from manim import get_dir_layout, get_video_metadata, logger def get_section_dir_layout(dirpath: Path) -> list[str]: """Return a list of all files in the sections directory.""" # test if
================================================ """Helpers for dev to set up new tests that use videos.""" from __future__ import annotations import json from pathlib import Path from typing import Any from manim import get_dir_layout, get_video_metadata, logger def get_section_dir_layout(dirpath: Path) -> list[str]: """Return a list of all files in the sections directory.""" # test if sections have been created in the first place, doesn't work with multiple scene but this isn't an issue with tests if not dirpath.is_dir(): return [] files = list(get_dir_layout(dirpath)) # indicate that the sections directory has been created files.append(".") return files def get_section_index(metapath: Path) -> list[dict[str, Any]]: """Return content of sections index file.""" parent_folder = metapath.parent.absolute() # test if sections have been created in the first place if not parent_folder.is_dir(): return [] with metapath.open() as file: index = json.load(file) return index def save_control_data_from_video(path_to_video: Path, name: str) -> None: """Helper used to set up a new test that will compare videos. This will create a new ``.json`` file in ``control_data/videos_data`` that contains: - the name of the video, - the metadata of the video, like fps and resolution and - the paths of all files in the sections subdirectory (like section videos). Refer to the documentation for more information. Parameters ---------- path_to_video Path to the video to extract information from. name Name of the test. The .json file will be named with it. See Also -------- tests/utils/video_tester.py : read control data and compare with output of test """ orig_path_to_sections = path_to_video path_to_sections = orig_path_to_sections.parent.absolute() / "sections" tests_directory = Path(__file__).absolute().parent.parent path_control_data = Path(tests_directory) / "control_data" / "videos_data" # 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 scene_name = orig_path_to_sections.stem movie_metadata = get_video_metadata(path_to_video) section_dir_layout = get_section_dir_layout(path_to_sections) section_index = get_section_index(path_to_sections / f"{scene_name}.json") data = { "name": name, "movie_metadata": movie_metadata, "section_dir_layout": section_dir_layout, "section_index": section_index, } path_saved = Path(path_control_data) / f"{name}.json" with path_saved.open("w") as f: json.dump(data, f, indent=4) logger.info(f"Data for {name} saved in {path_saved}") ================================================ FILE: tests/interface/test_commands.py ================================================ from __future__ import annotations import shutil import sys from pathlib import Path from textwrap import dedent from unittest.mock import patch from click.testing import CliRunner from manim import __version__, capture from manim.__main__ import main from manim.cli.checkhealth.checks import HEALTH_CHECKS def test_manim_version(): command = [ sys.executable, "-m", "manim", "--version", ] out, err, exit_code = capture(command) assert exit_code == 0, err assert __version__ in out def test_manim_cfg_subcommand(): command = ["cfg"] runner = CliRunner() result = runner.invoke(main, command, prog_name="manim") expected_output = f"""\ Manim Community v{__version__} Usage: manim cfg [OPTIONS] COMMAND [ARGS]... Manages Manim configuration files. Options: --help Show this message and exit. Commands: export show write Made with <3 by Manim Community developers. """ assert dedent(expected_output) == result.stdout def test_manim_plugins_subcommand(): command = ["plugins"] runner = CliRunner() result = runner.invoke(main, command, prog_name="manim") expected_output = f"""\ Manim Community v{__version__} Usage: manim plugins [OPTIONS] Manages Manim plugins. Options: -l, --list List available plugins. --help Show this message and exit. Made with <3 by Manim Community developers. """ assert dedent(expected_output) == result.output def test_manim_checkhealth_subcommand(): command = ["checkhealth"] runner
= CliRunner() result = runner.invoke(main, command, prog_name="manim") expected_output = f"""\ Manim Community v{__version__} Usage: manim plugins [OPTIONS] Manages Manim plugins. Options: -l, --list List available plugins. --help Show this message and exit. Made with <3 by Manim Community developers. """ assert dedent(expected_output) == result.output def test_manim_checkhealth_subcommand(): command = ["checkhealth"] runner = CliRunner() result = runner.invoke(main, command) output_lines = result.output.split("\n") num_passed = len([line for line in output_lines if "PASSED" in line]) assert num_passed == len(HEALTH_CHECKS), ( f"Some checks failed! Full output:\n{result.output}" ) assert "No problems detected, your installation seems healthy!" in output_lines def test_manim_checkhealth_failing_subcommand(): command = ["checkhealth"] runner = CliRunner() true_f = shutil.which def mock_f(s): if s == "latex": return None return true_f(s) with patch.object(shutil, "which", new=mock_f): result = runner.invoke(main, command) output_lines = result.output.split("\n") assert "- Checking whether latex is available ... FAILED" in output_lines assert "- Checking whether dvisvgm is available ... SKIPPED" in output_lines def test_manim_init_subcommand(): command = ["init"] runner = CliRunner() result = runner.invoke(main, command, prog_name="manim") expected_output = f"""\ Manim Community v{__version__} Usage: manim init [OPTIONS] COMMAND [ARGS]... Create a new project or insert a new scene. Options: --help Show this message and exit. Commands: project Creates a new project. scene Inserts a SCENE to an existing FILE or creates a new FILE. Made with <3 by Manim Community developers. """ assert dedent(expected_output) == result.output def test_manim_init_project(tmp_path): command = ["init", "project", "--default", "testproject"] runner = CliRunner() with runner.isolated_filesystem(temp_dir=tmp_path) as tmp_dir: result = runner.invoke(main, command, prog_name="manim", input="Default\n") assert not result.exception assert (Path(tmp_dir) / "testproject/main.py").exists() assert (Path(tmp_dir) / "testproject/manim.cfg").exists() def test_manim_init_scene(tmp_path): command_named = ["init", "scene", "NamedFileTestScene", "my_awesome_file.py"] command_unnamed = ["init", "scene", "DefaultFileTestScene"] runner = CliRunner() with runner.isolated_filesystem(temp_dir=tmp_path) as tmp_dir: result = runner.invoke( main, command_named, prog_name="manim", input="Default\n" ) assert not result.exception assert (Path(tmp_dir) / "my_awesome_file.py").exists() file_content = (Path(tmp_dir) / "my_awesome_file.py").read_text() assert "NamedFileTestScene(Scene):" in file_content result = runner.invoke( main, command_unnamed, prog_name="manim", input="Default\n" ) assert (Path(tmp_dir) / "main.py").exists() file_content = (Path(tmp_dir) / "main.py").read_text() assert "DefaultFileTestScene(Scene):" in file_content ================================================ FILE: tests/miscellaneous/test_version.py ================================================ from __future__ import annotations from importlib.metadata import version from manim import __name__, __version__ def test_version(): assert __version__ == version(__name__) ================================================ FILE: tests/module/animation/test_animate.py ================================================ from __future__ import annotations import numpy as np import pytest from manim.animation.creation import Uncreate from manim.mobject.geometry.arc import Dot from manim.mobject.geometry.line import Line from manim.mobject.geometry.polygram import Square from manim.mobject.mobject import override_animate from manim.mobject.types.vectorized_mobject import VGroup def test_simple_animate(): s = Square() scale_factor = 2 anim = s.animate.scale(scale_factor).build() assert anim.mobject.target.width == scale_factor * s.width def test_chained_animate(): s = Square() scale_factor = 2 direction = np.array((1, 1, 0)) anim = s.animate.scale(scale_factor).shift(direction).build() assert anim.mobject.target.width == scale_factor * s.width assert (anim.mobject.target.get_center() == direction).all() def test_overridden_animate(): class DotsWithLine(VGroup): def __init__(self): super().__init__() self.left_dot = Dot().shift((-1, 0, 0)) self.right_dot = Dot().shift((1, 0, 0)) self.line = Line(self.left_dot, self.right_dot) self.add(self.left_dot, self.right_dot, self.line) def remove_line(self): self.remove(self.line) @override_animate(remove_line) def _remove_line_animation(self, anim_args=None): if anim_args is None: anim_args = {} self.remove_line() return Uncreate(self.line, **anim_args) dots_with_line = DotsWithLine() anim = dots_with_line.animate.remove_line().build() assert len(dots_with_line.submobjects) == 2 assert type(anim) is Uncreate def test_chaining_overridden_animate(): class DotsWithLine(VGroup): def __init__(self): super().__init__() self.left_dot = Dot().shift((-1, 0, 0)) self.right_dot = Dot().shift((1, 0, 0)) self.line = Line(self.left_dot, self.right_dot) self.add(self.left_dot, self.right_dot, self.line) def remove_line(self):
anim_args is None: anim_args = {} self.remove_line() return Uncreate(self.line, **anim_args) dots_with_line = DotsWithLine() anim = dots_with_line.animate.remove_line().build() assert len(dots_with_line.submobjects) == 2 assert type(anim) is Uncreate def test_chaining_overridden_animate(): class DotsWithLine(VGroup): def __init__(self): super().__init__() self.left_dot = Dot().shift((-1, 0, 0)) self.right_dot = Dot().shift((1, 0, 0)) self.line = Line(self.left_dot, self.right_dot) self.add(self.left_dot, self.right_dot, self.line) def remove_line(self): self.remove(self.line) @override_animate(remove_line) def _remove_line_animation(self, anim_args=None): if anim_args is None: anim_args = {} self.remove_line() return Uncreate(self.line, **anim_args) with pytest.raises( NotImplementedError, match="not supported for overridden animations", ): DotsWithLine().animate.shift((1, 0, 0)).remove_line() with pytest.raises( NotImplementedError, match="not supported for overridden animations", ): DotsWithLine().animate.remove_line().shift((1, 0, 0)) def test_animate_with_args(): s = Square() scale_factor = 2 run_time = 2 anim = s.animate(run_time=run_time).scale(scale_factor).build() assert anim.mobject.target.width == scale_factor * s.width assert anim.run_time == run_time def test_chained_animate_with_args(): s = Square() scale_factor = 2 direction = np.array((1, 1, 0)) run_time = 2 anim = s.animate(run_time=run_time).scale(scale_factor).shift(direction).build() assert anim.mobject.target.width == scale_factor * s.width assert (anim.mobject.target.get_center() == direction).all() assert anim.run_time == run_time def test_animate_with_args_misplaced(): s = Square() scale_factor = 2 run_time = 2 with pytest.raises(ValueError, match="must be passed before"): s.animate.scale(scale_factor)(run_time=run_time) with pytest.raises(ValueError, match="must be passed before"): s.animate(run_time=run_time)(run_time=run_time).scale(scale_factor) ================================================ FILE: tests/module/animation/test_animation.py ================================================ from __future__ import annotations import pytest from manim import FadeIn, Scene def test_animation_zero_total_run_time(): test_scene = Scene() with pytest.raises( ValueError, match="The total run_time must be a positive number." ): test_scene.play(FadeIn(None, run_time=0)) def test_single_animation_zero_run_time_with_more_animations(): test_scene = Scene() test_scene.play(FadeIn(None, run_time=0), FadeIn(None, run_time=1)) def test_animation_negative_run_time(): with pytest.raises(ValueError, match="The run_time of FadeIn cannot be negative."): FadeIn(None, run_time=-1) def test_animation_run_time_shorter_than_frame_rate(manim_caplog, config): test_scene = Scene() test_scene.play(FadeIn(None, run_time=1 / (config.frame_rate + 1))) assert "too short for the current frame rate" in manim_caplog.text @pytest.mark.parametrize("duration", [0, -1]) def test_wait_invalid_duration(duration): test_scene = Scene() with pytest.raises(ValueError, match="The duration must be a positive number."): test_scene.wait(duration) @pytest.mark.parametrize("frozen_frame", [False, True]) def test_wait_duration_shorter_than_frame_rate(manim_caplog, frozen_frame): test_scene = Scene() test_scene.wait(1e-9, frozen_frame=frozen_frame) assert "too short for the current frame rate" in manim_caplog.text @pytest.mark.parametrize("duration", [0, -1]) def test_pause_invalid_duration(duration): test_scene = Scene() with pytest.raises(ValueError, match="The duration must be a positive number."): test_scene.pause(duration) @pytest.mark.parametrize("max_time", [0, -1]) def test_wait_until_invalid_max_time(max_time): test_scene = Scene() with pytest.raises(ValueError, match="The max_time must be a positive number."): test_scene.wait_until(lambda: True, max_time) ================================================ FILE: tests/module/animation/test_composition.py ================================================ from __future__ import annotations from unittest.mock import MagicMock import pytest from manim.animation.animation import Animation, Wait from manim.animation.composition import AnimationGroup, Succession from manim.animation.creation import Create, Write from manim.animation.fading import FadeIn, FadeOut from manim.constants import DOWN, UP from manim.mobject.geometry.arc import Circle from manim.mobject.geometry.line import Line from manim.mobject.geometry.polygram import RegularPolygon, Square from manim.scene.scene import Scene def test_succession_timing(): """Test timing of animations in a succession.""" line = Line() animation_1s = FadeIn(line, shift=UP, run_time=1.0) animation_4s = FadeOut(line, shift=DOWN, run_time=4.0) succession = Succession(animation_1s, animation_4s) assert succession.get_run_time() == 5.0 succession._setup_scene(MagicMock()) succession.begin() assert succession.active_index == 0 # The first animation takes 20% of the total run time. succession.interpolate(0.199) assert succession.active_index == 0 succession.interpolate(0.2) assert succession.active_index == 1 succession.interpolate(0.8) assert succession.active_index == 1 # At 100% and more, no animation must be active anymore. succession.interpolate(1.0) assert succession.active_index == 2 assert succession.active_animation is None succession.interpolate(1.2) assert succession.active_index == 2 assert succession.active_animation is None def test_succession_in_succession_timing(): """Test timing of nested successions.""" line = Line() animation_1s = FadeIn(line, shift=UP, run_time=1.0) animation_4s = FadeOut(line, shift=DOWN, run_time=4.0) nested_succession = Succession(animation_1s, animation_4s) succession =
no animation must be active anymore. succession.interpolate(1.0) assert succession.active_index == 2 assert succession.active_animation is None succession.interpolate(1.2) assert succession.active_index == 2 assert succession.active_animation is None def test_succession_in_succession_timing(): """Test timing of nested successions.""" line = Line() animation_1s = FadeIn(line, shift=UP, run_time=1.0) animation_4s = FadeOut(line, shift=DOWN, run_time=4.0) nested_succession = Succession(animation_1s, animation_4s) succession = Succession( FadeIn(line, shift=UP, run_time=4.0), nested_succession, FadeIn(line, shift=UP, run_time=1.0), ) assert nested_succession.get_run_time() == 5.0 assert succession.get_run_time() == 10.0 succession._setup_scene(MagicMock()) succession.begin() succession.interpolate(0.1) assert succession.active_index == 0 # The nested succession must not be active yet, and as a result hasn't set active_animation yet. assert not hasattr(nested_succession, "active_animation") succession.interpolate(0.39) assert succession.active_index == 0 assert not hasattr(nested_succession, "active_animation") # The nested succession starts at 40% of total run time succession.interpolate(0.4) assert succession.active_index == 1 assert nested_succession.active_index == 0 # The nested succession second animation starts at 50% of total run time. succession.interpolate(0.49) assert succession.active_index == 1 assert nested_succession.active_index == 0 succession.interpolate(0.5) assert succession.active_index == 1 assert nested_succession.active_index == 1 # The last animation starts at 90% of total run time. The nested succession must be finished at that time. succession.interpolate(0.89) assert succession.active_index == 1 assert nested_succession.active_index == 1 succession.interpolate(0.9) assert succession.active_index == 2 assert nested_succession.active_index == 2 assert nested_succession.active_animation is None # After 100%, nothing must be playing anymore. succession.interpolate(1.0) assert succession.active_index == 3 assert succession.active_animation is None assert nested_succession.active_index == 2 assert nested_succession.active_animation is None def test_timescaled_succession(): s1, s2, s3 = Square(), Square(), Square() anim = Succession( FadeIn(s1, run_time=2), FadeIn(s2), FadeIn(s3), ) anim.scene = MagicMock() anim.run_time = 42 anim.begin() anim.interpolate(0.2) assert anim.active_index == 0 anim.interpolate(0.4) assert anim.active_index == 0 anim.interpolate(0.6) assert anim.active_index == 1 anim.interpolate(0.8) assert anim.active_index == 2 def test_animationbuilder_in_group(): sqr = Square() circ = Circle() animation_group = AnimationGroup(sqr.animate.shift(DOWN).scale(2), FadeIn(circ)) assert all(isinstance(anim, Animation) for anim in animation_group.animations) succession = Succession(sqr.animate.shift(DOWN).scale(2), FadeIn(circ)) assert all(isinstance(anim, Animation) for anim in succession.animations) def test_animationgroup_with_wait(): sqr = Square() sqr_anim = FadeIn(sqr) wait = Wait() animation_group = AnimationGroup(wait, sqr_anim, lag_ratio=1) animation_group.begin() timings = animation_group.anims_with_timings assert timings.tolist() == [(wait, 0.0, 1.0), (sqr_anim, 1.0, 2.0)] @pytest.mark.parametrize( ("animation_remover", "animation_group_remover"), [(False, True), (True, False)], ) def test_animationgroup_is_passing_remover_to_animations( animation_remover, animation_group_remover ): scene = Scene() sqr_animation = Create(Square(), remover=animation_remover) circ_animation = Write(Circle(), remover=animation_remover) animation_group = AnimationGroup( sqr_animation, circ_animation, remover=animation_group_remover ) scene.play(animation_group) scene.wait(0.1) assert sqr_animation.remover assert circ_animation.remover def test_animationgroup_is_passing_remover_to_nested_animationgroups(): scene = Scene() sqr_animation = Create(Square()) circ_animation = Write(Circle(), remover=True) polygon_animation = Create(RegularPolygon(5)) animation_group = AnimationGroup( AnimationGroup(sqr_animation, polygon_animation), circ_animation, remover=True, ) scene.play(animation_group) scene.wait(0.1) assert sqr_animation.remover assert circ_animation.remover assert polygon_animation.remover def test_animationgroup_calls_finish(): class MyAnimation(Animation): def __init__(self, mobject): super().__init__(mobject) self.finished = False def finish(self): self.finished = True scene = Scene() sqr_animation = MyAnimation(Square()) circ_animation = MyAnimation(Circle()) animation_group = AnimationGroup(sqr_animation, circ_animation) scene.play(animation_group) assert sqr_animation.finished assert circ_animation.finished def test_empty_animation_group_fails(): with pytest.raises(ValueError, match="Please add at least one subanimation."): AnimationGroup().begin() def test_empty_succession_fails(): with pytest.raises(ValueError, match="Please add at least one subanimation."): Succession().begin() ================================================ FILE: tests/module/animation/test_creation.py ================================================ from __future__ import annotations import numpy as np import pytest from manim import AddTextLetterByLetter, Text def test_non_empty_text_creation(): """Check if AddTextLetterByLetter works for non-empty text.""" s = Text("Hello") anim = AddTextLetterByLetter(s) assert anim.mobject.text == "Hello" def test_empty_text_creation(): """Ensure ValueError is raised for empty text.""" with pytest.raises(ValueError, match="does not
FILE: tests/module/animation/test_creation.py ================================================ from __future__ import annotations import numpy as np import pytest from manim import AddTextLetterByLetter, Text def test_non_empty_text_creation(): """Check if AddTextLetterByLetter works for non-empty text.""" s = Text("Hello") anim = AddTextLetterByLetter(s) assert anim.mobject.text == "Hello" def test_empty_text_creation(): """Ensure ValueError is raised for empty text.""" with pytest.raises(ValueError, match="does not seem to contain any characters"): AddTextLetterByLetter(Text("")) def test_whitespace_text_creation(): """Ensure ValueError is raised for whitespace-only text, assuming the whitespace characters have no points.""" with pytest.raises(ValueError, match="does not seem to contain any characters"): AddTextLetterByLetter(Text(" ")) def test_run_time_for_non_empty_text(config): """Ensure the run_time is calculated correctly for non-empty text.""" s = Text("Hello") run_time_per_char = 0.1 expected_run_time = np.max((1 / config.frame_rate, run_time_per_char)) * len(s.text) anim = AddTextLetterByLetter(s, time_per_char=run_time_per_char) assert anim.run_time == expected_run_time ================================================ FILE: tests/module/animation/test_override_animation.py ================================================ from __future__ import annotations import pytest from manim import Animation, Mobject, override_animation from manim.utils.exceptions import MultiAnimationOverrideException class AnimationA1(Animation): pass class AnimationA2(Animation): pass class AnimationA3(Animation): pass class AnimationB1(AnimationA1): pass class AnimationC1(AnimationB1): pass class AnimationX(Animation): pass class MobjectA(Mobject): @override_animation(AnimationA1) def anim_a1(self): return AnimationA2(self) @override_animation(AnimationX) def anim_x(self, *args, **kwargs): return args, kwargs class MobjectB(MobjectA): pass class MobjectC(MobjectB): @override_animation(AnimationA1) def anim_a1(self): return AnimationA3(self) class MobjectX(Mobject): @override_animation(AnimationB1) def animation(self): return "Overridden" def test_mobject_inheritance(): mob = Mobject() a = MobjectA() b = MobjectB() c = MobjectC() assert type(AnimationA1(mob)) is AnimationA1 assert type(AnimationA1(a)) is AnimationA2 assert type(AnimationA1(b)) is AnimationA2 assert type(AnimationA1(c)) is AnimationA3 def test_arguments(): a = MobjectA() args = (1, "two", {"three": 3}, ["f", "o", "u", "r"]) kwargs = {"test": "manim", "keyword": 42, "arguments": []} animA = AnimationX(a, *args, **kwargs) assert animA[0] == args assert animA[1] == kwargs def test_multi_animation_override_exception(): with pytest.raises(MultiAnimationOverrideException): class MobjectB2(MobjectA): @override_animation(AnimationA1) def anim_a1_different_name(self): pass def test_animation_inheritance(): x = MobjectX() assert type(AnimationA1(x)) is AnimationA1 assert AnimationB1(x) == "Overridden" assert type(AnimationC1(x)) is AnimationC1 ================================================ FILE: tests/module/animation/test_transform.py ================================================ from __future__ import annotations from manim import Circle, ReplacementTransform, Scene, Square, VGroup def test_no_duplicate_references(): scene = Scene() c = Circle() sq = Square() scene.add(c, sq) scene.play(ReplacementTransform(c, sq)) assert len(scene.mobjects) == 1 assert scene.mobjects[0] is sq def test_duplicate_references_in_group(): scene = Scene() c = Circle() sq = Square() vg = VGroup(c, sq) scene.add(vg) scene.play(ReplacementTransform(c, sq)) submobs = vg.submobjects assert len(submobs) == 1 assert submobs[0] is sq ================================================ FILE: tests/module/mobject/test_boolean_ops.py ================================================ from __future__ import annotations import numpy as np import pytest from manim import Circle, Square from manim.mobject.geometry.boolean_ops import _BooleanOps @pytest.mark.parametrize( ("test_input", "expected"), [ ( [(1.0, 2.0), (3.0, 4.0)], [ np.array([1.0, 2.0, 0]), np.array([3.0, 4.0, 0]), ], ), ( [(1.1, 2.2)], [ np.array([1.1, 2.2, 0.0]), ], ), ], ) def test_convert_2d_to_3d_array(test_input, expected): a = _BooleanOps() result = a._convert_2d_to_3d_array(test_input) assert len(result) == len(expected) for i in range(len(result)): assert (result[i] == expected[i]).all() def test_convert_2d_to_3d_array_zdim(): a = _BooleanOps() result = a._convert_2d_to_3d_array([(1.0, 2.0)], z_dim=1.0) assert (result[0] == np.array([1.0, 2.0, 1.0])).all() @pytest.mark.parametrize( "test_input", [ Square(), Circle(), Square(side_length=4), Circle(radius=3), ], ) def test_vmobject_to_skia_path_and_inverse(test_input): a = _BooleanOps() path = a._convert_vmobject_to_skia_path(test_input) assert len(list(path.segments)) > 1 new_vmobject = a._convert_skia_path_to_vmobject(path) # for some reason there is an extra 4 points in new vmobject than original np.testing.assert_allclose(new_vmobject.points[:-4], test_input.points) ================================================ FILE: tests/module/mobject/test_graph.py ================================================ from __future__ import annotations import pytest from manim import DiGraph, Graph, LabeledLine, Scene, Text, tempconfig from manim.mobject.graph import _layouts
path = a._convert_vmobject_to_skia_path(test_input) assert len(list(path.segments)) > 1 new_vmobject = a._convert_skia_path_to_vmobject(path) # for some reason there is an extra 4 points in new vmobject than original np.testing.assert_allclose(new_vmobject.points[:-4], test_input.points) ================================================ FILE: tests/module/mobject/test_graph.py ================================================ from __future__ import annotations import pytest from manim import DiGraph, Graph, LabeledLine, Scene, Text, tempconfig from manim.mobject.graph import _layouts def test_graph_creation(): vertices = [1, 2, 3, 4] edges = [(1, 2), (2, 3), (3, 4), (4, 1)] layout = {1: [0, 0, 0], 2: [1, 1, 0], 3: [1, -1, 0], 4: [-1, 0, 0]} G_manual = Graph(vertices=vertices, edges=edges, layout=layout) assert str(G_manual) == "Undirected graph on 4 vertices and 4 edges" G_spring = Graph(vertices=vertices, edges=edges) assert str(G_spring) == "Undirected graph on 4 vertices and 4 edges" G_directed = DiGraph(vertices=vertices, edges=edges) assert str(G_directed) == "Directed graph on 4 vertices and 4 edges" def test_graph_add_vertices(): G = Graph([1, 2, 3], [(1, 2), (2, 3)]) G.add_vertices(4) assert str(G) == "Undirected graph on 4 vertices and 2 edges" G.add_vertices(5, labels={5: Text("5")}) assert str(G) == "Undirected graph on 5 vertices and 2 edges" assert 5 in G._labels assert 5 in G._vertex_config G.add_vertices(6, 7, 8) assert len(G.vertices) == 8 assert len(G._graph.nodes()) == 8 def test_graph_remove_vertices(): G = Graph([1, 2, 3, 4, 5], [(1, 2), (2, 3), (3, 4), (4, 5)]) removed_mobjects = G.remove_vertices(3) assert len(removed_mobjects) == 3 assert str(G) == "Undirected graph on 4 vertices and 2 edges" assert list(G.vertices.keys()) == [1, 2, 4, 5] assert list(G.edges.keys()) == [(1, 2), (4, 5)] removed_mobjects = G.remove_vertices(4, 5) assert len(removed_mobjects) == 3 assert str(G) == "Undirected graph on 2 vertices and 1 edges" assert list(G.vertices.keys()) == [1, 2] assert list(G.edges.keys()) == [(1, 2)] def test_graph_add_edges(): G = Graph([1, 2, 3, 4, 5], [(1, 2), (2, 3)]) added_mobjects = G.add_edges((1, 3)) assert str(added_mobjects.submobjects) == "[Line]" assert str(G) == "Undirected graph on 5 vertices and 3 edges" assert set(G.vertices.keys()) == {1, 2, 3, 4, 5} assert set(G.edges.keys()) == {(1, 2), (2, 3), (1, 3)} added_mobjects = G.add_edges((1, 42)) assert str(added_mobjects.submobjects) == "[Dot, Line]" assert str(G) == "Undirected graph on 6 vertices and 4 edges" assert set(G.vertices.keys()) == {1, 2, 3, 4, 5, 42} assert set(G.edges.keys()) == {(1, 2), (2, 3), (1, 3), (1, 42)} added_mobjects = G.add_edges((4, 5), (5, 6), (6, 7)) assert len(added_mobjects) == 5 assert str(G) == "Undirected graph on 8 vertices and 7 edges" assert set(G.vertices.keys()) == {1, 2, 3, 4, 5, 42, 6, 7} assert set(G._graph.nodes()) == set(G.vertices.keys()) assert set(G.edges.keys()) == { (1, 2), (2, 3), (1, 3), (1, 42), (4, 5), (5, 6), (6, 7), } assert set(G._graph.edges()) == set(G.edges.keys()) def test_graph_remove_edges(): G = Graph([1, 2, 3, 4, 5], [(1, 2), (2, 3), (3, 4), (4, 5), (1, 5)]) removed_mobjects = G.remove_edges((1, 2)) assert str(removed_mobjects.submobjects) == "[Line]" assert str(G) == "Undirected graph on 5 vertices and 4 edges" assert set(G.edges.keys()) == {(2, 3), (3, 4), (4, 5), (1, 5)} assert set(G._graph.edges()) == set(G.edges.keys()) removed_mobjects = G.remove_edges((2, 3), (3, 4), (4, 5), (1, 5)) assert len(removed_mobjects) == 4 assert str(G) == "Undirected graph on 5 vertices and 0 edges" assert set(G._graph.edges()) == set() assert set(G.edges.keys())
vertices and 4 edges" assert set(G.edges.keys()) == {(2, 3), (3, 4), (4, 5), (1, 5)} assert set(G._graph.edges()) == set(G.edges.keys()) removed_mobjects = G.remove_edges((2, 3), (3, 4), (4, 5), (1, 5)) assert len(removed_mobjects) == 4 assert str(G) == "Undirected graph on 5 vertices and 0 edges" assert set(G._graph.edges()) == set() assert set(G.edges.keys()) == set() def test_graph_accepts_labeledline_as_edge_type(): vertices = [1, 2, 3, 4] edges = [(1, 2), (2, 3), (3, 4), (4, 1)] edge_config = { (1, 2): {"label": "A"}, (2, 3): {"label": "B"}, (3, 4): {"label": "C"}, (4, 1): {"label": "D"}, } G_manual = Graph(vertices, edges, edge_type=LabeledLine, edge_config=edge_config) G_directed = DiGraph( vertices, edges, edge_type=LabeledLine, edge_config=edge_config ) for _edge_key, edge_obj in G_manual.edges.items(): assert isinstance(edge_obj, LabeledLine) assert hasattr(edge_obj, "label") for _edge_key, edge_obj in G_directed.edges.items(): assert isinstance(edge_obj, LabeledLine) assert hasattr(edge_obj, "label") def test_custom_animation_mobject_list(): G = Graph([1, 2, 3], [(1, 2), (2, 3)]) scene = Scene() scene.add(G) assert scene.mobjects == [G] with tempconfig({"dry_run": True, "quality": "low_quality"}): scene.play(G.animate.add_vertices(4)) assert str(G) == "Undirected graph on 4 vertices and 2 edges" assert scene.mobjects == [G] scene.play(G.animate.remove_vertices(2)) assert str(G) == "Undirected graph on 3 vertices and 0 edges" assert scene.mobjects == [G] def test_custom_graph_layout_dict(): G = Graph( [1, 2, 3], [(1, 2), (2, 3)], layout={1: [0, 0, 0], 2: [1, 1, 0], 3: [1, -1, 0]} ) assert str(G) == "Undirected graph on 3 vertices and 2 edges" assert all(G.vertices[1].get_center() == [0, 0, 0]) assert all(G.vertices[2].get_center() == [1, 1, 0]) assert all(G.vertices[3].get_center() == [1, -1, 0]) def test_graph_layouts(): for layout in (layout for layout in _layouts if layout not in ["tree", "partite"]): G = Graph([1, 2, 3], [(1, 2), (2, 3)], layout=layout) assert str(G) == "Undirected graph on 3 vertices and 2 edges" def test_tree_layout(): G = Graph([1, 2, 3], [(1, 2), (2, 3)], layout="tree", root_vertex=1) assert str(G) == "Undirected graph on 3 vertices and 2 edges" def test_partite_layout(): G = Graph( [1, 2, 3, 4, 5], [(1, 2), (2, 3), (3, 4), (4, 5)], layout="partite", partitions=[[1, 2], [3, 4, 5]], ) assert str(G) == "Undirected graph on 5 vertices and 4 edges" def test_custom_graph_layout_function(): def layout_func(graph, scale): return {vertex: [vertex, vertex, 0] for vertex in graph} G = Graph([1, 2, 3], [(1, 2), (2, 3)], layout=layout_func) assert all(G.vertices[1].get_center() == [1, 1, 0]) assert all(G.vertices[2].get_center() == [2, 2, 0]) assert all(G.vertices[3].get_center() == [3, 3, 0]) def test_custom_graph_layout_function_with_kwargs(): def layout_func(graph, scale, offset): return { vertex: [vertex * scale + offset, vertex * scale + offset, 0] for vertex in graph } G = Graph( [1, 2, 3], [(1, 2), (2, 3)], layout=layout_func, layout_config={"offset": 1} ) assert all(G.vertices[1].get_center() == [3, 3, 0]) assert all(G.vertices[2].get_center() == [5, 5, 0]) assert all(G.vertices[3].get_center() == [7, 7, 0]) def test_graph_change_layout(): for layout in (layout for layout in _layouts if layout not in ["tree", "partite"]): G = Graph([1, 2, 3], [(1, 2), (2, 3)]) G.change_layout(layout=layout) assert str(G) == "Undirected graph on 3 vertices and 2 edges" def test_tree_layout_no_root_error(): with pytest.raises(ValueError) as excinfo: G = Graph([1, 2, 3], [(1, 2), (2, 3)], layout="tree") assert str(excinfo.value) == "The tree layout requires the root_vertex parameter" def test_tree_layout_not_tree_error(): with pytest.raises(ValueError) as
Graph([1, 2, 3], [(1, 2), (2, 3)]) G.change_layout(layout=layout) assert str(G) == "Undirected graph on 3 vertices and 2 edges" def test_tree_layout_no_root_error(): with pytest.raises(ValueError) as excinfo: G = Graph([1, 2, 3], [(1, 2), (2, 3)], layout="tree") assert str(excinfo.value) == "The tree layout requires the root_vertex parameter" def test_tree_layout_not_tree_error(): with pytest.raises(ValueError) as excinfo: G = Graph([1, 2, 3], [(1, 2), (2, 3), (3, 1)], layout="tree", root_vertex=1) assert str(excinfo.value) == "The tree layout must be used with trees" ================================================ FILE: tests/module/mobject/test_image.py ================================================ import numpy as np import pytest from manim import ImageMobject @pytest.mark.parametrize("dtype", [np.uint8, np.uint16]) def test_invert_image(dtype): array = (255 * np.random.rand(10, 10, 4)).astype(dtype) image = ImageMobject(array, pixel_array_dtype=dtype, invert=True) assert image.pixel_array.dtype == dtype array[:, :, :3] = np.iinfo(dtype).max - array[:, :, :3] assert np.allclose(array, image.pixel_array) ================================================ FILE: tests/module/mobject/test_matrix.py ================================================ from __future__ import annotations import numpy as np import pytest from manim.mobject.matrix import ( DecimalMatrix, IntegerMatrix, Matrix, ) from manim.mobject.text.tex_mobject import MathTex from manim.mobject.types.vectorized_mobject import VGroup class TestMatrix: @pytest.mark.parametrize( ( "matrix_elements", "left_bracket", "right_bracket", "expected_rows", "expected_columns", ), [ ([[1, 2], [3, 4]], "[", "]", 2, 2), ([[1, 2, 3]], "[", "]", 1, 3), ([[1], [2], [3]], "[", "]", 3, 1), ([[5]], "[", "]", 1, 1), ([[1, 0], [0, 1]], "(", ")", 2, 2), ([["a", "b"], ["c", "d"]], "[", "]", 2, 2), (np.array([[10, 20], [30, 40]]), "[", "]", 2, 2), ], ids=[ "2x2_default", "1x3_default", "3x1_default", "1x1_default", "2x2_parentheses", "2x2_strings", "2x2_numpy", ], ) def test_matrix_init_valid( self, matrix_elements, left_bracket, right_bracket, expected_rows, expected_columns, ): matrix = Matrix( matrix_elements, left_bracket=left_bracket, right_bracket=right_bracket ) assert isinstance(matrix, Matrix) assert matrix.left_bracket == left_bracket assert matrix.right_bracket == right_bracket assert len(matrix.get_rows()) == expected_rows assert len(matrix.get_columns()) == expected_columns @pytest.mark.parametrize( ("invalid_elements", "expected_error"), [ (10, TypeError), (10.4, TypeError), ([1, 2, 3], TypeError), ], ids=[ "integer", "float", "flat_list", ], ) def test_matrix_init_invalid(self, invalid_elements, expected_error): with pytest.raises(expected_error): Matrix(invalid_elements) @pytest.mark.parametrize( ("matrix_elements", "expected_columns"), [ ([[1, 2], [3, 4]], 2), ([[1, 2, 3]], 3), ([[1], [2], [3]], 1), ], ids=["2x2", "1x3", "3x1"], ) def test_get_columns(self, matrix_elements, expected_columns): matrix = Matrix(matrix_elements) assert isinstance(matrix, Matrix) assert len(matrix.get_columns()) == expected_columns for column in matrix.get_columns(): assert isinstance(column, VGroup) @pytest.mark.parametrize( ("matrix_elements", "expected_rows"), [ ([[1, 2], [3, 4]], 2), ([[1, 2, 3]], 1), ([[1], [2], [3]], 3), ], ids=["2x2", "1x3", "3x1"], ) def test_get_rows(self, matrix_elements, expected_rows): matrix = Matrix(matrix_elements) assert isinstance(matrix, Matrix) assert len(matrix.get_rows()) == expected_rows for row in matrix.get_rows(): assert isinstance(row, VGroup) @pytest.mark.parametrize( ("matrix_elements", "expected_entries_tex_string", "expected_entries_count"), [ ([[1, 2], [3, 4]], ["1", "2", "3", "4"], 4), ([[1, 2, 3]], ["1", "2", "3"], 3), ], ids=["2x2", "1x3"], ) def test_get_entries( self, matrix_elements, expected_entries_tex_string, expected_entries_count ): matrix = Matrix(matrix_elements) entries = matrix.get_entries() assert isinstance(matrix, Matrix) assert len(entries) == expected_entries_count for index_entry, entry in enumerate(entries): assert isinstance(entry, MathTex) assert expected_entries_tex_string[index_entry] == entry.tex_string @pytest.mark.parametrize( ("matrix_elements", "row", "column", "expected_value_str"), [ ([[1, 2], [3, 4]], 0, 0, "1"), ([[1, 2], [3, 4]], 1, 1, "4"), ([[1, 2, 3]], 0, 2, "3"), ([[1], [2], [3]], 2, 0, "3"), ], ids=["2x2_00", "2x2_11", "1x3_02", "3x1_20"], ) def test_get_element(self, matrix_elements, row, column, expected_value_str): matrix = Matrix(matrix_elements) assert isinstance(matrix.get_columns()[column][row], MathTex) assert isinstance(matrix.get_rows()[row][column], MathTex) assert matrix.get_columns()[column][row].tex_string == expected_value_str assert matrix.get_rows()[row][column].tex_string == expected_value_str @pytest.mark.parametrize( ("matrix_elements", "row", "column", "expected_error"), [ ([[1, 2]], 1, 0,
2, 3]], 0, 2, "3"), ([[1], [2], [3]], 2, 0, "3"), ], ids=["2x2_00", "2x2_11", "1x3_02", "3x1_20"], ) def test_get_element(self, matrix_elements, row, column, expected_value_str): matrix = Matrix(matrix_elements) assert isinstance(matrix.get_columns()[column][row], MathTex) assert isinstance(matrix.get_rows()[row][column], MathTex) assert matrix.get_columns()[column][row].tex_string == expected_value_str assert matrix.get_rows()[row][column].tex_string == expected_value_str @pytest.mark.parametrize( ("matrix_elements", "row", "column", "expected_error"), [ ([[1, 2]], 1, 0, IndexError), ([[1, 2]], 0, 2, IndexError), ], ids=["row_out_of_bounds", "col_out_of_bounds"], ) def test_get_element_invalid(self, matrix_elements, row, column, expected_error): matrix = Matrix(matrix_elements) with pytest.raises(expected_error): matrix.get_columns()[column][row] with pytest.raises(expected_error): matrix.get_rows()[row][column] class TestDecimalMatrix: @pytest.mark.parametrize( ("matrix_elements", "num_decimal_places", "expected_elements"), [ ([[1.234, 5.678], [9.012, 3.456]], 2, [[1.234, 5.678], [9.012, 3.456]]), ([[1.0, 2.0], [3.0, 4.0]], 0, [[1, 2], [3, 4]]), ([[1, 2.3], [4.567, 7]], 1, [[1.0, 2.3], [4.567, 7.0]]), ], ids=[ "basic_2_decimal_points", "basic_0_decimal_points", "mixed_1_decimal_points", ], ) def test_decimal_matrix_init( self, matrix_elements, num_decimal_places, expected_elements ): matrix = DecimalMatrix( matrix_elements, element_to_mobject_config={"num_decimal_places": num_decimal_places}, ) assert isinstance(matrix, DecimalMatrix) for column_index, column in enumerate(matrix.get_columns()): for row_index, element in enumerate(column): assert element.number == expected_elements[row_index][column_index] assert element.num_decimal_places == num_decimal_places class TestIntegerMatrix: @pytest.mark.parametrize( ("matrix_elements", "expected_elements"), [ ([[1, 2], [3, 4]], [[1, 2], [3, 4]]), ([[1.2, 2.8], [3.5, 4]], [[1.2, 2.8], [3.5, 4]]), ], ids=["basic_int", "mixed_float_int"], ) def test_integer_matrix_init(self, matrix_elements, expected_elements): matrix = IntegerMatrix(matrix_elements) assert isinstance(matrix, IntegerMatrix) for row_index, row in enumerate(matrix.get_rows()): for column_index, element in enumerate(row): assert element.number == expected_elements[row_index][column_index] ================================================ FILE: tests/module/mobject/test_value_tracker.py ================================================ from __future__ import annotations from manim.mobject.value_tracker import ComplexValueTracker, ValueTracker def test_value_tracker_set_value(): """Test ValueTracker.set_value()""" tracker = ValueTracker() tracker.set_value(10.0) assert tracker.get_value() == 10.0 def test_value_tracker_get_value(): """Test ValueTracker.get_value()""" tracker = ValueTracker(10.0) assert tracker.get_value() == 10.0 def test_value_tracker_interpolate(): """Test ValueTracker.interpolate()""" tracker1 = ValueTracker(1.0) tracker2 = ValueTracker(2.5) tracker3 = ValueTracker().interpolate(tracker1, tracker2, 0.7) assert tracker3.get_value() == 2.05 def test_value_tracker_increment_value(): """Test ValueTracker.increment_value()""" tracker = ValueTracker(0.0) tracker.increment_value(10.0) assert tracker.get_value() == 10.0 def test_value_tracker_bool(): """Test ValueTracker.__bool__()""" tracker = ValueTracker(0.0) assert not tracker tracker.increment_value(1.0) assert tracker def test_value_tracker_add(): """Test ValueTracker.__add__()""" tracker = ValueTracker(0.0) tracker2 = tracker + 10.0 assert tracker2.get_value() == 10.0 def test_value_tracker_iadd(): """Test ValueTracker.__iadd__()""" tracker = ValueTracker(0.0) tracker += 10.0 assert tracker.get_value() == 10.0 def test_value_tracker_floordiv(): """Test ValueTracker.__floordiv__()""" tracker = ValueTracker(5.0) tracker2 = tracker // 2.0 assert tracker2.get_value() == 2.0 def test_value_tracker_ifloordiv(): """Test ValueTracker.__ifloordiv__()""" tracker = ValueTracker(5.0) tracker //= 2.0 assert tracker.get_value() == 2.0 def test_value_tracker_mod(): """Test ValueTracker.__mod__()""" tracker = ValueTracker(20.0) tracker2 = tracker % 3.0 assert tracker2.get_value() == 2.0 def test_value_tracker_imod(): """Test ValueTracker.__imod__()""" tracker = ValueTracker(20.0) tracker %= 3.0 assert tracker.get_value() == 2.0 def test_value_tracker_mul(): """Test ValueTracker.__mul__()""" tracker = ValueTracker(3.0) tracker2 = tracker * 4.0 assert tracker2.get_value() == 12.0 def test_value_tracker_imul(): """Test ValueTracker.__imul__()""" tracker = ValueTracker(3.0) tracker *= 4.0 assert tracker.get_value() == 12.0 def test_value_tracker_pow(): """Test ValueTracker.__pow__()""" tracker = ValueTracker(3.0) tracker2 = tracker**3.0 assert tracker2.get_value() == 27.0 def test_value_tracker_ipow(): """Test ValueTracker.__ipow__()""" tracker = ValueTracker(3.0) tracker **= 3.0 assert tracker.get_value() == 27.0 def test_value_tracker_sub(): """Test ValueTracker.__sub__()""" tracker = ValueTracker(20.0) tracker2 = tracker - 10.0 assert tracker2.get_value() == 10.0 def test_value_tracker_isub(): """Test ValueTracker.__isub__()""" tracker = ValueTracker(20.0) tracker -= 10.0 assert tracker.get_value() == 10.0 def test_value_tracker_truediv(): """Test ValueTracker.__truediv__()""" tracker = ValueTracker(5.0) tracker2 = tracker / 2.0 assert tracker2.get_value() == 2.5 def test_value_tracker_itruediv(): """Test ValueTracker.__itruediv__()""" tracker = ValueTracker(5.0) tracker /= 2.0 assert tracker.get_value() == 2.5 def test_complex_value_tracker_set_value(): """Test ComplexValueTracker.set_value()""" tracker = ComplexValueTracker() tracker.set_value(1 + 2j) assert
= ValueTracker(20.0) tracker -= 10.0 assert tracker.get_value() == 10.0 def test_value_tracker_truediv(): """Test ValueTracker.__truediv__()""" tracker = ValueTracker(5.0) tracker2 = tracker / 2.0 assert tracker2.get_value() == 2.5 def test_value_tracker_itruediv(): """Test ValueTracker.__itruediv__()""" tracker = ValueTracker(5.0) tracker /= 2.0 assert tracker.get_value() == 2.5 def test_complex_value_tracker_set_value(): """Test ComplexValueTracker.set_value()""" tracker = ComplexValueTracker() tracker.set_value(1 + 2j) assert tracker.get_value() == 1 + 2j def test_complex_value_tracker_get_value(): """Test ComplexValueTracker.get_value()""" tracker = ComplexValueTracker(2.0 - 3.0j) assert tracker.get_value() == 2.0 - 3.0j ================================================ FILE: tests/module/mobject/geometry/test_unit_geometry.py ================================================ from __future__ import annotations import logging import numpy as np from manim import ( DEGREES, LEFT, RIGHT, BackgroundRectangle, Circle, Line, Polygram, Sector, Square, SurroundingRectangle, ) logger = logging.getLogger(__name__) def test_get_arc_center(): np.testing.assert_array_equal( Sector(arc_center=[1, 2, 0]).get_arc_center(), [1, 2, 0] ) def test_Polygram_get_vertex_groups(): # Test that, once a Polygram polygram is created with some vertex groups, # polygram.get_vertex_groups() (usually) returns the same vertex groups. vertex_groups_arr = [ # 2 vertex groups for polygram 1 [ # Group 1: Triangle np.array( [ [2, 1, 0], [0, 2, 0], [-2, 1, 0], ] ), # Group 2: Square np.array( [ [1, 0, 0], [0, 1, 0], [-1, 0, 0], [0, -1, 0], ] ), ], # 3 vertex groups for polygram 1 [ # Group 1: Quadrilateral np.array( [ [2, 0, 0], [0, -1, 0], [0, 0, -2], [0, 1, 0], ] ), # Group 2: Triangle np.array( [ [3, 1, 0], [0, 0, 2], [2, 0, 0], ] ), # Group 3: Pentagon np.array( [ [1, -1, 0], [1, 1, 0], [0, 2, 0], [-1, 1, 0], [-1, -1, 0], ] ), ], ] for vertex_groups in vertex_groups_arr: polygram = Polygram(*vertex_groups) poly_vertex_groups = polygram.get_vertex_groups() for poly_group, group in zip(poly_vertex_groups, vertex_groups): np.testing.assert_array_equal(poly_group, group) # If polygram is a Polygram of a vertex group containing the start vertex N times, # then polygram.get_vertex_groups() splits it into N vertex groups. splittable_vertex_group = np.array( [ [0, 1, 0], [1, -2, 0], [1, 2, 0], [0, 1, 0], # same vertex as start [-1, 2, 0], [-1, -2, 0], [0, 1, 0], # same vertex as start [0.5, 2, 0], [-0.5, 2, 0], ] ) polygram = Polygram(splittable_vertex_group) assert len(polygram.get_vertex_groups()) == 3 def test_SurroundingRectangle(): circle = Circle() square = Square() sr = SurroundingRectangle(circle, square) sr.set_style(fill_opacity=0.42) assert sr.get_fill_opacity() == 0.42 def test_SurroundingRectangle_buff(): sq = Square() rect1 = SurroundingRectangle(sq, buff=1) assert rect1.width == sq.width + 2 assert rect1.height == sq.height + 2 rect2 = SurroundingRectangle(sq, buff=(1, 2)) assert rect2.width == sq.width + 2 assert rect2.height == sq.height + 4 def test_BackgroundRectangle(manim_caplog): circle = Circle() square = Square() bg = BackgroundRectangle(circle, square) bg.set_style(fill_opacity=0.42) assert bg.get_fill_opacity() == 0.42 bg.set_style(fill_opacity=1, hello="world") assert ( "Argument {'hello': 'world'} is ignored in BackgroundRectangle.set_style." in manim_caplog.text ) def test_Square_side_length_reflets_correct_width_and_height(): sq = Square(side_length=1).scale(3) assert sq.side_length == 3 assert sq.height == 3 assert sq.width == 3 def test_changing_Square_side_length_updates_the_square_appropriately(): sq = Square(side_length=1) sq.side_length = 3 assert sq.height == 3 assert sq.width == 3 def test_Square_side_length_consistent_after_scale_and_rotation(): sq = Square(side_length=1).scale(3).rotate(np.pi / 4) assert np.isclose(sq.side_length, 3) def test_line_with_buff_and_path_arc(): line = Line(LEFT, RIGHT, path_arc=60 * DEGREES, buff=0.3) expected_points = np.array( [ [-0.7299265, -0.12999304, 0.0], [-0.6605293, -0.15719695, 0.0], [-0.58965623, -0.18050364, 0.0], [-0.51763809,
def test_changing_Square_side_length_updates_the_square_appropriately(): sq = Square(side_length=1) sq.side_length = 3 assert sq.height == 3 assert sq.width == 3 def test_Square_side_length_consistent_after_scale_and_rotation(): sq = Square(side_length=1).scale(3).rotate(np.pi / 4) assert np.isclose(sq.side_length, 3) def test_line_with_buff_and_path_arc(): line = Line(LEFT, RIGHT, path_arc=60 * DEGREES, buff=0.3) expected_points = np.array( [ [-0.7299265, -0.12999304, 0.0], [-0.6605293, -0.15719695, 0.0], [-0.58965623, -0.18050364, 0.0], [-0.51763809, -0.19980085, 0.0], [-0.51763809, -0.19980085, 0.0], [-0.43331506, -0.22239513, 0.0], [-0.34760317, -0.23944429, 0.0], [-0.26105238, -0.25083892, 0.0], [-0.26105238, -0.25083892, 0.0], [-0.1745016, -0.26223354, 0.0], [-0.08729763, -0.26794919, 0.0], [0.0, -0.26794919, 0.0], [0.0, -0.26794919, 0.0], [0.08729763, -0.26794919, 0.0], [0.1745016, -0.26223354, 0.0], [0.26105238, -0.25083892, 0.0], [0.26105238, -0.25083892, 0.0], [0.34760317, -0.23944429, 0.0], [0.43331506, -0.22239513, 0.0], [0.51763809, -0.19980085, 0.0], [0.51763809, -0.19980085, 0.0], [0.58965623, -0.18050364, 0.0], [0.6605293, -0.15719695, 0.0], [0.7299265, -0.12999304, 0.0], ] ) np.testing.assert_allclose(line.points, expected_points) ================================================ FILE: tests/module/mobject/graphing/test_axes_shift.py ================================================ from __future__ import annotations import numpy as np from manim.mobject.graphing.coordinate_systems import Axes, ThreeDAxes from manim.mobject.graphing.scale import LogBase def test_axes_origin_shift(): ax = Axes(x_range=(5, 10, 1), y_range=(40, 45, 0.5)) np.testing.assert_allclose(ax.coords_to_point(5, 40), ax.x_axis.number_to_point(5)) np.testing.assert_allclose(ax.coords_to_point(5, 40), ax.y_axis.number_to_point(40)) def test_axes_origin_shift_logbase(): ax = Axes( x_range=(5, 10, 1), y_range=(3, 8, 1), x_axis_config={"scaling": LogBase()}, y_axis_config={"scaling": LogBase()}, ) np.testing.assert_allclose( ax.coords_to_point(10**5, 10**3), ax.x_axis.number_to_point(10**5) ) np.testing.assert_allclose( ax.coords_to_point(10**5, 10**3), ax.y_axis.number_to_point(10**3) ) def test_3daxes_origin_shift(): ax = ThreeDAxes(x_range=(3, 9, 1), y_range=(6, 12, 1), z_range=(-1, 1, 0.5)) np.testing.assert_allclose( ax.coords_to_point(3, 6, 0), ax.x_axis.number_to_point(3) ) np.testing.assert_allclose( ax.coords_to_point(3, 6, 0), ax.y_axis.number_to_point(6) ) np.testing.assert_allclose( ax.coords_to_point(3, 6, 0), ax.z_axis.number_to_point(0) ) def test_3daxes_origin_shift_logbase(): ax = ThreeDAxes( x_range=(3, 9, 1), y_range=(6, 12, 1), z_range=(2, 5, 1), x_axis_config={"scaling": LogBase()}, y_axis_config={"scaling": LogBase()}, z_axis_config={"scaling": LogBase()}, ) np.testing.assert_allclose( ax.coords_to_point(10**3, 10**6, 10**2), ax.x_axis.number_to_point(10**3), ) np.testing.assert_allclose( ax.coords_to_point(10**3, 10**6, 10**2), ax.y_axis.number_to_point(10**6), ) np.testing.assert_allclose( ax.coords_to_point(10**3, 10**6, 10**2), ax.z_axis.number_to_point(10**2), ) ================================================ FILE: tests/module/mobject/graphing/test_coordinate_system.py ================================================ from __future__ import annotations import math import numpy as np import pytest from manim import ( LEFT, ORIGIN, PI, UR, Axes, Circle, ComplexPlane, Dot, NumberPlane, PolarPlane, ThreeDAxes, config, tempconfig, ) from manim import CoordinateSystem as CS def test_initial_config(): """Check that all attributes are defined properly from the config.""" cs = CS() assert cs.x_range[0] == round(-config["frame_x_radius"]) assert cs.x_range[1] == round(config["frame_x_radius"]) assert cs.x_range[2] == 1.0 assert cs.y_range[0] == round(-config["frame_y_radius"]) assert cs.y_range[1] == round(config["frame_y_radius"]) assert cs.y_range[2] == 1.0 ax = Axes() np.testing.assert_allclose(ax.get_center(), ORIGIN) np.testing.assert_allclose(ax.y_axis_config["label_direction"], LEFT) with tempconfig({"frame_x_radius": 100, "frame_y_radius": 200}): cs = CS() assert cs.x_range[0] == -100 assert cs.x_range[1] == 100 assert cs.y_range[0] == -200 assert cs.y_range[1] == 200 def test_dimension(): """Check that objects have the correct dimension.""" assert Axes().dimension == 2 assert NumberPlane().dimension == 2 assert PolarPlane().dimension == 2 assert ComplexPlane().dimension == 2 assert ThreeDAxes().dimension == 3 def test_abstract_base_class(): """Check that CoordinateSystem has some abstract methods.""" with pytest.raises(NotImplementedError): CS().get_axes() def test_NumberPlane(): """Test that NumberPlane generates the correct number of lines when its ranges do not cross 0.""" pos_x_range = (0, 7) neg_x_range = (-7, 0) pos_y_range = (2, 6) neg_y_range = (-6, -2) testing_data = [ (pos_x_range, pos_y_range), (pos_x_range, neg_y_range), (neg_x_range, pos_y_range), (neg_x_range, neg_y_range), ] for test_data in testing_data: x_range, y_range = test_data x_start, x_end = x_range y_start, y_end = y_range plane = NumberPlane( x_range=x_range, y_range=y_range, # x_length = 7, axis_config={"include_numbers": True}, ) # normally these values would be need to be added by one to pass since there's an # overlapping pair of lines at the origin, but
x_range, y_range = test_data x_start, x_end = x_range y_start, y_end = y_range plane = NumberPlane( x_range=x_range, y_range=y_range, # x_length = 7, axis_config={"include_numbers": True}, ) # normally these values would be need to be added by one to pass since there's an # overlapping pair of lines at the origin, but since these planes do not cross 0, # this is not needed. num_y_lines = math.ceil(x_end - x_start) num_x_lines = math.floor(y_end - y_start) assert len(plane.y_lines) == num_y_lines assert len(plane.x_lines) == num_x_lines plane = NumberPlane((-5, 5, 0.5), (-8, 8, 2)) # <- test for different step values # horizontal lines: -6 -4, -2, 0, 2, 4, 6 assert len(plane.x_lines) == 7 # vertical lines: 0, +-0.5, +-1, +-1.5, +-2, +-2.5, # +-3, +-3.5, +-4, +-4.5 assert len(plane.y_lines) == 19 def test_point_to_coords(): ax = Axes(x_range=[0, 10, 2]) circ = Circle(radius=0.5).shift(UR * 2) # get the coordinates of the circle with respect to the axes coords = np.around(ax.point_to_coords(circ.get_right()), decimals=4) np.testing.assert_array_equal(coords, (7.0833, 2.6667)) def test_point_to_coords_vectorized(): ax = Axes(x_range=[0, 10, 2]) circ = Circle(radius=0.5).shift(UR * 2) points = np.array( [circ.get_right(), circ.get_left(), circ.get_bottom(), circ.get_top()] ) # get the coordinates of the circle with respect to the axes expected = [np.around(ax.point_to_coords(point), decimals=4) for point in points] actual = np.around(ax.point_to_coords(points), decimals=4) np.testing.assert_array_equal(expected, actual) def test_coords_to_point(): ax = Axes() # a point with respect to the axes c2p_coord = np.around(ax.coords_to_point(2, 2), decimals=4) c2p_coord_matmul = np.around(ax @ (2, 2), decimals=4) expected = (1.7143, 1.5, 0) np.testing.assert_array_equal(c2p_coord, expected) np.testing.assert_array_equal(c2p_coord_matmul, c2p_coord) mob = Dot().move_to((2, 2, 0)) np.testing.assert_array_equal(np.around(ax @ mob, decimals=4), expected) def test_coords_to_point_vectorized(): plane = NumberPlane(x_range=[2, 4]) origin = plane.x_axis.number_to_point( plane._origin_shift([plane.x_axis.x_min, plane.x_axis.x_max]), ) def ref_func(*coords): result = np.array(origin) for axis, number in zip(plane.get_axes(), coords): result += axis.number_to_point(number) - origin return result coords = [[1], [1, 2], [2, 2], [3, 4]] print(f"\n\nTesting coords_to_point {coords}") expected = np.round([ref_func(*coord) for coord in coords], 4) actual1 = np.round([plane.coords_to_point(*coord) for coord in coords], 4) coords[0] = [ 1, 0, ] # Extend the first coord because you can't vectorize items with different dimensions actual2 = np.round( plane.coords_to_point(coords), 4 ) # Test [x_0,y_0,z_0], [x_1,y_1,z_1], ... actual3 = np.round( plane.coords_to_point(*np.array(coords).T), 4 ) # Test [x_0,x_1,...], [y_0,y_1,...], ... print(actual3) np.testing.assert_array_equal(expected, actual1) np.testing.assert_array_equal(expected, actual2) np.testing.assert_array_equal(expected, actual3.T) def test_input_to_graph_point(): ax = Axes() curve = ax.plot(lambda x: np.cos(x)) line_graph = ax.plot_line_graph([1, 3, 5], [-1, 2, -2], add_vertex_dots=False)[ "line_graph" ] # move a square to PI on the cosine curve. position = np.around(ax.input_to_graph_point(x=PI, graph=curve), decimals=4) np.testing.assert_array_equal(position, (2.6928, -0.75, 0)) # test the line_graph implementation position = np.around(ax.input_to_graph_point(x=PI, graph=line_graph), decimals=4) np.testing.assert_array_equal(position, (2.6928, 1.2876, 0)) ================================================ FILE: tests/module/mobject/graphing/test_number_line.py ================================================ from __future__ import annotations import numpy as np from manim import DashedLine, NumberLine from manim.mobject.text.numbers import Integer def test_unit_vector(): """Check if the magnitude of unit vector along the NumberLine is equal to its unit_size. """ axis1 = NumberLine(unit_size=0.4) axis2 = NumberLine(x_range=[-2, 5], length=12) for axis in (axis1, axis2): assert np.linalg.norm(axis.get_unit_vector()) == axis.unit_size def test_decimal_determined_by_step(): """Checks that step size is considered when determining the number of decimal places. """ axis = NumberLine(x_range=[-2, 2, 0.5]) expected_decimal_places = 1 actual_decimal_places = axis.decimal_number_config["num_decimal_places"] assert actual_decimal_places == expected_decimal_places, ( "Expected 1 decimal place
axis2 = NumberLine(x_range=[-2, 5], length=12) for axis in (axis1, axis2): assert np.linalg.norm(axis.get_unit_vector()) == axis.unit_size def test_decimal_determined_by_step(): """Checks that step size is considered when determining the number of decimal places. """ axis = NumberLine(x_range=[-2, 2, 0.5]) expected_decimal_places = 1 actual_decimal_places = axis.decimal_number_config["num_decimal_places"] assert actual_decimal_places == expected_decimal_places, ( "Expected 1 decimal place but got " + actual_decimal_places ) axis2 = NumberLine(x_range=[-1, 1, 0.25]) expected_decimal_places = 2 actual_decimal_places = axis2.decimal_number_config["num_decimal_places"] assert actual_decimal_places == expected_decimal_places, ( "Expected 1 decimal place but got " + actual_decimal_places ) def test_decimal_config_overrides_defaults(): """Checks that ``num_decimal_places`` is determined by step size and gets overridden by ``decimal_number_config``.""" axis = NumberLine( x_range=[-2, 2, 0.5], decimal_number_config={"num_decimal_places": 0}, ) expected_decimal_places = 0 actual_decimal_places = axis.decimal_number_config["num_decimal_places"] assert actual_decimal_places == expected_decimal_places, ( "Expected 1 decimal place but got " + actual_decimal_places ) def test_whole_numbers_step_size_default_to_0_decimal_places(): """Checks that ``num_decimal_places`` defaults to 0 when a whole number step size is passed.""" axis = NumberLine(x_range=[-2, 2, 1]) expected_decimal_places = 0 actual_decimal_places = axis.decimal_number_config["num_decimal_places"] assert actual_decimal_places == expected_decimal_places, ( "Expected 1 decimal place but got " + actual_decimal_places ) def test_add_labels(): expected_label_length = 6 num_line = NumberLine(x_range=[-4, 4]) num_line.add_labels( dict(zip(list(range(-3, 3)), [Integer(m) for m in range(-1, 5)])), ) actual_label_length = len(num_line.labels) assert actual_label_length == expected_label_length, ( f"Expected a VGroup with {expected_label_length} integers but got {actual_label_length}." ) def test_number_to_point(): line = NumberLine() numbers = [1, 2, 3, 4, 5] numbers_np = np.array(numbers) expected = np.array( [ [1.0, 0.0, 0.0], [2.0, 0.0, 0.0], [3.0, 0.0, 0.0], [4.0, 0.0, 0.0], [5.0, 0.0, 0.0], ] ) vec_1 = np.array([line.number_to_point(x) for x in numbers]) vec_2 = line.number_to_point(numbers) vec_3 = line.number_to_point(numbers_np) np.testing.assert_equal( np.round(vec_1, 4), np.round(expected, 4), f"Expected {expected} but got {vec_1} with input as scalar", ) np.testing.assert_equal( np.round(vec_2, 4), np.round(expected, 4), f"Expected {expected} but got {vec_2} with input as params", ) np.testing.assert_equal( np.round(vec_2, 4), np.round(expected, 4), f"Expected {expected} but got {vec_3} with input as ndarray", ) def test_point_to_number(): line = NumberLine() points = [ [1.0, 0.0, 0.0], [2.0, 0.0, 0.0], [3.0, 0.0, 0.0], [4.0, 0.0, 0.0], [5.0, 0.0, 0.0], ] points_np = np.array(points) expected = [1, 2, 3, 4, 5] num_1 = [line.point_to_number(point) for point in points] num_2 = line.point_to_number(points) num_3 = line.point_to_number(points_np) np.testing.assert_array_equal(np.round(num_1, 4), np.round(expected, 4)) np.testing.assert_array_equal(np.round(num_2, 4), np.round(expected, 4)) np.testing.assert_array_equal(np.round(num_3, 4), np.round(expected, 4)) def test_start_and_end_at_same_point(): line = DashedLine(np.zeros(3), np.zeros(3)) line.put_start_and_end_on(np.zeros(3), np.array([0, 0, 0])) np.testing.assert_array_equal(np.round(np.zeros(3), 4), np.round(line.points, 4)) ================================================ FILE: tests/module/mobject/graphing/test_ticks.py ================================================ from __future__ import annotations import numpy as np from manim import PI, Axes, NumberLine def test_duplicate_ticks_removed_for_axes(): axis = NumberLine( x_range=[-10, 10], ) ticks = axis.get_tick_range() assert np.unique(ticks).size == ticks.size def test_elongated_ticks_float_equality(): nline = NumberLine( x_range=[1 + 1e-5, 1 + 2e-5, 1e-6], numbers_with_elongated_ticks=[ 1 + 12e-6, 1 + 17e-6, ], # Elongate the 3rd and 8th tick include_ticks=True, ) tick_heights = {tick.height for tick in nline.ticks} default_tick_height, elongated_tick_height = min(tick_heights), max(tick_heights) assert all( ( tick.height == elongated_tick_height if ind in [2, 7] else tick.height == default_tick_height ) for ind, tick in enumerate(nline.ticks) ) def test_ticks_not_generated_on_origin_for_axes(): axes = Axes( x_range=[-10, 10], y_range=[-10, 10], axis_config={"include_ticks": True}, ) x_axis_range = axes.x_axis.get_tick_range() y_axis_range = axes.y_axis.get_tick_range() assert 0 not in x_axis_range assert 0 not in y_axis_range def test_expected_ticks_generated(): axes
tick.height == elongated_tick_height if ind in [2, 7] else tick.height == default_tick_height ) for ind, tick in enumerate(nline.ticks) ) def test_ticks_not_generated_on_origin_for_axes(): axes = Axes( x_range=[-10, 10], y_range=[-10, 10], axis_config={"include_ticks": True}, ) x_axis_range = axes.x_axis.get_tick_range() y_axis_range = axes.y_axis.get_tick_range() assert 0 not in x_axis_range assert 0 not in y_axis_range def test_expected_ticks_generated(): axes = Axes(x_range=[-2, 2], y_range=[-2, 2], axis_config={"include_ticks": True}) x_axis_range = axes.x_axis.get_tick_range() y_axis_range = axes.y_axis.get_tick_range() assert 1 in x_axis_range assert 1 in y_axis_range assert -1 in x_axis_range assert -1 in y_axis_range def test_ticks_generated_from_origin_for_axes(): axes = Axes( x_range=[-PI, PI], y_range=[-PI, PI], axis_config={"include_ticks": True}, ) x_axis_range = axes.x_axis.get_tick_range() y_axis_range = axes.y_axis.get_tick_range() assert -2 in x_axis_range assert -1 in x_axis_range assert 0 not in x_axis_range assert 1 in x_axis_range assert 2 in x_axis_range assert -2 in y_axis_range assert -1 in y_axis_range assert 0 not in y_axis_range assert 1 in y_axis_range assert 2 in y_axis_range ================================================ FILE: tests/module/mobject/mobject/test_copy.py ================================================ from __future__ import annotations from pathlib import Path from manim import BraceLabel, Mobject def test_mobject_copy(): """Test that a copy is a deepcopy.""" orig = Mobject() orig.add(*(Mobject() for _ in range(10))) copy = orig.copy() assert orig is orig assert orig is not copy assert orig.submobjects is not copy.submobjects for i in range(10): assert orig.submobjects[i] is not copy.submobjects[i] def test_bracelabel_copy(tmp_path, config): """Test that a copy is a deepcopy.""" # For this test to work, we need to tweak some folders temporarily original_text_dir = config["text_dir"] original_tex_dir = config["tex_dir"] mediadir = Path(tmp_path) / "deepcopy" config["text_dir"] = str(mediadir.joinpath("Text")) config["tex_dir"] = str(mediadir.joinpath("Tex")) for el in ["text_dir", "tex_dir"]: Path(config[el]).mkdir(parents=True) # Before the refactoring of Mobject.copy(), the class BraceLabel was the # only one to have a non-trivial definition of copy. Here we test that it # still works after the refactoring. orig = BraceLabel(Mobject(), "label") copy = orig.copy() assert orig is orig assert orig is not copy assert orig.brace is not copy.brace assert orig.label is not copy.label assert orig.submobjects is not copy.submobjects assert orig.submobjects[0] is orig.brace assert copy.submobjects[0] is copy.brace assert orig.submobjects[0] is not copy.brace assert copy.submobjects[0] is not orig.brace # Restore the original folders config["text_dir"] = original_text_dir config["tex_dir"] = original_tex_dir ================================================ FILE: tests/module/mobject/mobject/test_family.py ================================================ from __future__ import annotations import numpy as np from manim import RIGHT, Circle, Mobject def test_family(): """Check that the family is gathered correctly.""" # Check that an empty mobject's family only contains itself mob = Mobject() assert mob.get_family() == [mob] # Check that all children are in the family mob = Mobject() children = [Mobject() for _ in range(10)] mob.add(*children) family = mob.get_family() assert len(family) == 1 + 10 assert mob in family for c in children: assert c in family # Nested children should be in the family mob = Mobject() grandchildren = {} for _ in range(10): child = Mobject() grandchildren[child] = [Mobject() for _ in range(10)] child.add(*grandchildren[child]) mob.add(*list(grandchildren.keys())) family = mob.get_family() assert len(family) == 1 + 10 + 10 * 10 assert mob in family for c in grandchildren: assert c in family for gc in grandchildren[c]: assert gc in family def test_overlapping_family(): """Check that each member of the family is only gathered once.""" ( mob,
child.add(*grandchildren[child]) mob.add(*list(grandchildren.keys())) family = mob.get_family() assert len(family) == 1 + 10 + 10 * 10 assert mob in family for c in grandchildren: assert c in family for gc in grandchildren[c]: assert gc in family def test_overlapping_family(): """Check that each member of the family is only gathered once.""" ( mob, child1, child2, ) = ( Mobject(), Mobject(), Mobject(), ) gchild1, gchild2, gchild_common = Mobject(), Mobject(), Mobject() child1.add(gchild1, gchild_common) child2.add(gchild2, gchild_common) mob.add(child1, child2) family = mob.get_family() assert mob in family assert len(family) == 6 assert family.count(gchild_common) == 1 def test_shift_family(): """Check that each member of the family is shifted along with the parent. Importantly, here we add a common grandchild to each of the children. So this test will fail if the grandchild moves twice as much as it should. """ # Note shift() needs the mobject to have a non-empty `points` attribute, so # we cannot use a plain Mobject or VMobject. We use Circle instead. ( mob, child1, child2, ) = ( Circle(), Circle(), Circle(), ) gchild1, gchild2, gchild_common = Circle(), Circle(), Circle() child1.add(gchild1, gchild_common) child2.add(gchild2, gchild_common) mob.add(child1, child2) family = mob.get_family() positions_before = {m: m.get_center() for m in family} mob.shift(RIGHT) positions_after = {m: m.get_center() for m in family} for m in family: np.testing.assert_allclose(positions_before[m] + RIGHT, positions_after[m]) ================================================ FILE: tests/module/mobject/mobject/test_get_set.py ================================================ from __future__ import annotations import types import pytest from manim.mobject.mobject import Mobject def test_generic_set(): m = Mobject() m.set(test=0) assert m.test == 0 @pytest.mark.filterwarnings("ignore::DeprecationWarning") def test_get_compat_layer(): m = Mobject() assert isinstance(m.get_test, types.MethodType) with pytest.raises(AttributeError): m.get_test() m.test = 0 assert m.get_test() == 0 @pytest.mark.filterwarnings("ignore::DeprecationWarning") def test_set_compat_layer(): m = Mobject() assert isinstance(m.set_test, types.MethodType) m.set_test(0) assert m.test == 0 def test_nonexistent_attr(): m = Mobject() with pytest.raises(AttributeError, match="object has no attribute"): m.test ================================================ FILE: tests/module/mobject/mobject/test_mobject.py ================================================ from __future__ import annotations import numpy as np import pytest from manim import DL, UR, Circle, Mobject, Rectangle, Square, VGroup def test_mobject_add(): """Test Mobject.add().""" """Call this function with a Container instance to test its add() method.""" # check that obj.submobjects is updated correctly obj = Mobject() assert len(obj.submobjects) == 0 obj.add(Mobject()) assert len(obj.submobjects) == 1 obj.add(*(Mobject() for _ in range(10))) assert len(obj.submobjects) == 11 # check that adding a mobject twice does not actually add it twice repeated = Mobject() obj.add(repeated) assert len(obj.submobjects) == 12 obj.add(repeated) assert len(obj.submobjects) == 12 # check that Mobject.add() returns the Mobject (for chained calls) assert obj.add(Mobject()) is obj assert len(obj.submobjects) == 13 obj = Mobject() # a Mobject cannot contain itself with pytest.raises(ValueError) as add_self_info: obj.add(Mobject(), obj, Mobject()) assert str(add_self_info.value) == ( "Cannot add Mobject as a submobject of itself (at index 1)." ) assert len(obj.submobjects) == 0 # can only add Mobjects with pytest.raises(TypeError) as add_str_info: obj.add(Mobject(), Mobject(), "foo") assert str(add_str_info.value) == ( "Only values of type Mobject can be added as submobjects of Mobject, " "but the value foo (at index 2) is of type str." ) assert len(obj.submobjects) == 0 def test_mobject_remove(): """Test Mobject.remove().""" obj = Mobject() to_remove = Mobject() obj.add(to_remove) obj.add(*(Mobject() for _ in range(10))) assert len(obj.submobjects) == 11 obj.remove(to_remove) assert len(obj.submobjects) == 10 obj.remove(to_remove) assert len(obj.submobjects)
added as submobjects of Mobject, " "but the value foo (at index 2) is of type str." ) assert len(obj.submobjects) == 0 def test_mobject_remove(): """Test Mobject.remove().""" obj = Mobject() to_remove = Mobject() obj.add(to_remove) obj.add(*(Mobject() for _ in range(10))) assert len(obj.submobjects) == 11 obj.remove(to_remove) assert len(obj.submobjects) == 10 obj.remove(to_remove) assert len(obj.submobjects) == 10 assert obj.remove(Mobject()) is obj def test_mobject_dimensions_single_mobject(): # A Mobject with no points and no submobjects has no dimensions empty = Mobject() assert empty.width == 0 assert empty.height == 0 assert empty.depth == 0 has_points = Mobject() has_points.points = np.array([[-1, -2, -3], [1, 3, 5]]) assert has_points.width == 2 assert has_points.height == 5 assert has_points.depth == 8 rect = Rectangle(width=3, height=5) assert rect.width == 3 assert rect.height == 5 assert rect.depth == 0 # Dimensions should be recalculated after scaling rect.scale(2.0) assert rect.width == 6 assert rect.height == 10 assert rect.depth == 0 # Dimensions should not be dependent on location rect.move_to([-3, -4, -5]) assert rect.width == 6 assert rect.height == 10 assert rect.depth == 0 circ = Circle(radius=2) assert circ.width == 4 assert circ.height == 4 assert circ.depth == 0 def is_close(x, y): return abs(x - y) < 0.00001 def test_mobject_dimensions_nested_mobjects(): vg = VGroup() for x in range(-5, 8, 1): row = VGroup() vg += row for y in range(-17, 2, 1): for z in range(0, 10, 1): s = Square().move_to([x, y, z / 10]) row += s assert vg.width == 14.0, vg.width assert vg.height == 20.0, vg.height assert is_close(vg.depth, 0.9), vg.depth # Dimensions should be recalculated after scaling vg.scale(0.5) assert vg.width == 7.0, vg.width assert vg.height == 10.0, vg.height assert is_close(vg.depth, 0.45), vg.depth # Adding a mobject changes the bounds/dimensions rect = Rectangle(width=3, height=5) rect.move_to([9, 3, 1]) vg += rect assert vg.width == 13.0, vg.width assert is_close(vg.height, 18.5), vg.height assert is_close(vg.depth, 0.775), vg.depth def test_mobject_dimensions_mobjects_with_no_points_are_at_origin(): rect = Rectangle(width=2, height=3) rect.move_to([-4, -5, 0]) outer_group = VGroup(rect) # This is as one would expect assert outer_group.width == 2 assert outer_group.height == 3 # Adding a mobject with no points has a quirk of adding a "point" # to [0, 0, 0] (the origin). This changes the size of the outer # group because now the bottom left corner is at [-5, -6.5, 0] # but the upper right corner is [0, 0, 0] instead of [-3, -3.5, 0] outer_group.add(VGroup()) assert outer_group.width == 5 assert outer_group.height == 6.5 def test_mobject_dimensions_has_points_and_children(): outer_rect = Rectangle(width=3, height=6) inner_rect = Rectangle(width=2, height=1) inner_rect.align_to(outer_rect.get_corner(UR), DL) outer_rect.add(inner_rect) # The width of a mobject should depend both on its points and # the points of all children mobjects. assert outer_rect.width == 5 # 3 from outer_rect, 2 from inner_rect assert outer_rect.height == 7 # 6 from outer_rect, 1 from inner_rect assert outer_rect.depth == 0 assert inner_rect.width == 2 assert inner_rect.height == 1 assert inner_rect.depth == 0 ================================================ FILE: tests/module/mobject/mobject/test_opengl_metaclass.py ================================================ from __future__ import annotations from manim import Mobject from manim.mobject.opengl.opengl_compatibility import ConvertToOpenGL from manim.mobject.opengl.opengl_mobject import OpenGLMobject def test_metaclass_registry(config): class SomeTestMobject(Mobject, metaclass=ConvertToOpenGL): pass assert SomeTestMobject in ConvertToOpenGL._converted_classes config.renderer = "opengl" assert OpenGLMobject in SomeTestMobject.__bases__ assert Mobject not in
2 assert inner_rect.height == 1 assert inner_rect.depth == 0 ================================================ FILE: tests/module/mobject/mobject/test_opengl_metaclass.py ================================================ from __future__ import annotations from manim import Mobject from manim.mobject.opengl.opengl_compatibility import ConvertToOpenGL from manim.mobject.opengl.opengl_mobject import OpenGLMobject def test_metaclass_registry(config): class SomeTestMobject(Mobject, metaclass=ConvertToOpenGL): pass assert SomeTestMobject in ConvertToOpenGL._converted_classes config.renderer = "opengl" assert OpenGLMobject in SomeTestMobject.__bases__ assert Mobject not in SomeTestMobject.__bases__ config.renderer = "cairo" assert Mobject in SomeTestMobject.__bases__ assert OpenGLMobject not in SomeTestMobject.__bases__ ================================================ FILE: tests/module/mobject/mobject/test_set_attr.py ================================================ from __future__ import annotations import numpy as np from manim.constants import RIGHT from manim.mobject.geometry.polygram import Square def test_Data(using_opengl_renderer): a = Square().move_to(RIGHT) data_bb = a.data["bounding_box"] np.testing.assert_array_equal( data_bb, np.array([[0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [2.0, 1.0, 0.0]]), ) # test that calling the attribute equals calling it from self.data np.testing.assert_array_equal(a.bounding_box, data_bb) # test that the array can be indexed np.testing.assert_array_equal( a.bounding_box[1], np.array( [1.0, 0.0, 0.0], ), ) # test that a value can be set a.bounding_box[1] = 300 # test that both the attr and self.data arrays match after adjusting a value data_bb = a.data["bounding_box"] np.testing.assert_array_equal( data_bb, np.array([[0.0, -1.0, 0.0], [300.0, 300.0, 300.0], [2.0, 1.0, 0.0]]), ) np.testing.assert_array_equal(a.bounding_box, data_bb) ================================================ FILE: tests/module/mobject/svg/test_svg_mobject.py ================================================ from __future__ import annotations from manim import * from tests.helpers.path_utils import get_svg_resource def test_set_fill_color(): expected_color = "#FF862F" svg = SVGMobject(get_svg_resource("heart.svg"), fill_color=expected_color) assert svg.fill_color.to_hex() == expected_color def test_set_stroke_color(): expected_color = "#FFFDDD" svg = SVGMobject(get_svg_resource("heart.svg"), stroke_color=expected_color) assert svg.stroke_color.to_hex() == expected_color def test_set_color_sets_fill_and_stroke(): expected_color = "#EEE777" svg = SVGMobject(get_svg_resource("heart.svg"), color=expected_color) assert svg.color.to_hex() == expected_color assert svg.fill_color.to_hex() == expected_color assert svg.stroke_color.to_hex() == expected_color def test_set_fill_opacity(): expected_opacity = 0.5 svg = SVGMobject(get_svg_resource("heart.svg"), fill_opacity=expected_opacity) assert svg.fill_opacity == expected_opacity def test_stroke_opacity(): expected_opacity = 0.4 svg = SVGMobject(get_svg_resource("heart.svg"), stroke_opacity=expected_opacity) assert svg.stroke_opacity == expected_opacity def test_fill_overrides_color(): expected_color = "#343434" svg = SVGMobject( get_svg_resource("heart.svg"), color="#123123", fill_color=expected_color, ) assert svg.fill_color.to_hex() == expected_color def test_stroke_overrides_color(): expected_color = "#767676" svg = SVGMobject( get_svg_resource("heart.svg"), color="#334433", stroke_color=expected_color, ) assert svg.stroke_color.to_hex() == expected_color def test_single_path_turns_into_sequence_of_points(): svg = SVGMobject( get_svg_resource("cubic_and_lineto.svg"), ) assert len(svg.points) == 0, svg.points assert len(svg.submobjects) == 1, svg.submobjects path = svg.submobjects[0] np.testing.assert_almost_equal( path.points, np.array( [ [-0.166666666666666, 0.66666666666666, 0.0], [-0.166666666666666, 0.0, 0.0], [0.5, 0.66666666666666, 0.0], [0.5, 0.0, 0.0], [0.5, 0.0, 0.0], [-0.16666666666666666, 0.0, 0.0], [0.5, -0.6666666666666666, 0.0], [-0.166666666666666, -0.66666666666666, 0.0], [-0.166666666666666, -0.66666666666666, 0.0], [-0.27777777777777, -0.77777777777777, 0.0], [-0.38888888888888, -0.88888888888888, 0.0], [-0.5, -1.0, 0.0], [-0.5, -1.0, 0.0], [-0.5, -0.333333333333, 0.0], [-0.5, 0.3333333333333, 0.0], [-0.5, 1.0, 0.0], [-0.5, 1.0, 0.0], [-0.38888888888888, 0.8888888888888, 0.0], [-0.27777777777777, 0.7777777777777, 0.0], [-0.16666666666666, 0.6666666666666, 0.0], ] ), decimal=5, ) def test_closed_path_does_not_have_extra_point(): # This dash.svg is the output of a "-" as generated from LaTex. # It ends back where it starts, so we shouldn't see a final line. svg = SVGMobject( get_svg_resource("dash.svg"), ) assert len(svg.points) == 0, svg.points assert len(svg.submobjects) == 1, svg.submobjects dash = svg.submobjects[0] np.testing.assert_almost_equal( dash.points, np.array( [ [13.524988331417841, -1.0, 0], [14.374988080480586, -1.0, 0], [15.274984567359079, -1.0, 0], [15.274984567359079, 0.0, 0.0], [15.274984567359079, 0.0, 0.0], [15.274984567359079, 1.0, 0.0], [14.374988080480586, 1.0, 0.0], [13.524988331417841, 1.0, 0.0], [13.524988331417841, 1.0, 0.0], [4.508331116720995, 1.0, 0], [-4.508326097975995, 1.0, 0.0], [-13.524983312672841, 1.0, 0.0], [-13.524983312672841, 1.0, 0.0], [-14.374983061735586, 1.0, 0.0], [-15.274984567359079, 1.0, 0.0], [-15.274984567359079, 0.0, 0.0], [-15.274984567359079, 0.0, 0.0], [-15.274984567359079, -1.0, 0], [-14.374983061735586, -1.0, 0], [-13.524983312672841, -1.0, 0], [-13.524983312672841, -1.0, 0], [-4.508326097975995, -1.0, 0],
1.0, 0.0], [14.374988080480586, 1.0, 0.0], [13.524988331417841, 1.0, 0.0], [13.524988331417841, 1.0, 0.0], [4.508331116720995, 1.0, 0], [-4.508326097975995, 1.0, 0.0], [-13.524983312672841, 1.0, 0.0], [-13.524983312672841, 1.0, 0.0], [-14.374983061735586, 1.0, 0.0], [-15.274984567359079, 1.0, 0.0], [-15.274984567359079, 0.0, 0.0], [-15.274984567359079, 0.0, 0.0], [-15.274984567359079, -1.0, 0], [-14.374983061735586, -1.0, 0], [-13.524983312672841, -1.0, 0], [-13.524983312672841, -1.0, 0], [-4.508326097975995, -1.0, 0], [4.508331116720995, -1.0, 0], [13.524988331417841, -1.0, 0], ] ), decimal=5, ) def test_close_command_closes_last_move_not_the_starting_one(): # This A.svg is the output of a Text("A") in some systems # It contains a path that moves from the outer boundary of the A # to the boundary of the inner triangle, and then closes the path # which should close the inner triangle and not the outer boundary. svg = SVGMobject( get_svg_resource("A.svg"), ) assert len(svg.points) == 0, svg.points assert len(svg.submobjects) == 1, svg.submobjects capital_A = svg.submobjects[0] # The last point should not be the same as the first point assert not all(capital_A.points[0] == capital_A.points[-1]) np.testing.assert_almost_equal( capital_A.points, np.array( [ [-0.8380339075214888, -1.0, 1.2246467991473532e-16], [-0.6132152047642527, -0.3333333333333336, 4.082155997157847e-17], [-0.388396502007016, 0.3333333333333336, -4.082155997157847e-17], [-0.16357779924977994, 1.0, -1.2246467991473532e-16], [-0.16357779924977994, 1.0, -1.2246467991473532e-16], [-0.05425733591657368, 1.0, -1.2246467991473532e-16], [0.05506312741663405, 1.0, -1.2246467991473532e-16], [0.16438359074984032, 1.0, -1.2246467991473532e-16], [0.16438359074984032, 1.0, -1.2246467991473532e-16], [0.3889336963403905, 0.3333333333333336, -4.082155997157847e-17], [0.6134838019309422, -0.3333333333333336, 4.082155997157847e-17], [0.8380339075214923, -1.0, 1.2246467991473532e-16], [0.8380339075214923, -1.0, 1.2246467991473532e-16], [0.744560897060354, -1.0, 1.2246467991473532e-16], [0.6510878865992157, -1.0, 1.2246467991473532e-16], [0.5576148761380774, -1.0, 1.2246467991473532e-16], [0.5576148761380774, -1.0, 1.2246467991473532e-16], [0.49717968849274957, -0.8138597980824822, 9.966907966764229e-17], [0.4367445008474217, -0.6277195961649644, 7.687347942054928e-17], [0.3763093132020939, -0.4415793942474466, 5.407787917345625e-17], [0.3763093132020939, -0.4415793942474466, 5.407787917345625e-17], [0.12167600863867864, -0.4415793942474466, 5.407787917345625e-17], [-0.13295729592473662, -0.4415793942474466, 5.407787917345625e-17], [-0.38759060048815186, -0.4415793942474466, 5.407787917345625e-17], [-0.38759060048815186, -0.4415793942474466, 5.407787917345625e-17], [-0.4480257881334797, -0.6277195961649644, 7.687347942054928e-17], [-0.5084609757788076, -0.8138597980824822, 9.966907966764229e-17], [-0.5688961634241354, -1.0, 1.2246467991473532e-16], [-0.5688961634241354, -1.0, 1.2246467991473532e-16], [-0.6586087447899202, -1.0, 1.2246467991473532e-16], [-0.7483213261557048, -1.0, 1.2246467991473532e-16], [-0.8380339075214888, -1.0, 1.2246467991473532e-16], [0.3021757525699033, -0.21434317946653003, 2.6249468865275272e-17], [0.1993017037512583, 0.09991949373745423, -1.2236608817799732e-17], [0.09642765493261184, 0.4141821669414385, -5.072268650087473e-17], [-0.006446393886033166, 0.7284448401454228, -8.920876418394973e-17], [-0.006446393886033166, 0.7284448401454228, -8.920876418394973e-17], [-0.10905185929034443, 0.4141821669414385, -5.072268650087473e-17], [-0.2116573246946542, 0.09991949373745423, -1.2236608817799732e-17], [-0.31426279009896546, -0.21434317946653003, 2.6249468865275272e-17], [-0.31426279009896546, -0.21434317946653003, 2.6249468865275272e-17], [-0.10878327587600921, -0.21434317946653003, 2.6249468865275272e-17], [0.09669623834694704, -0.21434317946653003, 2.6249468865275272e-17], [0.3021757525699033, -0.21434317946653003, 2.6249468865275272e-17], ] ), decimal=5, ) ================================================ FILE: tests/module/mobject/text/test_markup.py ================================================ from __future__ import annotations from manim import MarkupText def test_good_markup(): """Test creation of valid :class:`MarkupText` object""" try: text1 = MarkupText("<b>foo</b>") text2 = MarkupText("foo") success = True except ValueError: success = False assert success, "'<b>foo</b>' and 'foo' should not fail validation" def test_special_tags_markup(): """Test creation of valid :class:`MarkupText` object with unofficial tags""" try: text1 = MarkupText('<color col="RED">foo</color>') text1 = MarkupText('<gradient from="RED" to="YELLOW">foo</gradient>') success = True except ValueError: success = False assert success, ( '\'<color col="RED">foo</color>\' and \'<gradient from="RED" to="YELLOW">foo</gradient>\' should not fail validation' ) def test_unbalanced_tag_markup(): """Test creation of invalid :class:`MarkupText` object (unbalanced tag)""" try: text = MarkupText("<b>foo") success = False except ValueError: success = True assert success, "'<b>foo' should fail validation" def test_invalid_tag_markup(): """Test creation of invalid :class:`MarkupText` object (invalid tag)""" try: text = MarkupText("<invalidtag>foo</invalidtag>") success = False except ValueError: success = True assert success, "'<invalidtag>foo</invalidtag>' should fail validation" ================================================ FILE: tests/module/mobject/text/test_numbers.py ================================================ from __future__ import annotations from manim import RED, DecimalNumber, Integer def test_font_size(): """Test that DecimalNumber returns the correct font_size value after being scaled. """ num = DecimalNumber(0).scale(0.3) assert round(num.font_size, 5) == 14.4 def test_font_size_vs_scale(): """Test that scale produces the same results as .scale()""" num = DecimalNumber(0, font_size=12) num_scale = DecimalNumber(0).scale(1 / 4) assert num.height == num_scale.height def test_changing_font_size(): """Test that the font_size property properly
DecimalNumber returns the correct font_size value after being scaled. """ num = DecimalNumber(0).scale(0.3) assert round(num.font_size, 5) == 14.4 def test_font_size_vs_scale(): """Test that scale produces the same results as .scale()""" num = DecimalNumber(0, font_size=12) num_scale = DecimalNumber(0).scale(1 / 4) assert num.height == num_scale.height def test_changing_font_size(): """Test that the font_size property properly scales DecimalNumber.""" num = DecimalNumber(0, font_size=12) num.font_size = 48 assert num.height == DecimalNumber(0, font_size=48).height def test_set_value_size(): """Test that the size of DecimalNumber after set_value is correct.""" num = DecimalNumber(0).scale(0.3) test_num = num.copy() num.set_value(0) # round because the height is off by 1e-17 assert round(num.height, 12) == round(test_num.height, 12) def test_color_when_number_of_digits_changes(): """Test that all digits of an Integer are colored correctly when the number of digits changes. """ mob = Integer(color=RED) mob.set_value(42) assert all( submob.stroke_color.to_hex() == RED.to_hex() for submob in mob.submobjects ) ================================================ FILE: tests/module/mobject/text/test_texmobject.py ================================================ from __future__ import annotations from pathlib import Path import numpy as np import pytest from manim import MathTex, SingleStringMathTex, Tex, TexTemplate, tempconfig def test_MathTex(config): MathTex("a^2 + b^2 = c^2") assert Path(config.media_dir, "Tex", "e4be163a00cf424f.svg").exists() def test_SingleStringMathTex(config): SingleStringMathTex("test") assert Path(config.media_dir, "Tex", "8ce17c7f5013209f.svg").exists() @pytest.mark.parametrize( # : PT006 ("text_input", "length_sub"), [("{{ a }} + {{ b }} = {{ c }}", 5), (r"\frac{1}{a+b\sqrt{2}}", 1)], ) def test_double_braces_testing(text_input, length_sub): t1 = MathTex(text_input) assert len(t1.submobjects) == length_sub def test_tex(config): Tex("The horse does not eat cucumber salad.") assert Path(config.media_dir, "Tex", "c3945e23e546c95a.svg").exists() def test_tex_temp_directory(tmpdir, monkeypatch): # Adds a test for #3060 # It's not possible to reproduce the issue normally, because we use # tempconfig to change media directory to temporary directory by default # we partially, revert that change here. monkeypatch.chdir(tmpdir) Path(tmpdir, "media").mkdir() with tempconfig({"media_dir": "media"}): Tex("The horse does not eat cucumber salad.") assert Path("media", "Tex").exists() assert Path("media", "Tex", "c3945e23e546c95a.svg").exists() def test_percent_char_rendering(config): Tex(r"\%") assert Path(config.media_dir, "Tex", "4a583af4d19a3adf.tex").exists() def test_tex_whitespace_arg(): """Check that correct number of submobjects are created per string with whitespace separator""" separator = "\t" str_part_1 = "Hello" str_part_2 = "world" str_part_3 = "It is" str_part_4 = "me!" tex = Tex(str_part_1, str_part_2, str_part_3, str_part_4, arg_separator=separator) assert len(tex) == 4 assert len(tex[0]) == len("".join((str_part_1 + separator).split())) assert len(tex[1]) == len("".join((str_part_2 + separator).split())) assert len(tex[2]) == len("".join((str_part_3 + separator).split())) assert len(tex[3]) == len("".join(str_part_4.split())) def test_tex_non_whitespace_arg(): """Check that correct number of submobjects are created per string with non_whitespace characters""" separator = "," str_part_1 = "Hello" str_part_2 = "world" str_part_3 = "It is" str_part_4 = "me!" tex = Tex(str_part_1, str_part_2, str_part_3, str_part_4, arg_separator=separator) assert len(tex) == 4 assert len(tex[0]) == len("".join((str_part_1 + separator).split())) assert len(tex[1]) == len("".join((str_part_2 + separator).split())) assert len(tex[2]) == len("".join((str_part_3 + separator).split())) assert len(tex[3]) == len("".join(str_part_4.split())) def test_tex_white_space_and_non_whitespace_args(): """Check that correct number of submobjects are created per string when mixing characters with whitespace""" separator = ", \n . \t\t" str_part_1 = "Hello" str_part_2 = "world" str_part_3 = "It is" str_part_4 = "me!" tex = Tex(str_part_1, str_part_2, str_part_3, str_part_4, arg_separator=separator) assert len(tex) == 4 assert len(tex[0]) == len("".join((str_part_1 + separator).split())) assert len(tex[1]) == len("".join((str_part_2 + separator).split())) assert len(tex[2]) == len("".join((str_part_3 + separator).split())) assert len(tex[3]) == len("".join(str_part_4.split())) def test_multi_part_tex_with_empty_parts(): """Check that if a Tex or MathTex Mobject with multiple string arguments is created where some
= Tex(str_part_1, str_part_2, str_part_3, str_part_4, arg_separator=separator) assert len(tex) == 4 assert len(tex[0]) == len("".join((str_part_1 + separator).split())) assert len(tex[1]) == len("".join((str_part_2 + separator).split())) assert len(tex[2]) == len("".join((str_part_3 + separator).split())) assert len(tex[3]) == len("".join(str_part_4.split())) def test_multi_part_tex_with_empty_parts(): """Check that if a Tex or MathTex Mobject with multiple string arguments is created where some of the parts render as empty SVGs, then the number of family members with points should still be the same as the snipped in one singular part. """ tex_parts = ["(-1)", "^{", "0}"] one_part_fomula = MathTex("".join(tex_parts)) multi_part_formula = MathTex(*tex_parts) for one_part_glyph, multi_part_glyph in zip( one_part_fomula.family_members_with_points(), multi_part_formula.family_members_with_points(), ): np.testing.assert_allclose(one_part_glyph.points, multi_part_glyph.points) def test_tex_size(): """Check that the size of a :class:`Tex` string is not changed.""" text = Tex("what").center() vertical = text.get_top() - text.get_bottom() horizontal = text.get_right() - text.get_left() assert round(vertical[1], 4) == 0.3512 assert round(horizontal[0], 4) == 1.0420 def test_font_size(): """Test that tex_mobject classes return the correct font_size value after being scaled. """ string = MathTex(0).scale(0.3) assert round(string.font_size, 5) == 14.4 def test_font_size_vs_scale(): """Test that scale produces the same results as .scale()""" num = MathTex(0, font_size=12) num_scale = MathTex(0).scale(1 / 4) assert num.height == num_scale.height def test_changing_font_size(): """Test that the font_size property properly scales tex_mobject.py classes.""" num = Tex("0", font_size=12) num.font_size = 48 assert num.height == Tex("0", font_size=48).height def test_log_error_context(capsys): """Test that the environment context of an error is correctly logged if it exists""" invalid_tex = r""" some text that is fine \begin{unbalanced_braces}{ not fine \end{not_even_the_right_env} """ with pytest.raises(ValueError) as err: Tex(invalid_tex) # validate useful TeX error logged to user assert "unbalanced_braces" in str(capsys.readouterr().out) # validate useful error message raised assert "See log output above or the log file" in str(err.value) def test_log_error_no_relevant_context(capsys): """Test that an error with no environment context contains no environment context""" failing_preamble = r"""\usepackage{fontspec} \setmainfont[Ligatures=TeX]{not_a_font}""" with pytest.raises(ValueError) as err: Tex( "The template uses a non-existent font", tex_template=TexTemplate(preamble=failing_preamble), ) # validate useless TeX error not logged for user assert "Context" not in str(capsys.readouterr().out) # validate useful error message raised # this won't happen if an error is raised while formatting the message assert "See log output above or the log file" in str(err.value) def test_error_in_nested_context(capsys): """Test that displayed error context is not excessively large""" invalid_tex = r""" \begin{align} \begin{tabular}{ c } no need to display \\ this correct text \\ \end{tabular} \notacontrolsequence \end{align} """ with pytest.raises(ValueError): Tex(invalid_tex) stdout = str(capsys.readouterr().out) # validate useless context is not included assert r"\begin{frame}" not in stdout def test_tempconfig_resetting_tex_template(config): my_template = TexTemplate() my_template.preamble = "Custom preamble!" with tempconfig({"tex_template": my_template}): assert config.tex_template.preamble == "Custom preamble!" assert config.tex_template.preamble != "Custom preamble!" def test_tex_garbage_collection(tmpdir, monkeypatch, config): monkeypatch.chdir(tmpdir) Path(tmpdir, "media").mkdir() config.media_dir = "media" tex_without_log = Tex("Hello World!") # d771330b76d29ffb.tex assert Path("media", "Tex", "d771330b76d29ffb.tex").exists() assert not Path("media", "Tex", "d771330b76d29ffb.log").exists() config.no_latex_cleanup = True tex_with_log = Tex("Hello World, again!") # da27670a37b08799.tex assert Path("media", "Tex", "da27670a37b08799.log").exists() ================================================ FILE: tests/module/mobject/text/test_text_mobject.py ================================================ from __future__ import annotations from contextlib import redirect_stdout from io import StringIO from manim.mobject.text.text_mobject import MarkupText, Text def test_font_size(): """Test that Text and MarkupText return the correct font_size value after being scaled. """ text_string = Text("0").scale(0.3) markuptext_string = MarkupText("0").scale(0.3) assert round(text_string.font_size, 5) ==
Path("media", "Tex", "da27670a37b08799.log").exists() ================================================ FILE: tests/module/mobject/text/test_text_mobject.py ================================================ from __future__ import annotations from contextlib import redirect_stdout from io import StringIO from manim.mobject.text.text_mobject import MarkupText, Text def test_font_size(): """Test that Text and MarkupText return the correct font_size value after being scaled. """ text_string = Text("0").scale(0.3) markuptext_string = MarkupText("0").scale(0.3) assert round(text_string.font_size, 5) == 14.4 assert round(markuptext_string.font_size, 5) == 14.4 def test_font_warnings(): def warning_printed(font: str, **kwargs) -> bool: io = StringIO() with redirect_stdout(io): Text("hi!", font=font, **kwargs) txt = io.getvalue() return "Font" in txt and "not in" in txt # check for normal fonts (no warning) assert not warning_printed("System-ui", warn_missing_font=True) # should be converted to sans before checking assert not warning_printed("Sans-serif", warn_missing_font=True) # check random string (should be warning) assert warning_printed("Manim!" * 3, warn_missing_font=True) ================================================ FILE: tests/module/mobject/types/vectorized_mobject/test_stroke.py ================================================ from __future__ import annotations import manim.utils.color as C from manim import VMobject from manim.mobject.vector_field import StreamLines def test_stroke_props_in_ctor(): m = VMobject(stroke_color=C.ORANGE, stroke_width=10) assert m.stroke_color.to_hex() == C.ORANGE.to_hex() assert m.stroke_width == 10 def test_set_stroke(): m = VMobject() m.set_stroke(color=C.ORANGE, width=2, opacity=0.8) assert m.stroke_width == 2 assert m.stroke_opacity == 0.8 assert m.stroke_color.to_hex() == C.ORANGE.to_hex() def test_set_background_stroke(): m = VMobject() m.set_stroke(color=C.ORANGE, width=2, opacity=0.8, background=True) assert m.background_stroke_width == 2 assert m.background_stroke_opacity == 0.8 assert m.background_stroke_color.to_hex() == C.ORANGE.to_hex() def test_streamline_attributes_for_single_color(): vector_field = StreamLines( lambda x: x, # It is not important what this function is. x_range=[-1, 1, 0.1], y_range=[-1, 1, 0.1], padding=0.1, stroke_width=1.0, opacity=0.2, color=C.BLUE_D, ) assert vector_field[0].stroke_width == 1.0 assert vector_field[0].stroke_opacity == 0.2 def test_stroke_scale(): a = VMobject() b = VMobject() a.set_stroke(width=50) b.set_stroke(width=50) a.scale(0.5) b.scale(0.5, scale_stroke=True) assert a.get_stroke_width() == 50 assert b.get_stroke_width() == 25 def test_background_stroke_scale(): a = VMobject() b = VMobject() a.set_stroke(width=50, background=True) b.set_stroke(width=50, background=True) a.scale(0.5) b.scale(0.5, scale_stroke=True) assert a.get_stroke_width(background=True) == 50 assert b.get_stroke_width(background=True) == 25 ================================================ FILE: tests/module/mobject/types/vectorized_mobject/test_vectorized_mobject.py ================================================ from math import cos, sin import numpy as np import pytest from manim import ( Circle, CurvesAsSubmobjects, Line, Mobject, Polygon, RegularPolygon, Square, VDict, VGroup, VMobject, ) from manim.constants import PI def test_vmobject_add(): """Test the VMobject add method.""" obj = VMobject() assert len(obj.submobjects) == 0 obj.add(VMobject()) assert len(obj.submobjects) == 1 # Can't add non-VMobject values to a VMobject. with pytest.raises(TypeError) as add_int_info: obj.add(3) assert str(add_int_info.value) == ( "Only values of type VMobject can be added as submobjects of VMobject, " "but the value 3 (at index 0) is of type int." ) assert len(obj.submobjects) == 1 # Plain Mobjects can't be added to a VMobject if they're not # VMobjects. Suggest adding them into a Group instead. with pytest.raises(TypeError) as add_mob_info: obj.add(Mobject()) assert str(add_mob_info.value) == ( "Only values of type VMobject can be added as submobjects of VMobject, " "but the value Mobject (at index 0) is of type Mobject. You can try " "adding this value into a Group instead." ) assert len(obj.submobjects) == 1 with pytest.raises(TypeError) as add_vmob_and_mob_info: # If only one of the added objects is not an instance of VMobject, none of them should be added obj.add(VMobject(), Mobject()) assert str(add_vmob_and_mob_info.value) == ( "Only values of type VMobject can be added as submobjects of VMobject, " "but the value Mobject (at index 1) is of type Mobject. You can try
one of the added objects is not an instance of VMobject, none of them should be added obj.add(VMobject(), Mobject()) assert str(add_vmob_and_mob_info.value) == ( "Only values of type VMobject can be added as submobjects of VMobject, " "but the value Mobject (at index 1) is of type Mobject. You can try " "adding this value into a Group instead." ) assert len(obj.submobjects) == 1 # A VMobject or VGroup cannot contain itself. with pytest.raises(ValueError) as add_self_info: obj.add(obj) assert str(add_self_info.value) == ( "Cannot add VMobject as a submobject of itself (at index 0)." ) assert len(obj.submobjects) == 1 def test_vmobject_add_points_as_corners(): points = np.array( [ [2, 0, 0], [1, 1, 0], [-1, 1, 0], [-2, 0, 0], [-1, -1, 0], [1, -1, 0], [2, 0, 0], ] ) # Test that add_points_as_corners(points) is equivalent to calling # add_line_to(point) for every point in points. obj1 = VMobject().start_new_path(points[0]).add_points_as_corners(points[1:]) obj2 = VMobject().start_new_path(points[0]) for point in points[1:]: obj2.add_line_to(point) np.testing.assert_allclose(obj1.points, obj2.points) # Test that passing an array with no points does nothing. obj3 = VMobject().start_new_path(points[0]) points3_old = obj3.points.copy() obj3.add_points_as_corners([]) np.testing.assert_allclose(points3_old, obj3.points) obj3.add_points_as_corners(points[1:]).add_points_as_corners([]) np.testing.assert_allclose(obj1.points, obj3.points) def test_vmobject_point_from_proportion(): obj = VMobject() # One long line, one short line obj.set_points_as_corners( [ np.array([0, 0, 0]), np.array([4, 0, 0]), np.array([4, 2, 0]), ], ) # Total length of 6, so halfway along the object # would be at length 3, which lands in the first, long line. np.testing.assert_array_equal(obj.point_from_proportion(0.5), np.array([3, 0, 0])) with pytest.raises(ValueError, match="between 0 and 1"): obj.point_from_proportion(2) obj.clear_points() with pytest.raises(Exception, match="with no points"): obj.point_from_proportion(0) def test_curves_as_submobjects_point_from_proportion(): obj = CurvesAsSubmobjects(VGroup()) with pytest.raises(ValueError, match="between 0 and 1"): obj.point_from_proportion(2) with pytest.raises(Exception, match="with no submobjects"): obj.point_from_proportion(0) obj.add(VMobject()) with pytest.raises(Exception, match="have no points"): obj.point_from_proportion(0) # submobject[0] is a line of length 4 obj.submobjects[0].set_points_as_corners( [ np.array([0, 0, 0]), np.array([4, 0, 0]), ], ) obj.add(VMobject()) # submobject[1] is a line of length 2 obj.submobjects[1].set_points_as_corners( [ np.array([4, 0, 0]), np.array([4, 2, 0]), ], ) # point at proportion 0.5 should be at length 3, point [3, 0, 0] np.testing.assert_array_equal(obj.point_from_proportion(0.5), np.array([3, 0, 0])) def test_vgroup_init(): """Test the VGroup instantiation.""" VGroup() VGroup(VMobject()) VGroup(VMobject(), VMobject()) # A VGroup cannot contain non-VMobject values. with pytest.raises(TypeError) as init_with_float_info: VGroup(3.0) assert str(init_with_float_info.value) == ( "Only values of type VMobject can be added as submobjects of VGroup, " "but the value 3.0 (at index 0 of parameter 0) is of type float." ) with pytest.raises(TypeError) as init_with_mob_info: VGroup(Mobject()) assert str(init_with_mob_info.value) == ( "Only values of type VMobject can be added as submobjects of VGroup, " "but the value Mobject (at index 0 of parameter 0) is of type Mobject. You can try " "adding this value into a Group instead." ) with pytest.raises(TypeError) as init_with_vmob_and_mob_info: VGroup(VMobject(), Mobject()) assert str(init_with_vmob_and_mob_info.value) == ( "Only values of type VMobject can be added as submobjects of VGroup, " "but the value Mobject (at index 0 of parameter 1) is of type Mobject. You can try " "adding this value into a Group instead." ) def test_vgroup_init_with_iterable(): """Test VGroup instantiation with an iterable type.""" def type_generator(type_to_generate, n): return (type_to_generate() for _ in range(n)) def mixed_type_generator(major_type, minor_type, minor_type_positions, n): return ( minor_type() if
Mobject (at index 0 of parameter 1) is of type Mobject. You can try " "adding this value into a Group instead." ) def test_vgroup_init_with_iterable(): """Test VGroup instantiation with an iterable type.""" def type_generator(type_to_generate, n): return (type_to_generate() for _ in range(n)) def mixed_type_generator(major_type, minor_type, minor_type_positions, n): return ( minor_type() if i in minor_type_positions else major_type() for i in range(n) ) obj = VGroup(VMobject()) assert len(obj.submobjects) == 1 obj = VGroup(type_generator(VMobject, 38)) assert len(obj.submobjects) == 38 obj = VGroup(VMobject(), [VMobject(), VMobject()], type_generator(VMobject, 38)) assert len(obj.submobjects) == 41 # A VGroup cannot be initialised with an iterable containing a Mobject with pytest.raises(TypeError) as init_with_mob_iterable: VGroup(type_generator(Mobject, 5)) assert str(init_with_mob_iterable.value) == ( "Only values of type VMobject can be added as submobjects of VGroup, " "but the value Mobject (at index 0 of parameter 0) is of type Mobject." ) # A VGroup cannot be initialised with an iterable containing a Mobject in any position with pytest.raises(TypeError) as init_with_mobs_and_vmobs_iterable: VGroup(mixed_type_generator(VMobject, Mobject, [3, 5], 7)) assert str(init_with_mobs_and_vmobs_iterable.value) == ( "Only values of type VMobject can be added as submobjects of VGroup, " "but the value Mobject (at index 3 of parameter 0) is of type Mobject." ) # A VGroup cannot be initialised with an iterable containing non VMobject's in any position with pytest.raises(TypeError) as init_with_float_and_vmobs_iterable: VGroup(mixed_type_generator(VMobject, float, [6, 7], 9)) assert str(init_with_float_and_vmobs_iterable.value) == ( "Only values of type VMobject can be added as submobjects of VGroup, " "but the value 0.0 (at index 6 of parameter 0) is of type float." ) def test_vgroup_add(): """Test the VGroup add method.""" obj = VGroup() assert len(obj.submobjects) == 0 obj.add(VMobject()) assert len(obj.submobjects) == 1 # Can't add non-VMobject values to a VMobject or VGroup. with pytest.raises(TypeError) as add_int_info: obj.add(3) assert str(add_int_info.value) == ( "Only values of type VMobject can be added as submobjects of VGroup, " "but the value 3 (at index 0 of parameter 0) is of type int." ) assert len(obj.submobjects) == 1 # Plain Mobjects can't be added to a VMobject or VGroup if they're not # VMobjects. Suggest adding them into a Group instead. with pytest.raises(TypeError) as add_mob_info: obj.add(Mobject()) assert str(add_mob_info.value) == ( "Only values of type VMobject can be added as submobjects of VGroup, " "but the value Mobject (at index 0 of parameter 0) is of type Mobject. You can try " "adding this value into a Group instead." ) assert len(obj.submobjects) == 1 with pytest.raises(TypeError) as add_vmob_and_mob_info: # If only one of the added objects is not an instance of VMobject, none of them should be added obj.add(VMobject(), Mobject()) assert str(add_vmob_and_mob_info.value) == ( "Only values of type VMobject can be added as submobjects of VGroup, " "but the value Mobject (at index 0 of parameter 1) is of type Mobject. You can try " "adding this value into a Group instead." ) assert len(obj.submobjects) == 1 # A VMobject or VGroup cannot contain itself. with pytest.raises(ValueError) as add_self_info: obj.add(obj) assert str(add_self_info.value) == ( "Cannot add VGroup as a submobject of itself (at index 0)." ) assert len(obj.submobjects) == 1 def
You can try " "adding this value into a Group instead." ) assert len(obj.submobjects) == 1 # A VMobject or VGroup cannot contain itself. with pytest.raises(ValueError) as add_self_info: obj.add(obj) assert str(add_self_info.value) == ( "Cannot add VGroup as a submobject of itself (at index 0)." ) assert len(obj.submobjects) == 1 def test_vgroup_add_dunder(): """Test the VGroup __add__ magic method.""" obj = VGroup() assert len(obj.submobjects) == 0 obj + VMobject() assert len(obj.submobjects) == 0 obj += VMobject() assert len(obj.submobjects) == 1 with pytest.raises(TypeError): obj += Mobject() assert len(obj.submobjects) == 1 with pytest.raises(TypeError): # If only one of the added object is not an instance of VMobject, none of them should be added obj += (VMobject(), Mobject()) assert len(obj.submobjects) == 1 with pytest.raises(ValueError): # a Mobject cannot contain itself obj += obj def test_vgroup_remove(): """Test the VGroup remove method.""" a = VMobject() c = VMobject() b = VGroup(c) obj = VGroup(a, b) assert len(obj.submobjects) == 2 assert len(b.submobjects) == 1 obj.remove(a) b.remove(c) assert len(obj.submobjects) == 1 assert len(b.submobjects) == 0 obj.remove(b) assert len(obj.submobjects) == 0 def test_vgroup_remove_dunder(): """Test the VGroup __sub__ magic method.""" a = VMobject() c = VMobject() b = VGroup(c) obj = VGroup(a, b) assert len(obj.submobjects) == 2 assert len(b.submobjects) == 1 assert len(obj - a) == 1 assert len(obj.submobjects) == 2 obj -= a b -= c assert len(obj.submobjects) == 1 assert len(b.submobjects) == 0 obj -= b assert len(obj.submobjects) == 0 def test_vmob_add_to_back(): """Test the Mobject add_to_back method.""" a = VMobject() b = Line() c = "text" with pytest.raises(ValueError): # Mobject cannot contain self a.add_to_back(a) with pytest.raises(TypeError): # All submobjects must be of type Mobject a.add_to_back(c) # No submobject gets added twice a.add_to_back(b) a.add_to_back(b, b) assert len(a.submobjects) == 1 a.submobjects.clear() a.add_to_back(b, b, b) a.add_to_back(b, b) assert len(a.submobjects) == 1 a.submobjects.clear() # Make sure the ordering has not changed o1, o2, o3 = Square(), Line(), Circle() a.add_to_back(o1, o2, o3) assert a.submobjects.pop() == o3 assert a.submobjects.pop() == o2 assert a.submobjects.pop() == o1 def test_vdict_init(): """Test the VDict instantiation.""" # Test empty VDict VDict() # Test VDict made from list of pairs VDict([("a", VMobject()), ("b", VMobject()), ("c", VMobject())]) # Test VDict made from a python dict VDict({"a": VMobject(), "b": VMobject(), "c": VMobject()}) # Test VDict made using zip VDict(zip(["a", "b", "c"], [VMobject(), VMobject(), VMobject()])) # If the value is of type Mobject, must raise a TypeError with pytest.raises(TypeError): VDict({"a": Mobject()}) def test_vdict_add(): """Test the VDict add method.""" obj = VDict() assert len(obj.submob_dict) == 0 obj.add([("a", VMobject())]) assert len(obj.submob_dict) == 1 with pytest.raises(TypeError): obj.add([("b", Mobject())]) def test_vdict_remove(): """Test the VDict remove method.""" obj = VDict([("a", VMobject())]) assert len(obj.submob_dict) == 1 obj.remove("a") assert len(obj.submob_dict) == 0 with pytest.raises(KeyError): obj.remove("a") def test_vgroup_supports_item_assigment(): """Test VGroup supports array-like assignment for VMObjects""" a = VMobject() b = VMobject() vgroup = VGroup(a) assert vgroup[0] == a vgroup[0] = b assert vgroup[0] == b assert len(vgroup) == 1 def test_vgroup_item_assignment_at_correct_position(): """Test VGroup item-assignment adds to correct position for VMobjects""" n_items = 10 vgroup = VGroup() for _i in range(n_items): vgroup.add(VMobject()) new_obj = VMobject() vgroup[6] = new_obj assert vgroup[6] == new_obj assert
= VGroup(a) assert vgroup[0] == a vgroup[0] = b assert vgroup[0] == b assert len(vgroup) == 1 def test_vgroup_item_assignment_at_correct_position(): """Test VGroup item-assignment adds to correct position for VMobjects""" n_items = 10 vgroup = VGroup() for _i in range(n_items): vgroup.add(VMobject()) new_obj = VMobject() vgroup[6] = new_obj assert vgroup[6] == new_obj assert len(vgroup) == n_items def test_vgroup_item_assignment_only_allows_vmobjects(): """Test VGroup item-assignment raises TypeError when invalid type is passed""" vgroup = VGroup(VMobject()) with pytest.raises(TypeError) as assign_str_info: vgroup[0] = "invalid object" assert str(assign_str_info.value) == ( "Only values of type VMobject can be added as submobjects of VGroup, " "but the value invalid object (at index 0) is of type str." ) def test_trim_dummy(): o = VMobject() o.start_new_path(np.array([0, 0, 0])) o.add_line_to(np.array([1, 0, 0])) o.add_line_to(np.array([2, 0, 0])) o.add_line_to(np.array([2, 0, 0])) # Dummy point, will be stripped from points o.start_new_path(np.array([0, 1, 0])) o.add_line_to(np.array([1, 2, 0])) o2 = VMobject() o2.start_new_path(np.array([0, 0, 0])) o2.add_line_to(np.array([0, 1, 0])) o2.start_new_path(np.array([1, 0, 0])) o2.add_line_to(np.array([1, 1, 0])) o2.add_line_to(np.array([1, 2, 0])) def path_length(p): return len(p) // o.n_points_per_cubic_curve assert tuple(map(path_length, o.get_subpaths())) == (3, 1) assert tuple(map(path_length, o2.get_subpaths())) == (1, 2) o.align_points(o2) assert tuple(map(path_length, o.get_subpaths())) == (2, 2) assert tuple(map(path_length, o2.get_subpaths())) == (2, 2) def test_bounded_become(): """Tests that align_points generates a bounded number of points. https://github.com/ManimCommunity/manim/issues/1959 """ o = VMobject() def draw_circle(m: VMobject, n_points, x=0, y=0, r=1): center = np.array([x, y, 0]) m.start_new_path(center + [r, 0, 0]) for i in range(1, n_points + 1): theta = 2 * PI * i / n_points m.add_line_to(center + [cos(theta) * r, sin(theta) * r, 0]) # o must contain some points, or else become behaves differently draw_circle(o, 2) for _ in range(20): # Alternate between calls to become with different subpath sizes a = VMobject() draw_circle(a, 20) o.become(a) b = VMobject() draw_circle(b, 15) draw_circle(b, 15, x=3) o.become(b) # The number of points should be similar to the size of a and b assert len(o.points) <= (20 + 15 + 15) * 4 def test_vmobject_same_points_become(): a = Square() b = Circle() a.become(b) np.testing.assert_array_equal(a.points, b.points) assert len(a.submobjects) == len(b.submobjects) def test_vmobject_same_num_submobjects_become(): a = Square() b = RegularPolygon(n=6) a.become(b) np.testing.assert_array_equal(a.points, b.points) assert len(a.submobjects) == len(b.submobjects) def test_vmobject_different_num_points_and_submobjects_become(): a = Square() b = VGroup(Circle(), Square()) a.become(b) np.testing.assert_array_equal(a.points, b.points) assert len(a.submobjects) == len(b.submobjects) def test_vmobject_point_at_angle(): a = Circle() p = a.point_at_angle(4 * PI) np.testing.assert_array_equal(a.points[0], p) def test_proportion_from_point(): A = np.sqrt(3) * np.array([0, 1, 0]) B = np.array([-1, 0, 0]) C = np.array([1, 0, 0]) abc = Polygon(A, B, C) abc.shift(np.array([-1, 0, 0])) abc.scale(0.8) props = [abc.proportion_from_point(p) for p in abc.get_vertices()] np.testing.assert_allclose(props, [0, 1 / 3, 2 / 3]) def test_pointwise_become_partial_where_vmobject_is_self(): sq = Square() sq.pointwise_become_partial(vmobject=sq, a=0.2, b=0.7) expected_points = np.array( [ [-0.6, 1.0, 0.0], [-0.73333333, 1.0, 0.0], [-0.86666667, 1.0, 0.0], [-1.0, 1.0, 0.0], [-1.0, 1.0, 0.0], [-1.0, 0.33333333, 0.0], [-1.0, -0.33333333, 0.0], [-1.0, -1.0, 0.0], [-1.0, -1.0, 0.0], [-0.46666667, -1.0, 0.0], [0.06666667, -1.0, 0.0], [0.6, -1.0, 0.0], ] ) np.testing.assert_allclose(sq.points, expected_points) ================================================ FILE: tests/module/scene/test_auto_zoom.py ================================================ from __future__ import annotations from manim import * def test_zoom(): s1 = Square() s1.set_x(-10) s2 = Square() s2.set_x(10) with tempconfig({"dry_run": True, "quality": "low_quality"}): scene = MovingCameraScene() scene.add(s1, s2) scene.play(scene.camera.auto_zoom([s1, s2])) assert scene.camera.frame_width
0.0], [-0.46666667, -1.0, 0.0], [0.06666667, -1.0, 0.0], [0.6, -1.0, 0.0], ] ) np.testing.assert_allclose(sq.points, expected_points) ================================================ FILE: tests/module/scene/test_auto_zoom.py ================================================ from __future__ import annotations from manim import * def test_zoom(): s1 = Square() s1.set_x(-10) s2 = Square() s2.set_x(10) with tempconfig({"dry_run": True, "quality": "low_quality"}): scene = MovingCameraScene() scene.add(s1, s2) scene.play(scene.camera.auto_zoom([s1, s2])) assert scene.camera.frame_width == abs( s1.get_left()[0] - s2.get_right()[0], ) assert scene.camera.frame.get_center()[0] == ( abs(s1.get_center()[0] + s2.get_center()[0]) / 2 ) ================================================ FILE: tests/module/scene/test_scene.py ================================================ from __future__ import annotations import datetime import pytest from manim import Circle, FadeIn, Group, Mobject, Scene, Square from manim.animation.animation import Wait def test_scene_add_remove(dry_run): scene = Scene() assert len(scene.mobjects) == 0 scene.add(Mobject()) assert len(scene.mobjects) == 1 scene.add(*(Mobject() for _ in range(10))) assert len(scene.mobjects) == 11 # Check that adding a mobject twice does not actually add it twice repeated = Mobject() scene.add(repeated) assert len(scene.mobjects) == 12 scene.add(repeated) assert len(scene.mobjects) == 12 # Check that Scene.add() returns the Scene (for chained calls) assert scene.add(Mobject()) is scene to_remove = Mobject() scene = Scene() scene.add(to_remove) scene.add(*(Mobject() for _ in range(10))) assert len(scene.mobjects) == 11 scene.remove(to_remove) assert len(scene.mobjects) == 10 scene.remove(to_remove) assert len(scene.mobjects) == 10 # Check that Scene.remove() returns the instance (for chained calls) assert scene.add(Mobject()) is scene def test_scene_time(dry_run): scene = Scene() assert scene.time == 0 scene.wait(2) assert scene.time == 2 scene.play(FadeIn(Circle()), run_time=0.5) assert pytest.approx(scene.time) == 2.5 scene.renderer._original_skipping_status = True scene.play(FadeIn(Square()), run_time=5) # this animation gets skipped. assert pytest.approx(scene.time) == 7.5 def test_subcaption(dry_run): scene = Scene() scene.add_subcaption("Testing add_subcaption", duration=1, offset=0) scene.wait() scene.play( Wait(), run_time=2, subcaption="Testing Scene.play subcaption interface", subcaption_duration=1.5, subcaption_offset=0.5, ) subcaptions = scene.renderer.file_writer.subcaptions assert len(subcaptions) == 2 assert subcaptions[0].start == datetime.timedelta(seconds=0) assert subcaptions[0].end == datetime.timedelta(seconds=1) assert subcaptions[0].content == "Testing add_subcaption" assert subcaptions[1].start == datetime.timedelta(seconds=1.5) assert subcaptions[1].end == datetime.timedelta(seconds=3) assert subcaptions[1].content == "Testing Scene.play subcaption interface" def test_replace(dry_run): def assert_names(mobjs, names): assert len(mobjs) == len(names) for i in range(0, len(mobjs)): assert mobjs[i].name == names[i] scene = Scene() first = Mobject(name="first") second = Mobject(name="second") third = Mobject(name="third") fourth = Mobject(name="fourth") scene.add(first) scene.add(Group(second, third, name="group")) scene.add(fourth) assert_names(scene.mobjects, ["first", "group", "fourth"]) assert_names(scene.mobjects[1], ["second", "third"]) alpha = Mobject(name="alpha") beta = Mobject(name="beta") scene.replace(first, alpha) assert_names(scene.mobjects, ["alpha", "group", "fourth"]) assert_names(scene.mobjects[1], ["second", "third"]) scene.replace(second, beta) assert_names(scene.mobjects, ["alpha", "group", "fourth"]) assert_names(scene.mobjects[1], ["beta", "third"]) ================================================ FILE: tests/module/scene/test_sound.py ================================================ from __future__ import annotations import struct import wave from pathlib import Path from manim import Scene def test_add_sound(tmpdir): # create sound file sound_loc = Path(tmpdir, "noise.wav") with wave.open(str(sound_loc), "w") as f: f.setparams((2, 2, 44100, 0, "NONE", "not compressed")) for _ in range(22050): # half a second of sound packed_value = struct.pack("h", 14242) f.writeframes(packed_value) f.writeframes(packed_value) scene = Scene() scene.add_sound(sound_loc) ================================================ FILE: tests/module/scene/test_threed_scene.py ================================================ from manim import Circle, Square, ThreeDScene def test_fixed_mobjects(): scene = ThreeDScene() s = Square() c = Circle() scene.add_fixed_in_frame_mobjects(s, c) assert set(scene.mobjects) == {s, c} assert set(scene.camera.fixed_in_frame_mobjects) == {s, c} scene.remove_fixed_in_frame_mobjects(s) assert set(scene.mobjects) == {s, c} assert set(scene.camera.fixed_in_frame_mobjects) == {c} scene.add_fixed_orientation_mobjects(s) assert set(scene.camera.fixed_orientation_mobjects) == {s} scene.remove_fixed_orientation_mobjects(s) assert len(scene.camera.fixed_orientation_mobjects) == 0 ================================================ FILE: tests/module/utils/_split_matrices.py ================================================ import numpy as np # Defined because pre-commit is inserting an unacceptable line-break # between the "1" (or "2") and the "/ 3" one_third = 1 / 3 two_thirds
== {s, c} assert set(scene.camera.fixed_in_frame_mobjects) == {c} scene.add_fixed_orientation_mobjects(s) assert set(scene.camera.fixed_orientation_mobjects) == {s} scene.remove_fixed_orientation_mobjects(s) assert len(scene.camera.fixed_orientation_mobjects) == 0 ================================================ FILE: tests/module/utils/_split_matrices.py ================================================ import numpy as np # Defined because pre-commit is inserting an unacceptable line-break # between the "1" (or "2") and the "/ 3" one_third = 1 / 3 two_thirds = 2 / 3 # Expected values for matrices in split_bezier SPLIT_MATRICES = { # For 0-degree Béziers 0: { 0: np.array([[1], [1]]), one_third: np.array([[1], [1]]), two_thirds: np.array([[1], [1]]), 1: np.array([[1], [1]]), }, # For linear Béziers 1: { 0: np.array( [ [1, 0], [1, 0], [1, 0] [0, 1], ] ), one_third: np.array( [ [3, 0], [2, 1], [2, 1], [0, 3], ] ) / 3, two_thirds: np.array( [ [3, 0], [1, 2], [1, 2], [0, 3], ] ) / 3, 1: np.array( [ [1, 0], [0, 1], [0, 1], [0, 1], ] ), }, # For quadratic Béziers 2: { 0: np.array( [ [1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1], ] ), one_third: np.array( [ [9, 0, 0], [6, 3, 0], [4, 4, 1], [4, 4, 1], [0, 6, 3], [0, 0 9], ] ) / 9, two_thirds: np.array( [ [9, 0, 0], [3, 6, 0], [1, 4, 4], [1, 4, 4], [0, 3, 6], [0, 0, 9], ] ) / 9, 1: np.array( [ [1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 0, 1], [0, 0, 1], [0, 0, 1], ] ), }, # For cubic Béziers 3: { 0: np.array( [ [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], ] ), one_third: np.array( [ [27, 0, 0, 0], [18, 9, 0, 0], [12, 12, 3, 0], [8, 12, 6, 1], [8, 12, 6, 1], [0, 12, 12, 3], [0, 0, 18, 9], [0, 0, 0, 27], ] ) / 27, two_thirds: np.array( [ [27, 0, 0, 0], [9, 18, 0, 0], [3, 12, 12, 0], [1, 6, 12, 8], [1, 6, 12, 8], [0, 3, 12, 12], [0, 0, 9, 18], [0, 0, 0, 27], ] ) / 27, 1: np.array( [ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1], ] ), }, # Test case with a quartic Bézier # to check if the fallback algorithms work 4: { 0: np.array( [ [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1], ] ), one_third: np.array( [ [81, 0, 0, 0, 0], [54, 27, 0, 0, 0], [36, 36, 9, 0, 0], [24, 36,
0, 0, 0], [1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1], ] ), one_third: np.array( [ [81, 0, 0, 0, 0], [54, 27, 0, 0, 0], [36, 36, 9, 0, 0], [24, 36, 18, 3, 0], [16, 32, 24, 8, 1], [16, 32, 24, 8, 1], [0, 24, 36, 18, 3], [0, 0, 36, 36, 9], [0, 0, 0, 54, 27], [0, 0, 0, 0, 81], ] ) / 81, two_thirds: np.array( [ [81, 0, 0, 0, 0], [27, 54, 0, 0, 0], [9, 36, 36, 0, 0], [3, 18, 36, 24, 0], [1, 8, 24, 32, 16], [1, 8, 24, 32, 16], [0, 3, 18, 36, 24], [0, 0, 9, 36, 36], [0, 0, 0, 27, 54], [0, 0, 0, 0, 81], ] ) / 81, 1: np.array( [ [1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1], [0, 0, 0, 0, 1], [0, 0, 0, 0, 1], [0, 0, 0, 0, 1], [0, 0, 0, 0, 1], [0, 0, 0, 0, 1], ] ), }, } ================================================ FILE: tests/module/utils/_subdivision_matrices.py ================================================ import numpy as np # Expected values for matrices in subdivide_bezier and others # Note that in bezier.py this is a list of dicts, # not a dict of dicts! SUBDIVISION_MATRICES = { # For 0-degree Béziers 0: { 2: np.array([[1], [1]]), 3: np.array([[1], [1], [1]]), 4: np.array([[1], [1], [1], [1]]), }, # For linear Béziers 1: { 2: np.array( [ [2, 0], [1, 1], [1, 1], [0, 2], ] ) / 2, 3: np.array( [ [3, 0], [2, 1], [2, 1], [1, 2], [1, 2], [0, 3], ] ) / 3, 4: np.array( [ [4, 0], [3, 1], [3, 1], [2, 2], [2, 2], [1, 3], [1, 3], [0, 4], ] ) / 4, }, # For quadratic Béziers 2: { 2: np.array( [ [4, 0, 0], [2, 2, 0], [1, 2, 1], [1, 2, 1], [0, 2, 2], [0, 0, 4], ] ) / 4, 3: np.array( [ [9, 0, 0], [6, 3, 0], [4, 4, 1], [4, 4, 1], [2, 5, 2], [1, 4, 4], [1, 4, 4], [0, 3, 6], [0, 0, 9], ] ) / 9, 4: np.array( [ [16, 0, 0], [12, 4, 0], [9, 6, 1], [9, 6, 1], [6, 8, 2], [4, 8, 4], [4, 8, 4], [2, 8, 6], [1, 6, 9], [1, 6, 9], [0, 4, 12], [0, 0, 16], ] ) / 16, }, # For cubic Béziers 3: { 2: np.array( [ [8, 0, 0, 0], [4, 4, 0, 0], [2, 4, 2, 0], [1, 3, 3, 1], [1, 3, 3, 1], [0, 2, 4, 2], [0, 0, 4, 4], [0, 0, 0, 8], ] ) / 8, 3: np.array( [ [27, 0, 0 0], [18, 9, 0, 0], [12, 12, 3, 0], [8, 12, 6, 1], [8, 12, 6, 1], [4, 12,
0], [1, 3, 3, 1], [1, 3, 3, 1], [0, 2, 4, 2], [0, 0, 4, 4], [0, 0, 0, 8], ] ) / 8, 3: np.array( [ [27, 0, 0 0], [18, 9, 0, 0], [12, 12, 3, 0], [8, 12, 6, 1], [8, 12, 6, 1], [4, 12, 9, 2], [2, 9, 12, 4], [1, 6, 12, 8], [1, 6, 12, 8], [0, 3, 12, 12], [0, 0, 9, 18], [0, 0, 0, 27], ] ) / 27, 4: np.array( [ [64, 0, 0, 0], [48, 16, 0, 0], [36, 24, 4, 0], [27, 27, 9, 1], [27, 27, 9, 1], [18, 30, 14, 2], [12, 28, 20, 4], [8, 24, 24, 8], [8, 24, 24, 8], [4, 20, 28, 12], [2, 14, 30, 18], [1, 9, 27, 27], [1, 9, 27, 27], [0, 4, 24, 36], [0, 0, 16, 48], [0, 0, 0, 64], ] ) / 64, }, # Test case with a quartic Bézier #to check if the fallback algorithms work 4: { 2: np.array( [ [16, 0, 0, 0, 0], [8, 8, 0, 0, 0], [4, 8, 4, 0, 0], [2, 6, 6, 2, 0], [1, 4, 6, 4, 1], [1, 4, 6, 4, 1], [0, 2, 6, 6, 2], [0, 0, 4, 8, 4], [0, 0, 0, 8, 8], [0, 0, 0, 0, 16], ] ) / 16, }, } ================================================ FILE: tests/module/utils/test_bezier.py ================================================ from __future__ import annotations import numpy as np import numpy.testing as nt from _split_matrices import SPLIT_MATRICES from _subdivision_matrices import SUBDIVISION_MATRICES from manim.typing import ManimFloat from manim.utils.bezier import ( _get_subdivision_matrix, get_quadratic_approximation_of_cubic, get_smooth_cubic_bezier_handle_points, interpolate, partial_bezier_points, split_bezier, subdivide_bezier, ) QUARTIC_BEZIER = np.array( [ [-1, -1, 0], [-1, 0, 0], [0, 1, 0], [1, 0, 0], [1, -1, 0], ], dtype=float, ) def test_partial_bezier_points() -> None: """Test that :func:`partial_bezierpoints`, both in the portion-matrix-building algorithm (degrees up to 3) and the fallback algorithm (degree 4), works correctly. """ for degree, degree_dict in SUBDIVISION_MATRICES.items(): n_points = degree + 1 points = QUARTIC_BEZIER[:n_points] for n_divisions, subdivision_matrix in degree_dict.items(): for i in range(n_divisions): a = i / n_divisions b = (i + 1) / n_divisions portion_matrix = subdivision_matrix[n_points * i : n_points * (i + 1)] nt.assert_allclose( partial_bezier_points(points, a, b), portion_matrix @ points, atol=1e-15, # Needed because of floating-point errors ) def test_split_bezier() -> None: """Test that :func:`split_bezier`, both in the split-matrix-building algorithm (degrees up to 3) and the fallback algorithm (degree 4), works correctly. """ for degree, degree_dict in SPLIT_MATRICES.items(): n_points = degree + 1 points = QUARTIC_BEZIER[:n_points] for t, split_matrix in degree_dict.items(): nt.assert_allclose( split_bezier(points, t), split_matrix @ points, atol=1e-15 ) for degree, degree_dict in SUBDIVISION_MATRICES.items(): n_points = degree + 1 points = QUARTIC_BEZIER[:n_points] # Split in half split_matrix = degree_dict[2] nt.assert_allclose( split_bezier(points, 0.5), split_matrix @ points, ) def test_get_subdivision_matrix() -> None: """Test that the memos in .:meth:`_get_subdivision_matrix` are being correctly generated. """ # Only for degrees up to 3! for degree in range(4): degree_dict = SUBDIVISION_MATRICES[degree] for n_divisions, subdivision_matrix in degree_dict.items(): nt.assert_allclose( _get_subdivision_matrix(degree + 1, n_divisions), subdivision_matrix, ) def test_subdivide_bezier() -> None: """Test that :func:`subdivide_bezier`,
points, ) def test_get_subdivision_matrix() -> None: """Test that the memos in .:meth:`_get_subdivision_matrix` are being correctly generated. """ # Only for degrees up to 3! for degree in range(4): degree_dict = SUBDIVISION_MATRICES[degree] for n_divisions, subdivision_matrix in degree_dict.items(): nt.assert_allclose( _get_subdivision_matrix(degree + 1, n_divisions), subdivision_matrix, ) def test_subdivide_bezier() -> None: """Test that :func:`subdivide_bezier`, both in the memoized cases (degrees up to 3) and the fallback algorithm (degree 4), works correctly. """ for degree, degree_dict in SUBDIVISION_MATRICES.items(): n_points = degree + 1 points = QUARTIC_BEZIER[:n_points] for n_divisions, subdivision_matrix in degree_dict.items(): nt.assert_allclose( subdivide_bezier(points, n_divisions), subdivision_matrix @ points, ) def test_get_smooth_cubic_bezier_handle_points() -> None: """Test that :func:`.get_smooth_cubic_bezier_handle_points` returns the correct handles, both for open and closed Bézier splines. """ open_curve_corners = np.array( [ [1, 1, 0], [-1, 1, 1], [-1, -1, 2], [1, -1, 1], ], dtype=ManimFloat, ) h1, h2 = get_smooth_cubic_bezier_handle_points(open_curve_corners) assert np.allclose( h1, np.array( [ [1 / 5, 11 / 9, 13 / 45], [-7 / 5, 5 / 9, 64 / 45], [-3 / 5, -13 / 9, 91 / 45], ] ), ) assert np.allclose( h2, np.array( [ [-3 / 5, 13 / 9, 26 / 45], [-7 / 5, -5 / 9, 89 / 45], [1 / 5, -11 / 9, 68 / 45], ] ), ) closed_curve_corners = np.array( [ [1, 1, 0], [-1, 1, 1], [-1, -1, 2], [1, -1, 1], [1, 1, 0], ], dtype=ManimFloat, ) h1, h2 = get_smooth_cubic_bezier_handle_points(closed_curve_corners) assert np.allclose( h1, np.array( [ [1 / 2, 3 / 2, 0], [-3 / 2, 1 / 2, 3 / 2], [-1 / 2, -3 / 2, 2], [3 / 2, -1 / 2, 1 / 2], ] ), ) assert np.allclose( h2, np.array( [ [-1 / 2, 3 / 2, 1 / 2], [-3 / 2, -1 / 2, 2], [1 / 2, -3 / 2, 3 / 2], [3 / 2, 1 / 2, 0], ] ), ) def test_get_quadratic_approximation_of_cubic() -> None: C = np.array( [ [-5, 2, 0], [-4, 2, 0], [-3, 2, 0], [-2, 2, 0], [-2, 2, 0], [-7 / 3, 4 / 3, 0], [-8 / 3, 2 / 3, 0], [-3, 0, 0], [-3, 0, 0], [-1 / 3, -1, 0], [7 / 3, -2, 0], [5, -3, 0], ] ) a0, h0, h1, a1 = C[::4], C[1::4], C[2::4], C[3::4] Q = get_quadratic_approximation_of_cubic(a0, h0, h1, a1) assert np.allclose( Q, np.array( [ [-5, 2, 0], [-17 / 4, 2, 0], [-7 / 2, 2, 0], [-7 / 2, 2, 0], [-11 / 4, 2, 0], [-2, 2, 0], [-2, 2, 0], [-9 / 4, 3 / 2, 0], [-5 / 2, 1, 0], [-5 / 2, 1, 0], [-11 / 4, 1 / 2, 0], [-3, 0, 0], [-3, 0, 0], [-1, -3 / 4, 0], [1, -3 / 2, 0], [1, -3 / 2, 0], [3, -9 / 4, 0], [5, -3, 0], ] ), ) def test_interpolate() -> None: """Test that :func:`interpolate` handles interpolation of both float and uint8 values.""" start = 127.0 end = 25.0 alpha = 0.2 val =
/ 4, 0], [1, -3 / 2, 0], [1, -3 / 2, 0], [3, -9 / 4, 0], [5, -3, 0], ] ), ) def test_interpolate() -> None: """Test that :func:`interpolate` handles interpolation of both float and uint8 values.""" start = 127.0 end = 25.0 alpha = 0.2 val = interpolate(start, end, alpha) assert np.allclose(val, 106.6000000) start = np.array(127, dtype=np.uint8) end = np.array(25, dtype=np.uint8) alpha = 0.09739 val = interpolate(start, end, alpha) assert np.allclose(val, np.array([117.06622])) ================================================ FILE: tests/module/utils/test_color.py ================================================ from __future__ import annotations import numpy as np from manim import BLACK, RED, WHITE, ManimColor, Mobject, Scene, VMobject def test_import_color(): import manim.utils.color as C C.WHITE def test_background_color(): S = Scene() S.camera.background_color = "#ff0000" S.renderer.update_frame(S) np.testing.assert_array_equal( S.renderer.get_frame()[0, 0], np.array([255, 0, 0, 255]) ) S.camera.background_color = "#436f80" S.renderer.update_frame(S) np.testing.assert_array_equal( S.renderer.get_frame()[0, 0], np.array([67, 111, 128, 255]) ) S.camera.background_color = "#ffffff" S.renderer.update_frame(S) np.testing.assert_array_equal( S.renderer.get_frame()[0, 0], np.array([255, 255, 255, 255]) ) S.camera.background_color = "#bbffbb" S.camera.background_opacity = 0.5 S.renderer.update_frame(S) np.testing.assert_array_equal( S.renderer.get_frame()[0, 0], np.array([187, 255, 187, 127]) ) def test_set_color(): m = Mobject() assert m.color.to_hex() == "#FFFFFF" m.set_color(BLACK) assert m.color.to_hex() == "#000000" m = VMobject() assert m.color.to_hex() == "#FFFFFF" m.set_color(BLACK) assert m.color.to_hex() == "#000000" def test_color_hash(): assert hash(WHITE) == hash(ManimColor([1.0, 1.0, 1.0, 1.0])) assert hash(WHITE) == hash("#FFFFFFFF") assert hash(WHITE) != hash(RED) ================================================ FILE: tests/module/utils/test_deprecation.py ================================================ from __future__ import annotations from manim.utils.deprecation import deprecated, deprecated_params def _get_caplog_record_msg(manim_caplog): logger_name, level, message = manim_caplog.record_tuples[0] return message @deprecated class Foo: def __init__(self): pass @deprecated(since="v0.6.0") class Bar: """The Bar class.""" def __init__(self): pass @deprecated(until="06/01/2021") class Baz: """The Baz class.""" def __init__(self): pass @deprecated(since="0.7.0", until="0.9.0-rc2") class Qux: def __init__(self): pass @deprecated(message="Use something else.") class Quux: def __init__(self): pass @deprecated(replacement="ReplaceQuuz") class Quuz: def __init__(self): pass class ReplaceQuuz: def __init__(self): pass @deprecated( since="0.7.0", until="1.2.1", replacement="ReplaceQuuz", message="Don't use this please.", ) class QuuzAll: def __init__(self): pass doc_admonition = "\n\n.. attention:: Deprecated\n " def test_deprecate_class_no_args(manim_caplog): """Test the deprecation of a class (decorator with no arguments).""" f = Foo() assert len(manim_caplog.record_tuples) == 1 msg = _get_caplog_record_msg(manim_caplog) assert ( msg == "The class Foo has been deprecated and may be removed in a later version." ) assert f.__doc__ == f"{doc_admonition}{msg}" def test_deprecate_class_since(manim_caplog): """Test the deprecation of a class (decorator with since argument).""" b = Bar() assert len(manim_caplog.record_tuples) == 1 msg = _get_caplog_record_msg(manim_caplog) assert ( msg == "The class Bar has been deprecated since v0.6.0 and may be removed in a later version." ) assert b.__doc__ == f"The Bar class.{doc_admonition}{msg}" def test_deprecate_class_until(manim_caplog): """Test the deprecation of a class (decorator with until argument).""" bz = Baz() assert len(manim_caplog.record_tuples) == 1 msg = _get_caplog_record_msg(manim_caplog) assert ( msg == "The class Baz has been deprecated and is expected to be removed after 06/01/2021." ) assert bz.__doc__ == f"The Baz class.{doc_admonition}{msg}" def test_deprecate_class_since_and_until(manim_caplog): """Test the deprecation of a class (decorator with since and until arguments).""" qx = Qux() assert len(manim_caplog.record_tuples) == 1 msg = _get_caplog_record_msg(manim_caplog) assert ( msg == "The class Qux has been deprecated since 0.7.0 and is expected to be removed after 0.9.0-rc2." ) assert qx.__doc__ == f"{doc_admonition}{msg}" def test_deprecate_class_msg(manim_caplog): """Test the deprecation of a class (decorator with msg argument).""" qu = Quux()
qx = Qux() assert len(manim_caplog.record_tuples) == 1 msg = _get_caplog_record_msg(manim_caplog) assert ( msg == "The class Qux has been deprecated since 0.7.0 and is expected to be removed after 0.9.0-rc2." ) assert qx.__doc__ == f"{doc_admonition}{msg}" def test_deprecate_class_msg(manim_caplog): """Test the deprecation of a class (decorator with msg argument).""" qu = Quux() assert len(manim_caplog.record_tuples) == 1 msg = _get_caplog_record_msg(manim_caplog) assert ( msg == "The class Quux has been deprecated and may be removed in a later version. Use something else." ) assert qu.__doc__ == f"{doc_admonition}{msg}" def test_deprecate_class_replacement(manim_caplog): """Test the deprecation of a class (decorator with replacement argument).""" qz = Quuz() assert len(manim_caplog.record_tuples) == 1 msg = _get_caplog_record_msg(manim_caplog) assert ( msg == "The class Quuz has been deprecated and may be removed in a later version. Use ReplaceQuuz instead." ) doc_msg = "The class Quuz has been deprecated and may be removed in a later version. Use :class:`~.ReplaceQuuz` instead." assert qz.__doc__ == f"{doc_admonition}{doc_msg}" def test_deprecate_class_all(manim_caplog): """Test the deprecation of a class (decorator with all arguments).""" qza = QuuzAll() assert len(manim_caplog.record_tuples) == 1 msg = _get_caplog_record_msg(manim_caplog) assert ( msg == "The class QuuzAll has been deprecated since 0.7.0 and is expected to be removed after 1.2.1. Use ReplaceQuuz instead. Don't use this please." ) doc_msg = "The class QuuzAll has been deprecated since 0.7.0 and is expected to be removed after 1.2.1. Use :class:`~.ReplaceQuuz` instead. Don't use this please." assert qza.__doc__ == f"{doc_admonition}{doc_msg}" @deprecated def useless(**kwargs): pass class Top: def __init__(self): pass @deprecated(since="0.8.0", message="This method is useless.") def mid_func(self): """Middle function in Top.""" pass @deprecated(until="1.4.0", replacement="Top.NewNested") class Nested: def __init__(self): pass class NewNested: def __init__(self): pass @deprecated(since="1.0.0", until="12/25/2025") def nested_func(self): """Nested function in Top.NewNested.""" pass class Bottom: def __init__(self): pass def normal_func(self): @deprecated def nested_func(self): pass return nested_func @deprecated_params(params="a, b, c", message="Use something else.") def foo(self, **kwargs): pass @deprecated_params(params="a", since="v0.2", until="v0.4") def bar(self, **kwargs): pass @deprecated_params(redirections=[("old_param", "new_param")]) def baz(self, **kwargs): return kwargs @deprecated_params( redirections=[lambda runtime_in_ms: {"run_time": runtime_in_ms / 1000}], ) def qux(self, **kwargs): return kwargs @deprecated_params( redirections=[ lambda point2D_x=1, point2D_y=1: {"point2D": (point2D_x, point2D_y)}, ], ) def quux(self, **kwargs): return kwargs @deprecated_params( redirections=[ lambda point2D=1: ( {"x": point2D[0], "y": point2D[1]} if isinstance(point2D, tuple) else {"x": point2D, "y": point2D} ), ], ) def quuz(self, **kwargs): return kwargs def test_deprecate_func_no_args(manim_caplog): """Test the deprecation of a method (decorator with no arguments).""" useless() assert len(manim_caplog.record_tuples) == 1 msg = _get_caplog_record_msg(manim_caplog) assert ( msg == "The function useless has been deprecated and may be removed in a later version." ) assert useless.__doc__ == f"{doc_admonition}{msg}" def test_deprecate_func_in_class_since_and_message(manim_caplog): """Test the deprecation of a method within a class (decorator with since and message arguments).""" t = Top() t.mid_func() assert len(manim_caplog.record_tuples) == 1 msg = _get_caplog_record_msg(manim_caplog) assert ( msg == "The method Top.mid_func has been deprecated since 0.8.0 and may be removed in a later version. This method is useless." ) assert t.mid_func.__doc__ == f"Middle function in Top.{doc_admonition}{msg}" def test_deprecate_nested_class_until_and_replacement(manim_caplog): """Test the deprecation of a nested class (decorator with until and replacement arguments).""" n = Top().Nested() assert len(manim_caplog.record_tuples) == 1 msg = _get_caplog_record_msg(manim_caplog) assert ( msg == "The class Top.Nested has been deprecated and
later version. This method is useless." ) assert t.mid_func.__doc__ == f"Middle function in Top.{doc_admonition}{msg}" def test_deprecate_nested_class_until_and_replacement(manim_caplog): """Test the deprecation of a nested class (decorator with until and replacement arguments).""" n = Top().Nested() assert len(manim_caplog.record_tuples) == 1 msg = _get_caplog_record_msg(manim_caplog) assert ( msg == "The class Top.Nested has been deprecated and is expected to be removed after 1.4.0. Use Top.NewNested instead." ) doc_msg = "The class Top.Nested has been deprecated and is expected to be removed after 1.4.0. Use :class:`~.Top.NewNested` instead." assert n.__doc__ == f"{doc_admonition}{doc_msg}" def test_deprecate_nested_class_func_since_and_until(manim_caplog): """Test the deprecation of a method within a nested class (decorator with since and until arguments).""" n = Top().NewNested() n.nested_func() assert len(manim_caplog.record_tuples) == 1 msg = _get_caplog_record_msg(manim_caplog) assert ( msg == "The method Top.NewNested.nested_func has been deprecated since 1.0.0 and is expected to be removed after 12/25/2025." ) assert ( n.nested_func.__doc__ == f"Nested function in Top.NewNested.{doc_admonition}{msg}" ) def test_deprecate_nested_func(manim_caplog): """Test the deprecation of a nested method (decorator with no arguments).""" b = Top().Bottom() answer = b.normal_func() answer(1) assert len(manim_caplog.record_tuples) == 1 msg = _get_caplog_record_msg(manim_caplog) assert ( msg == "The method Top.Bottom.normal_func.<locals>.nested_func has been deprecated and may be removed in a later version." ) assert answer.__doc__ == f"{doc_admonition}{msg}" def test_deprecate_func_params(manim_caplog): """Test the deprecation of method parameters (decorator with params argument).""" t = Top() t.foo(a=2, b=3, z=4) assert len(manim_caplog.record_tuples) == 1 msg = _get_caplog_record_msg(manim_caplog) assert ( msg == "The parameters a and b of method Top.foo have been deprecated and may be removed in a later version. Use something else." ) def test_deprecate_func_single_param_since_and_until(manim_caplog): """Test the deprecation of a single method parameter (decorator with since and until arguments).""" t = Top() t.bar(a=1, b=2) assert len(manim_caplog.record_tuples) == 1 msg = _get_caplog_record_msg(manim_caplog) assert ( msg == "The parameter a of method Top.bar has been deprecated since v0.2 and is expected to be removed after v0.4." ) def test_deprecate_func_param_redirect_tuple(manim_caplog): """Test the deprecation of a method parameter and redirecting it to a new one using tuple.""" t = Top() obj = t.baz(x=1, old_param=2) assert len(manim_caplog.record_tuples) == 1 msg = _get_caplog_record_msg(manim_caplog) assert ( msg == "The parameter old_param of method Top.baz has been deprecated and may be removed in a later version." ) assert obj == {"x": 1, "new_param": 2} def test_deprecate_func_param_redirect_lambda(manim_caplog): """Test the deprecation of a method parameter and redirecting it to a new one using lambda function.""" t = Top() obj = t.qux(runtime_in_ms=500) assert len(manim_caplog.record_tuples) == 1 msg = _get_caplog_record_msg(manim_caplog) assert ( msg == "The parameter runtime_in_ms of method Top.qux has been deprecated and may be removed in a later version." ) assert obj == {"run_time": 0.5} def test_deprecate_func_param_redirect_many_to_one(manim_caplog): """Test the deprecation of multiple method parameters and redirecting them to one.""" t = Top() obj = t.quux(point2D_x=3, point2D_y=5) assert len(manim_caplog.record_tuples) == 1 msg = _get_caplog_record_msg(manim_caplog) assert ( msg == "The parameters point2D_x and point2D_y of method Top.quux have been deprecated and may be removed in a later version." ) assert obj == {"point2D": (3, 5)} def test_deprecate_func_param_redirect_one_to_many(manim_caplog): """Test the deprecation of one method parameter and redirecting it to many.""" t = Top() obj1 = t.quuz(point2D=0) assert len(manim_caplog.record_tuples) == 1 msg
parameters point2D_x and point2D_y of method Top.quux have been deprecated and may be removed in a later version." ) assert obj == {"point2D": (3, 5)} def test_deprecate_func_param_redirect_one_to_many(manim_caplog): """Test the deprecation of one method parameter and redirecting it to many.""" t = Top() obj1 = t.quuz(point2D=0) assert len(manim_caplog.record_tuples) == 1 msg = _get_caplog_record_msg(manim_caplog) assert ( msg == "The parameter point2D of method Top.quuz has been deprecated and may be removed in a later version." ) assert obj1 == {"x": 0, "y": 0} manim_caplog.clear() obj2 = t.quuz(point2D=(2, 3)) assert len(manim_caplog.record_tuples) == 1 msg = _get_caplog_record_msg(manim_caplog) assert ( msg == "The parameter point2D of method Top.quuz has been deprecated and may be removed in a later version." ) assert obj2 == {"x": 2, "y": 3} ================================================ FILE: tests/module/utils/test_file_ops.py ================================================ from __future__ import annotations from pathlib import Path from manim import * from tests.assert_utils import assert_dir_exists, assert_file_not_exists from tests.utils.video_tester import * def test_guarantee_existence(tmp_path: Path): test_dir = tmp_path / "test" guarantee_existence(test_dir) # test if file dir got created assert_dir_exists(test_dir) with (test_dir / "test.txt").open("x") as f: pass # test if file didn't get deleted guarantee_existence(test_dir) def test_guarantee_empty_existence(tmp_path: Path): test_dir = tmp_path / "test" test_dir.mkdir() with (test_dir / "test.txt").open("x"): pass guarantee_empty_existence(test_dir) # test if dir got created assert_dir_exists(test_dir) # test if dir got cleaned assert_file_not_exists(test_dir / "test.txt") ================================================ FILE: tests/module/utils/test_hashing.py ================================================ from __future__ import annotations import json from zlib import crc32 import pytest import manim.utils.hashing as hashing from manim import Square ALREADY_PROCESSED_PLACEHOLDER = hashing._Memoizer.ALREADY_PROCESSED_PLACEHOLDER @pytest.fixture(autouse=True) def reset_already_processed(): hashing._Memoizer.reset_already_processed() def test_JSON_basic(): o = {"test": 1, 2: 4, 3: 2.0} o_serialized = hashing.get_json(o) assert isinstance(o_serialized, str) assert o_serialized == str({"test": 1, "2": 4, "3": 2.0}).replace("'", '"') def test_JSON_with_object(): class Obj: def __init__(self, a): self.a = a self.b = 3.0 self.c = [1, 2, "test", ["nested list"]] self.d = {2: 3, "2": "salut"} o = Obj(2) o_serialized = hashing.get_json(o) assert ( str(o_serialized) == '{"a": 2, "b": 3.0, "c": [1, 2, "test", ["nested list"]], "d": {"2": 3, "2": "salut"}}' ) def test_JSON_with_function(): def test(uhu): uhu += 2 return uhu o_serialized = hashing.get_json(test) dict_o = json.loads(o_serialized) assert "code" in dict_o assert "nonlocals" in dict_o assert ( str(o_serialized) == r'{"code": " def test(uhu):\n uhu += 2\n return uhu\n", "nonlocals": {}}' ) def test_JSON_with_function_and_external_val(): external = 2 def test(uhu): uhu += external return uhu o_ser = hashing.get_json(test) external = 3 o_ser2 = hashing.get_json(test) assert json.loads(o_ser2)["nonlocals"] == {"external": 3} assert o_ser != o_ser2 def test_JSON_with_method(): class A: def __init__(self): self.a = self.method self.b = 3 def method(self, b): b += 3 return b o_ser = hashing.get_json(A()) dict_o = json.loads(o_ser) assert dict_o["a"]["nonlocals"] == {} def test_JSON_with_wrong_keys(): def test(): return 3 class Test: def __init__(self): self.a = 2 a = {(1, 2): 3} b = {Test(): 3} c = {test: 3} for el in [a, b, c]: o_ser = hashing.get_json(el) dict_o = json.loads(o_ser) # check if this is an int (it meant that the lkey has been hashed) assert int(list(dict_o.keys())[0]) def test_JSON_with_circular_references(): B = {1: 2} class A: def __init__(self): self.b = B B["circular_ref"] = A() o_ser = hashing.get_json(B) dict_o = json.loads(o_ser) assert dict_o["circular_ref"]["b"] == ALREADY_PROCESSED_PLACEHOLDER def
o_ser = hashing.get_json(el) dict_o = json.loads(o_ser) # check if this is an int (it meant that the lkey has been hashed) assert int(list(dict_o.keys())[0]) def test_JSON_with_circular_references(): B = {1: 2} class A: def __init__(self): self.b = B B["circular_ref"] = A() o_ser = hashing.get_json(B) dict_o = json.loads(o_ser) assert dict_o["circular_ref"]["b"] == ALREADY_PROCESSED_PLACEHOLDER def test_JSON_with_big_np_array(): import numpy as np a = np.zeros((1000, 1000)) o_ser = hashing.get_json(a) assert "TRUNCATED ARRAY" in o_ser def test_JSON_with_tuple(): o = [(1, [1])] o_ser = hashing.get_json(o) assert o_ser == "[[1, [1]]]" def test_JSON_with_object_that_is_itself_circular_reference(): class T: def __init__(self) -> None: self.a = None o = T() o.a = o hashing.get_json(o) def test_hash_consistency(): def assert_two_objects_produce_same_hash(obj1, obj2, debug=False): """ When debug is True, if the hashes differ an assertion comparing (element-wise) the two objects will be raised, and pytest will display a nice difference summary making it easier to debug. """ json1 = hashing.get_json(obj1) hashing._Memoizer.reset_already_processed() json2 = hashing.get_json(obj2) hashing._Memoizer.reset_already_processed() hash1 = crc32(repr(json1).encode()) hash2 = crc32(repr(json2).encode()) if hash1 != hash2 and debug: dict1 = json.loads(json1) dict2 = json.loads(json2) assert dict1 == dict2 assert hash1 == hash2, f"{obj1} and {obj2} have different hashes." assert_two_objects_produce_same_hash(Square(), Square()) s = Square() assert_two_objects_produce_same_hash(s, s.copy()) ================================================ FILE: tests/module/utils/test_manim_color.py ================================================ from __future__ import annotations import colorsys import numpy as np import numpy.testing as nt from manim.utils.color import ( BLACK, HSV, RED, WHITE, YELLOW, ManimColor, ManimColorDType, ) from manim.utils.color.XKCD import GREEN def test_init_with_int() -> None: color = ManimColor(0x123456, 0.5) nt.assert_array_equal( color._internal_value, np.array([0x12, 0x34, 0x56, 0.5 * 255], dtype=ManimColorDType) / 255, ) color = BLACK nt.assert_array_equal( color._internal_value, np.array([0, 0, 0, 1.0], dtype=ManimColorDType) ) color = WHITE nt.assert_array_equal( color._internal_value, np.array([1.0, 1.0, 1.0, 1.0], dtype=ManimColorDType) ) def test_init_with_hex() -> None: color = ManimColor("0xFF0000") nt.assert_array_equal(color._internal_value, np.array([1, 0, 0, 1])) color = ManimColor("0xFF000000") nt.assert_array_equal(color._internal_value, np.array([1, 0, 0, 0])) color = ManimColor("#FF0000") nt.assert_array_equal(color._internal_value, np.array([1, 0, 0, 1])) color = ManimColor("#FF000000") nt.assert_array_equal(color._internal_value, np.array([1, 0, 0, 0])) def test_init_with_hex_short() -> None: color = ManimColor("#F00") nt.assert_array_equal(color._internal_value, np.array([1, 0, 0, 1])) color = ManimColor("0xF00") nt.assert_array_equal(color._internal_value, np.array([1, 0, 0, 1])) color = ManimColor("#F000") nt.assert_array_equal(color._internal_value, np.array([1, 0, 0, 0])) color = ManimColor("0xF000") nt.assert_array_equal(color._internal_value, np.array([1, 0, 0, 0])) def test_init_with_string() -> None: color = ManimColor("BLACK") nt.assert_array_equal(color._internal_value, BLACK._internal_value) def test_init_with_tuple_int() -> None: color = ManimColor((50, 10, 50)) nt.assert_array_equal( color._internal_value, np.array([50 / 255, 10 / 255, 50 / 255, 1.0]) ) color = ManimColor((50, 10, 50, 50)) nt.assert_array_equal( color._internal_value, np.array([50 / 255, 10 / 255, 50 / 255, 50 / 255]) ) def test_init_with_tuple_float() -> None: color = ManimColor((0.5, 0.6, 0.7)) nt.assert_array_equal(color._internal_value, np.array([0.5, 0.6, 0.7, 1.0])) color = ManimColor((0.5, 0.6, 0.7, 0.1)) nt.assert_array_equal(color._internal_value, np.array([0.5, 0.6, 0.7, 0.1])) def test_to_integer() -> None: color = ManimColor((0x1, 0x2, 0x3, 0x4)) nt.assert_equal(color.to_integer(), 0x010203) def test_to_rgb() -> None: color = ManimColor((0x1, 0x2, 0x3, 0x4)) nt.assert_array_equal(color.to_rgb(), (0x1 / 255, 0x2 / 255, 0x3 / 255)) nt.assert_array_equal(color.to_int_rgb(), (0x1, 0x2, 0x3)) nt.assert_array_equal(color.to_rgba(), (0x1 / 255, 0x2 / 255, 0x3 / 255, 0x4 / 255)) nt.assert_array_equal(color.to_int_rgba(), (0x1, 0x2, 0x3, 0x4)) nt.assert_array_equal( color.to_rgba_with_alpha(0.5), (0x1 / 255, 0x2 / 255, 0x3 / 255, 0.5) ) nt.assert_array_equal( color.to_int_rgba_with_alpha(0.5), (0x1, 0x2, 0x3, int(0.5 * 255)) ) def test_to_hex() -> None: color = ManimColor((0x1, 0x2, 0x3, 0x4)) nt.assert_equal(color.to_hex(), "#010203") nt.assert_equal(color.to_hex(True), "#01020304")
0x2 / 255, 0x3 / 255, 0x4 / 255)) nt.assert_array_equal(color.to_int_rgba(), (0x1, 0x2, 0x3, 0x4)) nt.assert_array_equal( color.to_rgba_with_alpha(0.5), (0x1 / 255, 0x2 / 255, 0x3 / 255, 0.5) ) nt.assert_array_equal( color.to_int_rgba_with_alpha(0.5), (0x1, 0x2, 0x3, int(0.5 * 255)) ) def test_to_hex() -> None: color = ManimColor((0x1, 0x2, 0x3, 0x4)) nt.assert_equal(color.to_hex(), "#010203") nt.assert_equal(color.to_hex(True), "#01020304") def test_to_hsv() -> None: color = ManimColor((0x1, 0x2, 0x3, 0x4)) nt.assert_array_equal( color.to_hsv(), colorsys.rgb_to_hsv(0x1 / 255, 0x2 / 255, 0x3 / 255) ) def test_to_hsl() -> None: color = ManimColor((0x1, 0x2, 0x3, 0x4)) hls = colorsys.rgb_to_hls(0x1 / 255, 0x2 / 255, 0x3 / 255) nt.assert_array_equal(color.to_hsl(), np.array([hls[0], hls[2], hls[1]])) def test_from_hsl() -> None: hls = colorsys.rgb_to_hls(0x1 / 255, 0x2 / 255, 0x3 / 255) hsl = np.array([hls[0], hls[2], hls[1]]) color = ManimColor.from_hsl(hsl) rgb = np.array([0x1 / 255, 0x2 / 255, 0x3 / 255]) nt.assert_allclose(color.to_rgb(), rgb) def test_invert() -> None: color = ManimColor((0x1, 0x2, 0x3, 0x4)) rgba = color._internal_value inverted = color.invert() nt.assert_array_equal( inverted._internal_value, (1 - rgba[0], 1 - rgba[1], 1 - rgba[2], rgba[3]) ) def test_invert_with_alpha() -> None: color = ManimColor((0x1, 0x2, 0x3, 0x4)) rgba = color._internal_value inverted = color.invert(True) nt.assert_array_equal( inverted._internal_value, (1 - rgba[0], 1 - rgba[1], 1 - rgba[2], 1 - rgba[3]) ) def test_interpolate() -> None: r1 = RED._internal_value r2 = YELLOW._internal_value nt.assert_array_equal( RED.interpolate(YELLOW, 0.5)._internal_value, 0.5 * r1 + 0.5 * r2 ) def test_opacity() -> None: nt.assert_equal(RED.opacity(0.5)._internal_value[3], 0.5) def test_parse() -> None: nt.assert_equal(ManimColor.parse([RED, YELLOW]), [RED, YELLOW]) def test_mc_operators() -> None: c1 = RED c2 = GREEN halfway1 = 0.5 * c1 + 0.5 * c2 halfway2 = c1.interpolate(c2, 0.5) nt.assert_equal(halfway1, halfway2) nt.assert_array_equal((WHITE / 2.0)._internal_value, np.array([0.5, 0.5, 0.5, 0.5])) def test_mc_from_functions() -> None: color = ManimColor.from_hex("#ff00a0") nt.assert_equal(color.to_hex(), "#FF00A0") color = ManimColor.from_rgb((1.0, 1.0, 0.0)) nt.assert_equal(color.to_hex(), "#FFFF00") color = ManimColor.from_rgba((1.0, 1.0, 0.0, 1.0)) nt.assert_equal(color.to_hex(True), "#FFFF00FF") color = ManimColor.from_hsv((1.0, 1.0, 1.0), alpha=0.0) nt.assert_equal(color.to_hex(True), "#FF000000") def test_hsv_init() -> None: color = HSV((0.25, 1, 1)) nt.assert_array_equal(color._internal_value, np.array([0.5, 1.0, 0.0, 1.0])) def test_into_HSV() -> None: nt.assert_equal(RED.into(HSV).into(ManimColor), RED) def test_contrasting() -> None: nt.assert_equal(BLACK.contrasting(), WHITE) nt.assert_equal(WHITE.contrasting(), BLACK) nt.assert_equal(RED.contrasting(0.1), BLACK) nt.assert_equal(RED.contrasting(0.9), WHITE) nt.assert_equal(BLACK.contrasting(dark=GREEN, light=RED), RED) nt.assert_equal(WHITE.contrasting(dark=GREEN, light=RED), GREEN) def test_lighter() -> None: c = RED.opacity(0.42) cl = c.lighter(0.2) nt.assert_array_equal( cl._internal_value[:3], 0.8 * c._internal_value[:3] + 0.2 * WHITE._internal_value[:3], ) nt.assert_equal(cl[-1], c[-1]) def test_darker() -> None: c = RED.opacity(0.42) cd = c.darker(0.2) nt.assert_array_equal( cd._internal_value[:3], 0.8 * c._internal_value[:3] + 0.2 * BLACK._internal_value[:3], ) nt.assert_equal(cd[-1], c[-1]) ================================================ FILE: tests/module/utils/test_space_ops.py ================================================ from __future__ import annotations import numpy as np import pytest from manim.utils.space_ops import * from manim.utils.space_ops import shoelace def test_rotate_vector(): vec = np.array([0, 1, 0]) rotated = rotate_vector(vec, np.pi / 2) assert np.round(rotated[0], 5) == -1.0 assert not np.round(rotated[1:], 5).any() np.testing.assert_array_equal(rotate_vector(np.zeros(3), np.pi / 4), np.zeros(3)) def test_rotation_matrices(): ang = np.pi / 6 ax = np.array([1, 1, 1]) np.testing.assert_array_equal( np.round(rotation_matrix(ang, ax, True), 5), np.round( np.array( [ [0.91068, -0.24402, 0.33333, 0.0], [0.33333, 0.91068, -0.24402, 0.0], [-0.24402, 0.33333, 0.91068, 0.0], [0.0, 0.0, 0.0, 1.0], ] ), 5, ), ) np.testing.assert_array_equal( np.round(rotation_about_z(np.pi / 3), 5), np.array( [ [0.5, -0.86603, 0.0], [0.86603, 0.5, 0.0], [0.0, 0.0, 1.0], ] ), ) np.testing.assert_array_equal( np.round(z_to_vector(np.array([1, 2, 3])), 5), np.array( [ [0.96362, 0.0, 0.26726], [-0.14825, 0.83205, 0.53452], [-0.22237, -0.5547, 0.80178], ]
0.0], [-0.24402, 0.33333, 0.91068, 0.0], [0.0, 0.0, 0.0, 1.0], ] ), 5, ), ) np.testing.assert_array_equal( np.round(rotation_about_z(np.pi / 3), 5), np.array( [ [0.5, -0.86603, 0.0], [0.86603, 0.5, 0.0], [0.0, 0.0, 1.0], ] ), ) np.testing.assert_array_equal( np.round(z_to_vector(np.array([1, 2, 3])), 5), np.array( [ [0.96362, 0.0, 0.26726], [-0.14825, 0.83205, 0.53452], [-0.22237, -0.5547, 0.80178], ] ), ) def test_angle_of_vector(): assert angle_of_vector(np.array([1, 1, 1])) == np.pi / 4 assert ( np.round(angle_between_vectors(np.array([1, 1, 1]), np.array([-1, 1, 1])), 5) == 1.23096 ) np.testing.assert_equal(angle_of_vector(np.zeros(3)), 0.0) def test_angle_of_vector_vectorized(): vec = np.random.randn(4, 10) ref = [np.angle(complex(*v[:2])) for v in vec.T] np.testing.assert_array_equal(ref, angle_of_vector(vec)) def test_center_of_mass(): np.testing.assert_array_equal( center_of_mass([[0, 0, 0], [1, 2, 3]]), np.array([0.5, 1.0, 1.5]) ) def test_line_intersection(): np.testing.assert_array_equal( line_intersection( [[0, 0, 0], [3, 3, 0]], [[0, 3, 0], [3, 0, 0]], ), np.array([1.5, 1.5, 0.0]), ) with pytest.raises(ValueError): line_intersection( # parallel lines [[0, 1, 0], [5, 1, 0]], [[0, 6, 0], [5, 6, 0]], ) with pytest.raises(ValueError): line_intersection( # lines not in xy-plane [[0, 0, 3], [3, 3, 3]], [[0, 3, 3], [3, 0, 3]], ) with pytest.raises(ValueError): line_intersection( # lines are equal [[2, 2, 0], [3, 1, 0]], [[2, 2, 0], [3, 1, 0]], ) np.testing.assert_array_equal( line_intersection( # lines with ends out of bounds [[0, 0, 0], [1, 1, 0]], [[0, 4, 0], [1, 3, 0]], ), np.array([2, 2, 0]), ) def test_shoelace(): assert shoelace(np.array([[1, 2], [3, 4]])) == 6 def test_polar_coords(): a = np.array([1, 1, 0]) b = (2, np.pi / 2, np.pi / 2) np.testing.assert_array_equal( np.round(cartesian_to_spherical(a), 4), np.round([2**0.5, np.pi / 4, np.pi / 2], 4), ) np.testing.assert_array_equal( np.round(spherical_to_cartesian(b), 4), np.array([0, 2, 0]) ) ================================================ FILE: tests/module/utils/test_tex.py ================================================ import pytest from manim.utils.tex import TexTemplate, _texcode_for_environment DEFAULT_BODY = r"""\documentclass[preview]{standalone} \usepackage[english]{babel} \usepackage{amsmath} \usepackage{amssymb} \begin{document} YourTextHere \end{document}""" BODY_WITH_ADDED_PREAMBLE = r"""\documentclass[preview]{standalone} \usepackage[english]{babel} \usepackage{amsmath} \usepackage{amssymb} \usepackage{testpackage} \begin{document} YourTextHere \end{document}""" BODY_WITH_PREPENDED_PREAMBLE = r"""\documentclass[preview]{standalone} \usepackage{testpackage} \usepackage[english]{babel} \usepackage{amsmath} \usepackage{amssymb} \begin{document} YourTextHere \end{document}""" BODY_WITH_ADDED_DOCUMENT = r"""\documentclass[preview]{standalone} \usepackage[english]{babel} \usepackage{amsmath} \usepackage{amssymb} \begin{document} \boldmath YourTextHere \end{document}""" BODY_REPLACE = r"""\documentclass[preview]{standalone} \usepackage[english]{babel} \usepackage{amsmath} \usepackage{amssymb} \begin{document} \sqrt{2} \end{document}""" BODY_REPLACE_IN_ENV = r"""\documentclass[preview]{standalone} \usepackage[english]{babel} \usepackage{amsmath} \usepackage{amssymb} \begin{document} \begin{align} \sqrt{2} \end{align} \end{document}""" def test_tex_template_default_body(): template = TexTemplate() assert template.body == DEFAULT_BODY def test_tex_template_preamble(): template = TexTemplate() template.add_to_preamble(r"\usepackage{testpackage}") assert template.body == BODY_WITH_ADDED_PREAMBLE def test_tex_template_preprend_preamble(): template = TexTemplate() template.add_to_preamble(r"\usepackage{testpackage}", prepend=True) assert template.body == BODY_WITH_PREPENDED_PREAMBLE def test_tex_template_document(): template = TexTemplate() template.add_to_document(r"\boldmath") assert template.body == BODY_WITH_ADDED_DOCUMENT def test_tex_template_texcode_for_expression(): template = TexTemplate() assert template.get_texcode_for_expression(r"\sqrt{2}") == BODY_REPLACE def test_tex_template_texcode_for_expression_in_env(): template = TexTemplate() assert ( template.get_texcode_for_expression_in_env(r"\sqrt{2}", environment="align") == BODY_REPLACE_IN_ENV ) def test_tex_template_fixed_body(): template = TexTemplate() # Usually set when calling `from_file` template.body = "dummy" assert template.body == "dummy" with pytest.warns( UserWarning, match="This TeX template was created with a fixed body, trying to add text the preamble will have no effect.", ): template.add_to_preamble("dummys") with pytest.warns( UserWarning, match="This TeX template was created with a fixed body, trying to add text the document will have no effect.", ): template.add_to_document("dummy") def test_texcode_for_environment(): """Test that the environment is correctly extracted from the input""" # environment without arguments assert _texcode_for_environment("align*") == (r"\begin{align*}", r"\end{align*}") assert _texcode_for_environment("{align*}") == (r"\begin{align*}", r"\end{align*}") assert _texcode_for_environment(r"\begin{align*}") == ( r"\begin{align*}", r"\end{align*}", ) # environment with arguments assert _texcode_for_environment("{tabular}[t]{cccl}") == ( r"\begin{tabular}[t]{cccl}", r"\end{tabular}", ) assert _texcode_for_environment("tabular}{cccl") == (
): template.add_to_document("dummy") def test_texcode_for_environment(): """Test that the environment is correctly extracted from the input""" # environment without arguments assert _texcode_for_environment("align*") == (r"\begin{align*}", r"\end{align*}") assert _texcode_for_environment("{align*}") == (r"\begin{align*}", r"\end{align*}") assert _texcode_for_environment(r"\begin{align*}") == ( r"\begin{align*}", r"\end{align*}", ) # environment with arguments assert _texcode_for_environment("{tabular}[t]{cccl}") == ( r"\begin{tabular}[t]{cccl}", r"\end{tabular}", ) assert _texcode_for_environment("tabular}{cccl") == ( r"\begin{tabular}{cccl}", r"\end{tabular}", ) assert _texcode_for_environment(r"\begin{tabular}[t]{cccl}") == ( r"\begin{tabular}[t]{cccl}", r"\end{tabular}", ) ================================================ FILE: tests/module/utils/test_units.py ================================================ from __future__ import annotations import numpy as np import pytest from manim import PI, X_AXIS, Y_AXIS, Z_AXIS from manim.utils.unit import Degrees, Munits, Percent, Pixels def test_units(config): # make sure we are using the right frame geometry config.pixel_width = 1920 np.testing.assert_allclose(config.frame_height, 8.0) # Munits should be equivalent to the internal logical units np.testing.assert_allclose(8.0 * Munits, config.frame_height) # Pixels should convert from pixels to Munits np.testing.assert_allclose(1920 * Pixels, config.frame_width) # Percent should give the fractional length of the frame np.testing.assert_allclose(50 * Percent(X_AXIS), config.frame_width / 2) np.testing.assert_allclose(50 * Percent(Y_AXIS), config.frame_height / 2) # The length of the Z axis is not defined with pytest.raises(NotImplementedError): Percent(Z_AXIS) # Degrees should convert from degrees to radians np.testing.assert_allclose(180 * Degrees, PI) ================================================ FILE: tests/opengl/__init__.py ================================================ [Empty file] ================================================ FILE: tests/opengl/test_animate_opengl.py ================================================ from __future__ import annotations import numpy as np import pytest from manim.animation.creation import Uncreate from manim.mobject.geometry.arc import Dot from manim.mobject.geometry.line import Line from manim.mobject.geometry.polygram import Square from manim.mobject.mobject import override_animate from manim.mobject.types.vectorized_mobject import VGroup def test_simple_animate(using_opengl_renderer): s = Square() scale_factor = 2 anim = s.animate.scale(scale_factor).build() assert anim.mobject.target.width == scale_factor * s.width def test_chained_animate(using_opengl_renderer): s = Square() scale_factor = 2 direction = np.array((1, 1, 0)) anim = s.animate.scale(scale_factor).shift(direction).build() assert anim.mobject.target.width == scale_factor * s.width assert (anim.mobject.target.get_center() == direction).all() def test_overridden_animate(using_opengl_renderer): class DotsWithLine(VGroup): def __init__(self): super().__init__() self.left_dot = Dot().shift((-1, 0, 0)) self.right_dot = Dot().shift((1, 0, 0)) self.line = Line(self.left_dot, self.right_dot) self.add(self.left_dot, self.right_dot, self.line) def remove_line(self): self.remove(self.line) @override_animate(remove_line) def _remove_line_animation(self, anim_args=None): if anim_args is None: anim_args = {} self.remove_line() return Uncreate(self.line, **anim_args) dots_with_line = DotsWithLine() anim = dots_with_line.animate.remove_line().build() assert len(dots_with_line.submobjects) == 2 assert type(anim) is Uncreate def test_chaining_overridden_animate(using_opengl_renderer): class DotsWithLine(VGroup): def __init__(self): super().__init__() self.left_dot = Dot().shift((-1, 0, 0)) self.right_dot = Dot().shift((1, 0, 0)) self.line = Line(self.left_dot, self.right_dot) self.add(self.left_dot, self.right_dot, self.line) def remove_line(self): self.remove(self.line) @override_animate(remove_line) def _remove_line_animation(self, anim_args=None): if anim_args is None: anim_args = {} self.remove_line() return Uncreate(self.line, **anim_args) with pytest.raises( NotImplementedError, match="not supported for overridden animations", ): DotsWithLine().animate.shift((1, 0, 0)).remove_line() with pytest.raises( NotImplementedError, match="not supported for overridden animations", ): DotsWithLine().animate.remove_line().shift((1, 0, 0)) def test_animate_with_args(using_opengl_renderer): s = Square() scale_factor = 2 run_time = 2 anim = s.animate(run_time=run_time).scale(scale_factor).build() assert anim.mobject.target.width == scale_factor * s.width assert anim.run_time == run_time def test_chained_animate_with_args(using_opengl_renderer): s = Square() scale_factor = 2 direction = np.array((1, 1, 0)) run_time = 2 anim = s.animate(run_time=run_time).scale(scale_factor).shift(direction).build() assert anim.mobject.target.width == scale_factor * s.width assert (anim.mobject.target.get_center() == direction).all() assert anim.run_time == run_time def test_animate_with_args_misplaced(using_opengl_renderer): s = Square() scale_factor = 2 run_time = 2 with pytest.raises(ValueError, match="must be passed before"): s.animate.scale(scale_factor)(run_time=run_time) with pytest.raises(ValueError, match="must be passed before"): s.animate(run_time=run_time)(run_time=run_time).scale(scale_factor) ================================================ FILE: tests/opengl/test_axes_shift_opengl.py ================================================ from __future__ import annotations import numpy as np from manim.mobject.graphing.coordinate_systems import Axes def test_axes_origin_shift(using_opengl_renderer): ax = Axes(x_range=(5, 10, 1), y_range=(40, 45, 0.5)) np.testing.assert_allclose( ax.coords_to_point(5.0, 40.0), ax.x_axis.number_to_point(5) )
= 2 run_time = 2 with pytest.raises(ValueError, match="must be passed before"): s.animate.scale(scale_factor)(run_time=run_time) with pytest.raises(ValueError, match="must be passed before"): s.animate(run_time=run_time)(run_time=run_time).scale(scale_factor) ================================================ FILE: tests/opengl/test_axes_shift_opengl.py ================================================ from __future__ import annotations import numpy as np from manim.mobject.graphing.coordinate_systems import Axes def test_axes_origin_shift(using_opengl_renderer): ax = Axes(x_range=(5, 10, 1), y_range=(40, 45, 0.5)) np.testing.assert_allclose( ax.coords_to_point(5.0, 40.0), ax.x_axis.number_to_point(5) ) np.testing.assert_allclose( ax.coords_to_point(5.0, 40.0), ax.y_axis.number_to_point(40) ) ================================================ FILE: tests/opengl/test_color_opengl.py ================================================ from __future__ import annotations import numpy as np from manim import BLACK, BLUE, GREEN, PURE_BLUE, PURE_GREEN, PURE_RED, Scene from manim.mobject.opengl.opengl_mobject import OpenGLMobject from manim.mobject.opengl.opengl_vectorized_mobject import OpenGLVMobject def test_import_color(using_opengl_renderer): import manim.utils.color as C C.WHITE def test_background_color(using_opengl_renderer): S = Scene() S.renderer.background_color = "#FF0000" S.renderer.update_frame(S) np.testing.assert_array_equal( S.renderer.get_frame()[0, 0], np.array([255, 0, 0, 255]) ) S.renderer.background_color = "#436F80" S.renderer.update_frame(S) np.testing.assert_array_equal( S.renderer.get_frame()[0, 0], np.array([67, 111, 128, 255]) ) S.renderer.background_color = "#FFFFFF" S.renderer.update_frame(S) np.testing.assert_array_equal( S.renderer.get_frame()[0, 0], np.array([255, 255, 255, 255]) ) def test_set_color(using_opengl_renderer): m = OpenGLMobject() assert m.color.to_hex() == "#FFFFFF" np.all(m.rgbas == np.array([[0.0, 0.0, 0.0, 1.0]])) m.set_color(BLACK) assert m.color.to_hex() == "#000000" np.all(m.rgbas == np.array([[1.0, 1.0, 1.0, 1.0]])) m.set_color(PURE_GREEN, opacity=0.5) assert m.color.to_hex() == "#00FF00" np.all(m.rgbas == np.array([[0.0, 1.0, 0.0, 0.5]])) m = OpenGLVMobject() assert m.color.to_hex() == "#FFFFFF" np.all(m.fill_rgba == np.array([[0.0, 0.0, 0.0, 1.0]])) np.all(m.stroke_rgba == np.array([[0.0, 0.0, 0.0, 1.0]])) m.set_color(BLACK) assert m.color.to_hex() == "#000000" np.all(m.fill_rgba == np.array([[1.0, 1.0, 1.0, 1.0]])) np.all(m.stroke_rgba == np.array([[1.0, 1.0, 1.0, 1.0]])) m.set_color(PURE_GREEN, opacity=0.5) assert m.color.to_hex() == "#00FF00" np.all(m.fill_rgba == np.array([[0.0, 1.0, 0.0, 0.5]])) np.all(m.stroke_rgba == np.array([[0.0, 1.0, 0.0, 0.5]])) def test_set_fill_color(using_opengl_renderer): m = OpenGLVMobject() assert m.fill_color.to_hex() == "#FFFFFF" np.all(m.fill_rgba == np.array([[0.0, 1.0, 0.0, 0.5]])) m.set_fill(BLACK) assert m.fill_color.to_hex() == "#000000" np.all(m.fill_rgba == np.array([[1.0, 1.0, 1.0, 1.0]])) m.set_fill(PURE_GREEN, opacity=0.5) assert m.fill_color.to_hex() == "#00FF00" np.all(m.fill_rgba == np.array([[0.0, 1.0, 0.0, 0.5]])) def test_set_stroke_color(using_opengl_renderer): m = OpenGLVMobject() assert m.stroke_color.to_hex() == "#FFFFFF" np.all(m.stroke_rgba == np.array([[0.0, 1.0, 0.0, 0.5]])) m.set_stroke(BLACK) assert m.stroke_color.to_hex() == "#000000" np.all(m.stroke_rgba == np.array([[1.0, 1.0, 1.0, 1.0]])) m.set_stroke(PURE_GREEN, opacity=0.5) assert m.stroke_color.to_hex() == "#00FF00" np.all(m.stroke_rgba == np.array([[0.0, 1.0, 0.0, 0.5]])) def test_set_fill(using_opengl_renderer): m = OpenGLMobject() assert m.color.to_hex() == "#FFFFFF" m.set_color(BLACK) assert m.color.to_hex() == "#000000" m = OpenGLVMobject() assert m.color.to_hex() == "#FFFFFF" m.set_color(BLACK) assert m.color.to_hex() == "#000000" def test_set_color_handles_lists_of_strs(using_opengl_renderer): m = OpenGLVMobject() assert m.color.to_hex() == "#FFFFFF" m.set_color([BLACK, BLUE, GREEN]) assert m.get_colors()[0] == BLACK assert m.get_colors()[1] == BLUE assert m.get_colors()[2] == GREEN assert m.get_fill_colors()[0] == BLACK assert m.get_fill_colors()[1] == BLUE assert m.get_fill_colors()[2] == GREEN assert m.get_stroke_colors()[0] == BLACK assert m.get_stroke_colors()[1] == BLUE assert m.get_stroke_colors()[2] == GREEN def test_set_color_handles_lists_of_color_objects(using_opengl_renderer): m = OpenGLVMobject() assert m.color.to_hex() == "#FFFFFF" m.set_color([PURE_BLUE, PURE_GREEN, PURE_RED]) assert m.get_colors()[0].to_hex() == "#0000FF" assert m.get_colors()[1].to_hex() == "#00FF00" assert m.get_colors()[2].to_hex() == "#FF0000" assert m.get_fill_colors()[0].to_hex() == "#0000FF" assert m.get_fill_colors()[1].to_hex() == "#00FF00" assert m.get_fill_colors()[2].to_hex() == "#FF0000" assert m.get_stroke_colors()[0].to_hex() == "#0000FF" assert m.get_stroke_colors()[1].to_hex() == "#00FF00" assert m.get_stroke_colors()[2].to_hex() == "#FF0000" def test_set_fill_handles_lists_of_strs(using_opengl_renderer): m = OpenGLVMobject() assert m.fill_color.to_hex() == "#FFFFFF" m.set_fill([BLACK.to_hex(), BLUE.to_hex(), GREEN.to_hex()]) assert m.get_fill_colors()[0].to_hex() == BLACK.to_hex() assert m.get_fill_colors()[1].to_hex() == BLUE.to_hex() assert m.get_fill_colors()[2].to_hex() == GREEN.to_hex() def test_set_fill_handles_lists_of_color_objects(using_opengl_renderer): m = OpenGLVMobject() assert m.fill_color.to_hex() == "#FFFFFF" m.set_fill([PURE_BLUE, PURE_GREEN, PURE_RED]) assert m.get_fill_colors()[0].to_hex() == "#0000FF" assert m.get_fill_colors()[1].to_hex() == "#00FF00" assert m.get_fill_colors()[2].to_hex() == "#FF0000" def test_set_stroke_handles_lists_of_strs(using_opengl_renderer): m = OpenGLVMobject() assert m.stroke_color.to_hex() == "#FFFFFF" m.set_stroke([BLACK.to_hex(), BLUE.to_hex(), GREEN.to_hex()]) assert m.get_stroke_colors()[0].to_hex() == BLACK.to_hex() assert m.get_stroke_colors()[1].to_hex() == BLUE.to_hex() assert m.get_stroke_colors()[2].to_hex() == GREEN.to_hex() def test_set_stroke_handles_lists_of_color_objects(using_opengl_renderer): m = OpenGLVMobject()
= OpenGLVMobject() assert m.fill_color.to_hex() == "#FFFFFF" m.set_fill([PURE_BLUE, PURE_GREEN, PURE_RED]) assert m.get_fill_colors()[0].to_hex() == "#0000FF" assert m.get_fill_colors()[1].to_hex() == "#00FF00" assert m.get_fill_colors()[2].to_hex() == "#FF0000" def test_set_stroke_handles_lists_of_strs(using_opengl_renderer): m = OpenGLVMobject() assert m.stroke_color.to_hex() == "#FFFFFF" m.set_stroke([BLACK.to_hex(), BLUE.to_hex(), GREEN.to_hex()]) assert m.get_stroke_colors()[0].to_hex() == BLACK.to_hex() assert m.get_stroke_colors()[1].to_hex() == BLUE.to_hex() assert m.get_stroke_colors()[2].to_hex() == GREEN.to_hex() def test_set_stroke_handles_lists_of_color_objects(using_opengl_renderer): m = OpenGLVMobject() assert m.stroke_color.to_hex() == "#FFFFFF" m.set_stroke([PURE_BLUE, PURE_GREEN, PURE_RED]) assert m.get_stroke_colors()[0].to_hex() == "#0000FF" assert m.get_stroke_colors()[1].to_hex() == "#00FF00" assert m.get_stroke_colors()[2].to_hex() == "#FF0000" ================================================ FILE: tests/opengl/test_composition_opengl.py ================================================ from __future__ import annotations from unittest.mock import MagicMock from manim.animation.animation import Animation, Wait from manim.animation.composition import AnimationGroup, Succession from manim.animation.fading import FadeIn, FadeOut from manim.constants import DOWN, UP from manim.mobject.geometry.arc import Circle from manim.mobject.geometry.line import Line from manim.mobject.geometry.polygram import Square def test_succession_timing(using_opengl_renderer): """Test timing of animations in a succession.""" line = Line() animation_1s = FadeIn(line, shift=UP, run_time=1.0) animation_4s = FadeOut(line, shift=DOWN, run_time=4.0) succession = Succession(animation_1s, animation_4s) assert succession.get_run_time() == 5.0 succession._setup_scene(MagicMock()) succession.begin() assert succession.active_index == 0 # The first animation takes 20% of the total run time. succession.interpolate(0.199) assert succession.active_index == 0 succession.interpolate(0.2) assert succession.active_index == 1 succession.interpolate(0.8) assert succession.active_index == 1 # At 100% and more, no animation must be active anymore. succession.interpolate(1.0) assert succession.active_index == 2 assert succession.active_animation is None succession.interpolate(1.2) assert succession.active_index == 2 assert succession.active_animation is None def test_succession_in_succession_timing(using_opengl_renderer): """Test timing of nested successions.""" line = Line() animation_1s = FadeIn(line, shift=UP, run_time=1.0) animation_4s = FadeOut(line, shift=DOWN, run_time=4.0) nested_succession = Succession(animation_1s, animation_4s) succession = Succession( FadeIn(line, shift=UP, run_time=4.0), nested_succession, FadeIn(line, shift=UP, run_time=1.0), ) assert nested_succession.get_run_time() == 5.0 assert succession.get_run_time() == 10.0 succession._setup_scene(MagicMock()) succession.begin() succession.interpolate(0.1) assert succession.active_index == 0 # The nested succession must not be active yet, and as a result hasn't set active_animation yet. assert not hasattr(nested_succession, "active_animation") succession.interpolate(0.39) assert succession.active_index == 0 assert not hasattr(nested_succession, "active_animation") # The nested succession starts at 40% of total run time succession.interpolate(0.4) assert succession.active_index == 1 assert nested_succession.active_index == 0 # The nested succession second animation starts at 50% of total run time. succession.interpolate(0.49) assert succession.active_index == 1 assert nested_succession.active_index == 0 succession.interpolate(0.5) assert succession.active_index == 1 assert nested_succession.active_index == 1 # The last animation starts at 90% of total run time. The nested succession must be finished at that time. succession.interpolate(0.89) assert succession.active_index == 1 assert nested_succession.active_index == 1 succession.interpolate(0.9) assert succession.active_index == 2 assert nested_succession.active_index == 2 assert nested_succession.active_animation is None # After 100%, nothing must be playing anymore. succession.interpolate(1.0) assert succession.active_index == 3 assert succession.active_animation is None assert nested_succession.active_index == 2 assert nested_succession.active_animation is None def test_animationbuilder_in_group(using_opengl_renderer): sqr = Square() circ = Circle() animation_group = AnimationGroup(sqr.animate.shift(DOWN).scale(2), FadeIn(circ)) assert all(isinstance(anim, Animation) for anim in animation_group.animations) succession = Succession(sqr.animate.shift(DOWN).scale(2), FadeIn(circ)) assert all(isinstance(anim, Animation) for anim in succession.animations) def test_animationgroup_with_wait(using_opengl_renderer): sqr = Square() sqr_anim = FadeIn(sqr) wait = Wait() animation_group = AnimationGroup(wait, sqr_anim, lag_ratio=1) animation_group.begin() timings = animation_group.anims_with_timings assert timings.tolist() == [(wait, 0.0, 1.0), (sqr_anim, 1.0, 2.0)] ================================================ FILE: tests/opengl/test_config_opengl.py ================================================ from __future__ import annotations import tempfile from pathlib import Path import numpy as np from manim import WHITE, Scene, Square, tempconfig def test_tempconfig(config, using_opengl_renderer): """Test the tempconfig context manager.""" original = config.copy() with tempconfig({"frame_width": 100,
= animation_group.anims_with_timings assert timings.tolist() == [(wait, 0.0, 1.0), (sqr_anim, 1.0, 2.0)] ================================================ FILE: tests/opengl/test_config_opengl.py ================================================ from __future__ import annotations import tempfile from pathlib import Path import numpy as np from manim import WHITE, Scene, Square, tempconfig def test_tempconfig(config, using_opengl_renderer): """Test the tempconfig context manager.""" original = config.copy() with tempconfig({"frame_width": 100, "frame_height": 42}): # check that config was modified correctly assert config["frame_width"] == 100 assert config["frame_height"] == 42 # check that no keys are missing and no new keys were added assert set(original.keys()) == set(config.keys()) # check that the keys are still untouched assert set(original.keys()) == set(config.keys()) # check that config is correctly restored for k, v in original.items(): if isinstance(v, np.ndarray): np.testing.assert_allclose(config[k], v) else: assert config[k] == v class MyScene(Scene): def construct(self): self.add(Square()) self.wait(1) def test_background_color(config, using_opengl_renderer, dry_run): """Test the 'background_color' config option.""" config.background_color = WHITE config.verbose = "ERROR" scene = MyScene() scene.render() frame = scene.renderer.get_frame() np.testing.assert_allclose(frame[0, 0], [255, 255, 255, 255]) def test_digest_file(config, using_opengl_renderer, tmp_path): """Test that a config file can be digested programmatically.""" with tempfile.NamedTemporaryFile("w", dir=tmp_path, delete=False) as tmp_cfg: tmp_cfg.write( """ [CLI] media_dir = this_is_my_favorite_path video_dir = {media_dir}/videos frame_height = 10 """, ) config.digest_file(tmp_cfg.name) assert config.get_dir("media_dir") == Path("this_is_my_favorite_path") assert config.get_dir("video_dir") == Path("this_is_my_favorite_path/videos") def test_frame_size(config, using_opengl_renderer, tmp_path): """Test that the frame size can be set via config file.""" np.testing.assert_allclose( config.aspect_ratio, config.pixel_width / config.pixel_height ) np.testing.assert_allclose(config.frame_height, 8.0) with tempconfig({}): with tempfile.NamedTemporaryFile("w", dir=tmp_path, delete=False) as tmp_cfg: tmp_cfg.write( """ [CLI] pixel_height = 10 pixel_width = 10 """, ) config.digest_file(tmp_cfg.name) # aspect ratio is set using pixel measurements np.testing.assert_allclose(config.aspect_ratio, 1.0) # if not specified in the cfg file, frame_width is set using the aspect ratio np.testing.assert_allclose(config.frame_height, 8.0) np.testing.assert_allclose(config.frame_width, 8.0) def test_frame_size_if_frame_width(config, using_opengl_renderer, tmp_path): with tempfile.NamedTemporaryFile("w", dir=tmp_path, delete=False) as tmp_cfg: tmp_cfg.write( """ [CLI] pixel_height = 10 pixel_width = 10 frame_height = 10 frame_width = 10 """, ) tmp_cfg.close() config.digest_file(tmp_cfg.name) np.testing.assert_allclose(config.aspect_ratio, 1.0) # if both are specified in the cfg file, the aspect ratio is ignored np.testing.assert_allclose(config.frame_height, 10.0) np.testing.assert_allclose(config.frame_width, 10.0) def test_temporary_dry_run(config, using_opengl_renderer): """Test that tempconfig correctly restores after setting dry_run.""" assert config["write_to_movie"] assert not config["save_last_frame"] with tempconfig({"dry_run": True}): assert not config["write_to_movie"] assert not config["save_last_frame"] assert config["write_to_movie"] assert not config["save_last_frame"] def test_dry_run_with_png_format(config, using_opengl_renderer, dry_run): """Test that there are no exceptions when running a png without output""" config.disable_caching = True assert config["dry_run"] is True scene = MyScene() scene.render() def test_dry_run_with_png_format_skipped_animations( config, using_opengl_renderer, dry_run ): """Test that there are no exceptions when running a png without output and skipped animations""" config.write_to_movie = False config.disable_caching = True assert config["dry_run"] is True scene = MyScene(skip_animations=True) scene.render() ================================================ FILE: tests/opengl/test_coordinate_system_opengl.py ================================================ from __future__ import annotations import math import numpy as np import pytest from manim import ( LEFT, ORIGIN, PI, UR, Axes, Circle, ComplexPlane, NumberPlane, PolarPlane, ThreeDAxes, config, tempconfig, ) from manim import CoordinateSystem as CS from manim.utils.color import BLUE, GREEN, ORANGE, RED, YELLOW from manim.utils.testing.frames_comparison import frames_comparison __module_test__ = "coordinate_system_opengl" def test_initial_config(using_opengl_renderer): """Check that all attributes are defined properly from the config.""" cs = CS() assert cs.x_range[0] == round(-config["frame_x_radius"]) assert cs.x_range[1] == round(config["frame_x_radius"]) assert cs.x_range[2] == 1.0 assert cs.y_range[0] == round(-config["frame_y_radius"]) assert cs.y_range[1] == round(config["frame_y_radius"]) assert cs.y_range[2] == 1.0
GREEN, ORANGE, RED, YELLOW from manim.utils.testing.frames_comparison import frames_comparison __module_test__ = "coordinate_system_opengl" def test_initial_config(using_opengl_renderer): """Check that all attributes are defined properly from the config.""" cs = CS() assert cs.x_range[0] == round(-config["frame_x_radius"]) assert cs.x_range[1] == round(config["frame_x_radius"]) assert cs.x_range[2] == 1.0 assert cs.y_range[0] == round(-config["frame_y_radius"]) assert cs.y_range[1] == round(config["frame_y_radius"]) assert cs.y_range[2] == 1.0 ax = Axes() np.testing.assert_allclose(ax.get_center(), ORIGIN) np.testing.assert_allclose(ax.y_axis_config["label_direction"], LEFT) with tempconfig({"frame_x_radius": 100, "frame_y_radius": 200}): cs = CS() assert cs.x_range[0] == -100 assert cs.x_range[1] == 100 assert cs.y_range[0] == -200 assert cs.y_range[1] == 200 def test_dimension(using_opengl_renderer): """Check that objects have the correct dimension.""" assert Axes().dimension == 2 assert NumberPlane().dimension == 2 assert PolarPlane().dimension == 2 assert ComplexPlane().dimension == 2 assert ThreeDAxes().dimension == 3 def test_abstract_base_class(using_opengl_renderer): """Check that CoordinateSystem has some abstract methods.""" with pytest.raises(NotImplementedError): CS().get_axes() @pytest.mark.skip( reason="Causes conflicts with other tests due to axis_config changing default config", ) def test_NumberPlane(using_opengl_renderer): """Test that NumberPlane generates the correct number of lines when its ranges do not cross 0.""" pos_x_range = (0, 7) neg_x_range = (-7, 0) pos_y_range = (2, 6) neg_y_range = (-6, -2) x_vals = [0, 1.5, 2, 2.8, 4, 6.25] y_vals = [2, 5, 4.25, 6, 4.5, 2.75] testing_data = [ (pos_x_range, pos_y_range, x_vals, y_vals), (pos_x_range, neg_y_range, x_vals, [-v for v in y_vals]), (neg_x_range, pos_y_range, [-v for v in x_vals], y_vals), (neg_x_range, neg_y_range, [-v for v in x_vals], [-v for v in y_vals]), ] for test_data in testing_data: x_range, y_range, x_vals, y_vals = test_data x_start, x_end = x_range y_start, y_end = y_range plane = NumberPlane( x_range=x_range, y_range=y_range, # x_length = 7, axis_config={"include_numbers": True}, ) # normally these values would be need to be added by one to pass since there's an # overlapping pair of lines at the origin, but since these planes do not cross 0, # this is not needed. num_y_lines = math.ceil(x_end - x_start) num_x_lines = math.floor(y_end - y_start) assert len(plane.y_lines) == num_y_lines assert len(plane.x_lines) == num_x_lines plane = NumberPlane((-5, 5, 0.5), (-8, 8, 2)) # <- test for different step values assert len(plane.x_lines) == 8 assert len(plane.y_lines) == 20 def test_point_to_coords(using_opengl_renderer): ax = Axes(x_range=[0, 10, 2]) circ = Circle(radius=0.5).shift(UR * 2) # get the coordinates of the circle with respect to the axes coords = np.around(ax.point_to_coords(circ.get_right()), decimals=4) np.testing.assert_array_equal(coords, (7.0833, 2.6667)) def test_coords_to_point(using_opengl_renderer): ax = Axes() # a point with respect to the axes c2p_coord = np.around(ax.coords_to_point(2, 2), decimals=4) np.testing.assert_array_equal(c2p_coord, (1.7143, 1.5, 0)) def test_input_to_graph_point(using_opengl_renderer): ax = Axes() curve = ax.plot(lambda x: np.cos(x)) line_graph = ax.plot_line_graph([1, 3, 5], [-1, 2, -2], add_vertex_dots=False)[ "line_graph" ] # move a square to PI on the cosine curve. position = np.around(ax.input_to_graph_point(x=PI, graph=curve), decimals=4) np.testing.assert_array_equal(position, (2.6928, -0.75, 0)) # test the line_graph implementation position = np.around(ax.input_to_graph_point(x=PI, graph=line_graph), decimals=4) np.testing.assert_array_equal(position, (2.6928, 1.2876, 0)) @frames_comparison def test_gradient_line_graph_x_axis(scene, using_opengl_renderer): """Test that using `colorscale` generates a line whose gradient matches the y-axis""" axes = Axes(x_range=[-3, 3], y_range=[-3, 3]) curve = axes.plot( lambda x: 0.1 * x**3, x_range=(-3, 3, 0.001), colorscale=[BLUE, GREEN, YELLOW, ORANGE, RED], colorscale_axis=0, ) scene.add(axes, curve) @frames_comparison def test_gradient_line_graph_y_axis(scene, using_opengl_renderer): """Test that using `colorscale` generates a line whose gradient matches the y-axis""" axes = Axes(x_range=[-3, 3], y_range=[-3,
matches the y-axis""" axes = Axes(x_range=[-3, 3], y_range=[-3, 3]) curve = axes.plot( lambda x: 0.1 * x**3, x_range=(-3, 3, 0.001), colorscale=[BLUE, GREEN, YELLOW, ORANGE, RED], colorscale_axis=0, ) scene.add(axes, curve) @frames_comparison def test_gradient_line_graph_y_axis(scene, using_opengl_renderer): """Test that using `colorscale` generates a line whose gradient matches the y-axis""" axes = Axes(x_range=[-3, 3], y_range=[-3, 3]) curve = axes.plot( lambda x: 0.1 * x**3, x_range=(-3, 3, 0.001), colorscale=[BLUE, GREEN, YELLOW, ORANGE, RED], colorscale_axis=1, ) scene.add(axes, curve) ================================================ FILE: tests/opengl/test_copy_opengl.py ================================================ from __future__ import annotations from pathlib import Path from manim import BraceLabel from manim.mobject.opengl.opengl_mobject import OpenGLMobject def test_opengl_mobject_copy(using_opengl_renderer): """Test that a copy is a deepcopy.""" orig = OpenGLMobject() orig.add(*(OpenGLMobject() for _ in range(10))) copy = orig.copy() assert orig is orig assert orig is not copy assert orig.submobjects is not copy.submobjects for i in range(10): assert orig.submobjects[i] is not copy.submobjects[i] def test_bracelabel_copy(config, using_opengl_renderer, tmp_path): """Test that a copy is a deepcopy.""" # For this test to work, we need to tweak some folders temporarily original_text_dir = config["text_dir"] original_tex_dir = config["tex_dir"] mediadir = Path(tmp_path) / "deepcopy" config["text_dir"] = str(mediadir.joinpath("Text")) config["tex_dir"] = str(mediadir.joinpath("Tex")) for el in ["text_dir", "tex_dir"]: Path(config[el]).mkdir(parents=True) # Before the refactoring of OpenGLMobject.copy(), the class BraceLabel was the # only one to have a non-trivial definition of copy. Here we test that it # still works after the refactoring. orig = BraceLabel(OpenGLMobject(), "label") copy = orig.copy() assert orig is orig assert orig is not copy assert orig.brace is not copy.brace assert orig.label is not copy.label assert orig.submobjects is not copy.submobjects assert orig.submobjects[0] is orig.brace assert copy.submobjects[0] is copy.brace assert orig.submobjects[0] is not copy.brace assert copy.submobjects[0] is not orig.brace # Restore the original folders config["text_dir"] = original_text_dir config["tex_dir"] = original_tex_dir ================================================ FILE: tests/opengl/test_family_opengl.py ================================================ from __future__ import annotations import numpy as np from manim import RIGHT, Circle from manim.mobject.opengl.opengl_mobject import OpenGLMobject def test_family(using_opengl_renderer): """Check that the family is gathered correctly.""" # Check that an empty OpenGLMobject's family only contains itself mob = OpenGLMobject() assert mob.get_family() == [mob] # Check that all children are in the family mob = OpenGLMobject() children = [OpenGLMobject() for _ in range(10)] mob.add(*children) family = mob.get_family() assert len(family) == 1 + 10 assert mob in family for c in children: assert c in family # Nested children should be in the family mob = OpenGLMobject() grandchildren = {} for _ in range(10): child = OpenGLMobject() grandchildren[child] = [OpenGLMobject() for _ in range(10)] child.add(*grandchildren[child]) mob.add(*list(grandchildren.keys())) family = mob.get_family() assert len(family) == 1 + 10 + 10 * 10 assert mob in family for c in grandchildren: assert c in family for gc in grandchildren[c]: assert gc in family def test_overlapping_family(using_opengl_renderer): """Check that each member of the family is only gathered once.""" ( mob, child1, child2, ) = ( OpenGLMobject(), OpenGLMobject(), OpenGLMobject(), ) gchild1, gchild2, gchild_common = OpenGLMobject(), OpenGLMobject(), OpenGLMobject() child1.add(gchild1, gchild_common) child2.add(gchild2, gchild_common) mob.add(child1, child2) family = mob.get_family() assert mob in family assert len(family) == 6 assert family.count(gchild_common) == 1 def test_shift_family(using_opengl_renderer): """Check that each member of the family is shifted along with the parent. Importantly, here we add a common grandchild to each
gchild_common = OpenGLMobject(), OpenGLMobject(), OpenGLMobject() child1.add(gchild1, gchild_common) child2.add(gchild2, gchild_common) mob.add(child1, child2) family = mob.get_family() assert mob in family assert len(family) == 6 assert family.count(gchild_common) == 1 def test_shift_family(using_opengl_renderer): """Check that each member of the family is shifted along with the parent. Importantly, here we add a common grandchild to each of the children. So this test will fail if the grandchild moves twice as much as it should. """ # Note shift() needs the OpenGLMobject to have a non-empty `points` attribute, so # we cannot use a plain OpenGLMobject or OpenGLVMobject. We use Circle instead. ( mob, child1, child2, ) = ( Circle(), Circle(), Circle(), ) gchild1, gchild2, gchild_common = Circle(), Circle(), Circle() child1.add(gchild1, gchild_common) child2.add(gchild2, gchild_common) mob.add(child1, child2) family = mob.get_family() positions_before = {m: m.get_center().copy() for m in family} mob.shift(RIGHT) positions_after = {m: m.get_center().copy() for m in family} for m in family: np.testing.assert_allclose(positions_before[m] + RIGHT, positions_after[m]) ================================================ FILE: tests/opengl/test_graph_opengl.py ================================================ from __future__ import annotations from manim import Dot, Graph, Line, Text def test_graph_creation(using_opengl_renderer): vertices = [1, 2, 3, 4] edges = [(1, 2), (2, 3), (3, 4), (4, 1)] layout = {1: [0, 0, 0], 2: [1, 1, 0], 3: [1, -1, 0], 4: [-1, 0, 0]} G_manual = Graph(vertices=vertices, edges=edges, layout=layout) assert len(G_manual.vertices) == 4 assert len(G_manual.edges) == 4 G_spring = Graph(vertices=vertices, edges=edges) assert len(G_spring.vertices) == 4 assert len(G_spring.edges) == 4 def test_graph_add_vertices(using_opengl_renderer): G = Graph([1, 2, 3], [(1, 2), (2, 3)]) G.add_vertices(4) assert len(G.vertices) == 4 assert len(G.edges) == 2 G.add_vertices(5, labels={5: Text("5")}) assert len(G.vertices) == 5 assert len(G.edges) == 2 assert 5 in G._labels assert 5 in G._vertex_config G.add_vertices(6, 7, 8) assert len(G.vertices) == 8 assert len(G._graph.nodes()) == 8 def test_graph_remove_vertices(using_opengl_renderer): G = Graph([1, 2, 3, 4, 5], [(1, 2), (2, 3), (3, 4), (4, 5)]) removed_mobjects = G.remove_vertices(3) assert len(removed_mobjects) == 3 assert len(G.vertices) == 4 assert len(G.edges) == 2 assert list(G.vertices.keys()) == [1, 2, 4, 5] assert list(G.edges.keys()) == [(1, 2), (4, 5)] removed_mobjects = G.remove_vertices(4, 5) assert len(removed_mobjects) == 3 assert len(G.vertices) == 2 assert len(G.edges) == 1 assert list(G.vertices.keys()) == [1, 2] assert list(G.edges.keys()) == [(1, 2)] def test_graph_add_edges(using_opengl_renderer): G = Graph([1, 2, 3, 4, 5], [(1, 2), (2, 3)]) added_mobjects = G.add_edges((1, 3)) assert isinstance(added_mobjects.submobjects[0], Line) assert len(G.vertices) == 5 assert len(G.edges) == 3 assert set(G.vertices.keys()) == {1, 2, 3, 4, 5} assert set(G.edges.keys()) == {(1, 2), (2, 3), (1, 3)} added_mobjects = G.add_edges((1, 42)) removed_mobjects = added_mobjects.submobjects assert isinstance(removed_mobjects[0], Dot) assert isinstance(removed_mobjects[1], Line) assert len(G.vertices) == 6 assert len(G.edges) == 4 assert set(G.vertices.keys()) == {1, 2, 3, 4, 5, 42} assert set(G.edges.keys()) == {(1, 2), (2, 3), (1, 3), (1, 42)} added_mobjects = G.add_edges((4, 5), (5, 6), (6, 7)) assert len(added_mobjects) == 5 assert len(G.vertices) == 8 assert len(G.edges) == 7 assert set(G.vertices.keys()) == {1, 2, 3, 4, 5, 42, 6, 7} assert set(G._graph.nodes()) == set(G.vertices.keys()) assert set(G.edges.keys()) == { (1, 2), (2, 3), (1, 3), (1, 42), (4, 5), (5, 6), (6, 7), } assert set(G._graph.edges()) == set(G.edges.keys()) def test_graph_remove_edges(using_opengl_renderer): G = Graph([1, 2, 3, 4, 5], [(1, 2),
7 assert set(G.vertices.keys()) == {1, 2, 3, 4, 5, 42, 6, 7} assert set(G._graph.nodes()) == set(G.vertices.keys()) assert set(G.edges.keys()) == { (1, 2), (2, 3), (1, 3), (1, 42), (4, 5), (5, 6), (6, 7), } assert set(G._graph.edges()) == set(G.edges.keys()) def test_graph_remove_edges(using_opengl_renderer): G = Graph([1, 2, 3, 4, 5], [(1, 2), (2, 3), (3, 4), (4, 5), (1, 5)]) removed_mobjects = G.remove_edges((1, 2)) assert isinstance(removed_mobjects.submobjects[0], Line) assert len(G.vertices) == 5 assert len(G.edges) == 4 assert set(G.edges.keys()) == {(2, 3), (3, 4), (4, 5), (1, 5)} assert set(G._graph.edges()) == set(G.edges.keys()) removed_mobjects = G.remove_edges((2, 3), (3, 4), (4, 5), (1, 5)) assert len(removed_mobjects) == 4 assert len(G.vertices) == 5 assert len(G.edges) == 0 assert set(G._graph.edges()) == set() assert set(G.edges.keys()) == set() ================================================ FILE: tests/opengl/test_ipython_magic_opengl.py ================================================ from __future__ import annotations import re from manim.utils.ipython_magic import _generate_file_name def test_jupyter_file_naming(config, using_opengl_renderer): """Check the format of file names for jupyter""" scene_name = "SimpleScene" expected_pattern = r"[0-9a-zA-Z_]+[@_-]\d\d\d\d-\d\d-\d\d[@_-]\d\d-\d\d-\d\d" config.scene_names = [scene_name] file_name = _generate_file_name() match = re.match(expected_pattern, file_name) assert scene_name in file_name, ( "Expected file to contain " + scene_name + " but got " + file_name ) assert match, "file name does not match expected pattern " + expected_pattern def test_jupyter_file_output(tmp_path, config, using_opengl_renderer): """Check the jupyter file naming is valid and can be created""" scene_name = "SimpleScene" config.scene_names = [scene_name] file_name = _generate_file_name() actual_path = tmp_path.with_name(file_name) with actual_path.open("w") as outfile: outfile.write("") assert actual_path.exists() assert actual_path.is_file() ================================================ FILE: tests/opengl/test_markup_opengl.py ================================================ from __future__ import annotations from manim import MarkupText def test_good_markup(using_opengl_renderer): """Test creation of valid :class:`MarkupText` object""" try: MarkupText("<b>foo</b>") MarkupText("foo") success = True except ValueError: success = False assert success, "'<b>foo</b>' and 'foo' should not fail validation" def test_special_tags_markup(using_opengl_renderer): """Test creation of valid :class:`MarkupText` object with unofficial tags""" try: MarkupText('<color col="RED">foo</color>') MarkupText('<gradient from="RED" to="YELLOW">foo</gradient>') success = True except ValueError: success = False assert success, ( '\'<color col="RED">foo</color>\' and \'<gradient from="RED" to="YELLOW">foo</gradient>\' should not fail validation' ) def test_unbalanced_tag_markup(using_opengl_renderer): """Test creation of invalid :class:`MarkupText` object (unbalanced tag)""" try: MarkupText("<b>foo") success = False except ValueError: success = True assert success, "'<b>foo' should fail validation" def test_invalid_tag_markup(using_opengl_renderer): """Test creation of invalid :class:`MarkupText` object (invalid tag)""" try: MarkupText("<invalidtag>foo</invalidtag>") success = False except ValueError: success = True assert success, "'<invalidtag>foo</invalidtag>' should fail validation" ================================================ FILE: tests/opengl/test_number_line_opengl.py ================================================ from __future__ import annotations import numpy as np from manim import NumberLine from manim.mobject.text.numbers import Integer def test_unit_vector(): """Check if the magnitude of unit vector along the NumberLine is equal to its unit_size. """ axis1 = NumberLine(unit_size=0.4) axis2 = NumberLine(x_range=[-2, 5], length=12) for axis in (axis1, axis2): assert np.linalg.norm(axis.get_unit_vector()) == axis.unit_size def test_decimal_determined_by_step(): """Checks that step size is considered when determining the number of decimal places. """ axis = NumberLine(x_range=[-2, 2, 0.5]) expected_decimal_places = 1 actual_decimal_places = axis.decimal_number_config["num_decimal_places"] assert actual_decimal_places == expected_decimal_places, ( "Expected 1 decimal place but got " + actual_decimal_places ) axis2 = NumberLine(x_range=[-1, 1, 0.25]) expected_decimal_places = 2 actual_decimal_places = axis2.decimal_number_config["num_decimal_places"] assert actual_decimal_places == expected_decimal_places, ( "Expected 1 decimal place but got " + actual_decimal_places ) def test_decimal_config_overrides_defaults(): """Checks that ``num_decimal_places`` is determined by step size and gets overridden by ``decimal_number_config``.""" axis = NumberLine( x_range=[-2,
got " + actual_decimal_places ) axis2 = NumberLine(x_range=[-1, 1, 0.25]) expected_decimal_places = 2 actual_decimal_places = axis2.decimal_number_config["num_decimal_places"] assert actual_decimal_places == expected_decimal_places, ( "Expected 1 decimal place but got " + actual_decimal_places ) def test_decimal_config_overrides_defaults(): """Checks that ``num_decimal_places`` is determined by step size and gets overridden by ``decimal_number_config``.""" axis = NumberLine( x_range=[-2, 2, 0.5], decimal_number_config={"num_decimal_places": 0}, ) expected_decimal_places = 0 actual_decimal_places = axis.decimal_number_config["num_decimal_places"] assert actual_decimal_places == expected_decimal_places, ( "Expected 1 decimal place but got " + actual_decimal_places ) def test_whole_numbers_step_size_default_to_0_decimal_places(): """Checks that ``num_decimal_places`` defaults to 0 when a whole number step size is passed.""" axis = NumberLine(x_range=[-2, 2, 1]) expected_decimal_places = 0 actual_decimal_places = axis.decimal_number_config["num_decimal_places"] assert actual_decimal_places == expected_decimal_places, ( "Expected 1 decimal place but got " + actual_decimal_places ) def test_add_labels(): expected_label_length = 6 num_line = NumberLine(x_range=[-4, 4]) num_line.add_labels( dict(zip(list(range(-3, 3)), [Integer(m) for m in range(-1, 5)])), ) actual_label_length = len(num_line.labels) assert actual_label_length == expected_label_length, ( f"Expected a VGroup with {expected_label_length} integers but got {actual_label_length}." ) ================================================ FILE: tests/opengl/test_numbers_opengl.py ================================================ from __future__ import annotations from manim.mobject.text.numbers import DecimalNumber def test_font_size(): """Test that DecimalNumber returns the correct font_size value after being scaled. """ num = DecimalNumber(0).scale(0.3) assert round(num.font_size, 5) == 14.4 def test_font_size_vs_scale(): """Test that scale produces the same results as .scale()""" num = DecimalNumber(0, font_size=12) num_scale = DecimalNumber(0).scale(1 / 4) assert num.height == num_scale.height def test_changing_font_size(): """Test that the font_size property properly scales DecimalNumber.""" num = DecimalNumber(0, font_size=12) num.font_size = 48 assert num.height == DecimalNumber(0, font_size=48).height def test_set_value_size(): """Test that the size of DecimalNumber after set_value is correct.""" num = DecimalNumber(0).scale(0.3) test_num = num.copy() num.set_value(0) # round because the height is off by 1e-17 assert round(num.height, 12) == round(test_num.height, 12) ================================================ FILE: tests/opengl/test_opengl_mobject.py ================================================ from __future__ import annotations import pytest from manim.mobject.opengl.opengl_mobject import OpenGLMobject def test_opengl_mobject_add(using_opengl_renderer): """Test OpenGLMobject.add().""" """Call this function with a Container instance to test its add() method.""" # check that obj.submobjects is updated correctly obj = OpenGLMobject() assert len(obj.submobjects) == 0 obj.add(OpenGLMobject()) assert len(obj.submobjects) == 1 obj.add(*(OpenGLMobject() for _ in range(10))) assert len(obj.submobjects) == 11 # check that adding a OpenGLMobject twice does not actually add it twice repeated = OpenGLMobject() obj.add(repeated) assert len(obj.submobjects) == 12 obj.add(repeated) assert len(obj.submobjects) == 12 # check that OpenGLMobject.add() returns the OpenGLMobject (for chained calls) assert obj.add(OpenGLMobject()) is obj assert len(obj.submobjects) == 13 obj = OpenGLMobject() # an OpenGLMobject cannot contain itself with pytest.raises(ValueError) as add_self_info: obj.add(OpenGLMobject(), obj, OpenGLMobject()) assert str(add_self_info.value) == ( "Cannot add OpenGLMobject as a submobject of itself (at index 1)." ) assert len(obj.submobjects) == 0 # can only add Mobjects with pytest.raises(TypeError) as add_str_info: obj.add(OpenGLMobject(), OpenGLMobject(), "foo") assert str(add_str_info.value) == ( "Only values of type OpenGLMobject can be added as submobjects of " "OpenGLMobject, but the value foo (at index 2) is of type str." ) assert len(obj.submobjects) == 0 def test_opengl_mobject_remove(using_opengl_renderer): """Test OpenGLMobject.remove().""" obj = OpenGLMobject() to_remove = OpenGLMobject() obj.add(to_remove) obj.add(*(OpenGLMobject() for _ in range(10))) assert len(obj.submobjects) == 11 obj.remove(to_remove) assert len(obj.submobjects) == 10 obj.remove(to_remove) assert len(obj.submobjects) == 10 assert obj.remove(OpenGLMobject()) is obj ================================================ FILE: tests/opengl/test_opengl_surface.py ================================================ import numpy as np from manim.mobject.opengl.opengl_surface import OpenGLSurface from manim.mobject.opengl.opengl_three_dimensions
== 0 def test_opengl_mobject_remove(using_opengl_renderer): """Test OpenGLMobject.remove().""" obj = OpenGLMobject() to_remove = OpenGLMobject() obj.add(to_remove) obj.add(*(OpenGLMobject() for _ in range(10))) assert len(obj.submobjects) == 11 obj.remove(to_remove) assert len(obj.submobjects) == 10 obj.remove(to_remove) assert len(obj.submobjects) == 10 assert obj.remove(OpenGLMobject()) is obj ================================================ FILE: tests/opengl/test_opengl_surface.py ================================================ import numpy as np from manim.mobject.opengl.opengl_surface import OpenGLSurface from manim.mobject.opengl.opengl_three_dimensions import OpenGLSurfaceMesh def test_surface_initialization(using_opengl_renderer): surface = OpenGLSurface( lambda u, v: (u, v, u * np.sin(v) + v * np.cos(u)), u_range=(-3, 3), v_range=(-3, 3), ) mesh = OpenGLSurfaceMesh(surface) ================================================ FILE: tests/opengl/test_opengl_vectorized_mobject.py ================================================ from __future__ import annotations import numpy as np import pytest from manim import Circle, Line, Square, VDict, VGroup, VMobject from manim.mobject.opengl.opengl_mobject import OpenGLMobject from manim.mobject.opengl.opengl_vectorized_mobject import OpenGLVMobject def test_opengl_vmobject_add(using_opengl_renderer): """Test the OpenGLVMobject add method.""" obj = OpenGLVMobject() assert len(obj.submobjects) == 0 obj.add(OpenGLVMobject()) assert len(obj.submobjects) == 1 # Can't add non-OpenGLVMobject values to a VMobject. with pytest.raises(TypeError) as add_int_info: obj.add(3) assert str(add_int_info.value) == ( "Only values of type OpenGLVMobject can be added as submobjects of " "OpenGLVMobject, but the value 3 (at index 0) is of type int." ) assert len(obj.submobjects) == 1 # Plain OpenGLMobjects can't be added to a OpenGLVMobject if they're not # OpenGLVMobjects. Suggest adding them into an OpenGLGroup instead. with pytest.raises(TypeError) as add_mob_info: obj.add(OpenGLMobject()) assert str(add_mob_info.value) == ( "Only values of type OpenGLVMobject can be added as submobjects of " "OpenGLVMobject, but the value OpenGLMobject (at index 0) is of type " "OpenGLMobject. You can try adding this value into a Group instead." ) assert len(obj.submobjects) == 1 with pytest.raises(TypeError) as add_vmob_and_mob_info: # If only one of the added objects is not an instance of VMobject, none of them should be added obj.add(OpenGLVMobject(), OpenGLMobject()) assert str(add_vmob_and_mob_info.value) == ( "Only values of type OpenGLVMobject can be added as submobjects of " "OpenGLVMobject, but the value OpenGLMobject (at index 1) is of type " "OpenGLMobject. You can try adding this value into a Group instead." ) assert len(obj.submobjects) == 1 # A VMobject or VGroup cannot contain itself. with pytest.raises(ValueError) as add_self_info: obj.add(obj) assert str(add_self_info.value) == ( "Cannot add OpenGLVMobject as a submobject of itself (at index 0)." ) assert len(obj.submobjects) == 1 def test_opengl_vmobject_point_from_proportion(using_opengl_renderer): obj = OpenGLVMobject() # One long line, one short line obj.set_points_as_corners( [ np.array([0, 0, 0]), np.array([4, 0, 0]), np.array([4, 2, 0]), ], ) # Total length of 6, so halfway along the object # would be at length 3, which lands in the first, long line. np.testing.assert_array_equal(obj.point_from_proportion(0.5), np.array([3, 0, 0])) with pytest.raises(ValueError, match="between 0 and 1"): obj.point_from_proportion(2) obj.clear_points() with pytest.raises(Exception, match="with no points"): obj.point_from_proportion(0) def test_vgroup_init(using_opengl_renderer): """Test the VGroup instantiation.""" VGroup() VGroup(OpenGLVMobject()) VGroup(OpenGLVMobject(), OpenGLVMobject()) # A VGroup cannot contain non-VMobject values. with pytest.raises(TypeError) as init_with_float_info: VGroup(3.0) assert str(init_with_float_info.value) == ( "Only values of type OpenGLVMobject can be added as submobjects of " "VGroup, but the value 3.0 (at index 0 of parameter 0) is of type float." ) with pytest.raises(TypeError) as init_with_mob_info: VGroup(OpenGLMobject()) assert str(init_with_mob_info.value) == ( "Only values of type OpenGLVMobject can be added as submobjects of " "VGroup, but the value OpenGLMobject (at index 0 of parameter 0) is of
"VGroup, but the value 3.0 (at index 0 of parameter 0) is of type float." ) with pytest.raises(TypeError) as init_with_mob_info: VGroup(OpenGLMobject()) assert str(init_with_mob_info.value) == ( "Only values of type OpenGLVMobject can be added as submobjects of " "VGroup, but the value OpenGLMobject (at index 0 of parameter 0) is of type " "OpenGLMobject. You can try adding this value into a Group instead." ) with pytest.raises(TypeError) as init_with_vmob_and_mob_info: VGroup(OpenGLVMobject(), OpenGLMobject()) assert str(init_with_vmob_and_mob_info.value) == ( "Only values of type OpenGLVMobject can be added as submobjects of " "VGroup, but the value OpenGLMobject (at index 0 of parameter 1) is of type " "OpenGLMobject. You can try adding this value into a Group instead." ) def test_vgroup_init_with_iterable(using_opengl_renderer): """Test VGroup instantiation with an iterable type.""" def type_generator(type_to_generate, n): return (type_to_generate() for _ in range(n)) def mixed_type_generator(major_type, minor_type, minor_type_positions, n): return ( minor_type() if i in minor_type_positions else major_type() for i in range(n) ) obj = VGroup(OpenGLVMobject()) assert len(obj.submobjects) == 1 obj = VGroup(type_generator(OpenGLVMobject, 38)) assert len(obj.submobjects) == 38 obj = VGroup( OpenGLVMobject(), [OpenGLVMobject(), OpenGLVMobject()], type_generator(OpenGLVMobject, 38), ) assert len(obj.submobjects) == 41 # A VGroup cannot be initialised with an iterable containing a OpenGLMobject with pytest.raises(TypeError) as init_with_mob_iterable: VGroup(type_generator(OpenGLMobject, 5)) assert str(init_with_mob_iterable.value) == ( "Only values of type OpenGLVMobject can be added as submobjects of VGroup, " "but the value OpenGLMobject (at index 0 of parameter 0) is of type OpenGLMobject." ) # A VGroup cannot be initialised with an iterable containing a OpenGLMobject in any position with pytest.raises(TypeError) as init_with_mobs_and_vmobs_iterable: VGroup(mixed_type_generator(OpenGLVMobject, OpenGLMobject, [3, 5], 7)) assert str(init_with_mobs_and_vmobs_iterable.value) == ( "Only values of type OpenGLVMobject can be added as submobjects of VGroup, " "but the value OpenGLMobject (at index 3 of parameter 0) is of type OpenGLMobject." ) # A VGroup cannot be initialised with an iterable containing non OpenGLVMobject's in any position with pytest.raises(TypeError) as init_with_float_and_vmobs_iterable: VGroup(mixed_type_generator(OpenGLVMobject, float, [6, 7], 9)) assert str(init_with_float_and_vmobs_iterable.value) == ( "Only values of type OpenGLVMobject can be added as submobjects of VGroup, " "but the value 0.0 (at index 6 of parameter 0) is of type float." ) # A VGroup cannot be initialised with an iterable containing both OpenGLVMobject's and VMobject's with pytest.raises(TypeError) as init_with_mobs_and_vmobs_iterable: VGroup(mixed_type_generator(OpenGLVMobject, VMobject, [3, 5], 7)) assert str(init_with_mobs_and_vmobs_iterable.value) == ( "Only values of type OpenGLVMobject can be added as submobjects of VGroup, " "but the value VMobject (at index 3 of parameter 0) is of type VMobject." ) def test_vgroup_add(using_opengl_renderer): """Test the VGroup add method.""" obj = VGroup() assert len(obj.submobjects) == 0 obj.add(OpenGLVMobject()) assert len(obj.submobjects) == 1 # Can't add non-OpenGLVMobject values to a VMobject. with pytest.raises(TypeError) as add_int_info: obj.add(3) assert str(add_int_info.value) == ( "Only values of type OpenGLVMobject can be added as submobjects of " "VGroup, but the value 3 (at index 0 of parameter 0) is of type int." ) assert len(obj.submobjects) == 1 # Plain OpenGLMobjects can't be added to a OpenGLVMobject if they're not # OpenGLVMobjects. Suggest adding them into an OpenGLGroup instead. with pytest.raises(TypeError) as add_mob_info: obj.add(OpenGLMobject()) assert str(add_mob_info.value) == ( "Only values of type OpenGLVMobject can be
0 of parameter 0) is of type int." ) assert len(obj.submobjects) == 1 # Plain OpenGLMobjects can't be added to a OpenGLVMobject if they're not # OpenGLVMobjects. Suggest adding them into an OpenGLGroup instead. with pytest.raises(TypeError) as add_mob_info: obj.add(OpenGLMobject()) assert str(add_mob_info.value) == ( "Only values of type OpenGLVMobject can be added as submobjects of " "VGroup, but the value OpenGLMobject (at index 0 of parameter 0) is of type " "OpenGLMobject. You can try adding this value into a Group instead." ) assert len(obj.submobjects) == 1 with pytest.raises(TypeError) as add_vmob_and_mob_info: # If only one of the added objects is not an instance of VMobject, none of them should be added obj.add(OpenGLVMobject(), OpenGLMobject()) assert str(add_vmob_and_mob_info.value) == ( "Only values of type OpenGLVMobject can be added as submobjects of " "VGroup, but the value OpenGLMobject (at index 0 of parameter 1) is of type " "OpenGLMobject. You can try adding this value into a Group instead." ) assert len(obj.submobjects) == 1 # A VMobject or VGroup cannot contain itself. with pytest.raises(ValueError) as add_self_info: obj.add(obj) assert str(add_self_info.value) == ( "Cannot add VGroup as a submobject of itself (at index 0)." ) assert len(obj.submobjects) == 1 def test_vgroup_add_dunder(using_opengl_renderer): """Test the VGroup __add__ magic method.""" obj = VGroup() assert len(obj.submobjects) == 0 obj + OpenGLVMobject() assert len(obj.submobjects) == 0 obj += OpenGLVMobject() assert len(obj.submobjects) == 1 with pytest.raises(TypeError): obj += OpenGLMobject() assert len(obj.submobjects) == 1 with pytest.raises(TypeError): # If only one of the added object is not an instance of OpenGLVMobject, none of them should be added obj += (OpenGLVMobject(), OpenGLMobject()) assert len(obj.submobjects) == 1 with pytest.raises(ValueError): # a OpenGLMobject cannot contain itself obj += obj def test_vgroup_remove(using_opengl_renderer): """Test the VGroup remove method.""" a = OpenGLVMobject() c = OpenGLVMobject() b = VGroup(c) obj = VGroup(a, b) assert len(obj.submobjects) == 2 assert len(b.submobjects) == 1 obj.remove(a) b.remove(c) assert len(obj.submobjects) == 1 assert len(b.submobjects) == 0 obj.remove(b) assert len(obj.submobjects) == 0 def test_vgroup_remove_dunder(using_opengl_renderer): """Test the VGroup __sub__ magic method.""" a = OpenGLVMobject() c = OpenGLVMobject() b = VGroup(c) obj = VGroup(a, b) assert len(obj.submobjects) == 2 assert len(b.submobjects) == 1 assert len(obj - a) == 1 assert len(obj.submobjects) == 2 obj -= a b -= c assert len(obj.submobjects) == 1 assert len(b.submobjects) == 0 obj -= b assert len(obj.submobjects) == 0 def test_vmob_add_to_back(using_opengl_renderer): """Test the OpenGLMobject add_to_back method.""" a = OpenGLVMobject() b = Line() c = "text" with pytest.raises(ValueError): # OpenGLMobject cannot contain self a.add_to_back(a) with pytest.raises(TypeError): # All submobjects must be of type OpenGLMobject a.add_to_back(c) # No submobject gets added twice a.add_to_back(b) a.add_to_back(b, b) assert len(a.submobjects) == 1 a.submobjects.clear() a.add_to_back(b, b, b) a.add_to_back(b, b) assert len(a.submobjects) == 1 a.submobjects.clear() # Make sure the ordering has not changed o1, o2, o3 = Square(), Line(), Circle() a.add_to_back(o1, o2, o3) assert a.submobjects.pop() == o3 assert a.submobjects.pop() == o2 assert a.submobjects.pop() == o1 def test_vdict_init(using_opengl_renderer): """Test the VDict instantiation.""" # Test empty VDict VDict() # Test VDict made from list of pairs VDict([("a", OpenGLVMobject()), ("b", OpenGLVMobject()), ("c", OpenGLVMobject())]) # Test VDict made from a python dict VDict({"a": OpenGLVMobject(), "b": OpenGLVMobject(),
o3) assert a.submobjects.pop() == o3 assert a.submobjects.pop() == o2 assert a.submobjects.pop() == o1 def test_vdict_init(using_opengl_renderer): """Test the VDict instantiation.""" # Test empty VDict VDict() # Test VDict made from list of pairs VDict([("a", OpenGLVMobject()), ("b", OpenGLVMobject()), ("c", OpenGLVMobject())]) # Test VDict made from a python dict VDict({"a": OpenGLVMobject(), "b": OpenGLVMobject(), "c": OpenGLVMobject()}) # Test VDict made using zip VDict(zip(["a", "b", "c"], [OpenGLVMobject(), OpenGLVMobject(), OpenGLVMobject()])) # If the value is of type OpenGLMobject, must raise a TypeError with pytest.raises(TypeError): VDict({"a": OpenGLMobject()}) def test_vdict_add(using_opengl_renderer): """Test the VDict add method.""" obj = VDict() assert len(obj.submob_dict) == 0 obj.add([("a", OpenGLVMobject())]) assert len(obj.submob_dict) == 1 with pytest.raises(TypeError): obj.add([("b", OpenGLMobject())]) def test_vdict_remove(using_opengl_renderer): """Test the VDict remove method.""" obj = VDict([("a", OpenGLVMobject())]) assert len(obj.submob_dict) == 1 obj.remove("a") assert len(obj.submob_dict) == 0 with pytest.raises(KeyError): obj.remove("a") def test_vgroup_supports_item_assigment(using_opengl_renderer): """Test VGroup supports array-like assignment for OpenGLVMObjects""" a = OpenGLVMobject() b = OpenGLVMobject() vgroup = VGroup(a) assert vgroup[0] == a vgroup[0] = b assert vgroup[0] == b assert len(vgroup) == 1 def test_vgroup_item_assignment_at_correct_position(using_opengl_renderer): """Test VGroup item-assignment adds to correct position for OpenGLVMobjects""" n_items = 10 vgroup = VGroup() for _i in range(n_items): vgroup.add(OpenGLVMobject()) new_obj = OpenGLVMobject() vgroup[6] = new_obj assert vgroup[6] == new_obj assert len(vgroup) == n_items def test_vgroup_item_assignment_only_allows_vmobjects(using_opengl_renderer): """Test VGroup item-assignment raises TypeError when invalid type is passed""" vgroup = VGroup(OpenGLVMobject()) with pytest.raises(TypeError) as assign_str_info: vgroup[0] = "invalid object" assert str(assign_str_info.value) == ( "Only values of type OpenGLVMobject can be added as submobjects of " "VGroup, but the value invalid object (at index 0) is of type str." ) ================================================ FILE: tests/opengl/test_override_animation_opengl.py ================================================ from __future__ import annotations import pytest from manim import Animation, override_animation from manim.mobject.opengl.opengl_mobject import OpenGLMobject from manim.utils.exceptions import MultiAnimationOverrideException class AnimationA1(Animation): pass class AnimationA2(Animation): pass class AnimationA3(Animation): pass class AnimationB1(AnimationA1): pass class AnimationC1(AnimationB1): pass class AnimationX(Animation): pass class OpenGLMobjectA(OpenGLMobject): @override_animation(AnimationA1) def anim_a1(self): return AnimationA2(self) @override_animation(AnimationX) def anim_x(self, *args, **kwargs): return args, kwargs class OpenGLMobjectB(OpenGLMobjectA): pass class OpenGLMobjectC(OpenGLMobjectB): @override_animation(AnimationA1) def anim_a1(self): return AnimationA3(self) class OpenGLMobjectX(OpenGLMobject): @override_animation(AnimationB1) def animation(self): return "Overridden" @pytest.mark.xfail(reason="Needs investigating") def test_opengl_mobject_inheritance(): mob = OpenGLMobject() a = OpenGLMobjectA() b = OpenGLMobjectB() c = OpenGLMobjectC() assert type(AnimationA1(mob)) is AnimationA1 assert type(AnimationA1(a)) is AnimationA2 assert type(AnimationA1(b)) is AnimationA2 assert type(AnimationA1(c)) is AnimationA3 @pytest.mark.xfail(reason="Needs investigating") def test_arguments(): a = OpenGLMobjectA() args = (1, "two", {"three": 3}, ["f", "o", "u", "r"]) kwargs = {"test": "manim", "keyword": 42, "arguments": []} animA = AnimationX(a, *args, **kwargs) assert animA[0] == args assert animA[1] == kwargs @pytest.mark.xfail(reason="Needs investigating") def test_multi_animation_override_exception(): with pytest.raises(MultiAnimationOverrideException): class OpenGLMobjectB2(OpenGLMobjectA): @override_animation(AnimationA1) def anim_a1_different_name(self): pass @pytest.mark.xfail(reason="Needs investigating") def test_animation_inheritance(): x = OpenGLMobjectX() assert type(AnimationA1(x)) is AnimationA1 assert AnimationB1(x) == "Overridden" assert type(AnimationC1(x)) is AnimationC1 ================================================ FILE: tests/opengl/test_scene_opengl.py ================================================ from __future__ import annotations from manim import Scene, tempconfig from manim.mobject.opengl.opengl_mobject import OpenGLMobject def test_scene_add_remove(using_opengl_renderer): with tempconfig({"dry_run": True}): scene = Scene() assert len(scene.mobjects) == 0 scene.add(OpenGLMobject()) assert len(scene.mobjects) == 1 scene.add(*(OpenGLMobject() for _ in range(10))) assert len(scene.mobjects) == 11 # Check that adding a mobject twice does not actually add it twice repeated = OpenGLMobject() scene.add(repeated) assert len(scene.mobjects) == 12 scene.add(repeated) assert len(scene.mobjects) == 12 # Check that Scene.add() returns the Scene (for
== 0 scene.add(OpenGLMobject()) assert len(scene.mobjects) == 1 scene.add(*(OpenGLMobject() for _ in range(10))) assert len(scene.mobjects) == 11 # Check that adding a mobject twice does not actually add it twice repeated = OpenGLMobject() scene.add(repeated) assert len(scene.mobjects) == 12 scene.add(repeated) assert len(scene.mobjects) == 12 # Check that Scene.add() returns the Scene (for chained calls) assert scene.add(OpenGLMobject()) is scene to_remove = OpenGLMobject() scene = Scene() scene.add(to_remove) scene.add(*(OpenGLMobject() for _ in range(10))) assert len(scene.mobjects) == 11 scene.remove(to_remove) assert len(scene.mobjects) == 10 scene.remove(to_remove) assert len(scene.mobjects) == 10 # Check that Scene.remove() returns the instance (for chained calls) assert scene.add(OpenGLMobject()) is scene ================================================ FILE: tests/opengl/test_sound_opengl.py ================================================ from __future__ import annotations import struct import wave from pathlib import Path import pytest from manim import Scene @pytest.mark.xfail(reason="Not currently implemented for opengl") def test_add_sound(using_opengl_renderer, tmpdir): # create sound file sound_loc = Path(tmpdir, "noise.wav") with wave.open(str(sound_loc), "w") as f: f.setparams((2, 2, 44100, 0, "NONE", "not compressed")) for _ in range(22050): # half a second of sound packed_value = struct.pack("h", 14242) f.writeframes(packed_value) f.writeframes(packed_value) scene = Scene() scene.add_sound(sound_loc) ================================================ FILE: tests/opengl/test_stroke_opengl.py ================================================ from __future__ import annotations import manim.utils.color as C from manim.mobject.opengl.opengl_vectorized_mobject import OpenGLVMobject def test_stroke_props_in_ctor(using_opengl_renderer): m = OpenGLVMobject(stroke_color=C.ORANGE, stroke_width=10) assert m.stroke_color.to_hex() == C.ORANGE.to_hex() assert m.stroke_width == 10 def test_set_stroke(using_opengl_renderer): m = OpenGLVMobject() m.set_stroke(color=C.ORANGE, width=2, opacity=0.8) assert m.stroke_width == 2 assert m.stroke_opacity == 0.8 assert m.stroke_color.to_hex() == C.ORANGE.to_hex() ================================================ FILE: tests/opengl/test_svg_mobject_opengl.py ================================================ from __future__ import annotations from manim import * from tests.helpers.path_utils import get_svg_resource def test_set_fill_color(using_opengl_renderer): expected_color = "#FF862F" svg = SVGMobject(get_svg_resource("heart.svg"), fill_color=expected_color) assert svg.fill_color.to_hex() == expected_color def test_set_stroke_color(using_opengl_renderer): expected_color = "#FFFDDD" svg = SVGMobject(get_svg_resource("heart.svg"), stroke_color=expected_color) assert svg.stroke_color.to_hex() == expected_color def test_set_color_sets_fill_and_stroke(using_opengl_renderer): expected_color = "#EEE777" svg = SVGMobject(get_svg_resource("heart.svg"), color=expected_color) assert svg.color.to_hex() == expected_color assert svg.fill_color.to_hex() == expected_color assert svg.stroke_color.to_hex() == expected_color def test_set_fill_opacity(using_opengl_renderer): expected_opacity = 0.5 svg = SVGMobject(get_svg_resource("heart.svg"), fill_opacity=expected_opacity) assert svg.fill_opacity == expected_opacity def test_stroke_opacity(using_opengl_renderer): expected_opacity = 0.4 svg = SVGMobject(get_svg_resource("heart.svg"), stroke_opacity=expected_opacity) assert svg.stroke_opacity == expected_opacity def test_fill_overrides_color(using_opengl_renderer): expected_color = "#343434" svg = SVGMobject( get_svg_resource("heart.svg"), color="#123123", fill_color=expected_color, ) assert svg.fill_color.to_hex() == expected_color def test_stroke_overrides_color(using_opengl_renderer): expected_color = "#767676" svg = SVGMobject( get_svg_resource("heart.svg"), color="#334433", stroke_color=expected_color, ) assert svg.stroke_color.to_hex() == expected_color ================================================ FILE: tests/opengl/test_texmobject_opengl.py ================================================ from __future__ import annotations from pathlib import Path import pytest from manim import MathTex, SingleStringMathTex, Tex def test_MathTex(config, using_opengl_renderer): MathTex("a^2 + b^2 = c^2") assert Path(config.media_dir, "Tex", "e4be163a00cf424f.svg").exists() def test_SingleStringMathTex(config, using_opengl_renderer): SingleStringMathTex("test") assert Path(config.media_dir, "Tex", "8ce17c7f5013209f.svg").exists() @pytest.mark.parametrize( # : PT006 ("text_input", "length_sub"), [("{{ a }} + {{ b }} = {{ c }}", 5), (r"\frac{1}{a+b\sqrt{2}}", 1)], ) def test_double_braces_testing(using_opengl_renderer, text_input, length_sub): t1 = MathTex(text_input) assert len(t1.submobjects) == length_sub def test_tex(config, using_opengl_renderer): Tex("The horse does not eat cucumber salad.") assert Path(config.media_dir, "Tex", "c3945e23e546c95a.svg").exists() def test_tex_whitespace_arg(using_opengl_renderer): """Check that correct number of submobjects are created per string with whitespace separator""" separator = "\t" str_part_1 = "Hello" str_part_2 = "world" str_part_3 = "It is" str_part_4 = "me!" tex = Tex(str_part_1, str_part_2, str_part_3, str_part_4, arg_separator=separator) assert len(tex) == 4 assert len(tex[0]) == len("".join((str_part_1 + separator).split())) assert len(tex[1]) == len("".join((str_part_2 + separator).split())) assert len(tex[2]) == len("".join((str_part_3 + separator).split())) assert len(tex[3]) == len("".join(str_part_4.split())) def test_tex_non_whitespace_arg(using_opengl_renderer): """Check that correct number of submobjects are created per string with
is" str_part_4 = "me!" tex = Tex(str_part_1, str_part_2, str_part_3, str_part_4, arg_separator=separator) assert len(tex) == 4 assert len(tex[0]) == len("".join((str_part_1 + separator).split())) assert len(tex[1]) == len("".join((str_part_2 + separator).split())) assert len(tex[2]) == len("".join((str_part_3 + separator).split())) assert len(tex[3]) == len("".join(str_part_4.split())) def test_tex_non_whitespace_arg(using_opengl_renderer): """Check that correct number of submobjects are created per string with non_whitespace characters""" separator = "," str_part_1 = "Hello" str_part_2 = "world" str_part_3 = "It is" str_part_4 = "me!" tex = Tex(str_part_1, str_part_2, str_part_3, str_part_4, arg_separator=separator) assert len(tex) == 4 assert len(tex[0]) == len("".join((str_part_1 + separator).split())) assert len(tex[1]) == len("".join((str_part_2 + separator).split())) assert len(tex[2]) == len("".join((str_part_3 + separator).split())) assert len(tex[3]) == len("".join(str_part_4.split())) def test_tex_white_space_and_non_whitespace_args(using_opengl_renderer): """Check that correct number of submobjects are created per string when mixing characters with whitespace""" separator = ", \n . \t\t" str_part_1 = "Hello" str_part_2 = "world" str_part_3 = "It is" str_part_4 = "me!" tex = Tex(str_part_1, str_part_2, str_part_3, str_part_4, arg_separator=separator) assert len(tex) == 4 assert len(tex[0]) == len("".join((str_part_1 + separator).split())) assert len(tex[1]) == len("".join((str_part_2 + separator).split())) assert len(tex[2]) == len("".join((str_part_3 + separator).split())) assert len(tex[3]) == len("".join(str_part_4.split())) def test_tex_size(using_opengl_renderer): """Check that the size of a :class:`Tex` string is not changed.""" text = Tex("what").center() vertical = text.get_top() - text.get_bottom() horizontal = text.get_right() - text.get_left() assert round(vertical[1], 4) == 0.3512 assert round(horizontal[0], 4) == 1.0420 def test_font_size(using_opengl_renderer): """Test that tex_mobject classes return the correct font_size value after being scaled. """ string = MathTex(0).scale(0.3) assert round(string.font_size, 5) == 14.4 def test_font_size_vs_scale(using_opengl_renderer): """Test that scale produces the same results as .scale()""" num = MathTex(0, font_size=12) num_scale = MathTex(0).scale(1 / 4) assert num.height == num_scale.height def test_changing_font_size(using_opengl_renderer): """Test that the font_size property properly scales tex_mobject.py classes.""" num = Tex("0", font_size=12) num.font_size = 48 assert num.height == Tex("0", font_size=48).height ================================================ FILE: tests/opengl/test_text_mobject_opengl.py ================================================ from __future__ import annotations from manim.mobject.text.text_mobject import MarkupText, Text def test_font_size(using_opengl_renderer): """Test that Text and MarkupText return the correct font_size value after being scaled. """ text_string = Text("0").scale(0.3) markuptext_string = MarkupText("0").scale(0.3) assert round(text_string.font_size, 5) == 14.4 assert round(markuptext_string.font_size, 5) == 14.4 ================================================ FILE: tests/opengl/test_ticks_opengl.py ================================================ from __future__ import annotations import numpy as np from manim import PI, Axes, NumberLine def test_duplicate_ticks_removed_for_axes(using_opengl_renderer): axis = NumberLine( x_range=[-10, 10], ) ticks = axis.get_tick_range() assert np.unique(ticks).size == ticks.size def test_ticks_not_generated_on_origin_for_axes(using_opengl_renderer): axes = Axes( x_range=[-10, 10], y_range=[-10, 10], axis_config={"include_ticks": True}, ) x_axis_range = axes.x_axis.get_tick_range() y_axis_range = axes.y_axis.get_tick_range() assert 0 not in x_axis_range assert 0 not in y_axis_range def test_expected_ticks_generated(using_opengl_renderer): axes = Axes(x_range=[-2, 2], y_range=[-2, 2], axis_config={"include_ticks": True}) x_axis_range = axes.x_axis.get_tick_range() y_axis_range = axes.y_axis.get_tick_range() assert 1 in x_axis_range assert 1 in y_axis_range assert -1 in x_axis_range assert -1 in y_axis_range def test_ticks_generated_from_origin_for_axes(using_opengl_renderer): axes = Axes( x_range=[-PI, PI], y_range=[-PI, PI], axis_config={"include_ticks": True}, ) x_axis_range = axes.x_axis.get_tick_range() y_axis_range = axes.y_axis.get_tick_range() assert -2 in x_axis_range assert -1 in x_axis_range assert 0 not in x_axis_range assert 1 in x_axis_range assert 2 in x_axis_range assert -2 in y_axis_range assert -1 in y_axis_range assert 0 not in y_axis_range assert 1 in y_axis_range assert 2 in y_axis_range ================================================ FILE: tests/opengl/test_unit_geometry_opengl.py ================================================ from __future__ import annotations import numpy as np from manim import Sector def test_get_arc_center(using_opengl_renderer): np.testing.assert_array_equal( Sector(arc_center=[1, 2, 0]).get_arc_center(), [1, 2, 0] )
2 in x_axis_range assert -2 in y_axis_range assert -1 in y_axis_range assert 0 not in y_axis_range assert 1 in y_axis_range assert 2 in y_axis_range ================================================ FILE: tests/opengl/test_unit_geometry_opengl.py ================================================ from __future__ import annotations import numpy as np from manim import Sector def test_get_arc_center(using_opengl_renderer): np.testing.assert_array_equal( Sector(arc_center=[1, 2, 0]).get_arc_center(), [1, 2, 0] ) ================================================ FILE: tests/opengl/test_value_tracker_opengl.py ================================================ from __future__ import annotations from manim.mobject.value_tracker import ComplexValueTracker, ValueTracker def test_value_tracker_set_value(using_opengl_renderer): """Test ValueTracker.set_value()""" tracker = ValueTracker() tracker.set_value(10.0) assert tracker.get_value() == 10.0 def test_value_tracker_get_value(using_opengl_renderer): """Test ValueTracker.get_value()""" tracker = ValueTracker(10.0) assert tracker.get_value() == 10.0 def test_value_tracker_interpolate(using_opengl_renderer): """Test ValueTracker.interpolate()""" tracker1 = ValueTracker(1.0) tracker2 = ValueTracker(2.5) tracker3 = ValueTracker().interpolate(tracker1, tracker2, 0.7) assert tracker3.get_value() == 2.05 def test_value_tracker_increment_value(using_opengl_renderer): """Test ValueTracker.increment_value()""" tracker = ValueTracker(0.0) tracker.increment_value(10.0) assert tracker.get_value() == 10.0 def test_value_tracker_bool(using_opengl_renderer): """Test ValueTracker.__bool__()""" tracker = ValueTracker(0.0) assert not tracker tracker.increment_value(1.0) assert tracker def test_value_tracker_iadd(using_opengl_renderer): """Test ValueTracker.__iadd__()""" tracker = ValueTracker(0.0) tracker += 10.0 assert tracker.get_value() == 10.0 def test_value_tracker_ifloordiv(using_opengl_renderer): """Test ValueTracker.__ifloordiv__()""" tracker = ValueTracker(5.0) tracker //= 2.0 assert tracker.get_value() == 2.0 def test_value_tracker_imod(using_opengl_renderer): """Test ValueTracker.__imod__()""" tracker = ValueTracker(20.0) tracker %= 3.0 assert tracker.get_value() == 2.0 def test_value_tracker_imul(using_opengl_renderer): """Test ValueTracker.__imul__()""" tracker = ValueTracker(3.0) tracker *= 4.0 assert tracker.get_value() == 12.0 def test_value_tracker_ipow(using_opengl_renderer): """Test ValueTracker.__ipow__()""" tracker = ValueTracker(3.0) tracker **= 3.0 assert tracker.get_value() == 27.0 def test_value_tracker_isub(using_opengl_renderer): """Test ValueTracker.__isub__()""" tracker = ValueTracker(20.0) tracker -= 10.0 assert tracker.get_value() == 10.0 def test_value_tracker_itruediv(using_opengl_renderer): """Test ValueTracker.__itruediv__()""" tracker = ValueTracker(5.0) tracker /= 2.0 assert tracker.get_value() == 2.5 def test_complex_value_tracker_set_value(using_opengl_renderer): """Test ComplexValueTracker.set_value()""" tracker = ComplexValueTracker() tracker.set_value(1 + 2j) assert tracker.get_value() == 1 + 2j def test_complex_value_tracker_get_value(using_opengl_renderer): """Test ComplexValueTracker.get_value()""" tracker = ComplexValueTracker(2.0 - 3.0j) assert tracker.get_value() == 2.0 - 3.0j ================================================ FILE: tests/opengl/control_data/coordinate_system_opengl/gradient_line_graph_x_axis_using_opengl_renderer[None].npz ================================================ [Binary file] ================================================ FILE: tests/opengl/control_data/coordinate_system_opengl/gradient_line_graph_y_axis_using_opengl_renderer[None].npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/__init__.py ================================================ [Empty file] ================================================ FILE: tests/test_graphical_units/conftest.py ================================================ from __future__ import annotations import pytest @pytest.fixture def show_diff(request): return request.config.getoption("show_diff") @pytest.fixture(params=[True, False]) def use_vectorized(request): return request.param ================================================ FILE: tests/test_graphical_units/test_animation.py ================================================ from manim import * from manim.animation.animation import DEFAULT_ANIMATION_RUN_TIME __module_test__ = "animation" def test_animation_set_default(): s = Square() Rotate.set_default(run_time=100) anim = Rotate(s) assert anim.run_time == 100 anim = Rotate(s, run_time=5) assert anim.run_time == 5 Rotate.set_default() anim = Rotate(s) assert anim.run_time == DEFAULT_ANIMATION_RUN_TIME ================================================ FILE: tests/test_graphical_units/test_axes.py ================================================ from __future__ import annotations from manim import * from manim.utils.testing.frames_comparison import frames_comparison __module_test__ = "plot" @frames_comparison def test_axes(scene): graph = Axes( x_range=[-10, 10, 1], y_range=[-10, 10, 1], x_length=6, y_length=6, color=WHITE, y_axis_config={"tip_shape": StealthTip}, ) labels = graph.get_axis_labels() scene.add(graph, labels) @frames_comparison def test_plot_functions(scene, use_vectorized): ax = Axes(x_range=(-10, 10.3), y_range=(-1.5, 1.5)) graph = ax.plot(lambda x: x**2, use_vectorized=use_vectorized) scene.add(ax, graph) @frames_comparison def test_custom_coordinates(scene): ax = Axes(x_range=[0, 10]) ax.add_coordinates( dict(zip(list(range(1, 10)), [Tex("str") for _ in range(1, 10)])), ) scene.add(ax) @frames_comparison def test_get_axis_labels(scene): ax = Axes() labels = ax.get_axis_labels(Tex("$x$-axis").scale(0.7), Tex("$y$-axis").scale(0.45)) scene.add(ax, labels) @frames_comparison def test_get_x_axis_label(scene): ax = Axes(x_range=(0, 8), y_range=(0, 5), x_length=8, y_length=5) x_label = ax.get_x_axis_label( Tex("$x$-values").scale(0.65), edge=DOWN, direction=DOWN, buff=0.5, ) scene.add(ax, x_label) @frames_comparison def test_get_y_axis_label(scene): ax = Axes(x_range=(0, 8), y_range=(0, 5), x_length=8, y_length=5) y_label = ax.get_y_axis_label( Tex("$y$-values").scale(0.65).rotate(90 * DEGREES), edge=LEFT, direction=LEFT, buff=0.3, ) scene.add(ax, y_label) @frames_comparison def test_axis_tip_default_width_height(scene): ax = Axes( x_range=(0, 4), y_range=(0, 4), axis_config={"include_numbers": True, "include_tip": True}, ) scene.add(ax) @frames_comparison def test_axis_tip_custom_width_height(scene): ax = Axes( x_range=(0, 4),
) scene.add(ax, x_label) @frames_comparison def test_get_y_axis_label(scene): ax = Axes(x_range=(0, 8), y_range=(0, 5), x_length=8, y_length=5) y_label = ax.get_y_axis_label( Tex("$y$-values").scale(0.65).rotate(90 * DEGREES), edge=LEFT, direction=LEFT, buff=0.3, ) scene.add(ax, y_label) @frames_comparison def test_axis_tip_default_width_height(scene): ax = Axes( x_range=(0, 4), y_range=(0, 4), axis_config={"include_numbers": True, "include_tip": True}, ) scene.add(ax) @frames_comparison def test_axis_tip_custom_width_height(scene): ax = Axes( x_range=(0, 4), y_range=(0, 4), axis_config={"include_numbers": True, "include_tip": True}, x_axis_config={"tip_width": 1, "tip_height": 0.1}, y_axis_config={"tip_width": 0.1, "tip_height": 1}, ) scene.add(ax) @frames_comparison def test_plot_derivative_graph(scene, use_vectorized): ax = NumberPlane(y_range=[-1, 7], background_line_style={"stroke_opacity": 0.4}) curve_1 = ax.plot(lambda x: x**2, color=PURPLE_B, use_vectorized=use_vectorized) curve_2 = ax.plot_derivative_graph(curve_1, use_vectorized=use_vectorized) curve_3 = ax.plot_antiderivative_graph(curve_1, use_vectorized=use_vectorized) curves = VGroup(curve_1, curve_2, curve_3) scene.add(ax, curves) @frames_comparison def test_plot(scene, use_vectorized): # construct the axes ax_1 = Axes( x_range=[0.001, 6], y_range=[-8, 2], x_length=5, y_length=3, tips=False, ) ax_2 = ax_1.copy() ax_3 = ax_1.copy() # position the axes ax_1.to_corner(UL) ax_2.to_corner(UR) ax_3.to_edge(DOWN) axes = VGroup(ax_1, ax_2, ax_3) # create the logarithmic curves def log_func(x): return np.log(x) # a curve without adjustments; poor interpolation. curve_1 = ax_1.plot(log_func, color=PURE_RED, use_vectorized=use_vectorized) # disabling interpolation makes the graph look choppy as not enough # inputs are available curve_2 = ax_2.plot( log_func, use_smoothing=False, color=ORANGE, use_vectorized=use_vectorized ) # taking more inputs of the curve by specifying a step for the # x_range yields expected results, but increases rendering time. curve_3 = ax_3.plot( log_func, x_range=(0.001, 6, 0.001), color=PURE_GREEN, use_vectorized=use_vectorized, ) curves = VGroup(curve_1, curve_2, curve_3) scene.add(axes, curves) @frames_comparison def test_get_graph_label(scene): ax = Axes() sin = ax.plot(lambda x: np.sin(x), color=PURPLE_B) label = ax.get_graph_label( graph=sin, label=MathTex(r"\frac{\pi}{2}"), x_val=PI / 2, dot=True, dot_config={"radius": 0.04}, direction=UR, ) scene.add(ax, sin, label) @frames_comparison def test_get_lines_to_point(scene): ax = Axes() circ = Circle(radius=0.5).move_to([-4, -1.5, 0]) lines_1 = ax.get_lines_to_point(circ.get_right(), color=GREEN_B) lines_2 = ax.get_lines_to_point(circ.get_corner(DL), color=BLUE_B) scene.add(ax, lines_1, lines_2, circ) @frames_comparison def test_plot_line_graph(scene): plane = NumberPlane( x_range=(0, 7), y_range=(0, 5), x_length=7, axis_config={"include_numbers": True}, ) line_graph = plane.plot_line_graph( x_values=[0, 1.5, 2, 2.8, 4, 6.25], y_values=[1, 3, 2.25, 4, 2.5, 1.75], line_color=GOLD_E, vertex_dot_style={"stroke_width": 3, "fill_color": PURPLE}, vertex_dot_radius=0.04, stroke_width=4, ) # test that the line and dots can be accessed afterwards line_graph["line_graph"].set_stroke(width=2) line_graph["vertex_dots"].scale(2) scene.add(plane, line_graph) @frames_comparison def test_t_label(scene): # defines the axes and linear function axes = Axes(x_range=[-1, 10], y_range=[-1, 10], x_length=9, y_length=6) func = axes.plot(lambda x: x, color=BLUE) # creates the T_label t_label = axes.get_T_label(x_val=4, graph=func, label=Tex("$x$-value")) scene.add(axes, func, t_label) @frames_comparison def test_get_area(scene): ax = Axes().add_coordinates() curve1 = ax.plot( lambda x: 2 * np.sin(x), x_range=[-5, ax.x_range[1]], color=DARK_BLUE, ) curve2 = ax.plot(lambda x: (x + 4) ** 2 - 2, x_range=[-5, -2], color=RED) area1 = ax.get_area( curve1, x_range=(PI / 2, 3 * PI / 2), color=(GREEN_B, GREEN_D), opacity=1, ) area2 = ax.get_area( curve1, x_range=(-4.5, -2), color=(RED, YELLOW), opacity=0.2, bounded_graph=curve2, ) scene.add(ax, curve1, curve2, area1, area2) @frames_comparison def test_get_area_with_boundary_and_few_plot_points(scene): ax = Axes(x_range=[-2, 2], y_range=[-2, 2], color=WHITE) f1 = ax.plot(lambda t: t, [-1, 1, 0.5]) f2 = ax.plot(lambda t: 1, [-1, 1, 0.5]) a1 = ax.get_area(f1, [-1, 0.75], color=RED) a2 = ax.get_area(f1, [-0.75, 1], bounded_graph=f2, color=GREEN) scene.add(ax, f1, f2, a1, a2) @frames_comparison def test_get_riemann_rectangles(scene, use_vectorized): ax = Axes(y_range=[-2, 10]) quadratic = ax.plot(lambda x: 0.5 * x**2 - 0.5, use_vectorized=use_vectorized) # the rectangles are constructed from their top right corner. # passing an iterable to `color` produces
[-1, 0.75], color=RED) a2 = ax.get_area(f1, [-0.75, 1], bounded_graph=f2, color=GREEN) scene.add(ax, f1, f2, a1, a2) @frames_comparison def test_get_riemann_rectangles(scene, use_vectorized): ax = Axes(y_range=[-2, 10]) quadratic = ax.plot(lambda x: 0.5 * x**2 - 0.5, use_vectorized=use_vectorized) # the rectangles are constructed from their top right corner. # passing an iterable to `color` produces a gradient rects_right = ax.get_riemann_rectangles( quadratic, x_range=[-4, -3], dx=0.25, color=(TEAL, BLUE_B, DARK_BLUE), input_sample_type="right", ) # the colour of rectangles below the x-axis is inverted # due to show_signed_area rects_left = ax.get_riemann_rectangles( quadratic, x_range=[-1.5, 1.5], dx=0.15, color=YELLOW, ) bounding_line = ax.plot(lambda x: 1.5 * x, color=BLUE_B, x_range=[3.3, 6]) bounded_rects = ax.get_riemann_rectangles( bounding_line, bounded_graph=quadratic, dx=0.15, x_range=[4, 5], show_signed_area=False, color=(MAROON_A, RED_B, PURPLE_D), ) scene.add(ax, bounding_line, quadratic, rects_right, rects_left, bounded_rects) @frames_comparison(base_scene=ThreeDScene) def test_get_z_axis_label(scene): ax = ThreeDAxes() lab = ax.get_z_axis_label(Tex("$z$-label")) scene.set_camera_orientation(phi=2 * PI / 5, theta=PI / 5) scene.add(ax, lab) @frames_comparison def test_polar_graph(scene): polar = PolarPlane() def r(theta): return 4 * np.sin(theta * 4) polar_graph = polar.plot_polar_graph(r) scene.add(polar, polar_graph) @frames_comparison def test_log_scaling_graph(scene): ax = Axes( x_range=[0, 8], y_range=[-2, 4], x_length=10, y_axis_config={"scaling": LogBase()}, ) ax.add_coordinates() gr = ax.plot(lambda x: x, use_smoothing=False, x_range=[0.01, 8]) scene.add(ax, gr) ================================================ FILE: tests/test_graphical_units/test_banner.py ================================================ from __future__ import annotations from manim import ManimBanner from manim.utils.testing.frames_comparison import frames_comparison __module_test__ = "logo" @frames_comparison(last_frame=False) def test_banner(scene): banner = ManimBanner() scene.play(banner.create(), run_time=0.5) scene.play(banner.expand(), run_time=0.5) ================================================ FILE: tests/test_graphical_units/test_boolops.py ================================================ from __future__ import annotations from manim import ( BLUE, Circle, Difference, Exclusion, Intersection, Rectangle, Square, Triangle, Union, ) # not exported by default, so directly import from manim.utils.testing.frames_comparison import frames_comparison __module_test__ = "boolean_ops" @frames_comparison() def test_union(scene): a = Square() b = Circle().move_to([0.2, 0.2, 0.0]) c = Rectangle() un = Union(a, b, c).next_to(b) scene.add(a, b, c, un) @frames_comparison() def test_intersection(scene): a = Square() b = Circle().move_to([0.3, 0.3, 0.0]) i = Intersection(a, b).next_to(b) scene.add(a, b, i) @frames_comparison() def test_difference(scene): a = Square() b = Circle().move_to([0.2, 0.3, 0.0]) di = Difference(a, b).next_to(b) scene.add(a, b, di) @frames_comparison() def test_exclusion(scene): a = Square() b = Circle().move_to([0.3, 0.2, 0.0]) ex = Exclusion(a, b).next_to(a) scene.add(a, b, ex) @frames_comparison() def test_intersection_3_mobjects(scene): a = Square() b = Circle().move_to([0.2, 0.2, 0]) c = Triangle() i = Intersection(a, b, c, fill_opacity=0.5, color=BLUE) scene.add(a, b, c, i) ================================================ FILE: tests/test_graphical_units/test_brace.py ================================================ from __future__ import annotations from manim import * from manim.utils.testing.frames_comparison import frames_comparison __module_test__ = "brace" @frames_comparison def test_brace_sharpness(scene): line = Line(LEFT * 3, RIGHT * 3).shift(UP * 4) for sharpness in [0, 0.25, 0.5, 0.75, 1, 2, 3, 5]: scene.add(Brace(line, sharpness=sharpness)) line.shift(DOWN) scene.wait() @frames_comparison def test_braceTip(scene): line = Line().shift(LEFT * 3).rotate(PI / 2) steps = 8 for _i in range(steps): brace = Brace(line, direction=line.copy().rotate(PI / 2).get_unit_vector()) dot = Dot() brace.put_at_tip(dot) line.rotate_about_origin(TAU / steps) scene.add(brace, dot) scene.wait() @frames_comparison def test_arcBrace(scene): scene.play(Animation(ArcBrace())) ================================================ FILE: tests/test_graphical_units/test_composition.py ================================================ from __future__ import annotations from manim import * from manim.utils.testing.frames_comparison import frames_comparison __module_test__ = "composition" @frames_comparison def test_animationgroup_is_passing_remover_to_animations(scene): animation_group = AnimationGroup(Create(Square()), Write(Circle()), remover=True) scene.play(animation_group) scene.wait(0.1) @frames_comparison def test_animationgroup_is_passing_remover_to_nested_animationgroups(scene): animation_group = AnimationGroup( AnimationGroup(Create(Square()), Create(RegularPolygon(5))), Write(Circle(), remover=True), remover=True, ) scene.play(animation_group) scene.wait(0.1) ================================================ FILE: tests/test_graphical_units/test_coordinate_systems.py ================================================ from __future__ import annotations from manim import * from manim.utils.testing.frames_comparison import frames_comparison __module_test__ = "coordinate_system" @frames_comparison def test_number_plane(scene): plane = NumberPlane( x_range=[-4,
@frames_comparison def test_animationgroup_is_passing_remover_to_animations(scene): animation_group = AnimationGroup(Create(Square()), Write(Circle()), remover=True) scene.play(animation_group) scene.wait(0.1) @frames_comparison def test_animationgroup_is_passing_remover_to_nested_animationgroups(scene): animation_group = AnimationGroup( AnimationGroup(Create(Square()), Create(RegularPolygon(5))), Write(Circle(), remover=True), remover=True, ) scene.play(animation_group) scene.wait(0.1) ================================================ FILE: tests/test_graphical_units/test_coordinate_systems.py ================================================ from __future__ import annotations from manim import * from manim.utils.testing.frames_comparison import frames_comparison __module_test__ = "coordinate_system" @frames_comparison def test_number_plane(scene): plane = NumberPlane( x_range=[-4, 6, 1], axis_config={"include_numbers": True}, x_axis_config={"unit_size": 1.2}, y_range=[-2, 5], y_length=6, y_axis_config={"label_direction": UL}, ) scene.add(plane) @frames_comparison def test_line_graph(scene): plane = NumberPlane() first_line = plane.plot_line_graph( x_values=[-3, 1], y_values=[-2, 2], line_color=YELLOW, ) second_line = plane.plot_line_graph( x_values=[0, 2, 2, 4], y_values=[0, 0, 2, 4], line_color=RED, ) scene.add(plane, first_line, second_line) @frames_comparison(base_scene=ThreeDScene) def test_plot_surface(scene): axes = ThreeDAxes(x_range=(-5, 5, 1), y_range=(-5, 5, 1), z_range=(-5, 5, 1)) def param_trig(u, v): x = u y = v z = 2 * np.sin(x) + 2 * np.cos(y) return z trig_plane = axes.plot_surface( param_trig, u_range=(-5, 5), v_range=(-5, 5), color=BLUE, ) scene.add(axes, trig_plane) @frames_comparison(base_scene=ThreeDScene) def test_plot_surface_colorscale(scene): axes = ThreeDAxes(x_range=(-3, 3, 1), y_range=(-3, 3, 1), z_range=(-5, 5, 1)) def param_trig(u, v): x = u y = v z = 2 * np.sin(x) + 2 * np.cos(y) return z trig_plane = axes.plot_surface( param_trig, u_range=(-3, 3), v_range=(-3, 3), colorscale=[BLUE, GREEN, YELLOW, ORANGE, RED], ) scene.add(axes, trig_plane) @frames_comparison def test_implicit_graph(scene): ax = Axes() graph = ax.plot_implicit_curve(lambda x, y: x**2 + y**2 - 4) scene.add(ax, graph) @frames_comparison def test_plot_log_x_axis(scene): ax = Axes( x_range=[-1, 4], y_range=[0, 3], x_axis_config={"scaling": LogBase()}, ) graph = ax.plot(lambda x: 2 if x < 10 else 1, x_range=[-1, 4]) scene.add(ax, graph) @frames_comparison def test_plot_log_x_axis_vectorized(scene): ax = Axes( x_range=[-1, 4], y_range=[0, 3], x_axis_config={"scaling": LogBase()}, ) graph = ax.plot( lambda x: np.where(x < 10, 2, 1), x_range=[-1, 4], use_vectorized=True ) scene.add(ax, graph) @frames_comparison def test_number_plane_log(scene): """Test that NumberPlane generates its lines properly with a LogBase""" # y_axis log plane1 = ( NumberPlane( x_range=[0, 8, 1], y_range=[-2, 5], y_length=6, x_length=10, y_axis_config={"scaling": LogBase()}, ) .add_coordinates() .scale(1 / 2) ) # x_axis log plane2 = ( NumberPlane( x_range=[0, 8, 1], y_range=[-2, 5], y_length=6, x_length=10, x_axis_config={"scaling": LogBase()}, faded_line_ratio=4, ) .add_coordinates() .scale(1 / 2) ) scene.add(VGroup(plane1, plane2).arrange()) @frames_comparison def test_gradient_line_graph_x_axis(scene): """Test that using `colorscale` generates a line whose gradient matches the y-axis""" axes = Axes(x_range=[-3, 3], y_range=[-3, 3]) curve = axes.plot( lambda x: 0.1 * x**3, x_range=(-3, 3, 0.001), colorscale=[BLUE, GREEN, YELLOW, ORANGE, RED], colorscale_axis=0, ) scene.add(axes, curve) @frames_comparison def test_gradient_line_graph_y_axis(scene): """Test that using `colorscale` generates a line whose gradient matches the y-axis""" axes = Axes(x_range=[-3, 3], y_range=[-3, 3]) curve = axes.plot( lambda x: 0.1 * x**3, x_range=(-3, 3, 0.001), colorscale=[BLUE, GREEN, YELLOW, ORANGE, RED], colorscale_axis=1, ) scene.add(axes, curve) ================================================ FILE: tests/test_graphical_units/test_creation.py ================================================ from __future__ import annotations from manim import * from manim.utils.testing.frames_comparison import frames_comparison __module_test__ = "creation" @frames_comparison(last_frame=False) def test_create(scene): square = Square() scene.play(Create(square)) @frames_comparison(last_frame=False) def test_uncreate(scene): square = Square() scene.add(square) scene.play(Uncreate(square)) @frames_comparison(last_frame=False) def test_uncreate_rate_func(scene): square = Square() scene.add(square) scene.play(Uncreate(square), rate_func=linear) @frames_comparison(last_frame=False) def test_DrawBorderThenFill(scene): square = Square(fill_opacity=1) scene.play(DrawBorderThenFill(square)) # NOTE : Here should be the Write Test. But for some reasons it appears that this function is untestable (see issue #157) @frames_comparison(last_frame=False) def test_FadeOut(scene): square = Square() scene.add(square) scene.play(FadeOut(square)) @frames_comparison(last_frame=False) def test_FadeIn(scene): square = Square() scene.play(FadeIn(square)) @frames_comparison(last_frame=False) def test_GrowFromPoint(scene): square =
@frames_comparison(last_frame=False) def test_DrawBorderThenFill(scene): square = Square(fill_opacity=1) scene.play(DrawBorderThenFill(square)) # NOTE : Here should be the Write Test. But for some reasons it appears that this function is untestable (see issue #157) @frames_comparison(last_frame=False) def test_FadeOut(scene): square = Square() scene.add(square) scene.play(FadeOut(square)) @frames_comparison(last_frame=False) def test_FadeIn(scene): square = Square() scene.play(FadeIn(square)) @frames_comparison(last_frame=False) def test_GrowFromPoint(scene): square = Square() scene.play(GrowFromPoint(square, np.array((1, 1, 0)))) @frames_comparison(last_frame=False) def test_GrowFromCenter(scene): square = Square() scene.play(GrowFromCenter(square)) @frames_comparison(last_frame=False) def test_GrowFromEdge(scene): square = Square() scene.play(GrowFromEdge(square, DOWN)) @frames_comparison(last_frame=False) def test_SpinInFromNothing(scene): square = Square() scene.play(SpinInFromNothing(square)) @frames_comparison(last_frame=False) def test_ShrinkToCenter(scene): square = Square() scene.play(ShrinkToCenter(square)) @frames_comparison(last_frame=False) def test_bring_to_back_introducer(scene): a = Square(color=RED, fill_opacity=1) b = Square(color=BLUE, fill_opacity=1).shift(RIGHT) scene.add(a) scene.bring_to_back(b) scene.play(FadeIn(b)) scene.wait() @frames_comparison(last_frame=False) def test_z_index_introducer(scene): a = Circle().set_fill(color=RED, opacity=1.0) scene.add(a) b = Circle(arc_center=(0.5, 0.5, 0.0), color=GREEN, fill_opacity=1) b.set_z_index(-1) scene.play(Create(b)) scene.wait() @frames_comparison(last_frame=False) def test_SpiralIn(scene): circle = Circle().shift(LEFT) square = Square().shift(UP) shapes = VGroup(circle, square) scene.play(SpiralIn(shapes)) ================================================ FILE: tests/test_graphical_units/test_functions.py ================================================ from __future__ import annotations from manim import * from manim.utils.testing.frames_comparison import frames_comparison __module_test__ = "functions" @frames_comparison def test_FunctionGraph(scene): graph = FunctionGraph(lambda x: 2 * np.cos(0.5 * x), x_range=[-PI, PI], color=BLUE) scene.add(graph) @frames_comparison def test_ImplicitFunction(scene): graph = ImplicitFunction(lambda x, y: x**2 + y**2 - 9) scene.add(graph) ================================================ FILE: tests/test_graphical_units/test_geometry.py ================================================ from __future__ import annotations from manim import * from manim.utils.testing.frames_comparison import frames_comparison __module_test__ = "geometry" @frames_comparison(last_frame=True) def test_Coordinates(scene): dots = [Dot(np.array([x, y, 0])) for x in range(-7, 8) for y in range(-4, 5)] scene.add(VGroup(*dots)) @frames_comparison def test_Arc(scene): a = Arc(radius=1, start_angle=PI) scene.add(a) @frames_comparison def test_ArcBetweenPoints(scene): a = ArcBetweenPoints(np.array([1, 1, 0]), np.array([2, 2, 0])) scene.add(a) @frames_comparison def test_CurvedArrow(scene): a = CurvedArrow(np.array([1, 1, 0]), np.array([2, 2, 0])) scene.add(a) @frames_comparison def test_CustomDoubleArrow(scene): a = DoubleArrow( np.array([-1, -1, 0]), np.array([1, 1, 0]), tip_shape_start=ArrowCircleTip, tip_shape_end=ArrowSquareFilledTip, ) scene.add(a) @frames_comparison def test_Circle(scene): circle = Circle() scene.add(circle) @frames_comparison def test_CirclePoints(scene): circle = Circle.from_three_points(LEFT, LEFT + UP, UP * 2) scene.add(circle) @frames_comparison def test_Dot(scene): dot = Dot() scene.add(dot) @frames_comparison def test_DashedVMobject(scene): circle = DashedVMobject(Circle(), 12, 0.9, dash_offset=0.1) line = DashedLine(dash_length=0.5) scene.add(circle, line) @frames_comparison def test_AnnotationDot(scene): adot = AnnotationDot() scene.add(adot) @frames_comparison def test_Ellipse(scene): e = Ellipse() scene.add(e) @frames_comparison def test_Sector(scene): e = Sector() scene.add(e) @frames_comparison def test_Annulus(scene): a = Annulus() scene.add(a) @frames_comparison def test_AnnularSector(scene): a = AnnularSector() scene.add(a) @frames_comparison def test_Line(scene): a = Line(np.array([1, 1, 0]), np.array([2, 2, 0])) scene.add(a) @frames_comparison def test_Elbow(scene): a = Elbow() scene.add(a) @frames_comparison def test_DoubleArrow(scene): a = DoubleArrow() scene.add(a) @frames_comparison def test_Vector(scene): a = Vector(UP) scene.add(a) @frames_comparison def test_Polygon(scene): a = Polygon(*[np.array([1, 1, 0]), np.array([2, 2, 0]), np.array([2, 3, 0])]) scene.add(a) @frames_comparison def test_Rectangle(scene): a = Rectangle() scene.add(a) @frames_comparison def test_RoundedRectangle(scene): a = RoundedRectangle() scene.add(a) @frames_comparison def test_ConvexHull(scene): a = ConvexHull( *[ [-2.7, -0.6, 0], [0.2, -1.7, 0], [1.9, 1.2, 0], [-2.7, 0.9, 0], [1.6, 2.2, 0], ] ) scene.add(a) @frames_comparison def test_Arrange(scene): s1 = Square() s2 = Square() x = VGroup(s1, s2).set_x(0).arrange(buff=1.4) scene.add(x) @frames_comparison(last_frame=False) def test_ZIndex(scene): circle = Circle().set_fill(RED, opacity=1) square = Square(side_length=1.7).set_fill(BLUE, opacity=1) triangle = Triangle().set_fill(GREEN, opacity=1) square.z_index = 0 triangle.z_index = 1 circle.z_index = 2 scene.play(FadeIn(VGroup(circle, square, triangle))) scene.play(ApplyMethod(circle.shift, UP)) scene.play(ApplyMethod(triangle.shift, 2 * UP)) @frames_comparison def test_Angle(scene): l1 = Line(ORIGIN, RIGHT) l2 = Line(ORIGIN, UP) a = Angle(l1, l2) scene.add(a) @frames_comparison def test_three_points_Angle(scene): # acute angle acute =
square = Square(side_length=1.7).set_fill(BLUE, opacity=1) triangle = Triangle().set_fill(GREEN, opacity=1) square.z_index = 0 triangle.z_index = 1 circle.z_index = 2 scene.play(FadeIn(VGroup(circle, square, triangle))) scene.play(ApplyMethod(circle.shift, UP)) scene.play(ApplyMethod(triangle.shift, 2 * UP)) @frames_comparison def test_Angle(scene): l1 = Line(ORIGIN, RIGHT) l2 = Line(ORIGIN, UP) a = Angle(l1, l2) scene.add(a) @frames_comparison def test_three_points_Angle(scene): # acute angle acute = Angle.from_three_points( np.array([10, 0, 0]), np.array([0, 0, 0]), np.array([10, 10, 0]) ) # obtuse angle obtuse = Angle.from_three_points( np.array([-10, 1, 0]), np.array([0, 0, 0]), np.array([10, 1, 0]) ) # quadrant 1 angle q1 = Angle.from_three_points( np.array([10, 10, 0]), np.array([0, 0, 0]), np.array([10, 1, 0]) ) # quadrant 2 angle q2 = Angle.from_three_points( np.array([-10, 1, 0]), np.array([0, 0, 0]), np.array([-1, 10, 0]) ) # quadrant 3 angle q3 = Angle.from_three_points( np.array([-10, -1, 0]), np.array([0, 0, 0]), np.array([-1, -10, 0]) ) # quadrant 4 angle q4 = Angle.from_three_points( np.array([10, -1, 0]), np.array([0, 0, 0]), np.array([1, -10, 0]) ) scene.add(VGroup(acute, obtuse, q1, q2, q3, q4).arrange(RIGHT)) @frames_comparison def test_RightAngle(scene): l1 = Line(ORIGIN, RIGHT) l2 = Line(ORIGIN, UP) a = RightAngle(l1, l2) scene.add(a) @frames_comparison def test_Polygram(scene): hexagram = Polygram( [[0, 2, 0], [-np.sqrt(3), -1, 0], [np.sqrt(3), -1, 0]], [[-np.sqrt(3), 1, 0], [0, -2, 0], [np.sqrt(3), 1, 0]], ) scene.add(hexagram) @frames_comparison def test_RegularPolygram(scene): pentagram = RegularPolygram(5, radius=2) octagram = RegularPolygram(8, radius=2) scene.add(VGroup(pentagram, octagram).arrange(RIGHT)) @frames_comparison def test_Star(scene): star = Star(outer_radius=2) scene.add(star) @frames_comparison def test_AngledArrowTip(scene): arrow = Arrow(start=ORIGIN, end=UP + RIGHT + OUT) scene.add(arrow) @frames_comparison def test_CurvedArrowCustomTip(scene): arrow = CurvedArrow( LEFT, RIGHT, tip_shape=ArrowCircleTip, ) double_arrow = CurvedDoubleArrow( LEFT, RIGHT, tip_shape_start=ArrowCircleTip, tip_shape_end=ArrowSquareFilledTip, ) scene.add(arrow, double_arrow) @frames_comparison def test_LabeledLine(scene): line = LabeledLine( label="0.5", label_position=0.8, label_config={"font_size": 20}, start=LEFT + DOWN, end=RIGHT + UP, ) scene.add(line) @frames_comparison def test_LabeledArrow(scene): l_arrow = LabeledArrow( label="0.5", label_position=0.5, label_config={"font_size": 15}, start=LEFT * 3, end=RIGHT * 3 + UP * 2, ) scene.add(l_arrow) @frames_comparison def test_LabeledPolygram(scene): polygram = LabeledPolygram( [ [-2.5, -2.5, 0], [2.5, -2.5, 0], [2.5, 2.5, 0], [-2.5, 2.5, 0], [-2.5, -2.5, 0], ], [[-1, -1, 0], [0.5, -1, 0], [0.5, 0.5, 0], [-1, 0.5, 0], [-1, -1, 0]], [[1, 1, 0], [2, 1, 0], [2, 2, 0], [1, 2, 0], [1, 1, 0]], label="C", ) scene.add(polygram) ================================================ FILE: tests/test_graphical_units/test_img_and_svg.py ================================================ from __future__ import annotations from manim import * from manim.utils.testing.frames_comparison import frames_comparison from ..helpers.path_utils import get_svg_resource __module_test__ = "img_and_svg" # Tests break down into two kinds: one where the SVG is simple enough to step through # and ones where the SVG is realistically complex, and the output should be visually inspected. # First are the simple tests. @frames_comparison def test_Line(scene): line_demo = SVGMobject(get_svg_resource("line.svg")) scene.add(line_demo) scene.wait() @frames_comparison def test_CubicPath(scene): cubic_demo = SVGMobject(get_svg_resource("cubic_demo.svg")) scene.add(cubic_demo) scene.wait() @frames_comparison def test_CubicAndLineto(scene): cubic_lineto = SVGMobject(get_svg_resource("cubic_and_lineto.svg")) scene.add(cubic_lineto) scene.wait() @frames_comparison def test_Rhomboid(scene): rhomboid = SVGMobject(get_svg_resource("rhomboid.svg")).scale(0.5) rhomboid_fill = rhomboid.copy().set_fill(opacity=1).shift(UP * 2) rhomboid_no_fill = rhomboid.copy().set_fill(opacity=0).shift(DOWN * 2) scene.add(rhomboid, rhomboid_fill, rhomboid_no_fill) scene.wait() @frames_comparison def test_Inheritance(scene): three_arrows = SVGMobject(get_svg_resource("inheritance_test.svg")).scale(0.5) scene.add(three_arrows) scene.wait() @frames_comparison def test_MultiPartPath(scene): mpp = SVGMobject(get_svg_resource("multi_part_path.svg")) scene.add(mpp) scene.wait() @frames_comparison def test_QuadraticPath(scene): quad = SVGMobject(get_svg_resource("qcurve_demo.svg")) scene.add(quad) scene.wait() @frames_comparison def test_SmoothCurves(scene): smooths = SVGMobject(get_svg_resource("smooth_curves.svg")) scene.add(smooths) scene.wait() @frames_comparison def test_WatchTheDecimals(scene): def construct(scene): decimal = SVGMobject(get_svg_resource("watch_the_decimals.svg")) scene.add(decimal) scene.wait() @frames_comparison def test_UseTagInheritance(scene): aabbb = SVGMobject(get_svg_resource("aabbb.svg")) scene.add(aabbb) scene.wait() @frames_comparison def test_HalfEllipse(scene):
three_arrows = SVGMobject(get_svg_resource("inheritance_test.svg")).scale(0.5) scene.add(three_arrows) scene.wait() @frames_comparison def test_MultiPartPath(scene): mpp = SVGMobject(get_svg_resource("multi_part_path.svg")) scene.add(mpp) scene.wait() @frames_comparison def test_QuadraticPath(scene): quad = SVGMobject(get_svg_resource("qcurve_demo.svg")) scene.add(quad) scene.wait() @frames_comparison def test_SmoothCurves(scene): smooths = SVGMobject(get_svg_resource("smooth_curves.svg")) scene.add(smooths) scene.wait() @frames_comparison def test_WatchTheDecimals(scene): def construct(scene): decimal = SVGMobject(get_svg_resource("watch_the_decimals.svg")) scene.add(decimal) scene.wait() @frames_comparison def test_UseTagInheritance(scene): aabbb = SVGMobject(get_svg_resource("aabbb.svg")) scene.add(aabbb) scene.wait() @frames_comparison def test_HalfEllipse(scene): half_ellipse = SVGMobject(get_svg_resource("half_ellipse.svg")) scene.add(half_ellipse) scene.wait() @frames_comparison def test_Heart(scene): heart = SVGMobject(get_svg_resource("heart.svg")) scene.add(heart) scene.wait() @frames_comparison def test_Arcs01(scene): # See: https://www.w3.org/TR/SVG11/images/paths/arcs01.svg arcs = SVGMobject(get_svg_resource("arcs01.svg")) scene.add(arcs) scene.wait() @frames_comparison(last_frame=False) def test_Arcs02(scene): # See: https://www.w3.org/TR/SVG11/images/paths/arcs02.svg arcs = SVGMobject(get_svg_resource("arcs02.svg")) scene.add(arcs) scene.wait() # Second are the visual tests - these are probably too complex to verify step-by-step, so # these are really more of a spot-check @frames_comparison(last_frame=False) def test_WeightSVG(scene): path = get_svg_resource("weight.svg") svg_obj = SVGMobject(path) scene.add(svg_obj) scene.wait() @frames_comparison def test_BrachistochroneCurve(scene): brach_curve = SVGMobject(get_svg_resource("curve.svg")) scene.add(brach_curve) scene.wait() @frames_comparison def test_DesmosGraph1(scene): dgraph = SVGMobject(get_svg_resource("desmos-graph_1.svg")).scale(3) scene.add(dgraph) scene.wait() @frames_comparison def test_Penrose(scene): penrose = SVGMobject(get_svg_resource("penrose.svg")) scene.add(penrose) scene.wait() @frames_comparison def test_ManimLogo(scene): background_rect = Rectangle(color=WHITE, fill_opacity=1).scale(2) manim_logo = SVGMobject(get_svg_resource("manim-logo-sidebar.svg")) scene.add(background_rect, manim_logo) scene.wait() @frames_comparison def test_UKFlag(scene): uk_flag = SVGMobject(get_svg_resource("united-kingdom.svg")) scene.add(uk_flag) scene.wait() @frames_comparison def test_SingleUSState(scene): single_state = SVGMobject(get_svg_resource("single_state.svg")) scene.add(single_state) scene.wait() @frames_comparison def test_ContiguousUSMap(scene): states = SVGMobject(get_svg_resource("states_map.svg")).scale(3) scene.add(states) scene.wait() @frames_comparison def test_PixelizedText(scene): background_rect = Rectangle(color=WHITE, fill_opacity=1).scale(2) rgb_svg = SVGMobject(get_svg_resource("pixelated_text.svg")) scene.add(background_rect, rgb_svg) scene.wait() @frames_comparison def test_VideoIcon(scene): video_icon = SVGMobject(get_svg_resource("video_icon.svg")) scene.add(video_icon) scene.wait() @frames_comparison def test_MultipleTransform(scene): svg_obj = SVGMobject(get_svg_resource("multiple_transforms.svg")) scene.add(svg_obj) scene.wait() @frames_comparison def test_MatrixTransform(scene): svg_obj = SVGMobject(get_svg_resource("matrix.svg")) scene.add(svg_obj) scene.wait() @frames_comparison def test_ScaleTransform(scene): svg_obj = SVGMobject(get_svg_resource("scale.svg")) scene.add(svg_obj) scene.wait() @frames_comparison def test_TranslateTransform(scene): svg_obj = SVGMobject(get_svg_resource("translate.svg")) scene.add(svg_obj) scene.wait() @frames_comparison def test_SkewXTransform(scene): svg_obj = SVGMobject(get_svg_resource("skewX.svg")) scene.add(svg_obj) scene.wait() @frames_comparison def test_SkewYTransform(scene): svg_obj = SVGMobject(get_svg_resource("skewY.svg")) scene.add(svg_obj) scene.wait() @frames_comparison def test_RotateTransform(scene): svg_obj = SVGMobject(get_svg_resource("rotate.svg")) scene.add(svg_obj) scene.wait() @frames_comparison def test_path_multiple_moves(scene): svg_obj = SVGMobject( get_svg_resource("path_multiple_moves.svg"), fill_color=WHITE, stroke_color=WHITE, stroke_width=3, ) scene.add(svg_obj) @frames_comparison def test_ImageMobject(scene): file_path = get_svg_resource("tree_img_640x351.png") im1 = ImageMobject(file_path).shift(4 * LEFT + UP) im2 = ImageMobject(file_path, scale_to_resolution=1080).shift(4 * LEFT + 2 * DOWN) im3 = ImageMobject(file_path, scale_to_resolution=540).shift(4 * RIGHT) scene.add(im1, im2, im3) scene.wait(1) @frames_comparison def test_ImageInterpolation(scene): img = ImageMobject( np.uint8([[63, 0, 0, 0], [0, 127, 0, 0], [0, 0, 191, 0], [0, 0, 0, 255]]), ) img.height = 2 img1 = img.copy() img2 = img.copy() img3 = img.copy() img4 = img.copy() img5 = img.copy() img1.set_resampling_algorithm(RESAMPLING_ALGORITHMS["nearest"]) img2.set_resampling_algorithm(RESAMPLING_ALGORITHMS["lanczos"]) img3.set_resampling_algorithm(RESAMPLING_ALGORITHMS["linear"]) img4.set_resampling_algorithm(RESAMPLING_ALGORITHMS["cubic"]) img5.set_resampling_algorithm(RESAMPLING_ALGORITHMS["box"]) scene.add(img1, img2, img3, img4, img5) [s.shift(4 * LEFT + pos * 2 * RIGHT) for pos, s in enumerate(scene.mobjects)] scene.wait() def test_ImageMobject_points_length(): file_path = get_svg_resource("tree_img_640x351.png") im1 = ImageMobject(file_path) assert len(im1.points) == 4 def test_ImageMobject_rotation(): # see https://github.com/ManimCommunity/manim/issues/3067 # rotating an image to and from the same angle should not change the image file_path = get_svg_resource("tree_img_640x351.png") im1 = ImageMobject(file_path) im2 = im1.copy() im1.rotate(PI / 2) im1.rotate(-PI / 2) np.testing.assert_array_equal(im1.points, im2.points) ================================================ FILE: tests/test_graphical_units/test_indication.py ================================================ from __future__ import annotations from manim import * from manim.utils.testing.frames_comparison import frames_comparison __module_test__ = "indication" @frames_comparison(last_frame=False) def test_FocusOn(scene): square = Square() scene.add(square) scene.play(FocusOn(square)) @frames_comparison(last_frame=False) def test_Indicate(scene): square = Square() scene.add(square) scene.play(Indicate(square)) @frames_comparison(last_frame=False) def test_Flash(scene): square = Square() scene.add(square) scene.play(Flash(ORIGIN)) @frames_comparison(last_frame=False) def test_Circumscribe(scene): square = Square() scene.add(square) scene.play(Circumscribe(square)) scene.wait() @frames_comparison(last_frame=False) def test_ShowPassingFlash(scene): square = Square() scene.add(square) scene.play(ShowPassingFlash(square.copy())) @frames_comparison(last_frame=False) def test_ApplyWave(scene): square = Square() scene.add(square) scene.play(ApplyWave(square)) @frames_comparison(last_frame=False) def test_Wiggle(scene): square = Square() scene.add(square) scene.play(Wiggle(square)) def test_Wiggle_custom_about_points(): square = Square() wiggle
Square() scene.add(square) scene.play(Indicate(square)) @frames_comparison(last_frame=False) def test_Flash(scene): square = Square() scene.add(square) scene.play(Flash(ORIGIN)) @frames_comparison(last_frame=False) def test_Circumscribe(scene): square = Square() scene.add(square) scene.play(Circumscribe(square)) scene.wait() @frames_comparison(last_frame=False) def test_ShowPassingFlash(scene): square = Square() scene.add(square) scene.play(ShowPassingFlash(square.copy())) @frames_comparison(last_frame=False) def test_ApplyWave(scene): square = Square() scene.add(square) scene.play(ApplyWave(square)) @frames_comparison(last_frame=False) def test_Wiggle(scene): square = Square() scene.add(square) scene.play(Wiggle(square)) def test_Wiggle_custom_about_points(): square = Square() wiggle = Wiggle( square, scale_about_point=[1.0, 2.0, 3.0], rotate_about_point=[4.0, 5.0, 6.0], ) assert np.all(wiggle.get_scale_about_point() == [1.0, 2.0, 3.0]) assert np.all(wiggle.get_rotate_about_point() == [4.0, 5.0, 6.0]) ================================================ FILE: tests/test_graphical_units/test_mobjects.py ================================================ from __future__ import annotations from manim import * from manim.utils.testing.frames_comparison import frames_comparison __module_test__ = "mobjects" @frames_comparison(base_scene=ThreeDScene) def test_PointCloudDot(scene): p = PointCloudDot() scene.add(p) @frames_comparison def test_become(scene): s = Rectangle(width=2, height=1, color=RED).shift(UP) d = Dot() s1 = s.copy().become(d, match_width=True).set_opacity(0.25).set_color(BLUE) s2 = ( s.copy() .become(d, match_height=True, match_center=True) .set_opacity(0.25) .set_color(GREEN) ) s3 = s.copy().become(d, stretch=True).set_opacity(0.25).set_color(YELLOW) scene.add(s, d, s1, s2, s3) @frames_comparison def test_become_no_color_linking(scene): a = Circle() b = Square() scene.add(a) scene.add(b) b.become(a) b.shift(1 * RIGHT) b.set_stroke(YELLOW, opacity=1) @frames_comparison def test_match_style(scene): square = Square(fill_color=[RED, GREEN], fill_opacity=1) circle = Circle() VGroup(square, circle).arrange() circle.match_style(square) scene.add(square, circle) @frames_comparison def test_vmobject_joint_types(scene): angled_line = VMobject(stroke_width=20, color=GREEN).set_points_as_corners( [ np.array([-2, 0, 0]), np.array([0, 0, 0]), np.array([-2, 1, 0]), ] ) lines = VGroup(*[angled_line.copy() for _ in range(len(LineJointType))]) for line, joint_type in zip(lines, LineJointType): line.joint_type = joint_type lines.arrange(RIGHT, buff=1) scene.add(lines) @frames_comparison def test_vmobject_cap_styles(scene): arcs = VGroup( *[ Arc( radius=1, start_angle=0, angle=TAU / 4, stroke_width=20, color=GREEN, cap_style=cap_style, ) for cap_style in CapStyleType ] ) arcs.arrange(RIGHT, buff=1) scene.add(arcs) ================================================ FILE: tests/test_graphical_units/test_modifier_methods.py ================================================ from __future__ import annotations from manim import * from manim.utils.testing.frames_comparison import frames_comparison __module_test__ = "modifier_methods" @frames_comparison def test_Gradient(scene): c = Circle(fill_opacity=1).set_color(color=[YELLOW, GREEN]) scene.add(c) @frames_comparison def test_GradientRotation(scene): c = Circle(fill_opacity=1).set_color(color=[YELLOW, GREEN]).rotate(PI) scene.add(c) ================================================ FILE: tests/test_graphical_units/test_movements.py ================================================ from __future__ import annotations from manim import * from manim.utils.testing.frames_comparison import frames_comparison __module_test__ = "movements" @frames_comparison(last_frame=False) def test_Homotopy(scene): def func(x, y, z, t): norm = np.linalg.norm([x, y]) tau = interpolate(5, -5, t) + norm / config["frame_x_radius"] alpha = sigmoid(tau) return [x, y + 0.5 * np.sin(2 * np.pi * alpha) - t * SMALL_BUFF / 2, z] square = Square() scene.play(Homotopy(func, square)) @frames_comparison(last_frame=False) def test_PhaseFlow(scene): square = Square() def func(t): return t * 0.5 * UP scene.play(PhaseFlow(func, square)) @frames_comparison(last_frame=False) def test_MoveAlongPath(scene): square = Square() dot = Dot() scene.play(MoveAlongPath(dot, square)) @frames_comparison(last_frame=False) def test_Rotate(scene): square = Square() scene.play(Rotate(square, PI)) @frames_comparison(last_frame=False) def test_MoveTo(scene): square = Square() scene.play(square.animate.move_to(np.array([1.0, 1.0, 0.0]))) @frames_comparison(last_frame=False) def test_Shift(scene): square = Square() scene.play(square.animate.shift(UP)) ================================================ FILE: tests/test_graphical_units/test_numbers.py ================================================ from __future__ import annotations from manim import * from manim.utils.testing.frames_comparison import frames_comparison __module_test__ = "numbers" @frames_comparison(last_frame=False) def test_set_value_with_updaters(scene): """Test that the position of the decimal updates properly""" decimal = DecimalNumber( 0, show_ellipsis=True, num_decimal_places=3, include_sign=True, ) square = Square().to_edge(UP) decimal.add_updater(lambda d: d.next_to(square, RIGHT)) decimal.add_updater(lambda d: d.set_value(square.get_center()[1])) scene.add(square, decimal) scene.play( square.animate.to_edge(DOWN), rate_func=there_and_back, ) ================================================ FILE: tests/test_graphical_units/test_opengl.py ================================================ from __future__ import annotations from manim import * from manim.renderer.opengl_renderer import OpenGLRenderer from manim.utils.testing.frames_comparison import frames_comparison __module_test__ = "opengl" @frames_comparison(renderer_class=OpenGLRenderer, renderer="opengl") def test_Circle(scene): circle = Circle().set_color(RED) scene.add(circle) scene.wait() @frames_comparison( renderer_class=OpenGLRenderer, renderer="opengl", ) def test_FixedMobjects3D(scene: Scene): scene.renderer.camera.set_euler_angles(phi=75 * DEGREES, theta=-45 * DEGREES) circ = Circle(fill_opacity=1).to_edge(LEFT) square = Square(fill_opacity=1).to_edge(RIGHT) triangle = Triangle(fill_opacity=1).to_corner(UR) [i.fix_orientation() for i in (circ, square)] triangle.fix_in_frame() ================================================ FILE: tests/test_graphical_units/test_polyhedra.py
import OpenGLRenderer from manim.utils.testing.frames_comparison import frames_comparison __module_test__ = "opengl" @frames_comparison(renderer_class=OpenGLRenderer, renderer="opengl") def test_Circle(scene): circle = Circle().set_color(RED) scene.add(circle) scene.wait() @frames_comparison( renderer_class=OpenGLRenderer, renderer="opengl", ) def test_FixedMobjects3D(scene: Scene): scene.renderer.camera.set_euler_angles(phi=75 * DEGREES, theta=-45 * DEGREES) circ = Circle(fill_opacity=1).to_edge(LEFT) square = Square(fill_opacity=1).to_edge(RIGHT) triangle = Triangle(fill_opacity=1).to_corner(UR) [i.fix_orientation() for i in (circ, square)] triangle.fix_in_frame() ================================================ FILE: tests/test_graphical_units/test_polyhedra.py ================================================ from __future__ import annotations from manim import * from manim.utils.testing.frames_comparison import frames_comparison __module_test__ = "polyhedra" @frames_comparison def test_Tetrahedron(scene): scene.add(Tetrahedron()) @frames_comparison def test_Octahedron(scene): scene.add(Octahedron()) @frames_comparison def test_Icosahedron(scene): scene.add(Icosahedron()) @frames_comparison def test_Dodecahedron(scene): scene.add(Dodecahedron()) @frames_comparison def test_ConvexHull3D(scene): a = ConvexHull3D( *[ [-2.7, -0.6, 3.5], [0.2, -1.7, -2.8], [1.9, 1.2, 0.7], [-2.7, 0.9, 1.9], [1.6, 2.2, -4.2], ] ) scene.add(a) ================================================ FILE: tests/test_graphical_units/test_probability.py ================================================ from manim.constants import LEFT from manim.mobject.graphing.probability import BarChart from manim.mobject.text.tex_mobject import MathTex from manim.utils.color import BLUE, GREEN, RED, WHITE, YELLOW from manim.utils.testing.frames_comparison import frames_comparison __module_test__ = "probability" @frames_comparison def test_default_chart(scene): pull_req = [54, 23, 47, 48, 40, 64, 112, 87] versions = [ "v0.1.0", "v0.1.1", "v0.2.0", "v0.3.0", "v0.4.0", "v0.5.0", "v0.6.0", "v0.7.0", ] chart = BarChart(pull_req, versions) scene.add(chart) @frames_comparison def test_get_bar_labels(scene): chart = BarChart(values=[10, 9, 8, 7, 6, 5, 4, 3, 2, 1], y_range=[0, 10, 1]) c_bar_lbls = chart.get_bar_labels( color=WHITE, label_constructor=MathTex, font_size=36 ) scene.add(chart, c_bar_lbls) @frames_comparison def test_label_constructor(scene): chart = BarChart( values=[25, 46, 50, 10], bar_names=[r"\alpha \beta \gamma", r"a+c", r"\sqrt{a \over b}", r"a^2+b^2"], y_length=5, x_length=5, bar_width=0.8, x_axis_config={"font_size": 36, "label_constructor": MathTex}, ) scene.add(chart) @frames_comparison def test_negative_values(scene): chart = BarChart( values=[-5, 40, -10, 20, -3], bar_names=["one", "two", "three", "four", "five"], y_range=[-20, 50, 10], ) c_bar_lbls = chart.get_bar_labels() scene.add(chart, c_bar_lbls) @frames_comparison def test_advanced_customization(scene): """Tests to make sure advanced customization can be done through :class:`~.BarChart`""" chart = BarChart(values=[10, 40, 10, 20], bar_names=["one", "two", "three", "four"]) c_x_lbls = chart.x_axis.labels c_x_lbls.set_color_by_gradient(GREEN, RED, YELLOW) c_y_nums = chart.y_axis.numbers c_y_nums.set_color_by_gradient(BLUE, WHITE).shift(LEFT) c_y_axis = chart.y_axis c_y_axis.ticks.set_color(YELLOW) c_bar_lbls = chart.get_bar_labels() scene.add(chart, c_bar_lbls) @frames_comparison def test_change_bar_values_some_vals(scene): chart = BarChart( values=[-10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10], y_range=[-10, 10, 2], y_axis_config={"font_size": 24}, ) scene.add(chart) chart.change_bar_values([-6, -4, -2]) scene.add(chart.get_bar_labels(font_size=24)) @frames_comparison def test_change_bar_values_negative(scene): chart = BarChart( values=[-10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10], y_range=[-10, 10, 2], y_axis_config={"font_size": 24}, ) scene.add(chart) chart.change_bar_values(list(reversed([-10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10]))) scene.add(chart.get_bar_labels(font_size=24)) ================================================ FILE: tests/test_graphical_units/test_specialized.py ================================================ from __future__ import annotations from manim import * from manim.utils.testing.frames_comparison import frames_comparison __module_test__ = "specialized" @frames_comparison(last_frame=False) def test_Broadcast(scene): circle = Circle() scene.play(Broadcast(circle)) ================================================ FILE: tests/test_graphical_units/test_speed.py ================================================ from __future__ import annotations from manim import * from manim.utils.testing.frames_comparison import frames_comparison __module_test__ = "speed" @frames_comparison(last_frame=False) def test_SpeedModifier(scene): a = Dot().shift(LEFT * 2 + 0.5 * UP) b = Dot().shift(LEFT * 2 + 0.5 * DOWN) c = Dot().shift(2 * RIGHT) ChangeSpeed.add_updater(c, lambda x, dt: x.rotate_about_origin(PI / 3.7 * dt)) scene.add(a, b, c) scene.play(ChangeSpeed(Wait(0.5), speedinfo={0.3: 1, 0.4: 0.1, 0.6: 0.1, 1: 1})) scene.play( ChangeSpeed( AnimationGroup( a.animate(run_time=0.5, rate_func=linear).shift(RIGHT * 4), b.animate(run_time=0.5, rate_func=rush_from).shift(RIGHT * 4), ), speedinfo={0.3: 1, 0.4: 0.1, 0.6: 0.1, 1: 1}, affects_speed_updaters=False, ), ) scene.play( ChangeSpeed( AnimationGroup( a.animate(run_time=0.5, rate_func=linear).shift(LEFT * 4), b.animate(run_time=0.5, rate_func=rush_into).shift(LEFT * 4), ), speedinfo={0.3: 1, 0.4: 0.1, 0.6: 0.1, 1: 1}, rate_func=there_and_back, ), ) ================================================ FILE: tests/test_graphical_units/test_tables.py ================================================ from __future__ import
a.animate(run_time=0.5, rate_func=linear).shift(RIGHT * 4), b.animate(run_time=0.5, rate_func=rush_from).shift(RIGHT * 4), ), speedinfo={0.3: 1, 0.4: 0.1, 0.6: 0.1, 1: 1}, affects_speed_updaters=False, ), ) scene.play( ChangeSpeed( AnimationGroup( a.animate(run_time=0.5, rate_func=linear).shift(LEFT * 4), b.animate(run_time=0.5, rate_func=rush_into).shift(LEFT * 4), ), speedinfo={0.3: 1, 0.4: 0.1, 0.6: 0.1, 1: 1}, rate_func=there_and_back, ), ) ================================================ FILE: tests/test_graphical_units/test_tables.py ================================================ from __future__ import annotations from manim import * from manim.utils.testing.frames_comparison import frames_comparison __module_test__ = "tables" @frames_comparison def test_Table(scene): t = Table( [["1", "2"], ["3", "4"]], row_labels=[Tex("R1"), Tex("R2")], col_labels=[Tex("C1"), Tex("C2")], top_left_entry=MathTex("TOP"), element_to_mobject=Tex, include_outer_lines=True, ) scene.add(t) @frames_comparison def test_MathTable(scene): t = MathTable([[1, 2], [3, 4]]) scene.add(t) @frames_comparison def test_MobjectTable(scene): a = Circle().scale(0.5) t = MobjectTable([[a.copy(), a.copy()], [a.copy(), a.copy()]]) scene.add(t) @frames_comparison def test_IntegerTable(scene): t = IntegerTable( np.arange(1, 21).reshape(5, 4), ) scene.add(t) @frames_comparison def test_DecimalTable(scene): t = DecimalTable( np.linspace(0, 0.9, 20).reshape(5, 4), ) scene.add(t) ================================================ FILE: tests/test_graphical_units/test_tex_mobject.py ================================================ from manim import * from manim.utils.testing.frames_comparison import frames_comparison __module_test__ = "tex_mobject" @frames_comparison def test_color_inheritance(scene): """Test that Text and MarkupText correctly inherit colour from their parent class. """ VMobject.set_default(color=RED) tex = Tex("test color inheritance") mathtex = MathTex("test color inheritance") vgr = VGroup(tex, mathtex).arrange() VMobject.set_default() scene.add(vgr) @frames_comparison def test_set_opacity_by_tex(scene): """Test that set_opacity_by_tex works correctly.""" tex = MathTex("f(x) = y", substrings_to_isolate=["f(x)"]) tex.set_opacity_by_tex("f(x)", 0.2, 0.5) scene.add(tex) def test_preserve_tex_color(): """Test that Tex preserves original tex colors.""" template = TexTemplate(preamble=r"\usepackage{xcolor}") Tex.set_default(tex_template=template) txt = Tex(r"\textcolor{red}{Hello} World") assert len(txt[0].submobjects) == 10 assert all(char.fill_color.to_hex() == "#FF0000" for char in txt[0][:5]) # "Hello" assert all( char.fill_color.to_hex() == WHITE.to_hex() for char in txt[0][-5:] ) # "World" txt = Tex(r"\textcolor{red}{Hello} World", color=BLUE) assert len(txt[0].submobjects) == 10 assert all(char.fill_color.to_hex() == "#FF0000" for char in txt[0][:5]) # "Hello" assert all( char.fill_color.to_hex() == BLUE.to_hex() for char in txt[0][-5:] ) # "World" Tex.set_default(color=GREEN) txt = Tex(r"\textcolor{red}{Hello} World") assert len(txt[0].submobjects) == 10 assert all(char.fill_color.to_hex() == "#FF0000" for char in txt[0][:5]) # "Hello" assert all( char.fill_color.to_hex() == GREEN.to_hex() for char in txt[0][-5:] ) # "World" Tex.set_default() ================================================ FILE: tests/test_graphical_units/test_text.py ================================================ from manim import RED, MarkupText, Text, VMobject __module_test__ = "text" def test_Text2Color(): txt = Text( "this is a text with spaces!", t2c={"spaces": RED}, stroke_width=1, disable_ligatures=True, ) assert len(txt.submobjects) == 29 assert all(char.fill_color.to_hex() == "#FFFFFF" for char in txt[:4]) # "this" assert all( char.fill_color.to_hex() == RED.to_hex() for char in txt[-7:-1] ) # "spaces" assert txt[-1].fill_color.to_hex() == "#FFFFFF" # "!" def test_text_color_inheritance(): """Test that Text and MarkupText correctly inherit colour from their parent class. """ VMobject.set_default(color=RED) # set both to a singular font so that the tests agree. text = Text("test_color_inheritance", font="Sans") markup_text = MarkupText("test_color_inheritance", font="Sans") assert all(char.fill_color.to_hex() == RED.to_hex() for char in text) assert all(char.fill_color.to_hex() == RED.to_hex() for char in markup_text) # reset the default color so that future tests aren't affected by this change. VMobject.set_default() ================================================ FILE: tests/test_graphical_units/test_threed.py ================================================ from __future__ import annotations from manim import * from manim.utils.testing.frames_comparison import frames_comparison __module_test__ = "threed" @frames_comparison(base_scene=ThreeDScene) def test_AddFixedInFrameMobjects(scene): scene.set_camera_orientation(phi=75 * DEGREES, theta=-45 * DEGREES) text = Tex("This is a 3D tex") scene.add_fixed_in_frame_mobjects(text) @frames_comparison(base_scene=ThreeDScene) def test_Cube(scene): scene.add(Cube()) @frames_comparison(base_scene=ThreeDScene) def test_Sphere(scene): scene.add(Sphere()) @frames_comparison(base_scene=ThreeDScene) def test_Dot3D(scene): scene.add(Dot3D()) @frames_comparison(base_scene=ThreeDScene) def test_Cone(scene): scene.add(Cone(resolution=16)) def test_Cone_get_start_and_get_end(): cone = Cone().shift(RIGHT).rotate(PI / 4, about_point=ORIGIN, about_edge=OUT) start = [0.70710678, 0.70710678, -1.0] end = [0.70710678, 0.70710678, 0.0] assert
scene.set_camera_orientation(phi=75 * DEGREES, theta=-45 * DEGREES) text = Tex("This is a 3D tex") scene.add_fixed_in_frame_mobjects(text) @frames_comparison(base_scene=ThreeDScene) def test_Cube(scene): scene.add(Cube()) @frames_comparison(base_scene=ThreeDScene) def test_Sphere(scene): scene.add(Sphere()) @frames_comparison(base_scene=ThreeDScene) def test_Dot3D(scene): scene.add(Dot3D()) @frames_comparison(base_scene=ThreeDScene) def test_Cone(scene): scene.add(Cone(resolution=16)) def test_Cone_get_start_and_get_end(): cone = Cone().shift(RIGHT).rotate(PI / 4, about_point=ORIGIN, about_edge=OUT) start = [0.70710678, 0.70710678, -1.0] end = [0.70710678, 0.70710678, 0.0] assert np.allclose(cone.get_start(), start, atol=0.01), ( "start points of Cone do not match" ) assert np.allclose(cone.get_end(), end, atol=0.01), ( "end points of Cone do not match" ) @frames_comparison(base_scene=ThreeDScene) def test_Cylinder(scene): scene.add(Cylinder()) @frames_comparison(base_scene=ThreeDScene) def test_Line3D(scene): line1 = Line3D(resolution=16).shift(LEFT * 2) line2 = Line3D(resolution=16).shift(RIGHT * 2) perp_line = Line3D.perpendicular_to(line1, UP + OUT, resolution=16) parallel_line = Line3D.parallel_to(line2, DOWN + IN, resolution=16) scene.add(line1, line2, perp_line, parallel_line) @frames_comparison(base_scene=ThreeDScene) def test_Arrow3D(scene): scene.add(Arrow3D(resolution=16)) @frames_comparison(base_scene=ThreeDScene) def test_Torus(scene): scene.add(Torus()) @frames_comparison(base_scene=ThreeDScene) def test_Axes(scene): scene.add(ThreeDAxes()) @frames_comparison(base_scene=ThreeDScene) def test_CameraMoveAxes(scene): """Tests camera movement to explore varied views of a static scene.""" axes = ThreeDAxes() scene.add(axes) scene.add(Dot([1, 2, 3])) scene.move_camera(phi=PI / 8, theta=-PI / 8, frame_center=[1, 2, 3], zoom=2) @frames_comparison(base_scene=ThreeDScene) def test_CameraMove(scene): cube = Cube() scene.add(cube) scene.move_camera(phi=PI / 4, theta=PI / 4, frame_center=[0, 0, -1], zoom=0.5) @frames_comparison(base_scene=ThreeDScene) def test_AmbientCameraMove(scene): cube = Cube() scene.begin_ambient_camera_rotation(rate=0.5) scene.add(cube) scene.wait() @frames_comparison(base_scene=ThreeDScene) def test_MovingVertices(scene): scene.set_camera_orientation(phi=75 * DEGREES, theta=30 * DEGREES) vertices = [1, 2, 3, 4] edges = [(1, 2), (2, 3), (3, 4), (1, 3), (1, 4)] g = Graph(vertices, edges) scene.add(g) scene.play( g[1].animate.move_to([1, 1, 1]), g[2].animate.move_to([-1, 1, 2]), g[3].animate.move_to([1, -1, -1]), g[4].animate.move_to([-1, -1, 0]), ) scene.wait() @frames_comparison(base_scene=ThreeDScene) def test_SurfaceColorscale(scene): resolution_fa = 16 scene.set_camera_orientation(phi=75 * DEGREES, theta=-30 * DEGREES) axes = ThreeDAxes(x_range=(-3, 3, 1), y_range=(-3, 3, 1), z_range=(-4, 4, 1)) def param_trig(u, v): x = u y = v z = y**2 / 2 - x**2 / 2 return z trig_plane = Surface( lambda x, y: axes.c2p(x, y, param_trig(x, y)), resolution=(resolution_fa, resolution_fa), v_range=[-3, 3], u_range=[-3, 3], ) trig_plane.set_fill_by_value( axes=axes, colorscale=[BLUE, GREEN, YELLOW, ORANGE, RED] ) scene.add(axes, trig_plane) @frames_comparison(base_scene=ThreeDScene) def test_Y_Direction(scene): resolution_fa = 16 scene.set_camera_orientation(phi=75 * DEGREES, theta=-120 * DEGREES) axes = ThreeDAxes(x_range=(0, 5, 1), y_range=(0, 5, 1), z_range=(-1, 1, 0.5)) def param_surface(u, v): x = u y = v z = np.sin(x) * np.cos(y) return z surface_plane = Surface( lambda u, v: axes.c2p(u, v, param_surface(u, v)), resolution=(resolution_fa, resolution_fa), v_range=[0, 5], u_range=[0, 5], ) surface_plane.set_style(fill_opacity=1) surface_plane.set_fill_by_value( axes=axes, colorscale=[(RED, -0.4), (YELLOW, 0), (GREEN, 0.4)], axis=1 ) scene.add(axes, surface_plane) def test_get_start_and_end_Arrow3d(): start, end = ORIGIN, np.array([2, 1, 0]) arrow = Arrow3D(start, end) assert np.allclose(arrow.get_start(), start, atol=0.01), ( "start points of Arrow3D do not match" ) assert np.allclose(arrow.get_end(), end, atol=0.01), ( "end points of Arrow3D do not match" ) ================================================ FILE: tests/test_graphical_units/test_transform.py ================================================ from __future__ import annotations from manim import * from manim.utils.testing.frames_comparison import frames_comparison __module_test__ = "transform" @frames_comparison(last_frame=False) def test_Transform(scene): square = Square() circle = Circle() scene.play(Transform(square, circle)) @frames_comparison(last_frame=False) def test_TransformFromCopy(scene): square = Square() circle = Circle() scene.play(TransformFromCopy(square, circle)) @frames_comparison(last_frame=False) def test_FullRotation(scene): s = VGroup(*(Square() for _ in range(4))).arrange() scene.play( Rotate(s[0], -2 * TAU), Rotate(s[1], -1 * TAU), Rotate(s[2], 1 * TAU), Rotate(s[3], 2 * TAU), ) @frames_comparison(last_frame=False) def test_ClockwiseTransform(scene): square = Square() circle = Circle() scene.play(ClockwiseTransform(square, circle)) @frames_comparison(last_frame=False) def test_CounterclockwiseTransform(scene): square = Square() circle = Circle() scene.play(CounterclockwiseTransform(square, circle)) @frames_comparison(last_frame=False) def test_MoveToTarget(scene): square =
VGroup(*(Square() for _ in range(4))).arrange() scene.play( Rotate(s[0], -2 * TAU), Rotate(s[1], -1 * TAU), Rotate(s[2], 1 * TAU), Rotate(s[3], 2 * TAU), ) @frames_comparison(last_frame=False) def test_ClockwiseTransform(scene): square = Square() circle = Circle() scene.play(ClockwiseTransform(square, circle)) @frames_comparison(last_frame=False) def test_CounterclockwiseTransform(scene): square = Square() circle = Circle() scene.play(CounterclockwiseTransform(square, circle)) @frames_comparison(last_frame=False) def test_MoveToTarget(scene): square = Square() square.generate_target() square.target.shift(3 * UP) scene.play(MoveToTarget(square)) @frames_comparison(last_frame=False) def test_ApplyPointwiseFunction(scene): square = Square() def func(p): return np.array([1.0, 1.0, 0.0]) scene.play(ApplyPointwiseFunction(func, square)) @frames_comparison(last_frame=False) def test_FadeToColort(scene): square = Square() scene.play(FadeToColor(square, RED)) @frames_comparison(last_frame=False) def test_ScaleInPlace(scene): square = Square() scene.play(ScaleInPlace(square, scale_factor=0.1)) @frames_comparison(last_frame=False) def test_ShrinkToCenter(scene): square = Square() scene.play(ShrinkToCenter(square)) @frames_comparison(last_frame=False) def test_Restore(scene): square = Square() circle = Circle() scene.play(Transform(square, circle)) square.save_state() scene.play(square.animate.shift(UP)) scene.play(Restore(square)) @frames_comparison def test_ApplyFunction(scene): square = Square() scene.add(square) def apply_function(mob): mob.scale(2) mob.to_corner(UR) mob.rotate(PI / 4) mob.set_color(RED) return mob scene.play(ApplyFunction(apply_function, square)) @frames_comparison(last_frame=False) def test_ApplyComplexFunction(scene): square = Square() scene.play( ApplyComplexFunction( lambda complex_num: complex_num + 2 * complex(0, 1), square, ), ) @frames_comparison(last_frame=False) def test_ApplyMatrix(scene): square = Square() matrice = [[1.0, 0.5], [1.0, 0.0]] about_point = np.asarray((-10.0, 5.0, 0.0)) scene.play(ApplyMatrix(matrice, square, about_point)) @frames_comparison(last_frame=False) def test_CyclicReplace(scene): square = Square() circle = Circle() circle.shift(3 * UP) scene.play(CyclicReplace(square, circle)) @frames_comparison(last_frame=False) def test_FadeInAndOut(scene): square = Square(color=BLUE).shift(2 * UP) annotation = Square(color=BLUE) scene.add(annotation) scene.play(FadeIn(square)) annotation.become(Square(color=RED).rotate(PI / 4)) scene.add(annotation) scene.play(FadeOut(square)) @frames_comparison def test_MatchPointsScene(scene): circ = Circle(fill_color=RED, fill_opacity=0.8) square = Square(fill_color=BLUE, fill_opacity=0.2) scene.play(circ.animate.match_points(square)) @frames_comparison(last_frame=False) def test_AnimationBuilder(scene): scene.play(Square().animate.shift(RIGHT).rotate(PI / 4)) @frames_comparison(last_frame=False) def test_ReplacementTransform(scene): yellow = Square(fill_opacity=1.0, fill_color=YELLOW) yellow.move_to([0, 0.75, 0]) green = Square(fill_opacity=1.0, fill_color=GREEN) green.move_to([-0.75, 0, 0]) blue = Square(fill_opacity=1.0, fill_color=BLUE) blue.move_to([0.75, 0, 0]) orange = Square(fill_opacity=1.0, fill_color=ORANGE) orange.move_to([0, -0.75, 0]) scene.add(yellow) scene.add(VGroup(green, blue)) scene.add(orange) purple = Circle(fill_opacity=1.0, fill_color=PURPLE) purple.move_to(green) scene.play(ReplacementTransform(green, purple)) # This pause is important to verify the purple circle remains behind # the blue and orange squares, and the blue square remains behind the # orange square after the transform fully completes. scene.pause() @frames_comparison(last_frame=False) def test_TransformWithPathFunc(scene): dots_start = VGroup(*[Dot(LEFT, color=BLUE), Dot(3 * RIGHT, color=RED)]) dots_end = VGroup(*[Dot(LEFT + 2 * DOWN, color=BLUE), Dot(2 * UP, color=RED)]) scene.play(Transform(dots_start, dots_end, path_func=clockwise_path())) @frames_comparison(last_frame=False) def test_TransformWithPathArcCenters(scene): dots_start = VGroup(*[Dot(LEFT, color=BLUE), Dot(3 * RIGHT, color=RED)]) dots_end = VGroup(*[Dot(LEFT + 2 * DOWN, color=BLUE), Dot(2 * UP, color=RED)]) scene.play( Transform( dots_start, dots_end, path_arc=2 * PI, path_arc_centers=ORIGIN, ) ) @frames_comparison(last_frame=False) def test_TransformWithConflictingPaths(scene): dots_start = VGroup(*[Dot(LEFT, color=BLUE), Dot(3 * RIGHT, color=RED)]) dots_end = VGroup(*[Dot(LEFT + 2 * DOWN, color=BLUE), Dot(2 * UP, color=RED)]) scene.play( Transform( dots_start, dots_end, path_func=clockwise_path(), path_arc=2 * PI, path_arc_centers=ORIGIN, ) ) @frames_comparison(last_frame=False) def test_FadeTransformPieces(scene): src = VGroup(Square(), Circle().shift(LEFT + UP)) src.shift(3 * LEFT) target = VGroup(Circle(), Triangle().shift(RIGHT + DOWN)) target.shift(3 * RIGHT) scene.add(src) scene.play(FadeTransformPieces(src, target)) @frames_comparison(last_frame=False) def test_FadeTransform(scene): src = Square(fill_opacity=1.0) src.shift(3 * LEFT) target = Circle(fill_opacity=1.0, color=ORANGE) target.shift(3 * RIGHT) scene.add(src) scene.play(FadeTransform(src, target)) @frames_comparison(last_frame=False) def test_FadeTransform_TargetIsEmpty_FadesOutInPlace(scene): # https://github.com/ManimCommunity/manim/issues/2845 src = Square(fill_opacity=1.0) src.shift(3 * LEFT) target = VGroup() target.shift(3 * RIGHT) scene.add(src) scene.play(FadeTransform(src, target)) ================================================ FILE: tests/test_graphical_units/test_transform_matching_parts.py ================================================ from __future__ import annotations from manim import * from manim.utils.testing.frames_comparison import frames_comparison __module_test__ = "transform_matching_parts" @frames_comparison(last_frame=True) def test_TransformMatchingLeavesOneObject(scene): square = Square() circle = Circle().shift(RIGHT) scene.add(square) scene.play(TransformMatchingShapes(square, circle)) assert len(scene.mobjects) == 1 assert isinstance(scene.mobjects[0], Circle) @frames_comparison(last_frame=False) def test_TransformMatchingDisplaysCorrect(scene): square = Square() circle = Circle().shift(RIGHT) scene.add(square) scene.play(TransformMatchingShapes(square, circle)) # Wait to
================================================ from __future__ import annotations from manim import * from manim.utils.testing.frames_comparison import frames_comparison __module_test__ = "transform_matching_parts" @frames_comparison(last_frame=True) def test_TransformMatchingLeavesOneObject(scene): square = Square() circle = Circle().shift(RIGHT) scene.add(square) scene.play(TransformMatchingShapes(square, circle)) assert len(scene.mobjects) == 1 assert isinstance(scene.mobjects[0], Circle) @frames_comparison(last_frame=False) def test_TransformMatchingDisplaysCorrect(scene): square = Square() circle = Circle().shift(RIGHT) scene.add(square) scene.play(TransformMatchingShapes(square, circle)) # Wait to make sure object isn't missing in-between animations scene.wait(0.5) # Shift to make sure object isn't duplicated if moved scene.play(circle.animate.shift(DOWN)) @frames_comparison(last_frame=False) def test_TransformMatchingTex(scene): start = MathTex("A", "+", "B", "=", "C") end = MathTex("C", "=", "B", "-", "A") scene.add(start) scene.play(TransformMatchingTex(start, end)) @frames_comparison(last_frame=False) def test_TransformMatchingTex_FadeTransformMismatches(scene): start = MathTex("A", "+", "B", "=", "C") end = MathTex("C", "=", "B", "-", "A") scene.add(start) scene.play(TransformMatchingTex(start, end, fade_transform_mismatches=True)) @frames_comparison(last_frame=False) def test_TransformMatchingTex_TransformMismatches(scene): start = MathTex("A", "+", "B", "=", "C") end = MathTex("C", "=", "B", "-", "A") scene.add(start) scene.play(TransformMatchingTex(start, end, transform_mismatches=True)) @frames_comparison(last_frame=False) def test_TransformMatchingTex_FadeTransformMismatches_NothingToFade(scene): # https://github.com/ManimCommunity/manim/issues/2845 start = MathTex("A", r"\to", "B") end = MathTex("B", r"\to", "A") scene.add(start) scene.play(TransformMatchingTex(start, end, fade_transform_mismatches=True)) ================================================ FILE: tests/test_graphical_units/test_updaters.py ================================================ from __future__ import annotations from manim import * from manim.utils.testing.frames_comparison import frames_comparison __module_test__ = "updaters" @frames_comparison(last_frame=False) def test_Updater(scene): dot = Dot() square = Square() scene.add(dot, square) square.add_updater(lambda m: m.next_to(dot, RIGHT, buff=SMALL_BUFF)) scene.add(square) scene.play(dot.animate.shift(UP * 2)) square.clear_updaters() @frames_comparison def test_ValueTracker(scene): theta = ValueTracker(PI / 2) line = Line(ORIGIN, RIGHT) line.rotate(theta.get_value(), about_point=ORIGIN) scene.add(line) @frames_comparison(last_frame=False) def test_UpdateSceneDuringAnimation(scene): def f(mob): scene.add(Square()) s = Circle().add_updater(f) scene.play(Create(s)) @frames_comparison(last_frame=False) def test_LastFrameWhenCleared(scene): dot = Dot() square = Square() square.add_updater(lambda m: m.move_to(dot, UL)) scene.add(square) scene.play(dot.animate.shift(UP * 2), rate_func=linear) square.clear_updaters() scene.wait() ================================================ FILE: tests/test_graphical_units/test_utils.py ================================================ from __future__ import annotations from manim.utils.testing.frames_comparison import frames_comparison __module_test__ = "utils" @frames_comparison def test_pixel_error_threshold(scene): """Scene produces black frame, control data has 11 modified pixel values.""" pass ================================================ FILE: tests/test_graphical_units/test_vector_scene.py ================================================ from __future__ import annotations from manim.scene.vector_space_scene import LinearTransformationScene, VectorScene from manim.utils.testing.frames_comparison import frames_comparison __module_test__ = "vector_scene" @frames_comparison(base_scene=VectorScene, last_frame=False) def test_vector_to_coords(scene): scene.add_plane().add_coordinates() vector = scene.add_vector([-3, -2]) basis = scene.get_basis_vectors() scene.add(basis) scene.vector_to_coords(vector=vector) scene.wait() def test_apply_matrix(): scene = LinearTransformationScene(include_background_plane=False) scene.setup() matrix = [[-1, 1], [1, 1]] # use short runtimes to speed up animation rendering scene.apply_matrix(matrix, run_time=0.01) scene.wait() scene.apply_inverse(matrix, run_time=0.01) ================================================ FILE: tests/test_graphical_units/control_data/boolean_ops/difference.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/boolean_ops/exclusion.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/boolean_ops/intersection.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/boolean_ops/intersection_3_mobjects.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/boolean_ops/union.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/brace/arcBrace.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/brace/brace_sharpness.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/brace/braceTip.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/composition/animationgroup_is_passing_remover_to_animations.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/composition/animationgroup_is_passing_remover_to_nested_animationgroups.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/coordinate_system/gradient_line_graph_x_axis.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/coordinate_system/gradient_line_graph_y_axis.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/coordinate_system/implicit_graph.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/coordinate_system/line_graph.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/coordinate_system/number_plane.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/coordinate_system/number_plane_log.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/coordinate_system/plot_log_x_axis.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/coordinate_system/plot_log_x_axis_vectorized.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/coordinate_systems/NumberPlaneTest.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/creation/bring_to_back_introducer.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/creation/create.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/creation/DrawBorderThenFill.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/creation/FadeIn.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/creation/FadeOut.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/creation/GrowFromCenter.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/creation/GrowFromEdge.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/creation/GrowFromPoint.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/creation/ShrinkToCenter.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/creation/SpinInFromNothing.npz ================================================ [Binary file]
[Binary file] ================================================ FILE: tests/test_graphical_units/control_data/creation/DrawBorderThenFill.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/creation/FadeIn.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/creation/FadeOut.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/creation/GrowFromCenter.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/creation/GrowFromEdge.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/creation/GrowFromPoint.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/creation/ShrinkToCenter.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/creation/SpinInFromNothing.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/creation/SpiralIn.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/creation/uncreate.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/creation/uncreate_rate_func.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/creation/z_index_introducer.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/functions/FunctionGraph.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/functions/ImplicitFunction.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/geometry/Angle.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/geometry/AngledArrowTip.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/geometry/AnnotationDot.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/geometry/AnnularSector.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/geometry/Annulus.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/geometry/Arc.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/geometry/ArcBetweenPoints.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/geometry/Arrange.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/geometry/Circle.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/geometry/CirclePoints.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/geometry/ConvexHull.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/geometry/Coordinates.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/geometry/CurvedArrow.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/geometry/CurvedArrowCustomTip.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/geometry/CustomDoubleArrow.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/geometry/DashedVMobject.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/geometry/DashedVMobjectTest.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/geometry/Dot.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/geometry/DoubleArrow.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/geometry/Elbow.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/geometry/Ellipse.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/geometry/LabeledArrow.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/geometry/LabeledLine.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/geometry/LabeledPolygram.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/geometry/Line.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/geometry/Polygon.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/geometry/Polygram.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/geometry/Rectangle.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/geometry/RegularPolygram.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/geometry/RightAngle.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/geometry/RoundedRectangle.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/geometry/Sector.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/geometry/Star.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/geometry/three_points_Angle.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/geometry/Vector.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/geometry/ZIndex.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/Arcs01.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/Arcs02.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/BrachistochroneCurve.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/ContiguousUSMap.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/CubicAndLineto.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/CubicPath.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/DesmosGraph1.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/HalfEllipse.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/Heart.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/ImageInterpolation.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/Inheritance.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/Line.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/ManimLogo.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/MatrixTransform.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/MultiPartPath.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/MultipleTransform.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/path_multiple_moves.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/Penrose.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/PixelizedText.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/QuadraticPath.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/Rhomboid.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/RotateTransform.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/ScaleTransform.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/SingleUSState.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/SkewXTransform.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/SkewYTransform.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/SmoothCurves.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/TranslateTransform.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/UKFlag.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/UseTagInheritance.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/VideoIcon.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/WatchTheDecimals.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/WeightSVG.npz ================================================ [Binary file]
[Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/SkewYTransform.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/SmoothCurves.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/TranslateTransform.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/UKFlag.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/UseTagInheritance.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/VideoIcon.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/WatchTheDecimals.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/img_and_svg/WeightSVG.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/indication/ApplyWave.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/indication/Circumscribe.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/indication/Flash.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/indication/FocusOn.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/indication/Indicate.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/indication/ShowPassingFlash.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/indication/Wiggle.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/logo/banner.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/mobjects/become.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/mobjects/become_no_color_linking.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/mobjects/match_style.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/mobjects/PointCloudDot.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/mobjects/vmobject_cap_styles.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/mobjects/vmobject_joint_types.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/modifier_methods/Gradient.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/modifier_methods/GradientRotation.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/movements/Homotopy.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/movements/MoveAlongPath.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/movements/MoveTo.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/movements/PhaseFlow.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/movements/Rotate.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/movements/Shift.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/numbers/set_value_with_updaters.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/opengl/Circle.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/opengl/FixedMobjects3D.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/plot/axes.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/plot/axis_tip_custom_width_height.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/plot/axis_tip_default_width_height.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/plot/custom_coordinates.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/plot/get_area.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/plot/get_area_with_boundary_and_few_plot_points.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/plot/get_area_with_riemann_rectangles.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/plot/get_axis_labels.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/plot/get_graph_label.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/plot/get_lines_to_point.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/plot/get_riemann_rectangles_use_vectorized[False].npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/plot/get_riemann_rectangles_use_vectorized[True].npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/plot/get_x_axis_label.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/plot/get_y_axis_label.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/plot/get_z_axis_label.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/plot/log_scaling_graph.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/plot/plot_derivative_graph_use_vectorized[False].npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/plot/plot_derivative_graph_use_vectorized[True].npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/plot/plot_functions_use_vectorized[False].npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/plot/plot_functions_use_vectorized[True].npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/plot/plot_line_graph.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/plot/plot_use_vectorized[False].npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/plot/plot_use_vectorized[True].npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/plot/PlotFunctions.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/plot/t_label.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/polyhedra/ConvexHull3D.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/polyhedra/Dodecahedron.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/polyhedra/Icosahedron.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/polyhedra/Octahedron.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/polyhedra/Tetrahedron.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/probability/advanced_customization.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/probability/change_bar_values_negative.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/probability/change_bar_values_some_vals.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/probability/default_chart.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/probability/get_bar_labels.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/probability/label_constructor.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/probability/negative_values.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/specialized/Broadcast.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/speed/SpeedModifier.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/tables/DecimalTable.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/tables/IntegerTable.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/tables/MathTable.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/tables/MobjectTable.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/tables/Table.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/tex_mobject/color_inheritance.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/tex_mobject/set_opacity_by_tex.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/threed/AddFixedInFrameMobjects.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/threed/AmbientCameraMove.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/threed/Arrow3D.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/threed/Axes.npz ================================================ [Binary file]
[Binary file] ================================================ FILE: tests/test_graphical_units/control_data/tables/MobjectTable.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/tables/Table.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/tex_mobject/color_inheritance.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/tex_mobject/set_opacity_by_tex.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/threed/AddFixedInFrameMobjects.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/threed/AmbientCameraMove.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/threed/Arrow3D.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/threed/Axes.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/threed/CameraMove.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/threed/CameraMoveAxes.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/threed/Cone.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/threed/Cube.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/threed/Cylinder.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/threed/Dot3D.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/threed/Line3D.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/threed/MovingVertices.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/threed/Sphere.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/transform/AnimationBuilder.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/transform/ApplyComplexFunction.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/transform/ApplyFunction.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/transform/ApplyMatrix.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/transform/ApplyPointwiseFunction.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/transform/ClockwiseTransform.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/transform/CounterclockwiseTransform.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/transform/CyclicReplace.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/transform/FadeInAndOut.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/transform/FadeToColort.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/transform/FadeTransform.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/transform/FadeTransform_TargetIsEmpty_FadesOutInPlace.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/transform/FadeTransformPieces.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/transform/FullRotation.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/transform/MatchPointsScene.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/transform/MoveToTarget.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/transform/ReplacementTransform.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/transform/Restore.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/transform/ScaleInPlace.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/transform/ShrinkToCenter.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/transform/Transform.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/transform/TransformFromCopy.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/transform/TransformWithConflictingPaths.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/transform/TransformWithPathArcCenters.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/transform/TransformWithPathFunc.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/transform_matching_parts/TransformMatchingDisplaysCorrect.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/transform_matching_parts/TransformMatchingLeavesOneObject.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/transform_matching_parts/TransformMatchingTex.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/transform_matching_parts/TransformMatchingTex_FadeTransformMismatches.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/transform_matching_parts/TransformMatchingTex_FadeTransformMismatches_NothingToFade.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/transform_matching_parts/TransformMatchingTex_TransformMismatches.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/updaters/LastFrameWhenCleared.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/updaters/Updater.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/updaters/UpdateSceneDuringAnimation.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/updaters/ValueTracker.npz ================================================ [Binary file] ================================================ FILE: tests/test_graphical_units/control_data/utils/pixel_error_threshold.npz ================================================ [Binary file] ================================================ FILE: tests/test_logging/__init__.py ================================================ [Empty file] ================================================ FILE: tests/test_logging/bad_tex_scene.py ================================================ from manim import Scene, Tex, TexTemplate class BadTex(Scene): def construct(self): tex_template = TexTemplate(preamble=r"\usepackage{notapackage}") some_tex = r"\frac{1}{0}" my_tex = Tex(some_tex, tex_template=tex_template) self.add(my_tex) ================================================ FILE: tests/test_logging/basic_scenes_error.py ================================================ from __future__ import annotations from manim import * # This module is intended to raise an error. class Error(Scene): def construct(self): raise Exception("An error has occurred") ================================================ FILE: tests/test_logging/basic_scenes_square_to_circle.py ================================================ from __future__ import annotations from manim import * # This module is used in the CLI tests in tests_CLi.py. class SquareToCircle(Scene): def construct(self): self.play(Transform(Square(), Circle())) ================================================ FILE: tests/test_logging/basic_scenes_write_stuff.py ================================================ from __future__ import annotations from manim import * # This module is used in the CLI tests in tests_CLi.py. class WriteStuff(Scene): def construct(self): example_text = Tex("This is a some text", tex_to_color_map={"text": YELLOW}) example_tex = MathTex( "\\sum_{k=1}^\\infty {1 \\over k^2} = {\\pi^2 \\over 6}", ) group = VGroup(example_text, example_tex) group.arrange(DOWN) group.width = config["frame_width"] - 2 * LARGE_BUFF self.play(Write(example_text)) ================================================ FILE: tests/test_logging/test_logging.py ================================================ from __future__ import annotations from pathlib import Path from manim import capture from ..utils.logging_tester import * @logs_comparison( "BasicSceneLoggingTest.txt", "logs/basic_scenes_square_to_circle_SquareToCircle.log", ) def test_logging_to_file(tmp_path, python_version): path_basic_scene =
{1 \\over k^2} = {\\pi^2 \\over 6}", ) group = VGroup(example_text, example_tex) group.arrange(DOWN) group.width = config["frame_width"] - 2 * LARGE_BUFF self.play(Write(example_text)) ================================================ FILE: tests/test_logging/test_logging.py ================================================ from __future__ import annotations from pathlib import Path from manim import capture from ..utils.logging_tester import * @logs_comparison( "BasicSceneLoggingTest.txt", "logs/basic_scenes_square_to_circle_SquareToCircle.log", ) def test_logging_to_file(tmp_path, python_version): path_basic_scene = Path("tests/test_logging/basic_scenes_square_to_circle.py") command = [ python_version, "-m", "manim", "-ql", "-v", "DEBUG", "--log_to_file", "--media_dir", str(tmp_path), str(path_basic_scene), "SquareToCircle", ] _, err, exitcode = capture(command) assert exitcode == 0, err def test_error_logging(tmp_path, python_version): path_error_scene = Path("tests/test_logging/basic_scenes_error.py") command = [ python_version, "-m", "manim", "-ql", "--media_dir", str(tmp_path), str(path_error_scene), ] out, err, exitcode = capture(command) if err is None: err = out assert exitcode != 0 assert "Traceback (most recent call last)" in err @logs_comparison( "bad_tex_scene_BadTex.txt", "logs/bad_tex_scene_BadTex.log", ) def test_tex_error_logs(tmp_path, python_version): bad_tex_scene = Path("tests/test_logging/bad_tex_scene.py") command = [ python_version, "-m", "manim", "-ql", "--log_to_file", "-v", "INFO", "--media_dir", str(tmp_path), str(bad_tex_scene), "BadTex", ] _, err, exitcode = capture(command) assert exitcode != 0 assert len(err) > 0 ================================================ FILE: tests/test_plugins/__init__.py ================================================ [Empty file] ================================================ FILE: tests/test_plugins/simple_scenes.py ================================================ from __future__ import annotations from manim import * class SquareToCircle(Scene): def construct(self): square = Square() circle = Circle() self.play(Transform(square, circle)) ================================================ FILE: tests/test_plugins/test_plugins.py ================================================ from __future__ import annotations import random import string import textwrap from pathlib import Path import pytest from manim import capture plugin_pyproject_template = textwrap.dedent( """\ [project] name = "{plugin_name}" authors = [{name = "ManimCE Test Suite"},] version = "0.1.0" description = "A fantastic Manim plugin" requires-python = ">=3.9" [project.entry-points."manim.plugins"] "{plugin_name}" = "{plugin_entrypoint}" [build-system] requires = ["hatchling"] build-backend = "hatchling.build" """, ) plugin_init_template = textwrap.dedent( """\ from manim import * {all_dec} class {class_name}(VMobject): def __init__(self): super().__init__() dot1 = Dot(fill_color=GREEN).shift(LEFT) dot2 = Dot(fill_color=BLUE) dot3 = Dot(fill_color=RED).shift(RIGHT) self.dotgrid = VGroup(dot1, dot2, dot3) self.add(self.dotgrid) def update_dot(self): self.dotgrid.become(self.dotgrid.shift(UP)) def {function_name}(): return [{class_name}] """, ) cfg_file_contents = textwrap.dedent( """\ [CLI] plugins = {plugin_name} """, ) @pytest.fixture def simple_scenes_path(): return Path(__file__).parent / "simple_scenes.py" def cfg_file_create(cfg_file_contents, path): file_loc = (path / "manim.cfg").absolute() file_loc.write_text(cfg_file_contents) return file_loc @pytest.fixture def random_string(): all_letters = string.ascii_lowercase a = random.Random() final_letters = [a.choice(all_letters) for _ in range(8)] return "".join(final_letters) def test_plugin_warning(tmp_path, python_version, simple_scenes_path): cfg_file = cfg_file_create( cfg_file_contents.format(plugin_name="DNEplugin"), tmp_path, ) scene_name = "SquareToCircle" command = [ python_version, "-m", "manim", "-ql", "--media_dir", str(cfg_file.parent), "--config_file", str(cfg_file), str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command, cwd=str(cfg_file.parent)) assert exit_code == 0, err assert "Missing Plugins" in out, "Missing Plugins isn't in Output." @pytest.fixture def create_plugin(tmp_path, python_version, random_string): plugin_dir = tmp_path / "plugin_dir" plugin_name = random_string def _create_plugin(entry_point, class_name, function_name, all_dec=""): entry_point = entry_point.format(plugin_name=plugin_name) module_dir = plugin_dir / plugin_name module_dir.mkdir(parents=True) (module_dir / "__init__.py").write_text( plugin_init_template.format( class_name=class_name, function_name=function_name, all_dec=all_dec, ), ) (plugin_dir / "pyproject.toml").write_text( plugin_pyproject_template.format( plugin_name=plugin_name, plugin_entrypoint=entry_point, ), ) command = [ python_version, "-m", "pip", "install", str(plugin_dir.absolute()), ] out, err, exit_code = capture(command, cwd=str(plugin_dir)) print(out) assert exit_code == 0, err return { "module_dir": module_dir, "plugin_name": plugin_name, } yield _create_plugin command = [python_version, "-m", "pip", "uninstall", plugin_name, "-y"] out, err, exit_code = capture(command) print(out) assert exit_code == 0, err ================================================ FILE: tests/test_scene_rendering/__init__.py ================================================ [Empty file] ================================================ FILE: tests/test_scene_rendering/conftest.py ================================================ from __future__ import annotations from pathlib import Path import pytest @pytest.fixture def manim_cfg_file(): return Path(__file__).parent /
"plugin_name": plugin_name, } yield _create_plugin command = [python_version, "-m", "pip", "uninstall", plugin_name, "-y"] out, err, exit_code = capture(command) print(out) assert exit_code == 0, err ================================================ FILE: tests/test_scene_rendering/__init__.py ================================================ [Empty file] ================================================ FILE: tests/test_scene_rendering/conftest.py ================================================ from __future__ import annotations from pathlib import Path import pytest @pytest.fixture def manim_cfg_file(): return Path(__file__).parent / "manim.cfg" @pytest.fixture def simple_scenes_path(): return Path(__file__).parent / "simple_scenes.py" @pytest.fixture def standard_config(config): return config.digest_file(Path(__file__).parent.parent / "standard_config.cfg") @pytest.fixture def using_temp_config(tmpdir, standard_config): """Standard fixture that makes tests use a standard_config.cfg with a temp dir.""" standard_config.media_dir = tmpdir @pytest.fixture def using_temp_opengl_config(tmpdir, standard_config, using_opengl_renderer): """Standard fixture that makes tests use a standard_config.cfg with a temp dir.""" standard_config.media_dir = tmpdir @pytest.fixture def disabling_caching(config): config.disable_caching = True @pytest.fixture def infallible_scenes_path(): return Path(__file__).parent / "infallible_scenes.py" @pytest.fixture def force_window_config_write_to_movie(config): config.force_window = True config.write_to_movie = True @pytest.fixture def force_window_config_pngs(config): config.force_window = True config.format = "png" ================================================ FILE: tests/test_scene_rendering/infallible_scenes.py ================================================ from __future__ import annotations from manim import Scene, Square class Wait1(Scene): def construct(self): self.wait() class Wait2(Scene): def construct(self): self.add(Square()) class Wait3(Scene): def construct(self): self.wait(2) ================================================ FILE: tests/test_scene_rendering/simple_scenes.py ================================================ from __future__ import annotations from enum import Enum from manim import * __all__ = [ "SquareToCircle", "SceneWithMultipleCalls", "SceneWithMultipleWaitCalls", "NoAnimations", "SceneWithStaticWait", "SceneWithSceneUpdater", "SceneForFrozenFrameTests", "SceneWithNonStaticWait", "StaticScene", "InteractiveStaticScene", "SceneWithSections", "ElaborateSceneWithSections", ] class SquareToCircle(Scene): def construct(self): square = Square() circle = Circle() self.play(Transform(square, circle)) class SceneWithMultipleCalls(Scene): def construct(self): number = Integer(0) self.add(number) for _i in range(10): self.play(Animation(Square())) class SceneWithMultipleWaitCalls(Scene): def construct(self): self.play(Create(Square())) self.wait(1) self.play(Create(Square().shift(DOWN))) self.wait(1) self.play(Create(Square().shift(2 * DOWN))) self.wait(1) self.play(Create(Square().shift(3 * DOWN))) self.wait(1) class NoAnimations(Scene): def construct(self): dot = Dot().set_color(GREEN) self.add(dot) self.wait(0.1) class SceneWithStaticWait(Scene): def construct(self): self.add(Square()) self.wait() class SceneWithSceneUpdater(Scene): def construct(self): self.add(Square()) self.add_updater(lambda dt: 42) self.wait() class SceneForFrozenFrameTests(Scene): def construct(self): self.mobject_update_count = 0 self.scene_update_count = 0 def increment_mobject_update_count(mob, dt): self.mobject_update_count += 1 def increment_scene_update_count(dt): self.scene_update_count += 1 s = Square() s.add_updater(increment_mobject_update_count) self.add(s) self.add_updater(increment_scene_update_count) self.wait(frozen_frame=True) class SceneWithNonStaticWait(Scene): def construct(self): s = Square() # Non static wait are triggered by mobject with time based updaters. s.add_updater(lambda mob, dt: None) self.add(s) self.wait() class StaticScene(Scene): def construct(self): dot = Dot().set_color(GREEN) self.add(dot) class InteractiveStaticScene(Scene): def construct(self): dot = Dot().set_color(GREEN) self.add(dot) self.interactive_mode = True class SceneWithSections(Scene): def construct(self): # this would be defined in a third party application using the segmented video API class PresentationSectionType(str, Enum): # start, end, wait for continuation by user NORMAL = "presentation.normal" # start, end, immediately continue to next section SKIP = "presentation.skip" # start, end, restart, immediately continue to next section when continued by user LOOP = "presentation.loop" # start, end, restart, finish animation first when user continues COMPLETE_LOOP = "presentation.complete_loop" # this animation is part of the first, automatically created section self.wait() self.next_section() self.wait(2) self.next_section(name="test") self.wait() self.next_section( "Prepare For Unforeseen Consequences.", DefaultSectionType.NORMAL ) self.wait(2) self.next_section(section_type=PresentationSectionType.SKIP) self.wait() self.next_section( name="this section should be removed as it doesn't contain any animations" ) class ElaborateSceneWithSections(Scene): def construct(self): # the first automatically created section should be deleted <- it's empty self.next_section("create square") square = Square() self.play(FadeIn(square)) self.wait() self.next_section("transform to circle") circle = Circle() self.play(Transform(square, circle)) self.wait() # this section will be entirely skipped self.next_section("skipped animations section", skip_animations=True) circle = Circle() self.play(Transform(square, circle)) self.wait() self.next_section("fade out") self.play(FadeOut(square)) self.wait() ================================================ FILE: tests/test_scene_rendering/test_caching_related.py
first automatically created section should be deleted <- it's empty self.next_section("create square") square = Square() self.play(FadeIn(square)) self.wait() self.next_section("transform to circle") circle = Circle() self.play(Transform(square, circle)) self.wait() # this section will be entirely skipped self.next_section("skipped animations section", skip_animations=True) circle = Circle() self.play(Transform(square, circle)) self.wait() self.next_section("fade out") self.play(FadeOut(square)) self.wait() ================================================ FILE: tests/test_scene_rendering/test_caching_related.py ================================================ from __future__ import annotations import sys import pytest from manim import capture from ..utils.video_tester import * @pytest.mark.slow @video_comparison( "SceneWithMultipleWaitCallsWithNFlag.json", "videos/simple_scenes/480p15/SceneWithMultipleWaitCalls.mp4", ) def test_wait_skip(tmp_path, manim_cfg_file, simple_scenes_path): # Test for PR #468. Intended to test if wait calls are correctly skipped. scene_name = "SceneWithMultipleWaitCalls" command = [ sys.executable, "-m", "manim", "-ql", "--media_dir", str(tmp_path), "-n", "3", str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err @pytest.mark.slow @video_comparison( "SceneWithMultiplePlayCallsWithNFlag.json", "videos/simple_scenes/480p15/SceneWithMultipleCalls.mp4", ) def test_play_skip(tmp_path, manim_cfg_file, simple_scenes_path): # Intended to test if play calls are correctly skipped. scene_name = "SceneWithMultipleCalls" command = [ sys.executable, "-m", "manim", "-ql", "--media_dir", str(tmp_path), "-n", "3", str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err ================================================ FILE: tests/test_scene_rendering/test_cairo_renderer.py ================================================ from __future__ import annotations from unittest.mock import Mock, patch import pytest from manim import * from ..assert_utils import assert_file_exists from .simple_scenes import * def test_render(using_temp_config, disabling_caching): scene = SquareToCircle() renderer = scene.renderer renderer.update_frame = Mock(wraps=renderer.update_frame) renderer.add_frame = Mock(wraps=renderer.add_frame) scene.render() assert renderer.add_frame.call_count == config["frame_rate"] assert renderer.update_frame.call_count == config["frame_rate"] assert_file_exists(config["output_file"]) def test_skipping_status_with_from_to_and_up_to(using_temp_config, disabling_caching): """Test if skip_animations is well updated when -n flag is passed""" config.from_animation_number = 2 config.upto_animation_number = 6 class SceneWithMultipleCalls(Scene): def construct(self): number = Integer(0) self.add(number) for i in range(10): self.play(Animation(Square())) assert ((i >= 2) and (i <= 6)) or self.renderer.skip_animations SceneWithMultipleCalls().render() @pytest.mark.xfail(reason="caching issue") def test_when_animation_is_cached(using_temp_config): partial_movie_files = [] for _ in range(2): # Render several times to generate a cache. # In some edgy cases and on some OS, a same scene can produce # a (finite, generally 2) number of different hash. In this case, the scene wouldn't be detected as cached, making the test fail. scene = SquareToCircle() scene.render() partial_movie_files.append(scene.renderer.file_writer.partial_movie_files) scene = SquareToCircle() scene.update_to_time = Mock() scene.render() assert scene.renderer.file_writer.is_already_cached( scene.renderer.animations_hashes[0], ) # Check that the same partial movie files has been used (with he same hash). # As there might have been several hashes, a list is used. assert scene.renderer.file_writer.partial_movie_files in partial_movie_files # Check that manim correctly skipped the animation. scene.update_to_time.assert_called_once_with(1) # Check that the output video has been generated. assert_file_exists(config["output_file"]) def test_hash_logic_is_not_called_when_caching_is_disabled( using_temp_config, disabling_caching, ): with patch("manim.renderer.cairo_renderer.get_hash_from_play_call") as mocked: scene = SquareToCircle() scene.render() mocked.assert_not_called() assert_file_exists(config["output_file"]) def test_hash_logic_is_called_when_caching_is_enabled(using_temp_config): from manim.renderer.cairo_renderer import get_hash_from_play_call with patch( "manim.renderer.cairo_renderer.get_hash_from_play_call", wraps=get_hash_from_play_call, ) as mocked: scene = SquareToCircle() scene.render() mocked.assert_called_once() ================================================ FILE: tests/test_scene_rendering/test_cli_flags.py ================================================ from __future__ import annotations import sys import numpy as np import pytest from click.testing import CliRunner from PIL import Image from manim import capture, get_video_metadata from manim.__main__ import __version__, main from manim.utils.file_ops import add_version_before_extension from ..utils.video_tester import video_comparison @pytest.mark.slow @video_comparison( "SquareToCircleWithDefaultValues.json", "videos/simple_scenes/1080p60/SquareToCircle.mp4", ) def test_basic_scene_with_default_values(tmp_path, manim_cfg_file, simple_scenes_path): scene_name = "SquareToCircle" command = [ sys.executable, "-m", "manim", "--media_dir", str(tmp_path), str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err @pytest.mark.slow def test_resolution_flag(tmp_path, manim_cfg_file, simple_scenes_path): scene_name = "NoAnimations" # test different
import add_version_before_extension from ..utils.video_tester import video_comparison @pytest.mark.slow @video_comparison( "SquareToCircleWithDefaultValues.json", "videos/simple_scenes/1080p60/SquareToCircle.mp4", ) def test_basic_scene_with_default_values(tmp_path, manim_cfg_file, simple_scenes_path): scene_name = "SquareToCircle" command = [ sys.executable, "-m", "manim", "--media_dir", str(tmp_path), str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err @pytest.mark.slow def test_resolution_flag(tmp_path, manim_cfg_file, simple_scenes_path): scene_name = "NoAnimations" # test different separators resolutions = [ (720, 480, ";"), (1280, 720, ","), (1920, 1080, "-"), (2560, 1440, ";"), # (3840, 2160, ","), # (640, 480, "-"), # (800, 600, ";"), ] for width, height, separator in resolutions: command = [ sys.executable, "-m", "manim", "--media_dir", str(tmp_path), "--resolution", f"{width}{separator}{height}", str(simple_scenes_path), scene_name, ] _, err, exit_code = capture(command) assert exit_code == 0, err path = ( tmp_path / "videos" / "simple_scenes" / f"{height}p60" / f"{scene_name}.mp4" ) meta = get_video_metadata(path) assert (width, height) == (meta["width"], meta["height"]) @pytest.mark.slow @video_comparison( "SquareToCircleWithlFlag.json", "videos/simple_scenes/480p15/SquareToCircle.mp4", ) def test_basic_scene_l_flag(tmp_path, manim_cfg_file, simple_scenes_path): scene_name = "SquareToCircle" command = [ sys.executable, "-m", "manim", "-ql", "--media_dir", str(tmp_path), str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err @pytest.mark.slow @video_comparison( "SceneWithMultipleCallsWithNFlag.json", "videos/simple_scenes/480p15/SceneWithMultipleCalls.mp4", ) def test_n_flag(tmp_path, simple_scenes_path): scene_name = "SceneWithMultipleCalls" command = [ sys.executable, "-m", "manim", "-ql", "-n 3,6", "--media_dir", str(tmp_path), str(simple_scenes_path), scene_name, ] _, err, exit_code = capture(command) assert exit_code == 0, err @pytest.mark.slow def test_s_flag_no_animations(tmp_path, manim_cfg_file, simple_scenes_path): scene_name = "NoAnimations" command = [ sys.executable, "-m", "manim", "-ql", "-s", "--media_dir", str(tmp_path), str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err exists = (tmp_path / "videos").exists() assert not exists, "running manim with -s flag rendered a video" is_empty = not any((tmp_path / "images" / "simple_scenes").iterdir()) assert not is_empty, "running manim with -s flag did not render an image" @pytest.mark.slow def test_s_flag(tmp_path, manim_cfg_file, simple_scenes_path): scene_name = "SquareToCircle" command = [ sys.executable, "-m", "manim", "-ql", "-s", "--media_dir", str(tmp_path), str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err exists = (tmp_path / "videos").exists() assert not exists, "running manim with -s flag rendered a video" is_empty = not any((tmp_path / "images" / "simple_scenes").iterdir()) assert not is_empty, "running manim with -s flag did not render an image" @pytest.mark.slow def test_s_flag_opengl_renderer(tmp_path, manim_cfg_file, simple_scenes_path): scene_name = "SquareToCircle" command = [ sys.executable, "-m", "manim", "-ql", "-s", "--renderer", "opengl", "--media_dir", str(tmp_path), str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err exists = (tmp_path / "videos").exists() assert not exists, "running manim with -s flag rendered a video" is_empty = not any((tmp_path / "images" / "simple_scenes").iterdir()) assert not is_empty, "running manim with -s flag did not render an image" @pytest.mark.slow def test_r_flag(tmp_path, manim_cfg_file, simple_scenes_path): scene_name = "SquareToCircle" command = [ sys.executable, "-m", "manim", "-ql", "-s", "--media_dir", str(tmp_path), "-r", "200,100", str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err is_not_empty = any((tmp_path / "images").iterdir()) assert is_not_empty, "running manim with -s, -r flag did not render a file" filename = add_version_before_extension( tmp_path / "images" / "simple_scenes" / "SquareToCircle.png", ) assert np.asarray(Image.open(filename)).shape == (100, 200, 4) @pytest.mark.slow def test_a_flag(tmp_path, manim_cfg_file, infallible_scenes_path): command = [ sys.executable, "-m", "manim", "-ql", "--media_dir", str(tmp_path), "-a", str(infallible_scenes_path), ] _, err, exit_code = capture(command) assert exit_code == 0, err
flag did not render a file" filename = add_version_before_extension( tmp_path / "images" / "simple_scenes" / "SquareToCircle.png", ) assert np.asarray(Image.open(filename)).shape == (100, 200, 4) @pytest.mark.slow def test_a_flag(tmp_path, manim_cfg_file, infallible_scenes_path): command = [ sys.executable, "-m", "manim", "-ql", "--media_dir", str(tmp_path), "-a", str(infallible_scenes_path), ] _, err, exit_code = capture(command) assert exit_code == 0, err one_is_not_empty = ( tmp_path / "videos" / "infallible_scenes" / "480p15" / "Wait1.mp4" ).is_file() assert one_is_not_empty, "running manim with -a flag did not render the first scene" two_is_not_empty = ( tmp_path / "images" / "infallible_scenes" / f"Wait2_ManimCE_v{__version__}.png" ).is_file() assert two_is_not_empty, ( "running manim with -a flag did not render an image, possible leak of the config dictionary." ) three_is_not_empty = ( tmp_path / "videos" / "infallible_scenes" / "480p15" / "Wait3.mp4" ).is_file() assert three_is_not_empty, ( "running manim with -a flag did not render the second scene" ) @pytest.mark.slow def test_custom_folders(tmp_path, manim_cfg_file, simple_scenes_path): scene_name = "SquareToCircle" command = [ sys.executable, "-m", "manim", "-ql", "-s", "--media_dir", str(tmp_path), "--custom_folders", str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err exists = (tmp_path / "videos").exists() assert not exists, "--custom_folders produced a 'videos/' dir" exists = add_version_before_extension(tmp_path / "SquareToCircle.png").exists() assert exists, "--custom_folders did not produce the output file" @pytest.mark.slow def test_custom_output_name_gif(tmp_path, simple_scenes_path): scene_name = "SquareToCircle" custom_name = "custom_name" command = [ sys.executable, "-m", "manim", "-ql", "--media_dir", str(tmp_path), "--format=gif", "-o", custom_name, str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err wrong_gif_path = add_version_before_extension( tmp_path / "videos" / "simple_scenes" / "480p15" / f"{scene_name}.gif" ) assert not wrong_gif_path.exists(), ( "The gif file does not respect the custom name: " + custom_name + ".gif" ) unexpected_mp4_path = ( tmp_path / "videos" / "simple_scenes" / "480p15" / str(custom_name + ".mp4") ) assert not unexpected_mp4_path.exists(), "Found an unexpected mp4 file at " + str( unexpected_mp4_path ) expected_gif_path = ( tmp_path / "videos" / "simple_scenes" / "480p15" / str(custom_name + ".gif") ) assert expected_gif_path.exists(), "gif file not found at " + str(expected_gif_path) @pytest.mark.slow def test_custom_output_name_mp4(tmp_path, simple_scenes_path): scene_name = "SquareToCircle" custom_name = "custom_name" command = [ sys.executable, "-m", "manim", "-ql", "--media_dir", str(tmp_path), "-o", custom_name, str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err wrong_mp4_path = ( tmp_path / "videos" / "simple_scenes" / "480p15" / str(scene_name + ".mp4") ) assert not wrong_mp4_path.exists(), ( "The mp4 file does not respect the custom name: " + custom_name + ".mp4" ) unexpected_gif_path = add_version_before_extension( tmp_path / "videos" / "simple_scenes" / "480p15" / f"{custom_name}.gif" ) assert not unexpected_gif_path.exists(), "Found an unexpected gif file at " + str( unexpected_gif_path ) expected_mp4_path = ( tmp_path / "videos" / "simple_scenes" / "480p15" / str(custom_name + ".mp4") ) assert expected_mp4_path.exists(), "mp4 file not found at " + str(expected_mp4_path) @pytest.mark.slow def test_dash_as_filename(tmp_path): code = ( "class Test(Scene):\n" " def construct(self):\n" " self.add(Circle())\n" " self.wait()" ) command = [ "-ql", "-s", "--media_dir", str(tmp_path), "-", ] runner = CliRunner() result = runner.invoke(main, command, input=code) assert result.exit_code == 0 exists = add_version_before_extension( tmp_path / "images" / "-" / "Test.png", ).exists() assert exists, result.output @pytest.mark.slow def test_gif_format_output(tmp_path, manim_cfg_file, simple_scenes_path): """Test only gif created with manim version in file
) command = [ "-ql", "-s", "--media_dir", str(tmp_path), "-", ] runner = CliRunner() result = runner.invoke(main, command, input=code) assert result.exit_code == 0 exists = add_version_before_extension( tmp_path / "images" / "-" / "Test.png", ).exists() assert exists, result.output @pytest.mark.slow def test_gif_format_output(tmp_path, manim_cfg_file, simple_scenes_path): """Test only gif created with manim version in file name when --format gif is set""" scene_name = "SquareToCircle" command = [ sys.executable, "-m", "manim", "-ql", "--media_dir", str(tmp_path), "--format", "gif", str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err unexpected_mp4_path = ( tmp_path / "videos" / "simple_scenes" / "480p15" / "SquareToCircle.mp4" ) assert not unexpected_mp4_path.exists(), "unexpected mp4 file found at " + str( unexpected_mp4_path, ) expected_gif_path = add_version_before_extension( tmp_path / "videos" / "simple_scenes" / "480p15" / "SquareToCircle.gif" ) assert expected_gif_path.exists(), "gif file not found at " + str(expected_gif_path) @pytest.mark.slow def test_mp4_format_output(tmp_path, manim_cfg_file, simple_scenes_path): """Test only mp4 created without manim version in file name when --format mp4 is set""" scene_name = "SquareToCircle" command = [ sys.executable, "-m", "manim", "-ql", "--media_dir", str(tmp_path), "--format", "mp4", str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err unexpected_gif_path = add_version_before_extension( tmp_path / "videos" / "simple_scenes" / "480p15" / "SquareToCircle.gif" ) assert not unexpected_gif_path.exists(), "unexpected gif file found at " + str( unexpected_gif_path, ) expected_mp4_path = ( tmp_path / "videos" / "simple_scenes" / "480p15" / "SquareToCircle.mp4" ) assert expected_mp4_path.exists(), "expected mp4 file not found at " + str( expected_mp4_path, ) @pytest.mark.slow def test_videos_not_created_when_png_format_set( tmp_path, manim_cfg_file, simple_scenes_path, ): """Test mp4 and gifs are not created when --format png is set""" scene_name = "SquareToCircle" command = [ sys.executable, "-m", "manim", "-ql", "--media_dir", str(tmp_path), "--format", "png", str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err unexpected_gif_path = add_version_before_extension( tmp_path / "videos" / "simple_scenes" / "480p15" / "SquareToCircle.gif" ) assert not unexpected_gif_path.exists(), "unexpected gif file found at " + str( unexpected_gif_path, ) unexpected_mp4_path = ( tmp_path / "videos" / "simple_scenes" / "480p15" / "SquareToCircle.mp4" ) assert not unexpected_mp4_path.exists(), "expected mp4 file not found at " + str( unexpected_mp4_path, ) @pytest.mark.slow def test_images_are_created_when_png_format_set( tmp_path, manim_cfg_file, simple_scenes_path, ): """Test images are created in media directory when --format png is set""" scene_name = "SquareToCircle" command = [ sys.executable, "-m", "manim", "-ql", "--media_dir", str(tmp_path), "--format", "png", str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err expected_png_path = tmp_path / "images" / "simple_scenes" / "SquareToCircle0000.png" assert expected_png_path.exists(), "png file not found at " + str(expected_png_path) @pytest.mark.slow def test_images_are_created_when_png_format_set_for_opengl( tmp_path, manim_cfg_file, simple_scenes_path, ): """Test images are created in media directory when --format png is set for opengl""" scene_name = "SquareToCircle" command = [ sys.executable, "-m", "manim", "-ql", "--renderer", "opengl", "--media_dir", str(tmp_path), "--format", "png", str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err expected_png_path = tmp_path / "images" / "simple_scenes" / "SquareToCircle0000.png" assert expected_png_path.exists(), "png file not found at " + str(expected_png_path) @pytest.mark.slow def test_images_are_zero_padded_when_zero_pad_set( tmp_path, manim_cfg_file, simple_scenes_path, ): """Test images are zero padded when --format png and --zero_pad n are set""" scene_name = "SquareToCircle" command = [ sys.executable, "-m", "manim", "-ql", "--media_dir", str(tmp_path), "--format", "png", "--zero_pad", "3",
/ "simple_scenes" / "SquareToCircle0000.png" assert expected_png_path.exists(), "png file not found at " + str(expected_png_path) @pytest.mark.slow def test_images_are_zero_padded_when_zero_pad_set( tmp_path, manim_cfg_file, simple_scenes_path, ): """Test images are zero padded when --format png and --zero_pad n are set""" scene_name = "SquareToCircle" command = [ sys.executable, "-m", "manim", "-ql", "--media_dir", str(tmp_path), "--format", "png", "--zero_pad", "3", str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err unexpected_png_path = tmp_path / "images" / "simple_scenes" / "SquareToCircle0.png" assert not unexpected_png_path.exists(), "non zero padded png file found at " + str( unexpected_png_path, ) expected_png_path = tmp_path / "images" / "simple_scenes" / "SquareToCircle000.png" assert expected_png_path.exists(), "png file not found at " + str(expected_png_path) @pytest.mark.slow def test_images_are_zero_padded_when_zero_pad_set_for_opengl( tmp_path, manim_cfg_file, simple_scenes_path, ): """Test images are zero padded when --format png and --zero_pad n are set with the opengl renderer""" scene_name = "SquareToCircle" command = [ sys.executable, "-m", "manim", "-ql", "--renderer", "opengl", "--media_dir", str(tmp_path), "--format", "png", "--zero_pad", "3", str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err unexpected_png_path = tmp_path / "images" / "simple_scenes" / "SquareToCircle0.png" assert not unexpected_png_path.exists(), "non zero padded png file found at " + str( unexpected_png_path, ) expected_png_path = tmp_path / "images" / "simple_scenes" / "SquareToCircle000.png" assert expected_png_path.exists(), "png file not found at " + str(expected_png_path) @pytest.mark.slow def test_webm_format_output(tmp_path, manim_cfg_file, simple_scenes_path): """Test only webm created when --format webm is set""" scene_name = "SquareToCircle" command = [ sys.executable, "-m", "manim", "-ql", "--media_dir", str(tmp_path), "--format", "webm", str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err unexpected_mp4_path = ( tmp_path / "videos" / "simple_scenes" / "480p15" / "SquareToCircle.mp4" ) assert not unexpected_mp4_path.exists(), "unexpected mp4 file found at " + str( unexpected_mp4_path, ) expected_webm_path = ( tmp_path / "videos" / "simple_scenes" / "480p15" / "SquareToCircle.webm" ) assert expected_webm_path.exists(), "expected webm file not found at " + str( expected_webm_path, ) @pytest.mark.slow def test_default_format_output_for_transparent_flag( tmp_path, manim_cfg_file, simple_scenes_path, ): """Test .mov is created by default when transparent flag is set""" scene_name = "SquareToCircle" command = [ sys.executable, "-m", "manim", "-ql", "--media_dir", str(tmp_path), "-t", str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err unexpected_webm_path = ( tmp_path / "videos" / "simple_scenes" / "480p15" / "SquareToCircle.webm" ) assert not unexpected_webm_path.exists(), "unexpected webm file found at " + str( unexpected_webm_path, ) expected_mov_path = ( tmp_path / "videos" / "simple_scenes" / "480p15" / "SquareToCircle.mov" ) assert expected_mov_path.exists(), "expected .mov file not found at " + str( expected_mov_path, ) @pytest.mark.slow def test_mov_can_be_set_as_output_format(tmp_path, manim_cfg_file, simple_scenes_path): """Test .mov is created by when set using --format mov arg""" scene_name = "SquareToCircle" command = [ sys.executable, "-m", "manim", "-ql", "--media_dir", str(tmp_path), "--format", "mov", str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err unexpected_webm_path = ( tmp_path / "videos" / "simple_scenes" / "480p15" / "SquareToCircle.webm" ) assert not unexpected_webm_path.exists(), "unexpected webm file found at " + str( unexpected_webm_path, ) expected_mov_path = ( tmp_path / "videos" / "simple_scenes" / "480p15" / "SquareToCircle.mov" ) assert expected_mov_path.exists(), "expected .mov file not found at " + str( expected_mov_path, ) @pytest.mark.slow @video_comparison( "InputFileViaCfg.json", "videos/simple_scenes/480p15/SquareToCircle.mp4", ) def test_input_file_via_cfg(tmp_path, manim_cfg_file, simple_scenes_path): scene_name = "SquareToCircle"
not unexpected_webm_path.exists(), "unexpected webm file found at " + str( unexpected_webm_path, ) expected_mov_path = ( tmp_path / "videos" / "simple_scenes" / "480p15" / "SquareToCircle.mov" ) assert expected_mov_path.exists(), "expected .mov file not found at " + str( expected_mov_path, ) @pytest.mark.slow @video_comparison( "InputFileViaCfg.json", "videos/simple_scenes/480p15/SquareToCircle.mp4", ) def test_input_file_via_cfg(tmp_path, manim_cfg_file, simple_scenes_path): scene_name = "SquareToCircle" (tmp_path / "manim.cfg").write_text( f""" [CLI] input_file = {simple_scenes_path} """ ) command = [ sys.executable, "-m", "manim", "-ql", "--media_dir", ".", str(tmp_path), scene_name, ] out, err, exit_code = capture(command, cwd=tmp_path) assert exit_code == 0, err @pytest.mark.slow def test_dry_run_via_config_file_no_output(tmp_path, simple_scenes_path): """Test that no file is created when dry_run is set to true in a config file.""" scene_name = "SquareToCircle" config_file = tmp_path / "test_config.cfg" config_file.write_text( """ [CLI] dry_run = true """ ) command = [ sys.executable, "-m", "manim", "--config_file", str(config_file), "--media_dir", str(tmp_path), str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err assert not (tmp_path / "videos").exists(), "videos folder was created in dry_run" assert not (tmp_path / "images").exists(), "images folder was created in dry_run" ================================================ FILE: tests/test_scene_rendering/test_file_writer.py ================================================ import sys from fractions import Fraction from pathlib import Path import av import numpy as np import pytest from manim import DR, Circle, Create, Scene, Star, tempconfig from manim.scene.scene_file_writer import to_av_frame_rate from manim.utils.commands import capture, get_video_metadata class StarScene(Scene): def construct(self): circle = Circle(fill_opacity=1, color="#ff0000") circle.to_corner(DR).shift(DR) self.add(circle) star = Star() self.play(Create(star)) click_path = ( Path(__file__).parent.parent.parent / "docs" / "source" / "_static" / "click.wav" ) self.add_sound(click_path) self.wait() @pytest.mark.slow @pytest.mark.parametrize( "transparent", [False, True], ) def test_gif_writing(config, tmp_path, transparent): output_filename = f"gif_{'transparent' if transparent else 'opaque'}" with tempconfig( { "media_dir": tmp_path, "quality": "low_quality", "format": "gif", "transparent": transparent, "output_file": output_filename, } ): StarScene().render() video_path = tmp_path / "videos" / "480p15" / f"{output_filename}.gif" assert video_path.exists() metadata = get_video_metadata(video_path) # reported duration + avg_frame_rate is slightly off for gifs del metadata["duration"], metadata["avg_frame_rate"] target_metadata = { "width": 854, "height": 480, "nb_frames": "30", "codec_name": "gif", "pix_fmt": "bgra", } assert metadata == target_metadata with av.open(video_path) as container: first_frame = next(container.decode(video=0)) frame_format = "argb" if transparent else "rgb24" first_frame = first_frame.to_ndarray(format=frame_format) target_rgba_corner = ( np.array([0, 255, 255, 255], dtype=np.uint8) if transparent else np.array([0, 0, 0], dtype=np.uint8) ) np.testing.assert_array_equal(first_frame[0, 0], target_rgba_corner) target_rgba_center = ( np.array([255, 255, 0, 0]) # components (A, R, G, B) if transparent else np.array([255, 0, 0], dtype=np.uint8) ) np.testing.assert_allclose(first_frame[-1, -1], target_rgba_center, atol=5) @pytest.mark.slow @pytest.mark.parametrize( ("format", "transparent", "codec", "pixel_format"), [ ("mp4", False, "h264", "yuv420p"), ("mov", False, "h264", "yuv420p"), ("mov", True, "qtrle", "argb"), ("webm", False, "vp9", "yuv420p"), ("webm", True, "vp9", "yuv420p"), ], ) def test_codecs(config, tmp_path, format, transparent, codec, pixel_format): output_filename = f"codec_{format}_{'transparent' if transparent else 'opaque'}" with tempconfig( { "media_dir": tmp_path, "quality": "low_quality", "format": format, "transparent": transparent, "output_file": output_filename, } ): StarScene().render() video_path = tmp_path / "videos" / "480p15" / f"{output_filename}.{format}" assert video_path.exists() metadata = get_video_metadata(video_path) target_metadata = { "width": 854, "height": 480, "nb_frames": "30", "duration": "2.000000", "avg_frame_rate": "15/1", "codec_name": codec, "pix_fmt": pixel_format, } assert metadata == target_metadata with av.open(video_path) as container: if transparent and format == "webm": from av.codec.context import CodecContext context = CodecContext.create("libvpx-vp9", "r") packet = next(container.demux(video=0)) first_frame = context.decode(packet)[0].to_ndarray(format="argb") else: first_frame = next(container.decode(video=0)).to_ndarray() has_samples = [ np.any(frame.to_ndarray()) for
"height": 480, "nb_frames": "30", "duration": "2.000000", "avg_frame_rate": "15/1", "codec_name": codec, "pix_fmt": pixel_format, } assert metadata == target_metadata with av.open(video_path) as container: if transparent and format == "webm": from av.codec.context import CodecContext context = CodecContext.create("libvpx-vp9", "r") packet = next(container.demux(video=0)) first_frame = context.decode(packet)[0].to_ndarray(format="argb") else: first_frame = next(container.decode(video=0)).to_ndarray() has_samples = [ np.any(frame.to_ndarray()) for frame in container.decode(audio=0) ] assert any(has_samples), "All audio samples are zero, this is not intended" target_rgba_corner = ( np.array([0, 0, 0, 0]) if transparent else np.array(16, dtype=np.uint8) ) np.testing.assert_array_equal(first_frame[0, 0], target_rgba_corner) target_rgba_center = ( np.array([255, 255, 0, 0]) # components (A, R, G, B) if transparent else np.array(240, dtype=np.uint8) ) np.testing.assert_allclose(first_frame[-1, -1], target_rgba_center, atol=5) def test_scene_with_non_raw_or_wav_audio(config, manim_caplog): class SceneWithMP3(Scene): def construct(self): file_path = Path(__file__).parent / "click.mp3" self.add_sound(file_path) self.wait() SceneWithMP3().render() assert "click.mp3 to .wav" in manim_caplog.text @pytest.mark.slow def test_unicode_partial_movie(config, tmpdir, simple_scenes_path): # Characters that failed for a user on Windows # due to its weird default encoding. unicode_str = "三角函数" scene_name = "SquareToCircle" command = [ sys.executable, "-m", nim", "--media_dir", str(tmpdir / unicode_str), str(simple_scenes_path), scene_name, ] _, err, exit_code = capture(command) assert exit_code == 0, err def test_frame_rates(): assert to_av_frame_rate(25) == Fraction(25, 1) assert to_av_frame_rate(24.0) == Fraction(24, 1) assert to_av_frame_rate(23.976) == Fraction(24 * 1000, 1001) assert to_av_frame_rate(23.98) == Fraction(24 * 1000, 1001) assert to_av_frame_rate(59.94) == Fraction(60 * 1000, 1001) ================================================ FILE: tests/test_scene_rendering/test_play_logic.py ================================================ from __future__ import annotations import sys from unittest.mock import Mock import pytest from manim import ( Dot, Mobject, Scene, ValueTracker, Wait, np, ) from .simple_scenes import ( SceneForFrozenFrameTests, SceneWithMultipleCalls, SceneWithNonStaticWait, SceneWithSceneUpdater, SceneWithStaticWait, SquareToCircle, ) @pytest.mark.parametrize("frame_rate", argvalues=[15, 30, 60]) def test_t_values(config, using_temp_config, disabling_caching, frame_rate): """Test that the framerate corresponds to the number of t values generated""" config.frame_rate = frame_rate scene = SquareToCircle() scene.update_to_time = Mock() scene.render() assert scene.update_to_time.call_count == config["frame_rate"] np.testing.assert_allclose( ([call.args[0] for call in scene.update_to_time.call_args_list]), np.arange(0, 1, 1 / config["frame_rate"]), ) @pytest.mark.skipif( sys.version_info < (3, 8), reason="Mock object has a different implementation in python 3.7, which makes it broken with this logic.", ) def test_t_values_with_skip_animations(using_temp_config, disabling_caching): """Test the behaviour of scene.skip_animations""" scene = SquareToCircle() scene.update_to_time = Mock() scene.renderer._original_skipping_status = True scene.render() assert scene.update_to_time.call_count == 1 np.testing.assert_almost_equal( scene.update_to_time.call_args.args[0], 1.0, ) def test_static_wait_detection(using_temp_config, disabling_caching): """Test if a static wait (wait that freeze the frame) is correctly detected""" scene = SceneWithStaticWait() scene.render() # Test is is_static_wait of the Wait animation has been set to True by compile_animation_ata assert scene.animations[0].is_static_wait assert scene.is_current_animation_frozen_frame() def test_non_static_wait_detection(using_temp_config, disabling_caching): scene = SceneWithNonStaticWait() scene.render() assert not scene.animations[0].is_static_wait assert not scene.is_current_animation_frozen_frame() scene = SceneWithSceneUpdater() scene.render() assert not scene.animations[0].is_static_wait assert not scene.is_current_animation_frozen_frame() def test_wait_with_stop_condition(using_temp_config, disabling_caching): class TestScene(Scene): def construct(self): self.wait_until(lambda: self.time >= 1) assert self.time >= 1 d = Dot() d.add_updater(lambda mobj, dt: self.add(Mobject())) self.add(d) self.play(Wait(run_time=5, stop_condition=lambda: len(self.mobjects) > 5)) assert len(self.mobjects) > 5 assert self.time < 2 scene = TestScene() scene.render() def test_frozen_frame(using_temp_config, disabling_caching): scene = SceneForFrozenFrameTests() scene.render() assert scene.mobject_update_count == 0 assert scene.scene_update_count == 0 def test_t_values_with_cached_data(using_temp_config): """Test the proper generation and use of the t values when an animation is cached.""" scene = SceneWithMultipleCalls() # Mocking the file_writer will skip all the writing process. scene.renderer.file_writer = Mock(scene.renderer.file_writer) scene.renderer.update_skipping_status = Mock() # Simulate that all animations are
assert scene.mobject_update_count == 0 assert scene.scene_update_count == 0 def test_t_values_with_cached_data(using_temp_config): """Test the proper generation and use of the t values when an animation is cached.""" scene = SceneWithMultipleCalls() # Mocking the file_writer will skip all the writing process. scene.renderer.file_writer = Mock(scene.renderer.file_writer) scene.renderer.update_skipping_status = Mock() # Simulate that all animations are cached. scene.renderer.file_writer.is_already_cached.return_value = True scene.update_to_time = Mock() scene.render() assert scene.update_to_time.call_count == 10 def test_t_values_save_last_frame(config, using_temp_config): """Test that there is only one t value handled when only saving the last frame""" config.save_last_frame = True scene = SquareToCircle() scene.update_to_time = Mock() scene.render() scene.update_to_time.assert_called_once_with(1) def test_animate_with_changed_custom_attribute(using_temp_config): """Test that animating the change of a custom attribute using the animate syntax works correctly. """ class CustomAnimateScene(Scene): def construct(self): vt = ValueTracker(0) vt.custom_attribute = "hello" self.play(vt.animate.set_value(42).set(custom_attribute="world")) assert vt.get_value() == 42 assert vt.custom_attribute == "world" CustomAnimateScene().render() ================================================ FILE: tests/test_scene_rendering/test_sections.py ================================================ from __future__ import annotations import sys import pytest from manim import capture from tests.assert_utils import assert_dir_exists, assert_dir_not_exists from ..utils.video_tester import video_comparison @pytest.mark.slow @video_comparison( "SceneWithDisabledSections.json", "videos/simple_scenes/480p15/SquareToCircle.mp4", ) def test_no_sections(tmp_path, manim_cfg_file, simple_scenes_path): scene_name = "SquareToCircle" command = [ sys.executable, "-m", "manim", "-ql", "--media_dir", str(tmp_path), str(simple_scenes_path), scene_name, ] _, err, exit_code = capture(command) assert exit_code == 0, err scene_dir = tmp_path / "videos" / "simple_scenes" / "480p15" assert_dir_exists(scene_dir) assert_dir_not_exists(scene_dir / "sections") @pytest.mark.slow @video_comparison( "SceneWithEnabledSections.json", "videos/simple_scenes/480p15/SquareToCircle.mp4", ) def test_sections(tmp_path, manim_cfg_file, simple_scenes_path): scene_name = "SquareToCircle" command = [ sys.executable, "-m", "manim", "-ql", "--save_sections", "--media_dir", str(tmp_path), str(simple_scenes_path), scene_name, ] _, err, exit_code = capture(command) assert exit_code == 0, err scene_dir = tmp_path / "videos" / "simple_scenes" / "480p15" assert_dir_exists(scene_dir) assert_dir_exists(scene_dir / "sections") @pytest.mark.slow @video_comparison( "SceneWithSections.json", "videos/simple_scenes/480p15/SceneWithSections.mp4", ) def test_many_sections(tmp_path, manim_cfg_file, simple_scenes_path): scene_name = "SceneWithSections" command = [ sys.executable, "-m", "manim", "-ql", "--save_sections", "--media_dir", str(tmp_path), str(simple_scenes_path), scene_name, ] _, err, exit_code = capture(command) assert exit_code == 0, err @pytest.mark.slow @video_comparison( "SceneWithSkipAnimations.json", "videos/simple_scenes/480p15/ElaborateSceneWithSections.mp4", ) def test_skip_animations(tmp_path, manim_cfg_file, simple_scenes_path): scene_name = "ElaborateSceneWithSections" command = [ sys.executable, "-m", "manim", "-ql", "--save_sections", "--media_dir", str(tmp_path), str(simple_scenes_path), scene_name, ] _, err, exit_code = capture(command) assert exit_code == 0, err ================================================ FILE: tests/test_scene_rendering/opengl/__init__.py ================================================ [Empty file] ================================================ FILE: tests/test_scene_rendering/opengl/test_caching_related_opengl.py ================================================ from __future__ import annotations import sys import pytest from manim import capture from ...utils.video_tester import video_comparison @pytest.mark.slow @video_comparison( "SceneWithMultipleWaitCallsWithNFlag.json", "videos/simple_scenes/480p15/SceneWithMultipleWaitCalls.mp4", ) def test_wait_skip(tmp_path, manim_cfg_file, simple_scenes_path): # Test for PR #468. Intended to test if wait calls are correctly skipped. scene_name = "SceneWithMultipleWaitCalls" command = [ sys.executable, "-m", "manim", "--renderer", "opengl", "--write_to_movie", "-ql", "--media_dir", str(tmp_path), "-n", "3", str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err @pytest.mark.slow @video_comparison( "SceneWithMultiplePlayCallsWithNFlag.json", "videos/simple_scenes/480p15/SceneWithMultipleCalls.mp4", ) def test_play_skip(tmp_path, manim_cfg_file, simple_scenes_path): # Intended to test if play calls are correctly skipped. scene_name = "SceneWithMultipleCalls" command = [ sys.executable, "-m", "manim", "--renderer", "opengl", "--write_to_movie", "-ql", "--media_dir", str(tmp_path), "-n", "3", str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err ================================================ FILE: tests/test_scene_rendering/opengl/test_cli_flags_opengl.py ================================================ from __future__ import annotations import sys import numpy as np import pytest from click.testing import CliRunner from PIL import Image from manim import capture, get_video_metadata from manim.__main__ import __version__, main from manim.utils.file_ops import add_version_before_extension from tests.utils.video_tester import video_comparison @pytest.mark.slow @video_comparison( "SquareToCircleWithDefaultValues.json", "videos/simple_scenes/1080p60/SquareToCircle.mp4", ) def test_basic_scene_with_default_values(tmp_path, manim_cfg_file, simple_scenes_path): scene_name =
================================================ from __future__ import annotations import sys import numpy as np import pytest from click.testing import CliRunner from PIL import Image from manim import capture, get_video_metadata from manim.__main__ import __version__, main from manim.utils.file_ops import add_version_before_extension from tests.utils.video_tester import video_comparison @pytest.mark.slow @video_comparison( "SquareToCircleWithDefaultValues.json", "videos/simple_scenes/1080p60/SquareToCircle.mp4", ) def test_basic_scene_with_default_values(tmp_path, manim_cfg_file, simple_scenes_path): scene_name = "SquareToCircle" command = [ sys.executable, "-m", "manim", "--renderer", "opengl", "--write_to_movie", "--media_dir", str(tmp_path), str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err @pytest.mark.slow def test_resolution_flag(tmp_path, manim_cfg_file, simple_scenes_path): scene_name = "NoAnimations" # test different separators resolutions = [ (720, 480, ";"), (1280, 720, ","), (1920, 1080, "-"), (2560, 1440, ";"), # (3840, 2160, ","), # (640, 480, "-"), # (800, 600, ";"), ] for width, height, separator in resolutions: command = [ sys.executable, "-m", "manim", "--media_dir", str(tmp_path), "--resolution", f"{width}{separator}{height}", str(simple_scenes_path), scene_name, ] _, err, exit_code = capture(command) assert exit_code == 0, err path = ( tmp_path / "videos" / "simple_scenes" / f"{height}p60" / f"{scene_name}.mp4" ) meta = get_video_metadata(path) assert (width, height) == (meta["width"], meta["height"]) @pytest.mark.slow @video_comparison( "SquareToCircleWithlFlag.json", "videos/simple_scenes/480p15/SquareToCircle.mp4", ) def test_basic_scene_l_flag(tmp_path, manim_cfg_file, simple_scenes_path): scene_name = "SquareToCircle" command = [ sys.executable, "-m", "manim", "--renderer", "opengl", "-ql", "--write_to_movie", "--media_dir", str(tmp_path), str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err @pytest.mark.slow @video_comparison( "SceneWithMultipleCallsWithNFlag.json", "videos/simple_scenes/480p15/SceneWithMultipleCalls.mp4", ) def test_n_flag(tmp_path, simple_scenes_path): scene_name = "SceneWithMultipleCalls" command = [ sys.executable, "-m", "manim", "-ql", "--renderer", "opengl", "--write_to_movie", "-n 3,6", "--media_dir", str(tmp_path), str(simple_scenes_path), scene_name, ] _, err, exit_code = capture(command) assert exit_code == 0, err @pytest.mark.slow def test_s_flag_no_animations(tmp_path, manim_cfg_file, simple_scenes_path): scene_name = "NoAnimations" command = [ sys.executable, "-m", "manim", "--renderer", "opengl", "-ql", "-s", "--media_dir", str(tmp_path), str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err exists = (tmp_path / "videos").exists() assert not exists, "running manim with -s flag rendered a video" is_empty = not any((tmp_path / "images" / "simple_scenes").iterdir()) assert not is_empty, "running manim with -s flag did not render an image" @pytest.mark.slow def test_image_output_for_static_scene(tmp_path, manim_cfg_file, simple_scenes_path): scene_name = "StaticScene" command = [ sys.executable, "-m", "manim", "--renderer", "opengl", "-ql", "--media_dir", str(tmp_path), str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err exists = (tmp_path / "videos").exists() assert not exists, "running manim with static scene rendered a video" is_empty = not any((tmp_path / "images" / "simple_scenes").iterdir()) assert not is_empty, "running manim without animations did not render an image" @pytest.mark.slow def test_no_image_output_with_interactive_embed( tmp_path, manim_cfg_file, simple_scenes_path ): """Check no image is output for a static scene when interactive embed is called""" scene_name = "InteractiveStaticScene" command = [ sys.executable, "-m", "manim", "--renderer", "opengl", "-ql", "--media_dir", str(tmp_path), str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err exists = (tmp_path / "videos").exists() assert not exists, "running manim with static scene rendered a video" is_empty = not any((tmp_path / "images" / "simple_scenes").iterdir()) assert is_empty, ( "running manim static scene with interactive embed rendered an image" ) @pytest.mark.slow def test_no_default_image_output_with_non_static_scene( tmp_path, manim_cfg_file, simple_scenes_path ): scene_name = "SceneWithNonStaticWait" command = [ sys.executable, "-m", "manim", "--renderer", "opengl", "-ql", "--media_dir", str(tmp_path), str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err exists
"simple_scenes").iterdir()) assert is_empty, ( "running manim static scene with interactive embed rendered an image" ) @pytest.mark.slow def test_no_default_image_output_with_non_static_scene( tmp_path, manim_cfg_file, simple_scenes_path ): scene_name = "SceneWithNonStaticWait" command = [ sys.executable, "-m", "manim", "--renderer", "opengl", "-ql", "--media_dir", str(tmp_path), str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err exists = (tmp_path / "videos").exists() assert not exists, "running manim with static scene rendered a video" is_empty = not any((tmp_path / "images" / "simple_scenes").iterdir()) assert is_empty, ( "running manim static scene with interactive embed rendered an image" ) @pytest.mark.slow def test_image_output_for_static_scene_with_write_to_movie( tmp_path, manim_cfg_file, simple_scenes_path ): scene_name = "StaticScene" command = [ sys.executable, "-m", "manim", "--write_to_movie", "--renderer", "opengl", "-ql", "--media_dir", str(tmp_path), str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err is_empty = not any((tmp_path / "videos").iterdir()) assert not is_empty, "running manim with static scene rendered a video" is_empty = not any((tmp_path / "images" / "simple_scenes").iterdir()) assert not is_empty, "running manim without animations did not render an image" @pytest.mark.slow def test_s_flag(tmp_path, manim_cfg_file, simple_scenes_path): scene_name = "SquareToCircle" command = [ sys.executable, "-m", "manim", "--renderer", "opengl", "-ql", "-s", "--media_dir", str(tmp_path), str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err exists = (tmp_path / "videos").exists() assert not exists, "running manim with -s flag rendered a video" is_empty = not any((tmp_path / "images" / "simple_scenes").iterdir()) assert not is_empty, "running manim with -s flag did not render an image" @pytest.mark.slow def test_r_flag(tmp_path, manim_cfg_file, simple_scenes_path): scene_name = "SquareToCircle" command = [ sys.executable, "-m", "manim", "--renderer", "opengl", "-ql", "-s", "--media_dir", str(tmp_path), "-r", "200,100", str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err is_not_empty = any((tmp_path / "images").iterdir()) assert is_not_empty, "running manim with -s, -r flag did not render a file" filename = add_version_before_extension( tmp_path / "images" / "simple_scenes" / "SquareToCircle.png", ) assert np.asarray(Image.open(filename)).shape == (100, 200, 4) @pytest.mark.slow def test_a_flag(tmp_path, manim_cfg_file, infallible_scenes_path): command = [ sys.executable, "-m", "manim", "--renderer", "opengl", "--write_to_movie", "-ql", "--media_dir", str(tmp_path), "-a", str(infallible_scenes_path), ] out, err, exit_code = capture(command) assert exit_code == 0, err one_is_not_empty = ( tmp_path / "videos" / "infallible_scenes" / "480p15" / "Wait1.mp4" ).is_file() assert one_is_not_empty, "running manim with -a flag did not render the first scene" two_is_not_empty = ( tmp_path / "images" / "infallible_scenes" / f"Wait2_ManimCE_v{__version__}.png" ).is_file() assert two_is_not_empty, ( "running manim with -a flag did not render an image, possible leak of the config dictionary" ) three_is_not_empty = ( tmp_path / "videos" / "infallible_scenes" / "480p15" / "Wait3.mp4" ).is_file() assert three_is_not_empty, ( "running manim with -a flag did not render the second scene" ) @pytest.mark.slow def test_custom_folders(tmp_path, manim_cfg_file, simple_scenes_path): scene_name = "SquareToCircle" command = [ sys.executable, "-m", "manim", "--renderer", "opengl", "-ql", "-s", "--media_dir", str(tmp_path), "--custom_folders", str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err exists = (tmp_path / "videos").exists() assert not exists, "--custom_folders produced a 'videos/' dir" exists = add_version_before_extension(tmp_path / "SquareToCircle.png").exists() assert exists, "--custom_folders did not produce the output file" @pytest.mark.slow def test_dash_as_filename(tmp_path): code = ( "class Test(Scene):\n" " def construct(self):\n" " self.add(Circle())\n" " self.wait()" ) command = [ "-ql", "--renderer", "opengl", "-s", "--media_dir", str(tmp_path),
(tmp_path / "videos").exists() assert not exists, "--custom_folders produced a 'videos/' dir" exists = add_version_before_extension(tmp_path / "SquareToCircle.png").exists() assert exists, "--custom_folders did not produce the output file" @pytest.mark.slow def test_dash_as_filename(tmp_path): code = ( "class Test(Scene):\n" " def construct(self):\n" " self.add(Circle())\n" " self.wait()" ) command = [ "-ql", "--renderer", "opengl", "-s", "--media_dir", str(tmp_path), "-", ] runner = CliRunner() result = runner.invoke(main, command, input=code) assert result.exit_code == 0 exists = add_version_before_extension( tmp_path / "images" / "-" / "Test.png", ).exists() assert exists, result.output @pytest.mark.slow def test_gif_format_output(tmp_path, manim_cfg_file, simple_scenes_path): """Test only gif created with manim version in file name when --format gif is set""" scene_name = "SquareToCircle" command = [ sys.executable, "-m", "manim", "--renderer", "opengl", "-ql", "--media_dir", str(tmp_path), "--format", "gif", str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err unexpected_mp4_path = ( tmp_path / "videos" / "simple_scenes" / "480p15" / "SquareToCircle.mp4" ) assert not unexpected_mp4_path.exists(), "unexpected mp4 file found at " + str( unexpected_mp4_path, ) expected_gif_path = add_version_before_extension( tmp_path / "videos" / "simple_scenes" / "480p15" / "SquareToCircle.gif" ) assert expected_gif_path.exists(), "gif file not found at " + str(expected_gif_path) @pytest.mark.slow def test_mp4_format_output(tmp_path, manim_cfg_file, simple_scenes_path): """Test only mp4 created without manim version in file name when --format mp4 is set""" scene_name = "SquareToCircle" command = [ sys.executable, "-m", "manim", "--renderer", "opengl", "-ql", "--media_dir", str(tmp_path), "--format", "mp4", str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err unexpected_gif_path = add_version_before_extension( tmp_path / "videos" / "simple_scenes" / "480p15" / "SquareToCircle.gif" ) assert not unexpected_gif_path.exists(), "unexpected gif file found at " + str( unexpected_gif_path, ) expected_mp4_path = ( tmp_path / "videos" / "simple_scenes" / "480p15" / "SquareToCircle.mp4" ) assert expected_mp4_path.exists(), "expected mp4 file not found at " + str( expected_mp4_path, ) @pytest.mark.slow def test_videos_not_created_when_png_format_set( tmp_path, manim_cfg_file, simple_scenes_path, ): """Test mp4 and gifs are not created when --format png is set""" scene_name = "SquareToCircle" command = [ sys.executable, "-m", "manim", "--renderer", "opengl", "-ql", "--media_dir", str(tmp_path), "--format", "png", str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err unexpected_gif_path = add_version_before_extension( tmp_path / "videos" / "simple_scenes" / "480p15" / "SquareToCircle.gif" ) assert not unexpected_gif_path.exists(), "unexpected gif file found at " + str( unexpected_gif_path, ) unexpected_mp4_path = ( tmp_path / "videos" / "simple_scenes" / "480p15" / "SquareToCircle.mp4" ) assert not unexpected_mp4_path.exists(), "expected mp4 file not found at " + str( unexpected_mp4_path, ) @pytest.mark.slow def test_images_are_created_when_png_format_set( tmp_path, manim_cfg_file, simple_scenes_path, ): """Test images are created in media directory when --format png is set""" scene_name = "SquareToCircle" command = [ sys.executable, "-m", "manim", "--renderer", "opengl", "-ql", "--media_dir", str(tmp_path), "--format", "png", str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err expected_png_path = tmp_path / "images" / "simple_scenes" / "SquareToCircle0000.png" assert expected_png_path.exists(), "png file not found at " + str(expected_png_path) @pytest.mark.slow def test_images_are_zero_padded_when_zero_pad_set( tmp_path, manim_cfg_file, simple_scenes_path, ): """Test images are zero padded when --format png and --zero_pad n are set""" scene_name = "SquareToCircle" command = [ sys.executable, "-m", "manim", "--renderer", "opengl", "-ql", "--media_dir", str(tmp_path), "--format", "png", "--zero_pad", "3", str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err unexpected_png_path = tmp_path /
simple_scenes_path, ): """Test images are zero padded when --format png and --zero_pad n are set""" scene_name = "SquareToCircle" command = [ sys.executable, "-m", "manim", "--renderer", "opengl", "-ql", "--media_dir", str(tmp_path), "--format", "png", "--zero_pad", "3", str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err unexpected_png_path = tmp_path / "images" / "simple_scenes" / "SquareToCircle0.png" assert not unexpected_png_path.exists(), "non zero padded png file found at " + str( unexpected_png_path, ) expected_png_path = tmp_path / "images" / "simple_scenes" / "SquareToCircle000.png" assert expected_png_path.exists(), "png file not found at " + str(expected_png_path) @pytest.mark.slow def test_webm_format_output(tmp_path, manim_cfg_file, simple_scenes_path): """Test only webm created when --format webm is set""" scene_name = "SquareToCircle" command = [ sys.executable, "-m", "manim", "--renderer", "opengl", "-ql", "--media_dir", str(tmp_path), "--format", "webm", str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err unexpected_mp4_path = ( tmp_path / "videos" / "simple_scenes" / "480p15" / "SquareToCircle.mp4" ) assert not unexpected_mp4_path.exists(), "unexpected mp4 file found at " + str( unexpected_mp4_path, ) expected_webm_path = ( tmp_path / "videos" / "simple_scenes" / "480p15" / "SquareToCircle.webm" ) assert expected_webm_path.exists(), "expected webm file not found at " + str( expected_webm_path, ) @pytest.mark.slow def test_default_format_output_for_transparent_flag( tmp_path, manim_cfg_file, simple_scenes_path, ): """Test .mov is created by default when transparent flag is set""" scene_name = "SquareToCircle" command = [ sys.executable, "-m", "manim", "--renderer", "opengl", "-ql", "--write_to_movie", "--media_dir", str(tmp_path), "-t", str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err unexpected_webm_path = ( tmp_path / "videos" / "simple_scenes" / "480p15" / "SquareToCircle.webm" ) assert not unexpected_webm_path.exists(), "unexpected webm file found at " + str( unexpected_webm_path, ) expected_mov_path = ( tmp_path / "videos" / "simple_scenes" / "480p15" / "SquareToCircle.mov" ) assert expected_mov_path.exists(), "expected .mov file not found at " + str( expected_mov_path, ) @pytest.mark.slow def test_mov_can_be_set_as_output_format(tmp_path, manim_cfg_file, simple_scenes_path): """Test .mov is created by when set using --format mov arg""" scene_name = "SquareToCircle" command = [ sys.executable, "-m", "manim", "--renderer", "opengl", "-ql", "--media_dir", str(tmp_path), "--format", "mov", str(simple_scenes_path), scene_name, ] out, err, exit_code = capture(command) assert exit_code == 0, err unexpected_webm_path = ( tmp_path / "videos" / "simple_scenes" / "480p15" / "SquareToCircle.webm" ) assert not unexpected_webm_path.exists(), "unexpected webm file found at " + str( unexpected_webm_path, ) expected_mov_path = ( tmp_path / "videos" / "simple_scenes" / "480p15" / "SquareToCircle.mov" ) assert expected_mov_path.exists(), "expected .mov file not found at " + str( expected_mov_path, ) ================================================ FILE: tests/test_scene_rendering/opengl/test_opengl_renderer.py ================================================ from __future__ import annotations import platform from unittest.mock import Mock import numpy as np import pytest from manim.renderer.opengl_renderer import OpenGLRenderer from tests.assert_utils import assert_file_exists from tests.test_scene_rendering.simple_scenes import * def test_write_to_movie_disables_window( config, using_temp_opengl_config, disabling_caching ): """write_to_movie should disable window by default""" scene = SquareToCircle() renderer = scene.renderer renderer.update_frame = Mock(wraps=renderer.update_frame) scene.render() assert renderer.window is None assert_file_exists(config.output_file) @pytest.mark.skip(reason="Temporarily skip due to failing in Windows CI") def test_force_window_opengl_render_with_movies( config, using_temp_opengl_config, force_window_config_write_to_movie, disabling_caching, ): """force_window creates window when write_to_movie is set""" scene = SquareToCircle() renderer = scene.renderer renderer.update_frame = Mock(wraps=renderer.update_frame) scene.render() assert renderer.window is not None assert_file_exists(config["output_file"]) renderer.window.close() @pytest.mark.skipif( platform.processor() == "aarch64", reason="Fails on Linux-ARM runners" ) def test_force_window_opengl_render_with_format( using_temp_opengl_config, force_window_config_pngs, disabling_caching, ): """force_window creates window when format is set"""
using_temp_opengl_config, force_window_config_write_to_movie, disabling_caching, ): """force_window creates window when write_to_movie is set""" scene = SquareToCircle() renderer = scene.renderer renderer.update_frame = Mock(wraps=renderer.update_frame) scene.render() assert renderer.window is not None assert_file_exists(config["output_file"]) renderer.window.close() @pytest.mark.skipif( platform.processor() == "aarch64", reason="Fails on Linux-ARM runners" ) def test_force_window_opengl_render_with_format( using_temp_opengl_config, force_window_config_pngs, disabling_caching, ): """force_window creates window when format is set""" scene = SquareToCircle() renderer = scene.renderer renderer.update_frame = Mock(wraps=renderer.update_frame) scene.render() assert renderer.window is not None renderer.window.close() def test_get_frame_with_preview_disabled(config, using_opengl_renderer): """Get frame is able to fetch frame with the correct dimensions when preview is disabled""" config.preview = False scene = SquareToCircle() assert isinstance(scene.renderer, OpenGLRenderer) assert not config.preview renderer = scene.renderer renderer.update_frame(scene) frame = renderer.get_frame() # height and width are flipped assert renderer.get_pixel_shape()[0] == frame.shape[1] assert renderer.get_pixel_shape()[1] == frame.shape[0] @pytest.mark.slow def test_get_frame_with_preview_enabled(config, using_opengl_renderer): """Get frame is able to fetch frame with the correct dimensions when preview is enabled""" config.preview = True scene = SquareToCircle() assert isinstance(scene.renderer, OpenGLRenderer) assert config.preview is True renderer = scene.renderer renderer.update_frame(scene) frame = renderer.get_frame() # height and width are flipped assert renderer.get_pixel_shape()[0] == frame.shape[1] assert renderer.get_pixel_shape()[1] == frame.shape[0] def test_pixel_coords_to_space_coords(config, using_opengl_renderer): config.preview = True scene = SquareToCircle() assert isinstance(scene.renderer, OpenGLRenderer) renderer = scene.renderer renderer.update_frame(scene) px, py = 3, 2 pw, ph = renderer.get_pixel_shape() _, fh = renderer.camera.get_shape() fc = renderer.camera.get_center() ex = fc[0] + (fh / ph) * (px - pw / 2) ey = fc[1] + (fh / ph) * (py - ph / 2) ez = fc[2] assert ( renderer.pixel_coords_to_space_coords(px, py) == np.array([ex, ey, ez]) ).all() assert ( renderer.pixel_coords_to_space_coords(px, py, top_left=True) == np.array([ex, -ey, ez]) ).all() ================================================ FILE: tests/test_scene_rendering/opengl/test_play_logic_opengl.py ================================================ from __future__ import annotations import sys from unittest.mock import Mock import pytest from manim import ( Scene, ValueTracker, np, ) from ..simple_scenes import ( SceneForFrozenFrameTests, SceneWithMultipleCalls, SceneWithNonStaticWait, SceneWithSceneUpdater, SceneWithStaticWait, SquareToCircle, ) @pytest.mark.skipif( sys.version_info < (3, 8), reason="Mock object has a different implementation in python 3.7, which makes it broken with this logic.", ) @pytest.mark.parametrize("frame_rate", argvalues=[15, 30, 60]) def test_t_values(config, using_temp_opengl_config, disabling_caching, frame_rate): """Test that the framerate corresponds to the number of t values generated""" config.frame_rate = frame_rate scene = SquareToCircle() scene.update_to_time = Mock() scene.render() assert scene.update_to_time.call_count == config["frame_rate"] np.testing.assert_allclose( ([call.args[0] for call in scene.update_to_time.call_args_list]), np.arange(0, 1, 1 / config["frame_rate"]), ) def test_t_values_with_skip_animations(using_temp_opengl_config, disabling_caching): """Test the behaviour of scene.skip_animations""" scene = SquareToCircle() scene.update_to_time = Mock() scene.renderer._original_skipping_status = True scene.render() assert scene.update_to_time.call_count == 1 np.testing.assert_almost_equal( scene.update_to_time.call_args.args[0], 1.0, ) def test_static_wait_detection(using_temp_opengl_config, disabling_caching): """Test if a static wait (wait that freeze the frame) is correctly detected""" scene = SceneWithStaticWait() scene.render() # Test is is_static_wait of the Wait animation has been set to True by compile_animation_ata assert scene.animations[0].is_static_wait assert scene.is_current_animation_frozen_frame() def test_non_static_wait_detection(using_temp_opengl_config, disabling_caching): scene = SceneWithNonStaticWait() scene.render() assert not scene.animations[0].is_static_wait assert not scene.is_current_animation_frozen_frame() scene = SceneWithSceneUpdater() scene.render() assert not scene.animations[0].is_static_wait assert not scene.is_current_animation_frozen_frame() def test_frozen_frame(using_temp_opengl_config, disabling_caching): scene = SceneForFrozenFrameTests() scene.render() assert scene.mobject_update_count == 0 assert scene.scene_update_count == 0 @pytest.mark.xfail(reason="Should be fixed in #2133") def test_t_values_with_cached_data(using_temp_opengl_config): """Test the proper generation and use of the t values when an animation is cached.""" scene = SceneWithMultipleCalls() # Mocking the file_writer will skip all the writing process. scene.renderer.file_writer = Mock(scene.renderer.file_writer) # Simulate that all animations
scene.mobject_update_count == 0 assert scene.scene_update_count == 0 @pytest.mark.xfail(reason="Should be fixed in #2133") def test_t_values_with_cached_data(using_temp_opengl_config): """Test the proper generation and use of the t values when an animation is cached.""" scene = SceneWithMultipleCalls() # Mocking the file_writer will skip all the writing process. scene.renderer.file_writer = Mock(scene.renderer.file_writer) # Simulate that all animations are cached. scene.renderer.file_writer.is_already_cached.return_value = True scene.update_to_time = Mock() scene.render() assert scene.update_to_time.call_count == 10 @pytest.mark.xfail(reason="Not currently handled correctly for opengl") def test_t_values_save_last_frame(config, using_temp_opengl_config): """Test that there is only one t value handled when only saving the last frame""" config.save_last_frame = True scene = SquareToCircle() scene.update_to_time = Mock() scene.render() scene.update_to_time.assert_called_once_with(1) def test_animate_with_changed_custom_attribute(using_temp_opengl_config): """Test that animating the change of a custom attribute using the animate syntax works correctly. """ class CustomAnimateScene(Scene): def construct(self): vt = ValueTracker(0) vt.custom_attribute = "hello" self.play(vt.animate.set_value(42).set(custom_attribute="world")) assert vt.get_value() == 42 assert vt.custom_attribute == "world" CustomAnimateScene().render() ================================================ FILE: tests/utils/__init__.py ================================================ [Empty file] ================================================ FILE: tests/utils/logging_tester.py ================================================ from __future__ import annotations import itertools import json import os from functools import wraps from pathlib import Path import pytest def _check_logs(reference_logfile_path: Path, generated_logfile_path: Path) -> None: with reference_logfile_path.open() as reference_logfile: reference_logs = reference_logfile.readlines() with generated_logfile_path.open() as generated_logfile: generated_logs = generated_logfile.readlines() diff = abs(len(reference_logs) - len(generated_logs)) if len(reference_logs) != len(generated_logs): msg_assert = "" if len(reference_logs) > len(generated_logs): msg_assert += f"Logs generated are SHORTER than the expected logs. There are {diff} extra logs.\n" msg_assert += "Last log of the generated log is : \n" msg_assert += generated_logs[-1] else: msg_assert += f"Logs generated are LONGER than the expected logs.\n There are {diff} extra logs :\n" for log in generated_logs[len(reference_logs) :]: msg_assert += log msg_assert += f"\nPath of reference log: {reference_logfile}\nPath of generated logs: {generated_logfile}" pytest.fail(msg_assert) for index, ref, gen in zip(itertools.count(), reference_logs, generated_logs): # As they are string, we only need to check if they are equal. If they are not, we then compute a more precise difference, to debug. if ref == gen: continue ref_log = json.loads(ref) gen_log = json.loads(gen) diff_keys = [ d1[0] for d1, d2 in zip(ref_log.items(), gen_log.items()) if d1[1] != d2[1] ] # \n and \t don't not work in f-strings. newline = "\n" tab = "\t" assert len(diff_keys) == 0, ( f"Logs don't match at {index} log. : \n{newline.join([f'In {key} field, got -> {newline}{tab}{repr(gen_log[key])}. {newline}Expected : -> {newline}{tab}{repr(ref_log[key])}.' for key in diff_keys])}" + f"\nPath of reference log: {reference_logfile}\nPath of generated logs: {generated_logfile}" ) def logs_comparison( control_data_file: str | os.PathLike, log_path_from_media_dir: str | os.PathLike ): """Decorator used for any test that needs to check logs. Parameters ---------- control_data_file Name of the control data file, i.e. .log that will be compared to the outputted logs. .. warning:: You don't have to pass the path here. .. example:: "SquareToCircleWithLFlag.log" log_path_from_media_dir The path of the .log generated, from the media dir. Example: /logs/Square.log. Returns ------- Callable[[Any], Any] The test wrapped with which we are going to make the comparison. """ control_data_file = Path(control_data_file) log_path_from_media_dir = Path(log_path_from_media_dir) def decorator(f): @wraps(f) def wrapper(*args, **kwargs): # NOTE : Every args goes seemingly in kwargs instead of args; this is perhaps Pytest. result = f(*args, **kwargs) tmp_path = kwargs["tmp_path"]
Callable[[Any], Any] The test wrapped with which we are going to make the comparison. """ control_data_file = Path(control_data_file) log_path_from_media_dir = Path(log_path_from_media_dir) def decorator(f): @wraps(f) def wrapper(*args, **kwargs): # NOTE : Every args goes seemingly in kwargs instead of args; this is perhaps Pytest. result = f(*args, **kwargs) tmp_path = kwargs["tmp_path"] tests_directory = Path(__file__).absolute().parent.parent control_data_path = ( tests_directory / "control_data" / "logs_data" / control_data_file ) path_log_generated = tmp_path / log_path_from_media_dir # The following will say precisely which subdir does not exist. if not path_log_generated.exists(): for parent in reversed(path_log_generated.parents): if not parent.exists(): pytest.fail( f"'{parent.name}' does not exist in '{parent.parent}' (which exists). ", ) break _check_logs(control_data_path, path_log_generated) return result return wrapper return decorator ================================================ FILE: tests/utils/test_polylabels.py ================================================ import numpy as np import pytest from manim.utils.polylabel import Cell, Polygon, polylabel # Test simple square and square with a hole for inside/outside logic @pytest.mark.parametrize( ("rings", "inside_points", "outside_points"), [ ( # Simple square: basic convex polygon [[[0, 0], [4, 0], [4, 4], [0, 4], [0, 0]]], # rings [ [2, 2], [1, 1], [3.9, 3.9], [0, 0], [2, 0], [0, 2], [0, 4], [4, 0], [4, 2], [2, 4], [4, 4], ], # inside points [[-1, -1], [5, 5], [4.1, 2]], # outside points ), ( # Square with a square hole (donut shape): tests handling of interior voids [ [[1, 1], [5, 1], [5, 5], [1, 5], [1, 1]], [[2, 2], [2, 4], [4, 4], [4, 2], [2, 2]], ], # rings [[1.5, 1.5], [3, 1.5], [1.5, 3]], # inside points [[3, 3], [6, 6], [0, 0]], # outside points ), ( # Non-convex polygon (same shape as flags used in Brazilian june festivals) [[[0, 0], [2, 2], [4, 0], [4, 4], [0, 4], [0, 0]]], # rings [[1, 3], [3.9, 3.9], [2, 3.5]], # inside points [ [0.1, 0], [1, 0], [2, 0], [2, 1], [2, 1.9], [3, 0], [3.9, 0], ], # outside points ), ], ) def test_polygon_inside_outside(rings, inside_points, outside_points): polygon = Polygon(rings) for point in inside_points: assert polygon.inside(point) for point in outside_points: assert not polygon.inside(point) # Test distance calculation with known expected distances @pytest.mark.parametrize( ("rings", "points", "expected_distance"), [ ( [[[0, 0], [4, 0], [4, 4], [0, 4], [0, 0]]], # rings [[2, 2]], # points 2.0, # Distance from center to closest edge in square ), ( [[[0, 0], [4, 0], [4, 4], [0, 4], [0, 0]]], # rings [[0, 0], [2, 0], [4, 2], [2, 4], [0, 2]], # points 0.0, # On the edge ), ( [[[0, 0], [4, 0], [4, 4], [0, 4], [0, 0]]], # rings [[5, 5]], # points -np.sqrt(2), # Outside and diagonally offset ), ], ) def test_polygon_compute_distance(rings, points, expected_distance): polygon = Polygon(rings) for point in points: result = polygon.compute_distance(np.array(point)) assert pytest.approx(result, rel=1e-3) == expected_distance @pytest.mark.parametrize( ("center", "h", "rings"), [ ( [2, 2], # center 1.0, # h [[[0, 0], [4, 0], [4, 4], [0, 4], [0, 0]]], # rings ), ( [3, 1.5], # center 0.5, # h [ [[1, 1], [5, 1], [5, 5], [1, 5], [1, 1]], [[2, 2], [2, 4],
expected_distance @pytest.mark.parametrize( ("center", "h", "rings"), [ ( [2, 2], # center 1.0, # h [[[0, 0], [4, 0], [4, 4], [0, 4], [0, 0]]], # rings ), ( [3, 1.5], # center 0.5, # h [ [[1, 1], [5, 1], [5, 5], [1, 5], [1, 1]], [[2, 2], [2, 4], [4, 4], [4, 2], [2, 2]], ], # rings ), ], ) def test_cell(center, h, rings): polygon = Polygon(rings) cell = Cell(center, h, polygon) assert isinstance(cell.d, float) assert isinstance(cell.p, float) assert np.allclose(cell.c, center) assert cell.h == h other = Cell(np.add(center, [0.1, 0.1]), h, polygon) assert (cell < other) == (cell.d < other.d) assert (cell > other) == (cell.d > other.d) assert (cell <= other) == (cell.d <= other.d) assert (cell >= other) == (cell.d >= other.d) @pytest.mark.parametrize( ("rings", "expected_centers"), [ ( # Simple square: basic convex polygon [[[0, 0], [4, 0], [4, 4], [0, 4], [0, 0]]], [[2.0, 2.0]], # single correct pole of inaccessibility ), ( # Square with a square hole (donut shape): tests handling of interior voids [ [[1, 1], [5, 1], [5, 5], [1, 5], [1, 1]], [[2, 2], [2, 4], [4, 4], [4, 2], [2, 2]], ], [ # any of the four pole of inaccessibility options [1.5, 1.5], [1.5, 4.5], [4.5, 1.5], [4.5, 4.5], ], ), ], ) def test_polylabel(rings, expected_centers): # Add third dimension to conform to polylabel input format rings_3d = [np.column_stack([ring, np.zeros(len(ring))]) for ring in rings] result = polylabel(rings_3d, precision=0.01) assert isinstance(result, Cell) assert result.h <= 0.01 assert result.d >= 0.0 match_found = any(np.allclose(result.c, ec, atol=0.1) for ec in expected_centers) assert match_found, f"Expected one of {expected_centers}, but got {result.c}" ================================================ FILE: tests/utils/testing_utils.py ================================================ from __future__ import annotations import inspect import sys def get_scenes_to_test(module_name: str): """Get all Test classes of the module from which it is called. Used to fetch all the SceneTest of the module. Parameters ---------- module_name The name of the module tested. Returns ------- List[:class:`type`] The list of all the classes of the module. """ return inspect.getmembers( sys.modules[module_name], lambda m: inspect.isclass(m) and m.__module__ == module_name, ) ================================================ FILE: tests/utils/video_tester.py ================================================ from __future__ import annotations import json import os from functools import wraps from pathlib import Path from typing import Any from manim import get_video_metadata from ..assert_utils import assert_shallow_dict_compare from ..helpers.video_utils import get_section_dir_layout, get_section_index def load_control_data(path_to_data: Path) -> Any: with path_to_data.open() as f: return json.load(f) def check_video_data(path_control_data: Path, path_video_gen: Path) -> None: """Compare control data with generated output. Used abbreviations: exp -> expected gen -> generated sec -> section meta -> metadata """ # movie file specification path_sec_gen = path_video_gen.parent.absolute() / "sections" control_data = load_control_data(path_control_data) movie_meta_gen = get_video_metadata(path_video_gen) movie_meta_exp = control_data["movie_metadata"] assert_shallow_dict_compare( movie_meta_gen, movie_meta_exp, "Movie file metadata mismatch:" ) # sections directory layout sec_dir_layout_gen = set(get_section_dir_layout(path_sec_gen)) sec_dir_layout_exp = set(control_data["section_dir_layout"]) unexp_gen = sec_dir_layout_gen - sec_dir_layout_exp ungen_exp = sec_dir_layout_exp - sec_dir_layout_gen if len(unexp_gen) or len(ungen_exp): dif = [f"'{dif}' got unexpectedly generated" for dif in unexp_gen] + [ f"'{dif}' didn't get generated" for dif in ungen_exp ] mismatch = "\n".join(dif) raise AssertionError(f"Sections don't match:\n{mismatch}") # sections index file scene_name = path_video_gen.stem path_sec_index_gen =
= sec_dir_layout_gen - sec_dir_layout_exp ungen_exp = sec_dir_layout_exp - sec_dir_layout_gen if len(unexp_gen) or len(ungen_exp): dif = [f"'{dif}' got unexpectedly generated" for dif in unexp_gen] + [ f"'{dif}' didn't get generated" for dif in ungen_exp ] mismatch = "\n".join(dif) raise AssertionError(f"Sections don't match:\n{mismatch}") # sections index file scene_name = path_video_gen.stem path_sec_index_gen = path_sec_gen / f"{scene_name}.json" sec_index_gen = get_section_index(path_sec_index_gen) sec_index_exp = control_data["section_index"] if len(sec_index_gen) != len(sec_index_exp): raise AssertionError( f"expected {len(sec_index_exp)} sections ({', '.join([el['name'] for el in sec_index_exp])}), but {len(sec_index_gen)} ({', '.join([el['name'] for el in sec_index_gen])}) got generated (in '{path_sec_index_gen}')" ) # check individual sections for sec_gen, sec_exp in zip(sec_index_gen, sec_index_exp): assert_shallow_dict_compare( sec_gen, sec_exp, # using json to pretty print dicts f"Section {json.dumps(sec_gen, indent=4)} (in '{path_sec_index_gen}') doesn't match expected Section (in '{json.dumps(sec_exp, indent=4)}'):", ) def video_comparison( control_data_file: str | os.PathLike, scene_path_from_media_dir: str | os.PathLike ): """Decorator used for any test that needs to check a rendered scene/video. .. warning:: The directories, such as the movie dir or sections dir, are expected to abide by the default. This requirement could be dropped if the manim config were to be accessible from ``wrapper`` like in ``frames_comparison.py``. Parameters ---------- control_data_file Name of the control data file, i.e. the .json containing all the pre-rendered references of the scene tested. .. warning:: You don't have to pass the path here. scene_path_from_media_dir The path of the scene generated, from the media dir. Example: /videos/1080p60/SquareToCircle.mp4. See Also -------- tests/helpers/video_utils.py : create control data """ control_data_file = Path(control_data_file) scene_path_from_media_dir = Path(scene_path_from_media_dir) def decorator(f): @wraps(f) def wrapper(*args, **kwargs): # NOTE : Every args goes seemingly in kwargs instead of args; this is perhaps Pytest. result = f(*args, **kwargs) tmp_path = kwargs["tmp_path"] tests_directory = Path(__file__).absolute().parent.parent path_control_data = ( tests_directory / "control_data" / "videos_data" / control_data_file ) path_video_gen = tmp_path / scene_path_from_media_dir if not path_video_gen.exists(): for parent in reversed(path_video_gen.parents): if not parent.exists(): raise AssertionError( f"'{parent.name}' does not exist in '{parent.parent}' (which exists). ", ) # TODO: use when pytest --set_test option # save_control_data_from_video(path_video_gen, control_data_file.stem) check_video_data(path_control_data, path_video_gen) return result return wrapper return decorator ================================================ FILE: .github/codeql.yml ================================================ query-filters: - exclude: id: py/init-calls-subclass - exclude: id: py/unexpected-raise-in-special-method - exclude: id: py/modification-of-locals - exclude: id: py/multiple-calls-to-init - exclude: id: py/missing-call-to-init - exclude: id: py/method-first-arg-is-not-self - exclude: id: py/cyclic-import - exclude: id: py/unsafe-cyclic-import paths: - manim paths-ignore: - tests/ - example_scenes/ ================================================ FILE: .github/dependabot.yml ================================================ version: 2 updates: - package-ecosystem: "github-actions" directory: "/" schedule: interval: "monthly" ignore: - dependency-name: "*" update-types: - "version-update:semver-minor" - "version-update:semver-patch" ================================================ FILE: .github/manimdependency.json ================================================ { "windows": { "tinytex": [ "standalone", "preview", "doublestroke", "count1to", "multitoc", "prelim2e", "ragged2e", "everysel", "setspace", "rsfs", "relsize", "ragged2e", "fundus-calligra", "microtype", "wasysym", "physics", "dvisvgm", "jknapltx", "wasy", "cm-super", "babel-english", "gnu-freefont", "mathastext", "cbfonts-fd" ] }, "macos": { "tinytex": [ "standalone", "preview", "doublestroke", "count1to", "multitoc", "prelim2e", "ragged2e", "everysel", "setspace", "rsfs", "relsize", "ragged2e", "fundus-calligra", "microtype", "wasysym", "physics", "dvisvgm", "jknapltx", "wasy", "cm-super", "babel-english", "gnu-freefont", "mathastext", "cbfonts-fd" ] } } ================================================ FILE: .github/PULL_REQUEST_TEMPLATE.md ================================================ <!-- Thank you for contributing to Manim! Learn more about the process in our contributing guidelines: https://docs.manim.community/en/latest/contributing.html --> ## Overview: What does this pull request change? <!-- If there is more information than the
"physics", "dvisvgm", "jknapltx", "wasy", "cm-super", "babel-english", "gnu-freefont", "mathastext", "cbfonts-fd" ] } } ================================================ FILE: .github/PULL_REQUEST_TEMPLATE.md ================================================ <!-- Thank you for contributing to Manim! Learn more about the process in our contributing guidelines: https://docs.manim.community/en/latest/contributing.html --> ## Overview: What does this pull request change? <!-- If there is more information than the PR title that should be added to our release changelog, add it in the following changelog section. This is optional, but recommended for larger pull requests. --> <!--changelog-start--> <!--changelog-end--> ## Motivation and Explanation: Why and how do your changes improve the library? <!-- Optional for bugfixes, small enhancements, and documentation-related PRs. Otherwise, please give a short reasoning for your changes. --> ## Links to added or changed documentation pages <!-- Please add links to the affected documentation pages (edit the description after opening the PR). The link to the documentation for your PR is https://manimce--####.org.readthedocs.build/en/####/, where #### represents the PR number. --> ## Further Information and Comments <!-- If applicable, put further comments for the reviewers here. --> <!-- Thank you again for contributing! Do not modify the lines below, they are for reviewers. --> ## Reviewer Checklist - [ ] The PR title is descriptive enough for the changelog, and the PR is labeled correctly - [ ] If applicable: newly added non-private functions and classes have a docstring including a short summary and a PARAMETERS section - [ ] If applicable: newly added functions and classes are tested ================================================ FILE: .github/ISSUE_TEMPLATE/bug_report.md ================================================ --- name: Manim bug about: Report a bug or unexpected behavior when running Manim title: "" labels: bug assignees: '' --- ## Description of bug / unexpected behavior <!-- Add a clear and concise description of the problem you encountered. --> ## Expected behavior <!-- Add a clear and concise description of what you expected to happen. --> ## How to reproduce the issue <!-- Provide a piece of code illustrating the undesired behavior. --> <details><summary>Code for reproducing the problem</summary> ```py Paste your code here. ``` </details> ## Additional media files <!-- Paste in the files manim produced on rendering the code above. --> <details><summary>Images/GIFs</summary> <!-- PASTE MEDIA HERE --> </details> ## Logs <details><summary>Terminal output</summary> <!-- Add "-v DEBUG" when calling manim to generate more detailed logs --> ``` PASTE HERE OR PROVIDE LINK TO https://pastebin.com/ OR SIMILAR ``` <!-- Insert screenshots here (only when absolutely necessary, we prefer copy/pasted output!) --> </details> ## System specifications <details><summary>System Details</summary> - OS (with version, e.g., Windows 10 v2004 or macOS 10.15 (Catalina)): - RAM: - Python version (`python/py/python3 --version`): - Installed modules (provide output from `pip list`): ``` PASTE HERE ``` </details> <details><summary>LaTeX details</summary> + LaTeX distribution (e.g. TeX Live 2020): + Installed LaTeX packages: <!-- output of `tlmgr list --only-installed` for TeX Live or a screenshot of the Packages page for MikTeX --> </details> ## Additional comments <!-- Add further context that you think might be relevant for this issue here. --> ================================================ FILE: .github/ISSUE_TEMPLATE/feature_request.md ================================================ --- name: Feature request about: Request a new feature for Manim
`tlmgr list --only-installed` for TeX Live or a screenshot of the Packages page for MikTeX --> </details> ## Additional comments <!-- Add further context that you think might be relevant for this issue here. --> ================================================ FILE: .github/ISSUE_TEMPLATE/feature_request.md ================================================ --- name: Feature request about: Request a new feature for Manim title: "" labels: new feature assignees: '' --- ## Description of proposed feature <!-- Add a clear and concise description of the new feature, including a motivation: why do you think this will be useful? --> ## How can the new feature be used? <!-- If possible, illustrate how this new feature could be used. --> ## Additional comments <!-- Add further context that you think might be relevant. --> ================================================ FILE: .github/ISSUE_TEMPLATE/installation_issue.md ================================================ --- name: Installation issue about: Report issues with the installation process of Manim title: "" labels: bug, installation assignees: '' --- #### Preliminaries - [ ] I have followed the latest version of the [installation instructions](https://docs.manim.community/en/stable/installation.html). - [ ] I have checked the [installation FAQ](https://docs.manim.community/en/stable/faq/installation.html) and my problem is either not mentioned there, or the solution given there does not help. ## Description of error <!-- Add a clear and concise description of the problem you encountered. --> ## Installation logs <!-- Please paste the **full** terminal output; we can only help to identify the issue when we receive all required information. --> <details><summary>Terminal output</summary> ``` PASTE HERE OR PROVIDE LINK TO https://pastebin.com/ OR SIMILAR ``` <!-- Insert screenshots here (only when absolutely necessary, we prefer copy/pasted output!) --> </details> ## System specifications <details><summary>System Details</summary> - OS (with version, e.g., Windows 10 v2004 or macOS 10.15 (Catalina)): - RAM: - Python version (`python/py/python3 --version`): - Installed modules (provide output from `pip list`): ``` PASTE HERE ``` </details> <details><summary>LaTeX details</summary> + LaTeX distribution (e.g. TeX Live 2020): + Installed LaTeX packages: <!-- output of `tlmgr list --only-installed` for TeX Live or a screenshot of the Packages page for MikTeX --> </details> ## Additional comments <!-- Add further context that you think might be relevant for this issue here. --> ================================================ FILE: .github/PULL_REQUEST_TEMPLATE/bugfix.md ================================================ <!-- Thank you for contributing to ManimCommunity! Before filling in the details, ensure: - The title of your PR gives a descriptive summary to end-users. Some examples: - Fixed last animations not running to completion - Added gradient support and documentation for SVG files --> ## Changelog <!-- Optional: more descriptive changelog entry than just the title for the upcoming release. Write RST between the following start and end comments.--> <!--changelog-start--> <!--changelog-end--> ## Summary of Changes ## Checklist - [ ] I have read the [Contributing Guidelines](https://docs.manim.community/en/latest/contributing.html) - [ ] I have written a descriptive PR title (see top of PR template for examples) - [ ] I have added a test case to prevent software regression <!-- Do not modify the lines below. These are for the reviewers of your PR --> ## Reviewer Checklist - [ ] The PR title is descriptive enough - [ ] The PR is labeled appropriately -
- [ ] I have added a test case to prevent software regression <!-- Do not modify the lines below. These are for the reviewers of your PR --> ## Reviewer Checklist - [ ] The PR title is descriptive enough - [ ] The PR is labeled appropriately - [ ] Regression test(s) are implemented ================================================ FILE: .github/PULL_REQUEST_TEMPLATE/documentation.md ================================================ <!-- Thank you for contributing to ManimCommunity! Before filling in the details, ensure: - The title of your PR gives a descriptive summary to end-users. Some examples: - Fixed last animations not running to completion - Added gradient support and documentation for SVG files --> ## Summary of Changes ## Changelog <!-- Optional: more descriptive changelog entry than just the title for the upcoming release. Write RST between the following start and end comments.--> <!--changelog-start--> <!--changelog-end--> ## Checklist - [ ] I have read the [Contributing Guidelines](https://docs.manim.community/en/latest/contributing.html) - [ ] I have written a descriptive PR title (see top of PR template for examples) - [ ] My new documentation builds, looks correctly formatted, and adds no additional build warnings <!-- Do not modify the lines below. These are for the reviewers of your PR --> ## Reviewer Checklist - [ ] The PR title is descriptive enough - [ ] The PR is labeled appropriately - [ ] Newly added documentation builds, looks correctly formatted, and adds no additional build warnings ================================================ FILE: .github/PULL_REQUEST_TEMPLATE/hackathon.md ================================================ Thanks for your contribution for the manim community hackathon! Please make sure your pull request has a meaningful title. E.g. "Example for the class Angle". Details for the submissions can be found in the [discord announcement channel](https://discord.com/channels/581738731934056449/581739610154074112/846460718479966228 ). Docstrings can be created in the discord channel with the manimator like this: ``` !mdocstring ``` ```python class HelloWorld(Scene): def construct(self): self.add(Circle()) ``` Copy+paste the output docstring to the right place in the source code. If you need any help, do not hesitate to ask the hackathon-mentors in the discord channel. ================================================ FILE: .github/scripts/ci_build_cairo.py ================================================ # Logic is as follows: # 1. Download cairo source code: https://cairographics.org/releases/cairo-<version>.tar.xz # 2. Verify the downloaded file using the sha256sums file: https://cairographics.org/releases/cairo-<version>.tar.xz.sha256sum # 3. Extract the downloaded file. # 4. Create a virtual environment and install meson and ninja. # 5. Run meson build in the extracted directory. Also, set required prefix. # 6. Run meson compile -C build. # 7. Run meson install -C build. import hashlib import logging import os import subprocess import sys import tarfile import tempfile import urllib.request from collections.abc import Generator from contextlib import contextmanager from pathlib import Path from sys import stdout CAIRO_VERSION = "1.18.0" CAIRO_URL = f"https://cairographics.org/releases/cairo-{CAIRO_VERSION}.tar.xz" CAIRO_SHA256_URL = f"{CAIRO_URL}.sha256sum" VENV_NAME = "meson-venv" BUILD_DIR = "build" INSTALL_PREFIX = Path(__file__).parent.parent.parent / "third_party" / "cairo" logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") logger = logging.getLogger(__name__) def is_ci(): return os.getenv("CI", None) is not None def download_file(url, path): logger.info(f"Downloading {url} to {path}") block_size = 1024 * 1024 with urllib.request.urlopen(url) as response, open(path, "wb") as file: while True: data = response.read(block_size) if not data: break file.write(data) def verify_sha256sum(path, sha256sum): with open(path,
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") logger = logging.getLogger(__name__) def is_ci(): return os.getenv("CI", None) is not None def download_file(url, path): logger.info(f"Downloading {url} to {path}") block_size = 1024 * 1024 with urllib.request.urlopen(url) as response, open(path, "wb") as file: while True: data = response.read(block_size) if not data: break file.write(data) def verify_sha256sum(path, sha256sum): with open(path, "rb") as file: file_hash = hashlib.sha256(file.read()).hexdigest() if file_hash != sha256sum: raise Exception("SHA256SUM does not match") def extract_tar_xz(path, directory): with tarfile.open(path) as file: file.extractall(directory) def run_command(command, cwd=None, env=None): process = subprocess.Popen(command, cwd=cwd, env=env) process.communicate() if process.returncode != 0: raise Exception("Command failed") @contextmanager def gha_group(title: str) -> Generator: if not is_ci(): yield return print(f"\n::group::{title}") stdout.flush() try: yield finally: print("::endgroup::") stdout.flush() def set_env_var_gha(name: str, value: str) -> None: if not is_ci(): return env_file = os.getenv("GITHUB_ENV", None) if env_file is None: return with open(env_file, "a") as file: file.write(f"{name}={value}\n") stdout.flush() def get_ld_library_path(prefix: Path) -> str: # given a prefix, the ld library path can be found at # <prefix>/lib/* or sometimes just <prefix>/lib # this function returns the path to the ld library path # first, check if the ld library path exists at <prefix>/lib/* ld_library_paths = list(prefix.glob("lib/*")) if len(ld_library_paths) == 1: return ld_library_paths[0].absolute().as_posix() # if the ld library path does not exist at <prefix>/lib/*, # return <prefix>/lib ld_library_path = prefix / "lib" if ld_library_path.exists(): return ld_library_path.absolute().as_posix() return "" def main(): if sys.platform == "win32": logger.info("Skipping build on windows") return with tempfile.TemporaryDirectory() as tmpdir: with gha_group("Downloading and Extracting Cairo"): logger.info(f"Downloading cairo version {CAIRO_VERSION}") download_file(CAIRO_URL, os.path.join(tmpdir, "cairo.tar.xz")) logger.info("Downloading cairo sha256sum") download_file(CAIRO_SHA256_URL, os.path.join(tmpdir, "cairo.sha256sum")) logger.info("Verifying cairo sha256sum") with open(os.path.join(tmpdir, "cairo.sha256sum")) as file: sha256sum = file.read().split()[0] verify_sha256sum(os.path.join(tmpdir, "cairo.tar.xz"), sha256sum) logger.info("Extracting cairo") extract_tar_xz(os.path.join(tmpdir, "cairo.tar.xz"), tmpdir) with gha_group("Installing meson and ninja"): logger.info("Creating virtual environment") run_command([sys.executable, "-m", "venv", os.path.join(tmpdir, VENV_NAME)]) logger.info("Installing meson and ninja") run_command( [ os.path.join(tmpdir, VENV_NAME, "bin", "pip"), "install", "meson", "ninja", ] ) env_vars = { # add the venv bin directory to PATH so that meson can find ninja "PATH": f"{os.path.join(tmpdir, VENV_NAME, 'bin')}{os.pathsep}{os.environ['PATH']}", } with gha_group("Building and Installing Cairo"): logger.info("Running meson setup") run_command( [ os.path.join(tmpdir, VENV_NAME, "bin", "meson"), "setup", BUILD_DIR, f"--prefix={INSTALL_PREFIX.absolute().as_posix()}", "--buildtype=release", "-Dtests=disabled", ], cwd=os.path.join(tmpdir, f"cairo-{CAIRO_VERSION}"), env=env_vars, ) logger.info("Running meson compile") run_command( [ os.path.join(tmpdir, VENV_NAME, "bin", "meson"), "compile", "-C", BUILD_DIR, ], cwd=os.path.join(tmpdir, f"cairo-{CAIRO_VERSION}"), env=env_vars, ) logger.info("Running meson install") run_command( [ os.path.join(tmpdir, VENV_NAME, "bin", "meson"), "install", "-C", BUILD_DIR, ], cwd=os.path.join(tmpdir, f"cairo-{CAIRO_VERSION}"), env=env_vars, ) logger.info(f"Successfully built cairo and installed it to {INSTALL_PREFIX}") if __name__ == "__main__": if "--set-env-vars" in sys.argv: with gha_group("Setting environment variables"): # append the pkgconfig directory to PKG_CONFIG_PATH set_env_var_gha( "PKG_CONFIG_PATH", f"{Path(get_ld_library_path(INSTALL_PREFIX), 'pkgconfig').as_posix()}{os.pathsep}" f'{os.getenv("PKG_CONFIG_PATH", "")}', ) set_env_var_gha( "LD_LIBRARY_PATH", f"{get_ld_library_path(INSTALL_PREFIX)}{os.pathsep}" f'{os.getenv("LD_LIBRARY_PATH", "")}', ) sys.exit(0) main() ================================================ FILE: .github/workflows/cffconvert.yml ================================================ name: cffconvert on: push: paths: - CITATION.cff jobs: validate: name: "validate" runs-on: ubuntu-latest steps: - name: Check out a copy of the repository uses: actions/checkout@v4 - name: Check whether the citation metadata from CITATION.cff is valid uses: citation-file-format/cffconvert-github-action@2.0.0 with: args: "--validate" ================================================ FILE: .github/workflows/ci.yml ================================================ name: CI concurrency: group: ${{ github.ref }} cancel-in-progress: true on: push: branches: - main pull_request: branches: - main jobs: test: runs-on: ${{ matrix.os }} env: DISPLAY: :0 PYTEST_ADDOPTS: "--color=yes" # colors in pytest PYTHONIOENCODING: "utf8"
citation metadata from CITATION.cff is valid uses: citation-file-format/cffconvert-github-action@2.0.0 with: args: "--validate" ================================================ FILE: .github/workflows/ci.yml ================================================ name: CI concurrency: group: ${{ github.ref }} cancel-in-progress: true on: push: branches: - main pull_request: branches: - main jobs: test: runs-on: ${{ matrix.os }} env: DISPLAY: :0 PYTEST_ADDOPTS: "--color=yes" # colors in pytest PYTHONIOENCODING: "utf8" strategy: fail-fast: false matrix: os: [ubuntu-22.04, macos-13, windows-latest] python: ["3.9", "3.10", "3.11", "3.12", "3.13"] steps: - name: Checkout the repository uses: actions/checkout@v4 - name: Setup Python ${{ matrix.python }} uses: actions/setup-python@v5 with: python-version: ${{ matrix.python }} - name: Install uv uses: astral-sh/setup-uv@v6 with: enable-cache: true - name: Setup cache variables shell: bash id: cache-vars run: | echo "date=$(/bin/date -u "+%m%w%Y")" >> $GITHUB_OUTPUT - name: Install system dependencies (Linux) if: runner.os == 'Linux' uses: awalsh128/cache-apt-pkgs-action@latest with: packages: python3-opengl libpango1.0-dev xvfb freeglut3-dev version: 1.0 - name: Install Texlive (Linux) if: runner.os == 'Linux' uses: zauguin/install-texlive@v4 with: packages: > scheme-basic latex fontspec tipa calligra xcolor standalone preview doublestroke setspace rsfs relsize ragged2e fundus-calligra microtype wasysym physics dvisvgm jknapltx wasy cm-super babel-english gnu-freefont mathastext cbfonts-fd xetex - name: Start virtual display (Linux) if: runner.os == 'Linux' run: | # start xvfb in background sudo /usr/bin/Xvfb $DISPLAY -screen 0 1280x1024x24 & - name: Setup Cairo Cache uses: actions/cache@v4 id: cache-cairo if: runner.os == 'Linux' || runner.os == 'macOS' with: path: ${{ github.workspace }}/third_party key: ${{ runner.os }}-dependencies-cairo-${{ hashFiles('.github/scripts/ci_build_cairo.py') }} - name: Build and install Cairo (Linux and macOS) if: (runner.os == 'Linux' || runner.os == 'macOS') && steps.cache-cairo.outputs.cache-hit != 'true' run: python .github/scripts/ci_build_cairo.py - name: Set env vars for Cairo (Linux and macOS) if: runner.os == 'Linux' || runner.os == 'macOS' run: python .github/scripts/ci_build_cairo.py --set-env-vars - name: Setup macOS cache uses: actions/cache@v4 id: cache-macos if: runner.os == 'macOS' with: path: ${{ github.workspace }}/macos-cache key: ${{ runner.os }}-dependencies-tinytex-${{ hashFiles('.github/manimdependency.json') }}-${{ steps.cache-vars.outputs.date }}-1 - name: Install system dependencies (MacOS) if: runner.os == 'macOS' && steps.cache-macos.outputs.cache-hit != 'true' run: | tinyTexPackages=$(python -c "import json;print(' '.join(json.load(open('.github/manimdependency.json'))['macos']['tinytex']))") IFS=' ' read -a ttp <<< "$tinyTexPackages" oriPath=$PATH sudo mkdir -p $PWD/macos-cache echo "Install TinyTeX" sudo curl -L -o "/tmp/TinyTeX.tgz" "https://github.com/yihui/tinytex-releases/releases/download/daily/TinyTeX-1.tgz" sudo tar zxf "/tmp/TinyTeX.tgz" -C "$PWD/macos-cache" export PATH="$PWD/macos-cache/TinyTeX/bin/universal-darwin:$PATH" sudo tlmgr update --self for i in "${ttp[@]}"; do sudo tlmgr install "$i" done export PATH="$oriPath" echo "Completed TinyTeX" - name: Add macOS dependencies to PATH if: runner.os == 'macOS' shell: bash run: | echo "/Library/TeX/texbin" >> $GITHUB_PATH echo "$PWD/macos-cache/TinyTeX/bin/universal-darwin" >> $GITHUB_PATH - name: Setup Windows cache id: cache-windows if: runner.os == 'Windows' uses: actions/cache@v4 with: path: ${{ github.workspace }}\ManimCache key: ${{ runner.os }}-dependencies-tinytex-${{ hashFiles('.github/manimdependency.json') }}-${{ steps.cache-vars.outputs.date }}-1 - uses: ssciwr/setup-mesa-dist-win@v2 - name: Install system dependencies (Windows) if: runner.os == 'Windows' && steps.cache-windows.outputs.cache-hit != 'true' run: | $tinyTexPackages = $(python -c "import json;print(' '.join(json.load(open('.github/manimdependency.json'))['windows']['tinytex']))") -Split ' ' $OriPath = $env:PATH echo "Install Tinytex" Invoke-WebRequest "https://github.com/yihui/tinytex-releases/releases/download/daily/TinyTeX-1.zip" -OutFile "$($env:TMP)\TinyTex.zip" Expand-Archive -LiteralPath "$($env:TMP)\TinyTex.zip" -DestinationPath "$($PWD)\ManimCache\LatexWindows" $env:Path = "$($PWD)\ManimCache\LatexWindows\TinyTeX\bin\windows;$($env:PATH)" tlmgr update --self tlmgr install $tinyTexPackages $env:PATH=$OriPath echo "Completed Latex" - name: Add Windows dependencies to PATH if: runner.os == 'Windows' run: | $env:Path += ";" + "$($PWD)\ManimCache\LatexWindows\TinyTeX\bin\windows" echo "$env:Path" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append - name:
"https://github.com/yihui/tinytex-releases/releases/download/daily/TinyTeX-1.zip" -OutFile "$($env:TMP)\TinyTex.zip" Expand-Archive -LiteralPath "$($env:TMP)\TinyTex.zip" -DestinationPath "$($PWD)\ManimCache\LatexWindows" $env:Path = "$($PWD)\ManimCache\LatexWindows\TinyTeX\bin\windows;$($env:PATH)" tlmgr update --self tlmgr install $tinyTexPackages $env:PATH=$OriPath echo "Completed Latex" - name: Add Windows dependencies to PATH if: runner.os == 'Windows' run: | $env:Path += ";" + "$($PWD)\ManimCache\LatexWindows\TinyTeX\bin\windows" echo "$env:Path" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append - name: Install dependencies and manim run: | uv sync --all-extras --locked - name: Run tests run: | uv run python -m pytest - name: Run module doctests run: | uv run python -m pytest -v --cov-append --ignore-glob="*opengl*" --doctest-modules manim - name: Run doctests in rst files run: | cd docs && uv run make doctest O=-tskip-manim ================================================ FILE: .github/workflows/codeql.yml ================================================ name: "CodeQL" on: push: branches: [ "main" ] pull_request: branches: [ "main" ] schedule: - cron: "21 16 * * 3" jobs: analyze: name: Analyze runs-on: ubuntu-latest permissions: actions: read contents: read security-events: write strategy: fail-fast: false matrix: language: [ python ] steps: - name: Checkout uses: actions/checkout@v4 - name: Initialize CodeQL uses: github/codeql-action/init@v3 with: languages: ${{ matrix.language }} config-file: ./.github/codeql.yml queries: +security-and-quality - name: Autobuild uses: github/codeql-action/autobuild@v3 - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v3 with: category: "/language:${{ matrix.language }}" ================================================ FILE: .github/workflows/dependent-issues.yml ================================================ name: Dependent Issues on: issues: types: - opened - edited - reopened pull_request_target: types: - opened - edited - reopened - synchronize schedule: - cron: '0 0 * * *' # schedule daily check jobs: check: runs-on: ubuntu-latest steps: - uses: z0al/dependent-issues@v1 env: # (Required) The token to use to make API calls to GitHub. GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: # (Optional) The label to use to mark dependent issues label: dependent # (Optional) Enable checking for dependencies in issues. Enable by # setting the value to "on". Default "off" check_issues: on # (Optional) A comma-separated list of keywords. Default # "depends on, blocked by" keywords: depends on, blocked by ================================================ FILE: .github/workflows/publish-docker.yml ================================================ name: Publish Docker Image on: push: branches: - main release: types: [released] jobs: docker-latest: runs-on: ubuntu-latest if: github.event_name != 'release' steps: - name: Set up QEMU uses: docker/setup-qemu-action@v3 - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 - name: Login to DockerHub uses: docker/login-action@v3 with: username: ${{ secrets.DOCKERHUB_USERNAME }} password: ${{ secrets.DOCKERHUB_TOKEN }} - name: Build and push uses: docker/build-push-action@v6 with: platforms: linux/arm64,linux/amd64 push: true file: docker/Dockerfile tags: | manimcommunity/manim:latest docker-release: runs-on: ubuntu-latest if: github.event_name == 'release' steps: - name: Set up QEMU uses: docker/setup-qemu-action@v3 - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 - name: Login to DockerHub uses: docker/login-action@v3 with: username: ${{ secrets.DOCKERHUB_USERNAME }} password: ${{ secrets.DOCKERHUB_TOKEN }} - name: Get Version id: create_release shell: python env: tag_act: ${{ github.ref }} run: | import os ref_tag = os.getenv('tag_act').split('/')[-1] with open(os.getenv('GITHUB_OUTPUT'), 'w') as f: print(f"tag_name={ref_tag}", file=f) - name: Build and push uses: docker/build-push-action@v6 with: platforms: linux/arm64,linux/amd64 push: true file: docker/Dockerfile tags: | manimcommunity/manim:stable manimcommunity/manim:latest manimcommunity/manim:${{ steps.create_release.outputs.tag_name }} ================================================ FILE: .github/workflows/python-publish.yml ================================================ name: Publish Release on: release: types: [released] jobs: release: name: "Publish release" runs-on: ubuntu-latest environment: release permissions: id-token: write steps: - uses: actions/checkout@v4 - name: Set up Python 3.13 uses: actions/setup-python@v5 with: python-version:
platforms: linux/arm64,linux/amd64 push: true file: docker/Dockerfile tags: | manimcommunity/manim:stable manimcommunity/manim:latest manimcommunity/manim:${{ steps.create_release.outputs.tag_name }} ================================================ FILE: .github/workflows/python-publish.yml ================================================ name: Publish Release on: release: types: [released] jobs: release: name: "Publish release" runs-on: ubuntu-latest environment: release permissions: id-token: write steps: - uses: actions/checkout@v4 - name: Set up Python 3.13 uses: actions/setup-python@v5 with: python-version: 3.13 - name: Install uv uses: astral-sh/setup-uv@v6 - name: Build and push release to PyPI run: | uv sync uv build uv publish - name: Store artifacts uses: actions/upload-artifact@v4 with: path: dist/*.tar.gz name: manim.tar.gz - name: Install Dependency run: pip install requests - name: Get Upload URL id: create_release shell: python env: access_token: ${{ secrets.GITHUB_TOKEN }} tag_act: ${{ github.ref }} run: | import requests import os ref_tag = os.getenv('tag_act').split('/')[-1] access_token = os.getenv('access_token') headers = { "Accept":"application/vnd.github.v3+json", "Authorization": f"token {access_token}" } url = f"https://api.github.com/repos/ManimCommunity/manim/releases/tags/{ref_tag}" c = requests.get(url,headers=headers) upload_url=c.json()['upload_url'] with open(os.getenv('GITHUB_OUTPUT'), 'w') as f: print(f"upload_url={upload_url}", file=f) print(f"tag_name={ref_tag[1:]}", file=f) - name: Upload Release Asset id: upload-release uses: actions/upload-release-asset@v1 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: upload_url: ${{ steps.create_release.outputs.upload_url }} asset_path: dist/manim-${{ steps.create_release.outputs.tag_name }}.tar.gz asset_name: manim-${{ steps.create_release.outputs.tag_name }}.tar.gz asset_content_type: application/gzip ================================================ FILE: .github/workflows/release-publish-documentation.yml ================================================ name: Publish downloadable documentation on: release: types: [released] workflow_dispatch: jobs: build-and-publish-htmldocs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Set up Python uses: actions/setup-python@v5 with: python-version: 3.13 - name: Install uv uses: astral-sh/setup-uv@v6 - name: Install system dependencies run: | sudo apt update && sudo apt install -y \ pkg-config libcairo-dev libpango1.0-dev wget fonts-roboto wget -qO- "https://yihui.org/tinytex/install-bin-unix.sh" | sh echo ${HOME}/.TinyTeX/bin/x86_64-linux >> $GITHUB_PATH - name: Install LaTeX and Python dependencies run: | tlmgr update --self tlmgr install \ babel-english ctex doublestroke dvisvgm frcursive fundus-calligra jknapltx \ mathastext microtype physics preview ragged2e relsize rsfs setspace standalone \ wasy wasysym uv sync - name: Build and package documentation run: | cd docs/ uv run make html cd build/html/ tar -czvf ../html-docs.tar.gz * - name: Store artifacts uses: actions/upload-artifact@v4 with: path: ${{ github.workspace }}/docs/build/html-docs.tar.gz name: html-docs.tar.gz - name: Install Dependency run: pip install requests - name: Get Upload URL if: github.event == 'release' id: create_release shell: python env: access_token: ${{ secrets.GITHUB_TOKEN }} tag_act: ${{ github.ref }} run: | import requests import os ref_tag = os.getenv('tag_act').split('/')[-1] access_token = os.getenv('access_token') headers = { "Accept":"application/vnd.github.v3+json", "Authorization": f"token {access_token}" } url = f"https://api.github.com/repos/ManimCommunity/manim/releases/tags/{ref_tag}" c = requests.get(url,headers=headers) upload_url=c.json()['upload_url'] with open(os.getenv('GITHUB_OUTPUT'), 'w') as f: print(f"upload_url={upload_url}", file=f) print(f"tag_name={ref_tag[1:]}", file=f) - name: Upload Release Asset if: github.event == 'release' id: upload-release uses: actions/upload-release-asset@v1 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: upload_url: ${{ steps.create_release.outputs.upload_url }} asset_path: ${{ github.workspace }}/docs/build/html-docs.tar.gz asset_name: manim-htmldocs-${{ steps.create_release.outputs.tag_name }}.tar.gz asset_content_type: application/gzip