file_path
stringlengths 29
93
| content
stringlengths 0
117k
|
---|---|
manim_ManimCommunity/tests/assert_utils.py
|
from __future__ import annotations
import os
from pathlib import Path
from pprint import pformat
def assert_file_exists(filepath: str | os.PathLike) -> None:
"""Assert that filepath points to an existing file. Print all the elements (files and dir) of the parent dir of the given filepath.
This is mostly to have better assert message than using a raw assert filepath.is_file().
Parameters
----------
filepath
Filepath to check.
Raises
------
AssertionError
If filepath does not point to a file (if the file does not exist or it's a dir).
"""
path = Path(filepath)
if not path.is_file():
elems = pformat([path.name for path in path.parent.iterdir()])
message = f"{path.absolute()} is not a file. Other elements in the parent directory are \n{elems}"
raise AssertionError(message)
def assert_dir_exists(dirpath: str | os.PathLike) -> None:
"""Assert that directory exists.
Parameters
----------
dirpath
Path to directory to check.
Raises
------
AssertionError
If dirpath does not point to a directory (if the file does exist or it's a file).
"""
path = Path(dirpath)
if not path.is_dir():
elems = pformat([path.name for path in list(path.parent.iterdir())])
message = f"{path.absolute()} is not a directory. Other elements in the parent directory are \n{elems}"
raise AssertionError(message)
def assert_dir_filled(dirpath: str | os.PathLike) -> None:
"""Assert that directory exists and contains at least one file or directory (or file like objects like symlinks on Linux).
Parameters
----------
dirpath
Path to directory to check.
Raises
------
AssertionError
If dirpath does not point to a directory (if the file does exist or it's a file) or the directory is empty.
"""
if not any(Path(dirpath).iterdir()):
raise AssertionError(f"{dirpath} is an empty directory.")
def assert_file_not_exists(filepath: str | os.PathLike) -> None:
"""Assert that filepath does not point to an existing file. Print all the elements (files and dir) of the parent dir of the given filepath.
This is mostly to have better assert message than using a raw assert filepath.is_file().
Parameters
----------
filepath
Filepath to check.
Raises
------
AssertionError
If filepath does point to a file.
"""
path = Path(filepath)
if path.is_file():
elems = pformat([path.name for path in path.parent.iterdir()])
message = f"{path.absolute()} is a file. Other elements in the parent directory are \n{elems}"
raise AssertionError(message)
def assert_dir_not_exists(dirpath: str | os.PathLike) -> None:
"""Assert that directory does not exist.
Parameters
----------
dirpath
Path to directory to check.
Raises
------
AssertionError
If dirpath points to a directory.
"""
path = Path(dirpath)
if path.is_dir():
elems = pformat([path.name for path in list(path.parent.iterdir())])
message = f"{path.absolute()} is a directory. Other elements in the parent directory are \n{elems}"
raise AssertionError(message)
def assert_shallow_dict_compare(a: dict, b: dict, message_start: str) -> None:
"""Assert that Directories ``a`` and ``b`` are the same.
``b`` is treated as the expected values that ``a`` shall abide by.
Print helpful error with custom message start.
"""
mismatch: list[str] = []
for b_key, b_value in b.items():
if b_key not in a:
mismatch.append(f"Missing item {b_key}: {b_value}")
elif b_value != a[b_key]:
mismatch.append(f"For {b_key} got {a[b_key]}, expected {b_value}")
for a_key, a_value in a.items():
if a_key not in b:
mismatch.append(f"Extraneous item {a_key}: {a_value}")
mismatch_str = "\n".join(mismatch)
assert len(mismatch) == 0, f"{message_start}\n{mismatch_str}"
|
manim_ManimCommunity/tests/test_ipython_magic.py
|
from __future__ import annotations
import re
from manim import tempconfig
from manim.utils.ipython_magic import _generate_file_name
def test_jupyter_file_naming():
"""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"
with tempconfig({"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):
"""Check the jupyter file naming is valid and can be created"""
scene_name = "SimpleScene"
with tempconfig({"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()
|
manim_ManimCommunity/tests/test_config.py
|
from __future__ import annotations
import os
import tempfile
from pathlib import Path
import numpy as np
from manim import WHITE, Scene, Square, Tex, Text, config, tempconfig
from manim._config.utils import ManimConfig
from tests.assert_utils import assert_dir_exists, assert_dir_filled, assert_file_exists
def test_tempconfig():
"""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.add(Text("Prepare for unforeseen consequencesλ"))
self.add(Tex(r"$\lambda$"))
self.wait(1)
def test_transparent():
"""Test the 'transparent' config option."""
orig_verbosity = config["verbosity"]
config["verbosity"] = "ERROR"
with tempconfig({"dry_run": True}):
scene = MyScene()
scene.render()
frame = scene.renderer.get_frame()
np.testing.assert_allclose(frame[0, 0], [0, 0, 0, 255])
with tempconfig({"transparent": True, "dry_run": True}):
scene = MyScene()
scene.render()
frame = scene.renderer.get_frame()
np.testing.assert_allclose(frame[0, 0], [0, 0, 0, 0])
config["verbosity"] = orig_verbosity
def test_background_color():
"""Test the 'background_color' config option."""
with tempconfig({"background_color": WHITE, "verbosity": "ERROR", "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):
"""Test that a config file can be digested programmatically."""
with tempconfig({}):
tmp_cfg = tempfile.NamedTemporaryFile("w", dir=tmp_path, delete=False)
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
""",
)
tmp_cfg.close()
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):
with tempconfig(
{
"media_dir": tmp_path,
"save_sections": True,
"log_to_file": True,
"frame_rate": 15,
"pixel_height": 854,
"pixel_width": 480,
"save_sections": True,
"sections_dir": "{media_dir}/test_sections",
"video_dir": "{media_dir}/test_video",
"partial_movie_dir": "{media_dir}/test_partial_movie_dir",
"images_dir": "{media_dir}/test_images",
"text_dir": "{media_dir}/test_text",
"tex_dir": "{media_dir}/test_tex",
"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_frame_size(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({}):
tmp_cfg = tempfile.NamedTemporaryFile("w", dir=tmp_path, delete=False)
tmp_cfg.write(
"""
[CLI]
pixel_height = 10
pixel_width = 10
""",
)
tmp_cfg.close()
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)
with tempconfig({}):
tmp_cfg = tempfile.NamedTemporaryFile("w", dir=tmp_path, delete=False)
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():
"""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():
"""Test that there are no exceptions when running a png without output"""
with tempconfig(
{"dry_run": True, "write_to_movie": False, "disable_caching": True}
):
assert config["dry_run"] is True
scene = MyScene()
scene.render()
def test_dry_run_with_png_format_skipped_animations():
"""Test that there are no exceptions when running a png without output and skipped animations"""
with tempconfig(
{"dry_run": True, "write_to_movie": False, "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!")
tmp_cfg = tempfile.NamedTemporaryFile("w", dir=tmp_path, delete=False)
tmp_cfg.write(
f"""
[CLI]
tex_template_file = { tex_file }
""",
)
tmp_cfg.close()
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!"
|
manim_ManimCommunity/tests/template_generate_graphical_units_data.py
|
from __future__ import annotations
from manim import *
from tests.helpers.graphical_units import set_test_scene
# Note: DO NOT COMMIT THIS FILE. The purpose of this template is to produce control data for graphical_units_data. As
# soon as the test data is produced, please revert all changes you made to this file, so this template file will be
# still available for others :)
# More about graphical unit tests: https://github.com/ManimCommunity/manim/wiki/Testing#graphical-unit-test
class YourClassTest(Scene): # e.g. RoundedRectangleTest
def construct(self):
circle = Circle()
self.play(Animation(circle))
set_test_scene(
YourClassTest,
"INSERT_MODULE_NAME",
) # INSERT_MODULE_NAME can be e.g. "geometry" or "movements"
|
manim_ManimCommunity/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) and isinstance(ghosts[0], VGroup)
assert all(isinstance(x, Vector) for x in ghosts[0])
|
manim_ManimCommunity/tests/test_code_mobject.py
|
from manim.mobject.text.code_mobject import Code
def test_code_indentation():
co = Code(
code="""\
def test()
print("Hi")
""",
language="Python",
indentation_chars=" ",
)
assert co.tab_spaces[0] == 1
assert co.tab_spaces[1] == 2
|
manim_ManimCommunity/tests/test_camera.py
|
from __future__ import annotations
from manim import MovingCamera, Square
def test_movingcamera_auto_zoom():
camera = MovingCamera()
square = Square()
margin = 0.5
camera.auto_zoom([square], margin=margin, animate=False)
assert camera.frame.height == square.height + margin
|
manim_ManimCommunity/tests/helpers/__init__.py
| |
manim_ManimCommunity/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 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}")
|
manim_ManimCommunity/tests/helpers/graphical_units.py
|
"""Helpers functions for devs to set up new graphical-units data."""
from __future__ import annotations
import tempfile
from pathlib import Path
import numpy as np
from manim import config, logger
from manim.scene.scene import Scene
def set_test_scene(scene_object: type[Scene], module_name: str):
"""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 {str(scene)} 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")
|
manim_ManimCommunity/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,
)
|
manim_ManimCommunity/tests/interface/test_commands.py
|
from __future__ import annotations
import shutil
import sys
from pathlib import Path
from textwrap import dedent
from click.testing import CliRunner
from manim import __version__, capture, tempconfig
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)
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()
with tempconfig({"ffmpeg_executable": "/path/to/nowhere"}):
result = runner.invoke(main, command)
output_lines = result.output.split("\n")
assert "- Checking whether ffmpeg is available ... FAILED" in output_lines
assert "- Checking whether ffmpeg is working ... 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
|
manim_ManimCommunity/tests/utils/__init__.py
| |
manim_ManimCommunity/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,
)
|
manim_ManimCommunity/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 = 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
|
manim_ManimCommunity/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"]
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
|
manim_ManimCommunity/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__)
|
manim_ManimCommunity/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()
|
manim_ManimCommunity/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]
)
|
manim_ManimCommunity/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
|
manim_ManimCommunity/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
from manim import CoordinateSystem as CS
from manim import NumberPlane, PolarPlane, ThreeDAxes, config, tempconfig
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(Exception):
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))
|
manim_ManimCommunity/tests/opengl/test_ipython_magic_opengl.py
|
from __future__ import annotations
import re
from manim import config, tempconfig
from manim.utils.ipython_magic import _generate_file_name
def test_jupyter_file_naming():
"""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"
current_renderer = config.renderer
with tempconfig({"scene_names": [scene_name], "renderer": "opengl"}):
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
# needs manually set back to avoid issues across tests
config.renderer = current_renderer
def test_jupyter_file_output(tmp_path):
"""Check the jupyter file naming is valid and can be created"""
scene_name = "SimpleScene"
current_renderer = config.renderer
with tempconfig({"scene_names": [scene_name], "renderer": "opengl"}):
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()
# needs manually set back to avoid issues across tests
config.renderer = current_renderer
|
manim_ManimCommunity/tests/opengl/__init__.py
| |
manim_ManimCommunity/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"
|
manim_ManimCommunity/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 == [(wait, 0.0, 1.0), (sqr_anim, 1.0, 2.0)]
|
manim_ManimCommunity/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), (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()
|
manim_ManimCommunity/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, config, tempconfig
def test_tempconfig(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(using_opengl_renderer):
"""Test the 'background_color' config option."""
with tempconfig({"background_color": WHITE, "verbosity": "ERROR", "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(using_opengl_renderer, tmp_path):
"""Test that a config file can be digested programmatically."""
with tempconfig({}):
tmp_cfg = tempfile.NamedTemporaryFile("w", dir=tmp_path, delete=False)
tmp_cfg.write(
"""
[CLI]
media_dir = this_is_my_favorite_path
video_dir = {media_dir}/videos
frame_height = 10
""",
)
tmp_cfg.close()
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(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({}):
tmp_cfg = tempfile.NamedTemporaryFile("w", dir=tmp_path, delete=False)
tmp_cfg.write(
"""
[CLI]
pixel_height = 10
pixel_width = 10
""",
)
tmp_cfg.close()
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)
with tempconfig({}):
tmp_cfg = tempfile.NamedTemporaryFile("w", dir=tmp_path, delete=False)
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(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(using_opengl_renderer):
"""Test that there are no exceptions when running a png without output"""
with tempconfig(
{"dry_run": True, "write_to_movie": False, "disable_caching": True}
):
assert config["dry_run"] is True
scene = MyScene()
scene.render()
def test_dry_run_with_png_format_skipped_animations(using_opengl_renderer):
"""Test that there are no exceptions when running a png without output and skipped animations"""
with tempconfig(
{"dry_run": True, "write_to_movie": False, "disable_caching": True}
):
assert config["dry_run"] is True
scene = MyScene(skip_animations=True)
scene.render()
|
manim_ManimCommunity/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 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
|
manim_ManimCommunity/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)
|
manim_ManimCommunity/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")
f = wave.open(str(sound_loc), "w")
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)
f.close()
scene = Scene()
scene.add_sound(sound_loc)
|
manim_ManimCommunity/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)
)
|
manim_ManimCommunity/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)
|
manim_ManimCommunity/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
from manim.mobject.opengl.opengl_mobject import OpenGLMobject
from manim.mobject.opengl.opengl_vectorized_mobject import OpenGLVMobject
def test_opengl_vmobject_point_from_propotion(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())
with pytest.raises(TypeError):
VGroup(OpenGLMobject())
with pytest.raises(TypeError):
VGroup(OpenGLMobject(), OpenGLMobject())
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
with pytest.raises(TypeError):
obj.add(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.add(OpenGLVMobject(), OpenGLMobject())
assert len(obj.submobjects) == 1
with pytest.raises(ValueError):
# a OpenGLMobject cannot contain itself
obj.add(obj)
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(), "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, match="All submobjects must be of type VMobject"):
vgroup[0] = "invalid object"
|
manim_ManimCommunity/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
obj = OpenGLMobject()
# a OpenGLMobject cannot contain itself
with pytest.raises(ValueError):
obj.add(obj)
# can only add OpenGLMobjects
with pytest.raises(TypeError):
obj.add("foo")
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
|
manim_ManimCommunity/tests/opengl/test_texmobject_opengl.py
|
from __future__ import annotations
from pathlib import Path
import pytest
from manim import MathTex, SingleStringMathTex, Tex, config
def test_MathTex(using_opengl_renderer):
MathTex("a^2 + b^2 = c^2")
assert Path(config.media_dir, "Tex", "e4be163a00cf424f.svg").exists()
def test_SingleStringMathTex(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(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 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
|
manim_ManimCommunity/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 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])
|
manim_ManimCommunity/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
and (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
and (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)
|
manim_ManimCommunity/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
|
manim_ManimCommunity/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()
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"
|
manim_ManimCommunity/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
|
manim_ManimCommunity/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, 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}."
|
manim_ManimCommunity/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
|
manim_ManimCommunity/tests/opengl/test_copy_opengl.py
|
from __future__ import annotations
from pathlib import Path
from manim import BraceLabel, config
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(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
|
manim_ManimCommunity/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
|
manim_ManimCommunity/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)
|
manim_ManimCommunity/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()))
|
manim_ManimCommunity/tests/test_logging/__init__.py
| |
manim_ManimCommunity/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")
|
manim_ManimCommunity/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))
|
manim_ManimCommunity/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),
]
_, err, exitcode = capture(command)
assert exitcode != 0 and len(err) > 0
@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 and len(err) > 0
|
manim_ManimCommunity/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],
) and scene.camera.frame.get_center()[0] == (
abs(s1.get_center()[0] + s2.get_center()[0]) / 2
)
|
manim_ManimCommunity/tests/module/scene/test_scene.py
|
from __future__ import annotations
import datetime
import pytest
from manim import Circle, FadeIn, Group, Mobject, Scene, Square, tempconfig
from manim.animation.animation import Wait
def test_scene_add_remove():
with tempconfig({"dry_run": True}):
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():
with tempconfig({"dry_run": True}):
scene = Scene()
assert scene.renderer.time == 0
scene.wait(2)
assert scene.renderer.time == 2
scene.play(FadeIn(Circle()), run_time=0.5)
assert pytest.approx(scene.renderer.time) == 2.5
scene.renderer._original_skipping_status = True
scene.play(FadeIn(Square()), run_time=5) # this animation gets skipped.
assert pytest.approx(scene.renderer.time) == 7.5
def test_subcaption():
with tempconfig({"dry_run": True}):
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():
def assert_names(mobjs, names):
assert len(mobjs) == len(names)
for i in range(0, len(mobjs)):
assert mobjs[i].name == names[i]
with tempconfig({"dry_run": True}):
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"])
|
manim_ManimCommunity/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")
f = wave.open(str(sound_loc), "w")
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)
f.close()
scene = Scene()
scene.add_sound(sound_loc)
|
manim_ManimCommunity/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
|
manim_ManimCommunity/tests/module/mobject/test_graph.py
|
from __future__ import annotations
import pytest
from manim import DiGraph, Graph, Scene, Text, tempconfig
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()) == set()
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_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"
|
manim_ManimCommunity/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)
|
manim_ManimCommunity/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)
|
manim_ManimCommunity/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_iadd():
"""Test ValueTracker.__iadd__()"""
tracker = ValueTracker(0.0)
tracker += 10.0
assert tracker.get_value() == 10.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_imod():
"""Test ValueTracker.__imod__()"""
tracker = ValueTracker(20.0)
tracker %= 3.0
assert tracker.get_value() == 2.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_ipow():
"""Test ValueTracker.__ipow__()"""
tracker = ValueTracker(3.0)
tracker **= 3.0
assert tracker.get_value() == 27.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_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
|
manim_ManimCommunity/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)
|
manim_ManimCommunity/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, config, tempconfig
from manim.mobject.types.vectorized_mobject import VMobject
from manim.utils.color import RED
def test_MathTex():
MathTex("a^2 + b^2 = c^2")
assert Path(config.media_dir, "Tex", "e4be163a00cf424f.svg").exists()
def test_SingleStringMathTex():
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():
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():
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 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) as err:
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():
my_template = TexTemplate()
my_template.preamble = "Custom preamble!"
tex_template_config_value = config.tex_template
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):
monkeypatch.chdir(tmpdir)
Path(tmpdir, "media").mkdir()
with tempconfig({"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()
with tempconfig({"media_dir": "media", "no_latex_cleanup": True}):
tex_with_log = Tex("Hello World, again!") # da27670a37b08799.tex
assert Path("media", "Tex", "da27670a37b08799.log").exists()
|
manim_ManimCommunity/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"
|
manim_ManimCommunity/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 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
)
|
manim_ManimCommunity/tests/module/mobject/mobject/test_opengl_metaclass.py
|
from __future__ import annotations
from manim import Mobject, config, tempconfig
from manim.mobject.opengl.opengl_compatibility import ConvertToOpenGL
from manim.mobject.opengl.opengl_mobject import OpenGLMobject
def test_metaclass_registry():
class SomeTestMobject(Mobject, metaclass=ConvertToOpenGL):
pass
assert SomeTestMobject in ConvertToOpenGL._converted_classes
with tempconfig({"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__
|
manim_ManimCommunity/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
obj = Mobject()
# a Mobject cannot contain itself
with pytest.raises(ValueError):
obj.add(obj)
# can only add Mobjects
with pytest.raises(TypeError):
obj.add("foo")
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
|
manim_ManimCommunity/tests/module/mobject/mobject/test_copy.py
|
from __future__ import annotations
from pathlib import Path
from manim import BraceLabel, Mobject, config
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):
"""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
|
manim_ManimCommunity/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
|
manim_ManimCommunity/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,
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])
|
manim_ManimCommunity/tests/module/mobject/mobject/test_set_attr.py
|
from __future__ import annotations
import numpy as np
from manim import RendererType, config
from manim.constants import RIGHT
from manim.mobject.geometry.polygram import Square
def test_Data():
config.renderer = RendererType.OPENGL
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)
config.renderer = (
RendererType.CAIRO
) # needs to be here or else the following cairo tests fail
|
manim_ManimCommunity/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],
[4.508331116720995, -1.0, 0],
[13.524988331417841, -1.0, 0],
]
),
decimal=5,
)
|
manim_ManimCommunity/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 = 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
|
manim_ManimCommunity/tests/module/mobject/graphing/test_number_line.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, 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))
|
manim_ManimCommunity/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),
)
|
manim_ManimCommunity/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
from manim import CoordinateSystem as CS
from manim import NumberPlane, PolarPlane, ThreeDAxes, config, tempconfig
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(Exception):
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 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)
np.testing.assert_array_equal(c2p_coord, (1.7143, 1.5, 0))
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))
|
manim_ManimCommunity/tests/module/mobject/geometry/test_unit_geometry.py
|
from __future__ import annotations
import logging
import numpy as np
logger = logging.getLogger(__name__)
from manim import BackgroundRectangle, Circle, Sector
def test_get_arc_center():
np.testing.assert_array_equal(
Sector(arc_center=[1, 2, 0]).get_arc_center(), [1, 2, 0]
)
def test_BackgroundRectangle(caplog):
caplog.set_level(logging.INFO)
c = Circle()
bg = BackgroundRectangle(c)
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 caplog.text
)
|
manim_ManimCommunity/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_point_from_propotion():
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())
with pytest.raises(TypeError):
VGroup(Mobject())
with pytest.raises(TypeError):
VGroup(Mobject(), Mobject())
def test_vgroup_add():
"""Test the VGroup add method."""
obj = VGroup()
assert len(obj.submobjects) == 0
obj.add(VMobject())
assert len(obj.submobjects) == 1
with pytest.raises(TypeError):
obj.add(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.add(VMobject(), Mobject())
assert len(obj.submobjects) == 1
with pytest.raises(ValueError):
# a Mobject cannot contain itself
obj.add(obj)
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 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, match="All submobjects must be of type VMobject"):
vgroup[0] = "invalid object"
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])
|
manim_ManimCommunity/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
|
manim_ManimCommunity/tests/module/utils/test_tex.py
|
import pytest
from manim.utils.tex import TexTemplate
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")
|
manim_ManimCommunity/tests/module/utils/test_deprecation.py
|
from __future__ import annotations
import logging
import pytest
from manim.utils.deprecation import deprecated, deprecated_params
def _get_caplog_record_msg(warn_caplog_manim):
logger_name, level, message = warn_caplog_manim.record_tuples[0]
return message
@pytest.fixture()
def warn_caplog_manim(caplog):
caplog.set_level(logging.WARNING, logger="manim")
yield caplog
@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(warn_caplog_manim):
"""Test the deprecation of a class (decorator with no arguments)."""
f = Foo()
assert len(warn_caplog_manim.record_tuples) == 1
msg = _get_caplog_record_msg(warn_caplog_manim)
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(warn_caplog_manim):
"""Test the deprecation of a class (decorator with since argument)."""
b = Bar()
assert len(warn_caplog_manim.record_tuples) == 1
msg = _get_caplog_record_msg(warn_caplog_manim)
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(warn_caplog_manim):
"""Test the deprecation of a class (decorator with until argument)."""
bz = Baz()
assert len(warn_caplog_manim.record_tuples) == 1
msg = _get_caplog_record_msg(warn_caplog_manim)
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(warn_caplog_manim):
"""Test the deprecation of a class (decorator with since and until arguments)."""
qx = Qux()
assert len(warn_caplog_manim.record_tuples) == 1
msg = _get_caplog_record_msg(warn_caplog_manim)
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(warn_caplog_manim):
"""Test the deprecation of a class (decorator with msg argument)."""
qu = Quux()
assert len(warn_caplog_manim.record_tuples) == 1
msg = _get_caplog_record_msg(warn_caplog_manim)
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(warn_caplog_manim):
"""Test the deprecation of a class (decorator with replacement argument)."""
qz = Quuz()
assert len(warn_caplog_manim.record_tuples) == 1
msg = _get_caplog_record_msg(warn_caplog_manim)
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(warn_caplog_manim):
"""Test the deprecation of a class (decorator with all arguments)."""
qza = QuuzAll()
assert len(warn_caplog_manim.record_tuples) == 1
msg = _get_caplog_record_msg(warn_caplog_manim)
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(warn_caplog_manim):
"""Test the deprecation of a method (decorator with no arguments)."""
useless()
assert len(warn_caplog_manim.record_tuples) == 1
msg = _get_caplog_record_msg(warn_caplog_manim)
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(warn_caplog_manim):
"""Test the deprecation of a method within a class (decorator with since and message arguments)."""
t = Top()
t.mid_func()
assert len(warn_caplog_manim.record_tuples) == 1
msg = _get_caplog_record_msg(warn_caplog_manim)
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(warn_caplog_manim):
"""Test the deprecation of a nested class (decorator with until and replacement arguments)."""
n = Top().Nested()
assert len(warn_caplog_manim.record_tuples) == 1
msg = _get_caplog_record_msg(warn_caplog_manim)
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(warn_caplog_manim):
"""Test the deprecation of a method within a nested class (decorator with since and until arguments)."""
n = Top().NewNested()
n.nested_func()
assert len(warn_caplog_manim.record_tuples) == 1
msg = _get_caplog_record_msg(warn_caplog_manim)
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(warn_caplog_manim):
"""Test the deprecation of a nested method (decorator with no arguments)."""
b = Top().Bottom()
answer = b.normal_func()
answer(1)
assert len(warn_caplog_manim.record_tuples) == 1
msg = _get_caplog_record_msg(warn_caplog_manim)
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(warn_caplog_manim):
"""Test the deprecation of method parameters (decorator with params argument)."""
t = Top()
t.foo(a=2, b=3, z=4)
assert len(warn_caplog_manim.record_tuples) == 1
msg = _get_caplog_record_msg(warn_caplog_manim)
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(warn_caplog_manim):
"""Test the deprecation of a single method parameter (decorator with since and until arguments)."""
t = Top()
t.bar(a=1, b=2)
assert len(warn_caplog_manim.record_tuples) == 1
msg = _get_caplog_record_msg(warn_caplog_manim)
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(warn_caplog_manim):
"""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(warn_caplog_manim.record_tuples) == 1
msg = _get_caplog_record_msg(warn_caplog_manim)
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(warn_caplog_manim):
"""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(warn_caplog_manim.record_tuples) == 1
msg = _get_caplog_record_msg(warn_caplog_manim)
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(warn_caplog_manim):
"""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(warn_caplog_manim.record_tuples) == 1
msg = _get_caplog_record_msg(warn_caplog_manim)
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(warn_caplog_manim):
"""Test the deprecation of one method parameter and redirecting it to many."""
t = Top()
obj1 = t.quuz(point2D=0)
assert len(warn_caplog_manim.record_tuples) == 1
msg = _get_caplog_record_msg(warn_caplog_manim)
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}
warn_caplog_manim.clear()
obj2 = t.quuz(point2D=(2, 3))
assert len(warn_caplog_manim.record_tuples) == 1
msg = _get_caplog_record_msg(warn_caplog_manim)
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}
|
manim_ManimCommunity/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")
|
manim_ManimCommunity/tests/module/utils/test_manim_color.py
|
from __future__ import annotations
import numpy as np
import numpy.testing as nt
from manim.utils.color import BLACK, WHITE, ManimColor, ManimColorDType
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)
)
|
manim_ManimCommunity/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 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())
|
manim_ManimCommunity/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, shoelace_direction
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],
]
),
)
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])
)
|
manim_ManimCommunity/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, config
from manim.utils.unit import Degrees, Munits, Percent, Pixels
def test_units():
# make sure we are using the right frame geometry
assert 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)
|
manim_ManimCommunity/tests/module/utils/test_color.py
|
from __future__ import annotations
import numpy as np
from manim import BLACK, 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"
|
manim_ManimCommunity/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
|
manim_ManimCommunity/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 = 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 == [(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_empty_animation_group_fails():
with pytest.raises(ValueError, match="Please add at least one Animation"):
AnimationGroup().begin()
def test_empty_animation_fails():
with pytest.raises(ValueError, match="Please set the run_time to be positive"):
FadeIn(None, run_time=0).begin()
|
manim_ManimCommunity/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
and (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):
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
and (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)
|
manim_ManimCommunity/tests/module/animation/test_creation.py
|
from __future__ import annotations
import numpy as np
import pytest
from manim import AddTextLetterByLetter, Text, config
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():
"""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
|
manim_ManimCommunity/tests/test_plugins/__init__.py
| |
manim_ManimCommunity/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))
|
manim_ManimCommunity/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(
"""\
[tool.poetry]
name = "{plugin_name}"
authors = ["ManimCE Test Suite"]
version = "0.1.0"
description = ""
[tool.poetry.dependencies]
python = "^3.7"
[tool.poetry.plugins."manim.plugins"]
"{plugin_name}" = "{plugin_entrypoint}"
[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"
""",
)
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():
yield 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)]
yield "".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
|
manim_ManimCommunity/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)
|
manim_ManimCommunity/tests/test_graphical_units/test_vector_scene.py
|
from __future__ import annotations
from manim.scene.vector_space_scene import 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()
|
manim_ManimCommunity/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),
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 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()
r = lambda theta: 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)
|
manim_ManimCommunity/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
|
manim_ManimCommunity/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))
|
manim_ManimCommunity/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()
|
manim_ManimCommunity/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())
|
manim_ManimCommunity/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):
yield request.param
|
manim_ManimCommunity/tests/test_graphical_units/__init__.py
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.