Video editing with Python
Rewrite helpers as fixtures in tests (#1612)
Álvaro Mondéjar890822626482
diff --git a/setup.cfg b/setup.cfgindex df55fff3..9abc1632 100644--- a/setup.cfg+++ b/setup.cfg@@ -47,8 +47,8 @@ use_parentheses = Truecombine_as_imports = Trueinclude_trailing_comma = Truepy_version = 36-known_tests = tests-sections = STDLIB,THIRDPARTY,FIRSTPARTY,TESTS,LOCALFOLDER+known_tests_third_party = pytest+sections = STDLIB,THIRDPARTY,TESTS_THIRD_PARTY,FIRSTPARTY,LOCALFOLDER[coverage:report]exclude_lines =diff --git a/tests/test_helper.py b/tests/conftest.pysimilarity index 86%rename from tests/test_helper.pyrename to tests/conftest.pyindex d3065ad5..e0626337 100644--- a/tests/test_helper.py+++ b/tests/conftest.py@@ -15,10 +15,11 @@ import threadingimport numpy as np+import pytest+from moviepy.video.io.VideoFileClip import VideoFileClip-PYTHON_VERSION = "%s.%s" % (sys.version_info.major, sys.version_info.minor)TMP_DIR = tempfile.gettempdir() # because tempfile.tempdir is sometimes None# Arbitrary font used in caption testing.@@ -33,8 +34,10 @@ else:@functools.lru_cache(maxsize=None)-def get_test_video():- return VideoFileClip("media/big_buck_bunny_432_433.webm").subclip(0, 1)+def get_video(start_time=0, end_time=1):+ return VideoFileClip("media/big_buck_bunny_432_433.webm").subclip(+ start_time, end_time+ )@functools.lru_cache(maxsize=None)@@ -56,7 +59,7 @@ def get_mono_wave(freq=440):@contextlib.contextmanager-def static_files_server(port=8000):+def get_static_files_server(port=8000):my_server = socketserver.TCPServer(("", port), http.server.SimpleHTTPRequestHandler)thread = threading.Thread(target=my_server.serve_forever, daemon=True)thread.start()@@ -139,3 +142,42 @@ def get_functions_with_decorator_defined(code, decorator_name):visitor = FunctionsWithDefinedDecoratorExtractor()visitor.visit(modtree)return visitor.functions_with_decorator+++def util():+ class MoviepyTestUtils:+ FONT = FONT+ TMP_DIR = TMP_DIR++ return MoviepyTestUtils+++def video():+ return get_video+++def stereo_wave():+ return get_stereo_wave+++def mono_wave():+ return get_mono_wave+++def static_files_server():+ return get_static_files_server+++def moviepy_modules():+ return get_moviepy_modules+++def functions_with_decorator_defined():+ return get_functions_with_decorator_defineddiff --git a/tests/test_AudioClips.py b/tests/test_AudioClips.pyindex 40e0ce2d..1039f30d 100644--- a/tests/test_AudioClips.py+++ b/tests/test_AudioClips.py@@ -3,6 +3,7 @@import osimport numpy as np+import pytestfrom moviepy.audio.AudioClip import (@@ -12,59 +13,57 @@ from moviepy.audio.AudioClip import (concatenate_audioclips,)from moviepy.audio.io.AudioFileClip import AudioFileClip-from moviepy.utils import close_all_clips--from tests.test_helper import TMP_DIR, get_mono_wave, get_stereo_wave-def test_audioclip():- audio = AudioClip(get_mono_wave(440), duration=2, fps=22050)- audio.write_audiofile(os.path.join(TMP_DIR, "audioclip.mp3"), bitrate="16")+def test_audioclip(util, mono_wave):+ filename = os.path.join(util.TMP_DIR, "audioclip.mp3")+ audio = AudioClip(mono_wave(440), duration=2, fps=22050)+ audio.write_audiofile(filename, bitrate="16", logger=None)- assert os.path.exists(os.path.join(TMP_DIR, "audioclip.mp3"))+ assert os.path.exists(filename)- clip = AudioFileClip(os.path.join(TMP_DIR, "audioclip.mp3"))+ AudioFileClip(filename)# TODO Write better tests; find out why the following fail# assert clip.duration == 2# assert clip.fps == 22050# assert clip.reader.bitrate == 16- close_all_clips(locals())-def test_audioclip_io():+def test_audioclip_io(util):+ filename = os.path.join(util.TMP_DIR, "random.wav")+# Generate a random audio clip of 4.989 seconds at 44100 Hz,# and save it to a file.input_array = np.random.random((220000, 2)) * 1.98 - 0.99clip = AudioArrayClip(input_array, fps=44100)- clip.write_audiofile(os.path.join(TMP_DIR, "random.wav"))+ clip.write_audiofile(filename, logger=None)# Load the clip.# The loaded clip will be slightly longer because the duration is rounded# up to 4.99 seconds.# Verify that the extra frames are all zero, and the remainder is identical# to the original signal.- clip = AudioFileClip(os.path.join(TMP_DIR, "random.wav"))+ clip = AudioFileClip(filename)output_array = clip.to_soundarray()np.testing.assert_array_almost_equal(output_array[: len(input_array)], input_array, decimal=4)assert (output_array[len(input_array) :] == 0).all()- close_all_clips(locals())--def test_concatenate_audioclips_render():+def test_concatenate_audioclips_render(util, mono_wave):"""Concatenated AudioClips through ``concatenate_audioclips`` should returna clip that can be rendered to a file."""- clip_440 = AudioClip(get_mono_wave(440), duration=0.01, fps=44100)- clip_880 = AudioClip(get_mono_wave(880), duration=0.000001, fps=22050)+ filename = os.path.join(util.TMP_DIR, "concatenate_audioclips.mp3")++ clip_440 = AudioClip(mono_wave(440), duration=0.01, fps=44100)+ clip_880 = AudioClip(mono_wave(880), duration=0.000001, fps=22050)concat_clip = concatenate_audioclips((clip_440, clip_880))- concat_clip.write_audiofile(os.path.join(TMP_DIR, "concatenate_audioclips.mp3"))+ concat_clip.write_audiofile(filename, logger=None)assert concat_clip.duration == clip_440.duration + clip_880.duration- close_all_clips(locals())def test_concatenate_audioclips_CompositeAudioClip():@@ -107,8 +106,6 @@ def test_concatenate_audioclips_CompositeAudioClip():# channels are maximum number of channels of the clipsassert concat_clip.nchannels == max(clip.nchannels for clip in clips)- close_all_clips(locals())-def test_CompositeAudioClip_by__init__():"""The difference between the CompositeAudioClip returned by@@ -146,12 +143,10 @@ def test_CompositeAudioClip_by__init__():# channels are maximum number of channels of the clipsassert compound_clip.nchannels == max(clip.nchannels for clip in clips)- close_all_clips(locals())--def test_concatenate_audioclip_with_audiofileclip():+def test_concatenate_audioclip_with_audiofileclip(util, stereo_wave):clip1 = AudioClip(- get_stereo_wave(left_freq=440, right_freq=880),+ stereo_wave(left_freq=440, right_freq=880),duration=1,fps=44100,)@@ -159,28 +154,30 @@ def test_concatenate_audioclip_with_audiofileclip():concat_clip = concatenate_audioclips((clip1, clip2))concat_clip.write_audiofile(- os.path.join(TMP_DIR, "concat_clip_with_file_audio.mp3")+ os.path.join(util.TMP_DIR, "concat_clip_with_file_audio.mp3"),+ logger=None,)assert concat_clip.duration == clip1.duration + clip2.duration-def test_concatenate_audiofileclips():+def test_concatenate_audiofileclips(util):clip1 = AudioFileClip("media/crunching.mp3").subclip(1, 4)# Checks it works with videos as wellclip2 = AudioFileClip("media/big_buck_bunny_432_433.webm")concat_clip = concatenate_audioclips((clip1, clip2))- concat_clip.write_audiofile(os.path.join(TMP_DIR, "concat_audio_file.mp3"))+ concat_clip.write_audiofile(+ os.path.join(util.TMP_DIR, "concat_audio_file.mp3"),+ logger=None,+ )assert concat_clip.duration == clip1.duration + clip2.duration- close_all_clips(locals())--def test_audioclip_mono_max_volume():- clip = AudioClip(get_mono_wave(440), duration=1, fps=44100)+def test_audioclip_mono_max_volume(mono_wave):+ clip = AudioClip(mono_wave(440), duration=1, fps=44100)max_volume = clip.max_volume()assert isinstance(max_volume, float)assert max_volume > 0diff --git a/tests/test_BitmapClip.py b/tests/test_BitmapClip.pyindex cdaa9077..32df3fa0 100644--- a/tests/test_BitmapClip.py+++ b/tests/test_BitmapClip.py@@ -1,6 +1,7 @@"""BitmapClip tests."""import numpy as np+import pytestfrom moviepy.video.VideoClip import BitmapClipdiff --git a/tests/test_Clip.py b/tests/test_Clip.pyindex 0372692f..19d51b9c 100644--- a/tests/test_Clip.py+++ b/tests/test_Clip.py@@ -3,6 +3,7 @@import copyimport numpy as np+import pytestfrom moviepy.Clip import Clipdiff --git a/tests/test_ImageSequenceClip.py b/tests/test_ImageSequenceClip.pyindex 9fa11973..973c6d8f 100644--- a/tests/test_ImageSequenceClip.py+++ b/tests/test_ImageSequenceClip.py@@ -6,10 +6,8 @@ import pytestfrom moviepy.video.io.ImageSequenceClip import ImageSequenceClip-from tests.test_helper import TMP_DIR--def test_1():+def test_1(util):images = []durations = []@@ -21,7 +19,9 @@ def test_1():with ImageSequenceClip(images, durations=durations) as clip:assert clip.duration == sum(durations)- clip.write_videofile(os.path.join(TMP_DIR, "ImageSequenceClip1.mp4"), fps=30)+ clip.write_videofile(+ os.path.join(util.TMP_DIR, "ImageSequenceClip1.mp4"), fps=30, logger=None+ )def test_2():diff --git a/tests/test_PR.py b/tests/test_PR.pyindex 4f46cd90..ab895eb8 100644--- a/tests/test_PR.py+++ b/tests/test_PR.py@@ -6,7 +6,6 @@ from pathlib import Pathimport pytestfrom moviepy.audio.io.AudioFileClip import AudioFileClip-from moviepy.utils import close_all_clipsfrom moviepy.video.compositing.CompositeVideoClip import CompositeVideoClipfrom moviepy.video.fx.scroll import scrollfrom moviepy.video.io.VideoFileClip import VideoFileClip@@ -14,8 +13,6 @@ from moviepy.video.tools.interpolators import Trajectoryfrom moviepy.video.tools.subtitles import SubtitlesClipfrom moviepy.video.VideoClip import ColorClip, ImageClip, TextClip-from tests.test_helper import FONT, TMP_DIR, get_test_video-def test_PR_306():assert TextClip.list("font") != []@@ -23,15 +20,14 @@ def test_PR_306():with pytest.raises(Exception):TextClip.list("blah")- close_all_clips(locals())-def test_PR_339():+def test_PR_339(util):# In caption mode.TextClip(text="foo",color="white",- font=FONT,+ font=util.FONT,size=(640, 480),method="caption",align="center",@@ -39,15 +35,15 @@ def test_PR_339():).close()# In label mode.- TextClip(text="foo", font=FONT, method="label").close()+ TextClip(text="foo", font=util.FONT, method="label").close()-def test_PR_373():+def test_PR_373(util):result = Trajectory.load_list("media/traj.txt")- Trajectory.save_list(result, os.path.join(TMP_DIR, "traj1.txt"))+ Trajectory.save_list(result, os.path.join(util.TMP_DIR, "traj1.txt"))- result1 = Trajectory.load_list(os.path.join(TMP_DIR, "traj1.txt"))+ result1 = Trajectory.load_list(os.path.join(util.TMP_DIR, "traj1.txt"))assert len(result[0].tt) == len(result1[0].tt)for i in range(len(result[0].tt)):@@ -62,9 +58,9 @@ def test_PR_373():assert result[0].yy[i] == result1[0].yy[i]-def test_PR_458():+def test_PR_458(util):clip = ColorClip([1000, 600], color=(60, 60, 60), duration=2)- clip.write_videofile(os.path.join(TMP_DIR, "test.mp4"), logger=None, fps=30)+ clip.write_videofile(os.path.join(util.TMP_DIR, "test.mp4"), logger=None, fps=30)clip.close()@@ -76,12 +72,12 @@ def test_PR_515():assert clip.fps == 10.51-def test_PR_528():+def test_PR_528(util):with ImageClip("media/vacation_2017.jpg") as clip:new_clip = scroll(clip, w=1000, x_speed=50)new_clip = new_clip.with_duration(0.2)new_clip.fps = 24- new_clip.write_videofile(os.path.join(TMP_DIR, "pano.mp4"))+ new_clip.write_videofile(os.path.join(util.TMP_DIR, "pano.mp4"), logger=None)def test_PR_529():@@ -99,17 +95,17 @@ def test_PR_610():assert composite.fps == 25-def test_PR_1137_video():+def test_PR_1137_video(util, video):"""Test support for path-like objects as arguments for VideoFileClip."""- with get_test_video().subclip(0.2, 0.4) as video:- video.write_videofile(Path(TMP_DIR) / "pathlike.mp4")+ with video(start_time=0.2, end_time=0.24) as video:+ video.write_videofile(Path(util.TMP_DIR) / "pathlike.mp4", logger=None)assert isinstance(video.filename, str)-def test_PR_1137_audio():+def test_PR_1137_audio(util):"""Test support for path-like objects as arguments for AudioFileClip."""with AudioFileClip(Path("media/crunching.mp3")) as audio:- audio.write_audiofile(Path(TMP_DIR) / "pathlike.mp3")+ audio.write_audiofile(Path(util.TMP_DIR) / "pathlike.mp3")assert isinstance(audio.filename, str)@@ -118,13 +114,13 @@ def test_PR_1137_image():ImageClip(Path("media/vacation_2017.jpg")).close()-def test_PR_1137_subtitles():+def test_PR_1137_subtitles(util):"""Test support for path-like objects as arguments for SubtitlesClip."""def make_textclip(txt):return TextClip(txt,- font=FONT,+ font=util.FONT,font_size=24,color="white",stroke_color="black",diff --git a/tests/test_SubtitlesClip.py b/tests/test_SubtitlesClip.pyindex 207de53d..911708f7 100644--- a/tests/test_SubtitlesClip.py+++ b/tests/test_SubtitlesClip.py@@ -9,8 +9,6 @@ from moviepy.video.compositing.concatenate import concatenate_videoclipsfrom moviepy.video.tools.subtitles import SubtitlesClip, file_to_subtitlesfrom moviepy.video.VideoClip import ColorClip, TextClip-from tests.test_helper import FONT, TMP_DIR-MEDIA_SUBTITLES_DATA = [([0.0, 1.0], "Red!"),@@ -25,7 +23,7 @@ MEDIA_SUBTITLES_UNICODE_DATA = []-def test_subtitles():+def test_subtitles(util):red = ColorClip((800, 600), color=(255, 0, 0)).with_duration(10)green = ColorClip((800, 600), color=(0, 255, 0)).with_duration(10)blue = ColorClip((800, 600), color=(0, 0, 255)).with_duration(10)@@ -34,7 +32,7 @@ def test_subtitles():generator = lambda txt: TextClip(txt,- font=FONT,+ font=util.FONT,size=(800, 600),font_size=24,method="caption",@@ -45,7 +43,7 @@ def test_subtitles():subtitles = SubtitlesClip("media/subtitles.srt", generator)final = CompositeVideoClip([myvideo, subtitles])final.subclip(0, 0.5).write_videofile(- os.path.join(TMP_DIR, "subtitles.mp4"),+ os.path.join(util.TMP_DIR, "subtitles.mp4"),fps=5,logger=None,)diff --git a/tests/test_TextClip.py b/tests/test_TextClip.pyindex a9ca51d8..c6703755 100644--- a/tests/test_TextClip.py+++ b/tests/test_TextClip.py@@ -2,12 +2,9 @@import pytest-from moviepy.utils import close_all_clipsfrom moviepy.video.fx.blink import blinkfrom moviepy.video.VideoClip import TextClip-from tests.test_helper import FONT-def test_list():fonts = TextClip.list("font")@@ -27,8 +24,8 @@ def test_search():assert "blue" in blues-def test_duration():- clip = TextClip("hello world", size=(1280, 720), color="white", font=FONT)+def test_duration(util):+ clip = TextClip("hello world", size=(1280, 720), color="white", font=util.FONT)clip = clip.with_duration(5)assert clip.duration == 5clip.close()@@ -36,11 +33,10 @@ def test_duration():clip2 = clip.fx(blink, duration_on=1, duration_off=1)clip2 = clip2.with_duration(5)assert clip2.duration == 5- close_all_clips(locals())# Moved from tests.py. Maybe we can remove these?-def test_if_textclip_crashes_in_caption_mode():+def test_if_textclip_crashes_in_caption_mode(util):TextClip(text="foo",color="white",@@ -48,12 +44,12 @@ def test_if_textclip_crashes_in_caption_mode():method="caption",align="center",font_size=25,- font=FONT,+ font=util.FONT,).close()-def test_if_textclip_crashes_in_label_mode():- TextClip(text="foo", method="label", font=FONT).close()+def test_if_textclip_crashes_in_label_mode(util):+ TextClip(text="foo", method="label", font=util.FONT).close()if __name__ == "__main__":diff --git a/tests/test_VideoClip.py b/tests/test_VideoClip.pyindex 787635fd..56c85254 100644--- a/tests/test_VideoClip.py+++ b/tests/test_VideoClip.py@@ -4,21 +4,19 @@ import copyimport osimport numpy as np-import pytestfrom PIL import Image+import pytest+from moviepy.audio.AudioClip import AudioClipfrom moviepy.audio.io.AudioFileClip import AudioFileClipfrom moviepy.tools import convert_to_seconds-from moviepy.utils import close_all_clipsfrom moviepy.video.compositing.CompositeVideoClip import CompositeVideoClipfrom moviepy.video.fx.mask_color import mask_colorfrom moviepy.video.fx.multiply_speed import multiply_speedfrom moviepy.video.io.VideoFileClip import VideoFileClipfrom moviepy.video.VideoClip import BitmapClip, ColorClip, ImageClip, VideoClip-from tests.test_helper import TMP_DIR, get_stereo_wave, get_test_video-def test_aspect_ratio():clip = BitmapClip([["AAA", "BBB"]], fps=1)@@ -38,25 +36,25 @@ def test_n_frames(duration, fps, expected_n_frames):assert clip.n_frames == expected_n_frames-def test_with_audio():+def test_with_audio(stereo_wave):clip = VideoClip(duration=1).with_fps(1)assert clip.audio is None- audio_clip = AudioClip(get_stereo_wave(), duration=1, fps=22050)+ audio_clip = AudioClip(stereo_wave(), duration=1, fps=22050)assert clip.with_audio(audio_clip).audio is audio_clip-def test_without_audio():- audio_clip = AudioClip(get_stereo_wave(), duration=1, fps=22050)+def test_without_audio(stereo_wave):+ audio_clip = AudioClip(stereo_wave(), duration=1, fps=22050)clip = VideoClip(duration=1).with_fps(1).with_audio(audio_clip)assert clip.audio is audio_clipassert clip.without_audio().audio is None-def test_check_codec():- clip = get_test_video()- location = os.path.join(TMP_DIR, "not_a_video.mas")+def test_check_codec(util, video):+ clip = video()+ location = os.path.join(util.TMP_DIR, "not_a_video.mas")try:clip.write_videofile(location)except ValueError as e:@@ -64,39 +62,36 @@ def test_check_codec():"MoviePy couldn't find the codec associated with the filename."" Provide the 'codec' parameter in write_videofile." in str(e))- close_all_clips(locals())-def test_write_frame_errors():+def test_write_frame_errors(util, video):"""Checks error cases return helpful messages."""- clip = get_test_video()- location = os.path.join(TMP_DIR, "unlogged-write.mp4")+ clip = video()+ location = os.path.join(util.TMP_DIR, "unlogged-write.mp4")with pytest.raises(IOError) as e:clip.write_videofile(location, codec="nonexistent-codec")assert ("The video export failed because FFMPEG didn't find the specified"" codec for video encoding nonexistent-codec" in str(e.value)), e.value- close_all_clips(locals())autogenerated_location = "unlogged-writeTEMP_MPY_wvf_snd.mp3"if os.path.exists(autogenerated_location):os.remove(autogenerated_location)-def test_write_frame_errors_with_redirected_logs():+def test_write_frame_errors_with_redirected_logs(util, video):"""Checks error cases return helpful messages even when logs redirected.See https://github.com/Zulko/moviepy/issues/877"""- clip = get_test_video()- location = os.path.join(TMP_DIR, "logged-write.mp4")+ clip = video()+ location = os.path.join(util.TMP_DIR, "logged-write.mp4")with pytest.raises(IOError) as e:clip.write_videofile(location, codec="nonexistent-codec", write_logfile=True)assert ("The video export failed because FFMPEG didn't find the specified"" codec for video encoding nonexistent-codec" in str(e.value))- close_all_clips(locals())autogenerated_location_mp3 = "logged-writeTEMP_MPY_wvf_snd.mp3"autogenerated_location_log = autogenerated_location_mp3 + ".log"@@ -105,17 +100,16 @@ def test_write_frame_errors_with_redirected_logs():os.remove(fp)-def test_write_videofiles_with_temp_audiofile_path():+def test_write_videofiles_with_temp_audiofile_path(util):clip = VideoFileClip("media/big_buck_bunny_432_433.webm").subclip(0.2, 0.5)- location = os.path.join(TMP_DIR, "temp_audiofile_path.webm")- temp_location = os.path.join(TMP_DIR, "temp_audiofile")+ location = os.path.join(util.TMP_DIR, "temp_audiofile_path.webm")+ temp_location = os.path.join(util.TMP_DIR, "temp_audiofile")if not os.path.exists(temp_location):os.mkdir(temp_location)clip.write_videofile(location, temp_audiofile_path=temp_location, remove_temp=False)assert os.path.isfile(location)contents_of_temp_dir = os.listdir(temp_location)assert any(file.startswith("temp_audiofile_path") for file in contents_of_temp_dir)- close_all_clips(locals())@pytest.mark.parametrize("mask_color", (0, 0.5, 0.8, 1))@@ -138,8 +132,8 @@ def test_write_videofiles_with_temp_audiofile_path():),),)-def test_save_frame(with_mask, t, mask_color, frames):- filename = os.path.join(TMP_DIR, "moviepy_VideoClip_save_frame.png")+def test_save_frame(util, with_mask, t, mask_color, frames):+ filename = os.path.join(util.TMP_DIR, "moviepy_VideoClip_save_frame.png")if os.path.isfile(filename):os.remove(filename)@@ -177,94 +171,84 @@ def test_save_frame(with_mask, t, mask_color, frames):assert round(a / 254, 2) == mask_color-def test_write_image_sequence():- clip = get_test_video().subclip(0.2, 0.24)- locations = clip.write_images_sequence(os.path.join(TMP_DIR, "frame%02d.png"))+def test_write_image_sequence(util, video):+ clip = video(start_time=0.2, end_time=0.24)+ locations = clip.write_images_sequence(os.path.join(util.TMP_DIR, "frame%02d.png"))for location in locations:assert os.path.isfile(location)- close_all_clips(locals())-def test_write_gif_imageio():- clip = get_test_video().subclip(0.2, 0.8)- location = os.path.join(TMP_DIR, "imageio_gif.gif")+def test_write_gif_imageio(util, video):+ clip = video(start_time=0.2, end_time=0.8)+ location = os.path.join(util.TMP_DIR, "imageio_gif.gif")clip.write_gif(location, program="imageio")assert os.path.isfile(location)- close_all_clips(locals())-def test_write_gif_ffmpeg():- clip = get_test_video().subclip(0.2, 0.4)- location = os.path.join(TMP_DIR, "ffmpeg_gif.gif")+def test_write_gif_ffmpeg(util, video):+ clip = video(start_time=0.2, end_time=0.28)+ location = os.path.join(util.TMP_DIR, "ffmpeg_gif.gif")clip.write_gif(location, program="ffmpeg")assert os.path.isfile(location)- close_all_clips(locals())-def test_write_gif_ffmpeg_pixel_format():- clip = get_test_video().subclip(0.2, 0.4)- location = os.path.join(TMP_DIR, "ffmpeg_gif.gif")+def test_write_gif_ffmpeg_pixel_format(util, video):+ clip = video(start_time=0.2, end_time=0.28)+ location = os.path.join(util.TMP_DIR, "ffmpeg_gif.gif")clip.write_gif(location, program="ffmpeg", pixel_format="bgr24")assert os.path.isfile(location)- close_all_clips(locals())-def test_write_gif_ffmpeg_tmpfiles():- clip = get_test_video().subclip(0.2, 0.24)- location = os.path.join(TMP_DIR, "ffmpeg_tmpfiles_gif.gif")+def test_write_gif_ffmpeg_tmpfiles(util, video):+ clip = video(start_time=0.2, end_time=0.24)+ location = os.path.join(util.TMP_DIR, "ffmpeg_tmpfiles_gif.gif")clip.write_gif(location, program="ffmpeg", tempfiles=True)assert os.path.isfile(location)- close_all_clips(locals())-def test_write_gif_ffmpeg_tmpfiles_pixel_format():- clip = get_test_video().subclip(0.2, 0.24)- location = os.path.join(TMP_DIR, "ffmpeg_tmpfiles_gif.gif")+def test_write_gif_ffmpeg_tmpfiles_pixel_format(util, video):+ clip = video(start_time=0.2, end_time=0.24)+ location = os.path.join(util.TMP_DIR, "ffmpeg_tmpfiles_gif.gif")clip.write_gif(location, program="ffmpeg", tempfiles=True, pixel_format="bgr24")assert os.path.isfile(location)- close_all_clips(locals())-def test_write_gif_ImageMagick():- clip = get_test_video().subclip(0.2, 0.5)- location = os.path.join(TMP_DIR, "imagemagick_gif.gif")+def test_write_gif_ImageMagick(util, video):+ clip = video(start_time=0.2, end_time=0.5)+ location = os.path.join(util.TMP_DIR, "imagemagick_gif.gif")clip.write_gif(location, program="ImageMagick")- close_all_clips(locals())# Fails for some reason# assert os.path.isfile(location)-def test_write_gif_ImageMagick_tmpfiles():- clip = get_test_video().subclip(0.2, 0.24)- location = os.path.join(TMP_DIR, "imagemagick_tmpfiles_gif.gif")+def test_write_gif_ImageMagick_tmpfiles(util, video):+ clip = video(start_time=0.2, end_time=0.24)+ location = os.path.join(util.TMP_DIR, "imagemagick_tmpfiles_gif.gif")clip.write_gif(location, program="ImageMagick", tempfiles=True)assert os.path.isfile(location)- close_all_clips(locals())-def test_write_gif_ImageMagick_tmpfiles_pixel_format():- clip = get_test_video().subclip(0.2, 0.24)- location = os.path.join(TMP_DIR, "imagemagick_tmpfiles_gif.gif")+def test_write_gif_ImageMagick_tmpfiles_pixel_format(util, video):+ clip = video(start_time=0.2, end_time=0.24)+ location = os.path.join(util.TMP_DIR, "imagemagick_tmpfiles_gif.gif")clip.write_gif(location, program="ImageMagick", tempfiles=True, pixel_format="SGI")assert os.path.isfile(location)- close_all_clips(locals())-def test_subfx():+def test_subfx(util):clip = VideoFileClip("media/big_buck_bunny_0_30.webm").subclip(0, 1)transform = lambda c: multiply_speed(c, 0.5)new_clip = clip.subfx(transform, 0.5, 0.8)- location = os.path.join(TMP_DIR, "subfx.mp4")+ location = os.path.join(util.TMP_DIR, "subfx.mp4")new_clip.write_videofile(location)assert os.path.isfile(location)- close_all_clips(locals())-def test_oncolor():+def test_oncolor(util):# It doesn't need to be a ColorClipclip = ColorClip(size=(100, 60), color=(255, 0, 0), duration=0.5)on_color_clip = clip.on_color(size=(200, 160), color=(0, 0, 255))- location = os.path.join(TMP_DIR, "oncolor.mp4")+ location = os.path.join(util.TMP_DIR, "oncolor.mp4")on_color_clip.write_videofile(location, fps=24)assert os.path.isfile(location)@@ -279,39 +263,34 @@ def test_oncolor():with pytest.raises(Exception):clip = ColorClip(size=(100, 60), color=0.4, is_mask=False)- close_all_clips(locals())--def test_setaudio():+def test_setaudio(util):clip = ColorClip(size=(100, 60), color=(255, 0, 0), duration=0.5)make_frame_440 = lambda t: [np.sin(440 * 2 * np.pi * t)]audio = AudioClip(make_frame_440, duration=0.5)audio.fps = 44100clip = clip.with_audio(audio)- location = os.path.join(TMP_DIR, "setaudio.mp4")+ location = os.path.join(util.TMP_DIR, "setaudio.mp4")clip.write_videofile(location, fps=24)assert os.path.isfile(location)- close_all_clips(locals())-def test_setaudio_with_audiofile():+def test_setaudio_with_audiofile(util):clip = ColorClip(size=(100, 60), color=(255, 0, 0), duration=0.5)audio = AudioFileClip("media/crunching.mp3").subclip(0, 0.5)clip = clip.with_audio(audio)- location = os.path.join(TMP_DIR, "setaudiofile.mp4")+ location = os.path.join(util.TMP_DIR, "setaudiofile.mp4")clip.write_videofile(location, fps=24)assert os.path.isfile(location)- close_all_clips(locals())-def test_setopacity():- clip = get_test_video().subclip(0.2, 0.6)+def test_setopacity(util, video):+ clip = video(start_time=0.2, end_time=0.6)clip = clip.with_opacity(0.5)clip = clip.on_color(size=(1000, 1000), color=(0, 0, 255), col_opacity=0.8)- location = os.path.join(TMP_DIR, "setopacity.mp4")+ location = os.path.join(util.TMP_DIR, "setopacity.mp4")clip.write_videofile(location)assert os.path.isfile(location)- close_all_clips(locals())def test_with_layer():@@ -343,24 +322,22 @@ def test_compositing_with_same_layers():assert reversed_composite_clip == bottom_clip-def test_toimageclip():- clip = get_test_video().subclip(0.2, 0.6)+def test_toimageclip(util, video):+ clip = video(start_time=0.2, end_time=0.6)clip = clip.to_ImageClip(t=0.1, duration=0.4)- location = os.path.join(TMP_DIR, "toimageclip.mp4")+ location = os.path.join(util.TMP_DIR, "toimageclip.mp4")clip.write_videofile(location, fps=24)assert os.path.isfile(location)- close_all_clips(locals())-def test_withoutaudio():- clip = get_test_video().subclip(0.2, 0.6)+def test_withoutaudio(video):+ clip = video(start_time=0.2, end_time=0.6)new_clip = clip.without_audio()assert new_clip.audio is None- close_all_clips(locals())-def test_setfps_withoutchangeduration():- clip = get_test_video()+def test_setfps_withoutchangeduration(video):+ clip = video()# The sum is unique for each frame, so we can use it as a frame-ID# to check which frames are being preservedclip_sums = [f.sum() for f in clip.iter_frames()]@@ -369,11 +346,10 @@ def test_setfps_withoutchangeduration():clip2_sums = [f.sum() for f in clip2.iter_frames()]assert clip2_sums[::2] == clip_sumsassert clip2.duration == clip.duration- close_all_clips(locals())-def test_setfps_withchangeduration():- clip = get_test_video()+def test_setfps_withchangeduration(video):+ clip = video(end_time=0.2)# The sum is unique for each frame, so we can use it as a frame-ID# to check which frames are being preservedclip_sums = [f.sum() for f in clip.iter_frames()]@@ -382,17 +358,16 @@ def test_setfps_withchangeduration():clip2_sums = [f.sum() for f in clip2.iter_frames()]assert clip2_sums == clip_sumsassert clip2.duration == clip.duration / 2- close_all_clips(locals())-def test_copied_videoclip_write_videofile():+def test_copied_videoclip_write_videofile(util):"""Check if a copied ``VideoClip`` instance can render a file which hasthe same features as the copied clip when opening with ``VideoFileClip``."""clip = BitmapClip([["RRR", "GGG", "BBB"]], fps=1)copied_clip = clip.copy()- output_filepath = os.path.join(TMP_DIR, "copied_videoclip_from_bitmap.webm")+ output_filepath = os.path.join(util.TMP_DIR, "copied_videoclip_from_bitmap.webm")copied_clip.write_videofile(output_filepath)copied_clip_from_file = VideoFileClip(output_filepath)@@ -451,7 +426,7 @@ def test_videoclip_copy(copy_func):assert other_clip.audio is None-def test_afterimage():+def test_afterimage(util):ai = ImageClip("media/afterimage.png")masked_clip = mask_color(ai, color=[0, 255, 1]) # for greensome_background_clip = ColorClip((800, 600), color=(255, 255, 255))@@ -459,7 +434,7 @@ def test_afterimage():[some_background_clip, masked_clip], use_bgclip=True).with_duration(0.2)- filename = os.path.join(TMP_DIR, "afterimage.mp4")+ filename = os.path.join(util.TMP_DIR, "afterimage.mp4")final_clip.write_videofile(filename, fps=30, logger=None)diff --git a/tests/test_VideoFileClip.py b/tests/test_VideoFileClip.pyindex 48814d7c..3fca0ec6 100644--- a/tests/test_VideoFileClip.py+++ b/tests/test_VideoFileClip.py@@ -4,32 +4,30 @@ import osimport pytest-from moviepy.utils import close_all_clipsfrom moviepy.video.compositing.CompositeVideoClip import clips_arrayfrom moviepy.video.io.VideoFileClip import VideoFileClipfrom moviepy.video.VideoClip import ColorClip-from tests.test_helper import TMP_DIR--def test_setup():+def test_setup(util):"""Test VideoFileClip setup."""+ filename = os.path.join(util.TMP_DIR, "test.mp4")+red = ColorClip((256, 200), color=(255, 0, 0))green = ColorClip((256, 200), color=(0, 255, 0))blue = ColorClip((256, 200), color=(0, 0, 255))red.fps = green.fps = blue.fps = 10with clips_array([[red, green, blue]]).with_duration(5) as video:- video.write_videofile(os.path.join(TMP_DIR, "test.mp4"))+ video.write_videofile(filename, logger=None)- assert os.path.exists(os.path.join(TMP_DIR, "test.mp4"))+ assert os.path.exists(filename)- clip = VideoFileClip(os.path.join(TMP_DIR, "test.mp4"))+ clip = VideoFileClip(filename)assert clip.duration == 5assert clip.fps == 10assert clip.size == [256 * 3, 200]assert clip.reader.bitrate == 2- close_all_clips(locals())def test_ffmpeg_resizing():@@ -45,13 +43,13 @@ def test_ffmpeg_resizing():video.close()-def test_copied_videofileclip_write_videofile():+def test_copied_videofileclip_write_videofile(util):"""Check that a copied ``VideoFileClip`` can be renderizable using``write_videofile``, opened from that render and the new video sharesthe same data that the original clip."""input_video_filepath = "media/big_buck_bunny_432_433.webm"- output_video_filepath = os.path.join(TMP_DIR, "copied_videofileclip.mp4")+ output_video_filepath = os.path.join(util.TMP_DIR, "copied_videofileclip.mp4")clip = VideoFileClip(input_video_filepath).subclip(0, 1)copied_clip = clip.copy()diff --git a/tests/test_compositing.py b/tests/test_compositing.pyindex 1859259d..8f9c5d5e 100644--- a/tests/test_compositing.py+++ b/tests/test_compositing.py@@ -3,9 +3,9 @@import osimport numpy as np+import pytest-from moviepy.utils import close_all_clipsfrom moviepy.video.compositing.CompositeVideoClip import CompositeVideoClip, clips_arrayfrom moviepy.video.compositing.concatenate import concatenate_videoclipsfrom moviepy.video.compositing.transitions import slide_in, slide_out@@ -13,8 +13,6 @@ from moviepy.video.fx.resize import resizefrom moviepy.video.io.VideoFileClip import VideoFileClipfrom moviepy.video.VideoClip import BitmapClip, ColorClip-from tests.test_helper import TMP_DIR-class ClipPixelTest:ALLOWABLE_COLOR_VARIATION = 3 # from 0-767: how much mismatch do we allow@@ -38,7 +36,7 @@ class ClipPixelTest:)-def test_clips_array():+def test_clips_array(util):red = ColorClip((1024, 800), color=(255, 0, 0))green = ColorClip((1024, 800), color=(0, 255, 0))blue = ColorClip((1024, 800), color=(0, 0, 255))@@ -47,12 +45,13 @@ def test_clips_array():with pytest.raises(ValueError): # duration not setvideo.fx(resize, width=480).write_videofile(- os.path.join(TMP_DIR, "test_clips_array.mp4")+ os.path.join(util.TMP_DIR, "test_clips_array.mp4"))- close_all_clips(locals())-def test_clips_array_duration():+def test_clips_array_duration(util):+ filename = os.path.join(util.TMP_DIR, "test_clips_array.mp4")+# NOTE: anyone knows what behaviour this sets ? If yes please replace# this comment.red = ColorClip((256, 200), color=(255, 0, 0))@@ -61,37 +60,37 @@ def test_clips_array_duration():video = clips_array([[red, green, blue]]).with_duration(5)with pytest.raises(AttributeError): # fps not set- video.write_videofile(os.path.join(TMP_DIR, "test_clips_array.mp4"))+ video.write_videofile(filename)# this one should work correctlyred.fps = green.fps = blue.fps = 30video = clips_array([[red, green, blue]]).with_duration(5)- video.write_videofile(os.path.join(TMP_DIR, "test_clips_array.mp4"))- close_all_clips(locals())+ video.write_videofile(filename)-def test_concatenate_self():+def test_concatenate_self(util):clip = BitmapClip([["AAA", "BBB"], ["CCC", "DDD"]], fps=1)target = BitmapClip([["AAA", "BBB"], ["CCC", "DDD"]], fps=1)concatenated = concatenate_videoclips([clip])- concatenated.write_videofile(os.path.join(TMP_DIR, "test_concatenate_self.mp4"))+ concatenated.write_videofile(+ os.path.join(util.TMP_DIR, "test_concatenate_self.mp4")+ )assert concatenated == target-def test_concatenate_floating_point():+def test_concatenate_floating_point(util):""">>> print("{0:.20f}".format(1.12))1.12000000000000010658- This test uses duration=1.12 to check that it still works when the clip duration is- represented as being bigger than it actually is. Fixed in #1195.+ This test uses duration=1.12 to check that it still works when the clip+ duration is represented as being bigger than it actually is. Fixed in #1195."""clip = ColorClip([100, 50], color=[255, 128, 64], duration=1.12).with_fps(25.0)concat = concatenate_videoclips([clip])- concat.write_videofile(os.path.join(TMP_DIR, "concat.mp4"), preset="ultrafast")- close_all_clips(locals())+ concat.write_videofile(os.path.join(util.TMP_DIR, "concat.mp4"), preset="ultrafast")def test_blit_with_opacity():diff --git a/tests/test_examples.py b/tests/test_examples.pyindex e61afd3b..085c3cd9 100644--- a/tests/test_examples.py+++ b/tests/test_examples.py@@ -3,13 +3,12 @@import osimport numpy as np+import pytestfrom moviepy.video.io.bindings import mplfig_to_npimagefrom moviepy.video.VideoClip import VideoClip-from tests.test_helper import TMP_DIR-try:import matplotlib.pyplot@@ -20,7 +19,7 @@ else:@pytest.mark.skipif(not matplotlib, reason="no matplotlib")-def test_matplotlib_simple_example():+def test_matplotlib_simple_example(util):import matplotlib.pyplot as pltplt.switch_backend("Agg")@@ -38,7 +37,7 @@ def test_matplotlib_simple_example():animation = VideoClip(make_frame, duration=duration)- filename = os.path.join(TMP_DIR, "matplotlib.gif")+ filename = os.path.join(util.TMP_DIR, "matplotlib.gif")animation.write_gif(filename, fps=20)assert os.path.isfile(filename)diff --git a/tests/test_ffmpeg_reader.py b/tests/test_ffmpeg_reader.pyindex 7c398486..1281d1b5 100644--- a/tests/test_ffmpeg_reader.py+++ b/tests/test_ffmpeg_reader.py@@ -5,11 +5,11 @@ import subprocessimport timeimport numpy as np+import pytestfrom moviepy.audio.AudioClip import AudioClipfrom moviepy.config import FFMPEG_BINARY-from moviepy.utils import close_all_clipsfrom moviepy.video.compositing.CompositeVideoClip import clips_arrayfrom moviepy.video.io.ffmpeg_reader import (FFMPEG_VideoReader,@@ -19,8 +19,6 @@ from moviepy.video.io.ffmpeg_reader import (from moviepy.video.io.VideoFileClip import VideoFileClipfrom moviepy.video.VideoClip import BitmapClip, ColorClip-from tests.test_helper import TMP_DIR, get_mono_wave-def test_ffmpeg_parse_infos():d = ffmpeg_parse_infos("media/big_buck_bunny_432_433.webm")@@ -96,21 +94,21 @@ def test_ffmpeg_parse_infos_decode_file(decode_file, expected_duration):assert streams[1]["language"] is None-def test_ffmpeg_parse_infos_multiple_audio_streams():+def test_ffmpeg_parse_infos_multiple_audio_streams(util, mono_wave):"""Check that ``ffmpeg_parse_infos`` can parse multiple audio streams."""# Create two mono audio filesclip_440_filepath = os.path.join(- TMP_DIR, "ffmpeg_parse_infos_multiple_streams_440.mp3"+ util.TMP_DIR, "ffmpeg_parse_infos_multiple_streams_440.mp3")clip_880_filepath = os.path.join(- TMP_DIR, "ffmpeg_parse_infos_multiple_streams_880.mp3"+ util.TMP_DIR, "ffmpeg_parse_infos_multiple_streams_880.mp3")multiple_streams_filepath = os.path.join(- TMP_DIR, "ffmpeg_parse_infos_multiple_streams.mp4"+ util.TMP_DIR, "ffmpeg_parse_infos_multiple_streams.mp4")- clip_440 = AudioClip(get_mono_wave(440), fps=22050, duration=0.01)- clip_880 = AudioClip(get_mono_wave(880), fps=22050, duration=0.01)+ clip_440 = AudioClip(mono_wave(440), fps=22050, duration=0.01)+ clip_880 = AudioClip(mono_wave(880), fps=22050, duration=0.01)clip_440.write_audiofile(clip_440_filepath)clip_880.write_audiofile(clip_880_filepath)@@ -158,17 +156,16 @@ def test_ffmpeg_parse_infos_multiple_audio_streams():# cleanupfor filepath in [clip_440_filepath, clip_880_filepath, multiple_streams_filepath]:os.remove(filepath)- close_all_clips(locals())-def test_ffmpeg_parse_infos_metadata():+def test_ffmpeg_parse_infos_metadata(util, mono_wave):"""Check that `ffmpeg_parse_infos` is able to retrieve metadata from files."""- filepath = os.path.join(TMP_DIR, "ffmpeg_parse_infos_metadata.mkv")+ filepath = os.path.join(util.TMP_DIR, "ffmpeg_parse_infos_metadata.mkv")if os.path.isfile(filepath):os.remove(filepath)# create video with 2 streams, video and audio- audioclip = AudioClip(get_mono_wave(440), fps=22050).with_duration(1)+ audioclip = AudioClip(mono_wave(440), fps=22050).with_duration(1)videoclip = BitmapClip([["RGB"]], fps=1).with_duration(1).with_audio(audioclip)# build metadata key-value pairs which will be passed to ``ffmpeg_params``@@ -248,8 +245,6 @@ def test_ffmpeg_parse_infos_metadata():os.remove(filepath)- close_all_clips(locals())-def test_ffmpeg_parse_infos_chapters():"""Check that `ffmpeg_parse_infos` can parse chapters with their metadata."""@@ -295,12 +290,12 @@ def test_ffmpeg_parse_video_rotation():assert d["video_size"] == [1920, 1080]-def test_correct_video_rotation():+def test_correct_video_rotation(util):"""See https://github.com/Zulko/moviepy/pull/577"""clip = VideoFileClip("media/rotated-90-degrees.mp4").subclip(0.2, 0.4)corrected_rotation_filename = os.path.join(- TMP_DIR,+ util.TMP_DIR,"correct_video_rotation.mp4",)clip.write_videofile(corrected_rotation_filename)@@ -611,7 +606,7 @@ def test_seeking_beyond_file_end():assert reader.pos == 30 * 24 + 1-def test_release_of_file_via_close():+def test_release_of_file_via_close(util):# Create a random video file.red = ColorClip((256, 200), color=(255, 0, 0))green = ColorClip((256, 200), color=(0, 255, 0))@@ -623,7 +618,7 @@ def test_release_of_file_via_close():for i in range(3):# Get the name of a temporary file we can use.local_video_filename = os.path.join(- TMP_DIR, "test_release_of_file_via_close_%s.mp4" % int(time.time())+ util.TMP_DIR, "test_release_of_file_via_close_%s.mp4" % int(time.time()))clip = clips_array([[red, green, blue]]).with_duration(0.5)@@ -645,7 +640,7 @@ def test_release_of_file_via_close():blue.close()-def test_failure_to_release_file():+def test_failure_to_release_file(util):"""Expected to fail. It demonstrates that there *is* a problem with notreleasing resources when running on Windows.@@ -655,7 +650,7 @@ def test_failure_to_release_file():"""# Get the name of a temporary file we can use.local_video_filename = os.path.join(- TMP_DIR, "test_release_of_file_%s.mp4" % int(time.time())+ util.TMP_DIR, "test_release_of_file_%s.mp4" % int(time.time()))# Repeat this so we can see that the problems escalate:diff --git a/tests/test_ffmpeg_tools.py b/tests/test_ffmpeg_tools.pyindex 7c817f18..bc9a8323 100644--- a/tests/test_ffmpeg_tools.py+++ b/tests/test_ffmpeg_tools.py@@ -12,11 +12,11 @@ from moviepy.video.io.ffmpeg_tools import ()from moviepy.video.io.VideoFileClip import VideoFileClip-from tests.test_helper import TMP_DIR--def test_ffmpeg_extract_subclip():- extract_subclip_tempdir = os.path.join(TMP_DIR, "moviepy_ffmpeg_extract_subclip")+def test_ffmpeg_extract_subclip(util):+ extract_subclip_tempdir = os.path.join(+ util.TMP_DIR, "moviepy_ffmpeg_extract_subclip"+ )if os.path.isdir(extract_subclip_tempdir):shutil.rmtree(extract_subclip_tempdir)os.mkdir(extract_subclip_tempdir)@@ -47,8 +47,8 @@ def test_ffmpeg_extract_subclip():pass-def test_ffmpeg_resize():- outputfile = os.path.join(TMP_DIR, "moviepy_ffmpeg_resize.mp4")+def test_ffmpeg_resize(util):+ outputfile = os.path.join(util.TMP_DIR, "moviepy_ffmpeg_resize.mp4")if os.path.isfile(outputfile):os.remove(outputfile)@@ -72,8 +72,8 @@ def test_ffmpeg_resize():pass-def test_ffmpeg_stabilize_video():- stabilize_video_tempdir = os.path.join(TMP_DIR, "moviepy_ffmpeg_stabilize")+def test_ffmpeg_stabilize_video(util):+ stabilize_video_tempdir = os.path.join(util.TMP_DIR, "moviepy_ffmpeg_stabilize")if os.path.isdir(stabilize_video_tempdir):shutil.rmtree(stabilize_video_tempdir)os.mkdir(stabilize_video_tempdir)diff --git a/tests/test_ffmpeg_writer.py b/tests/test_ffmpeg_writer.pyindex a3c7e515..e9ca3dcc 100644--- a/tests/test_ffmpeg_writer.py+++ b/tests/test_ffmpeg_writer.py@@ -3,9 +3,10 @@import multiprocessingimport os-import pytestfrom PIL import Image+import pytest+from moviepy.video.compositing.concatenate import concatenate_videoclipsfrom moviepy.video.io.ffmpeg_writer import ffmpeg_write_image, ffmpeg_write_videofrom moviepy.video.io.gif_writers import write_gif@@ -13,8 +14,6 @@ from moviepy.video.io.VideoFileClip import VideoFileClipfrom moviepy.video.tools.drawing import color_gradientfrom moviepy.video.VideoClip import BitmapClip, ColorClip-from tests.test_helper import TMP_DIR-@pytest.mark.parametrize("with_mask",@@ -47,6 +46,7 @@ from tests.test_helper import TMP_DIRids=("threads=None", "threads=multiprocessing.cpu_count()"),)def test_ffmpeg_write_video(+ util,codec,is_valid_codec,ext,@@ -55,7 +55,7 @@ def test_ffmpeg_write_video(bitrate,threads,):- filename = os.path.join(TMP_DIR, f"moviepy_ffmpeg_write_video{ext}")+ filename = os.path.join(util.TMP_DIR, f"moviepy_ffmpeg_write_video{ext}")if os.path.isfile(filename):try:os.remove(filename)@@ -135,8 +135,8 @@ def test_ffmpeg_write_video(),),)-def test_ffmpeg_write_image(size, logfile, pixel_format, expected_result):- filename = os.path.join(TMP_DIR, "moviepy_ffmpeg_write_image.png")+def test_ffmpeg_write_image(util, size, logfile, pixel_format, expected_result):+ filename = os.path.join(util.TMP_DIR, "moviepy_ffmpeg_write_image.png")if os.path.isfile(filename):os.remove(filename)@@ -189,8 +189,8 @@ def test_ffmpeg_write_image(size, logfile, pixel_format, expected_result):"with_mask", (False, True), ids=("with_mask=False", "with_mask=True"))@pytest.mark.parametrize("pixel_format", ("invalid", None))-def test_write_gif(clip_class, opt, loop, with_mask, pixel_format):- filename = os.path.join(TMP_DIR, "moviepy_write_gif.gif")+def test_write_gif(util, clip_class, opt, loop, with_mask, pixel_format):+ filename = os.path.join(util.TMP_DIR, "moviepy_write_gif.gif")if os.path.isfile(filename):os.remove(filename)diff --git a/tests/test_fx.py b/tests/test_fx.pyindex 5699bf4f..99cf7313 100644--- a/tests/test_fx.py+++ b/tests/test_fx.py@@ -9,6 +9,7 @@ import randomimport sysimport numpy as np+import pytestfrom moviepy import (@@ -28,7 +29,6 @@ from moviepy.audio.fx import (multiply_volume,)from moviepy.tools import convert_to_seconds-from moviepy.utils import close_all_clipsfrom moviepy.video.fx import (blackwhite,crop,@@ -54,8 +54,6 @@ from moviepy.video.fx import (time_symmetrize,)-from tests.test_helper import TMP_DIR, get_mono_wave, get_stereo_wave, get_test_video-def test_accel_decel():pass@@ -129,14 +127,12 @@ def test_blackwhite():# all characters returned by ``to_bitmap`` are in the b/w spectrumassert char in bw_color_dict- close_all_clips(locals())-# This currently fails with a with_mask error!-# def test_blink():+# def test_blink(util):# with VideoFileClip("media/big_buck_bunny_0_30.webm").subclip(0,10) as clip:# clip1 = blink(clip, 1, 1)-# clip1.write_videofile(os.path.join(TMP_DIR,"blink1.webm"))+# clip1.write_videofile(os.path.join(util.TMP_DIR,"blink1.webm"))def test_multiply_color():@@ -214,11 +210,10 @@ def test_fadein():assert clip2 == target2-def test_fadeout():- clip = get_test_video()+def test_fadeout(util, video):+ clip = video(end_time=0.5)clip1 = fadeout(clip, 0.5)- clip1.write_videofile(os.path.join(TMP_DIR, "fadeout1.webm"))- close_all_clips(locals())+ clip1.write_videofile(os.path.join(util.TMP_DIR, "fadeout1.webm"))@pytest.mark.parametrize(@@ -382,7 +377,7 @@ def test_invert_colors():assert clip1 == target1-def test_loop():+def test_loop(util, video):clip = BitmapClip([["R"], ["G"], ["B"]], fps=1)clip1 = loop(clip, n=2) # loop 2 times@@ -399,15 +394,15 @@ def test_loop():target3 = BitmapClip([["R"], ["G"], ["B"], ["R"], ["G"]], fps=1)assert clip3 == target3- clip = get_test_video().subclip(0.2, 0.3) # 0.1 seconds long+ clip = video(start_time=0.2, end_time=0.3) # 0.1 seconds longclip1 = loop(clip).with_duration(0.5) # infinite looping- clip1.write_videofile(os.path.join(TMP_DIR, "loop1.webm"))+ clip1.write_videofile(os.path.join(util.TMP_DIR, "loop1.webm"))clip2 = loop(clip, duration=0.5) # loop for 1 second- clip2.write_videofile(os.path.join(TMP_DIR, "loop2.webm"))+ clip2.write_videofile(os.path.join(util.TMP_DIR, "loop2.webm"))clip3 = loop(clip, n=3) # loop 3 times- clip3.write_videofile(os.path.join(TMP_DIR, "loop3.webm"))+ clip3.write_videofile(os.path.join(util.TMP_DIR, "loop3.webm"))# Test audio loopingclip = AudioClip(@@ -417,25 +412,21 @@ def test_loop():# TODO fix AudioClip.__eq__()# assert concatenate_audioclips([clip, clip]) == clip1- close_all_clips(objects=locals())--def test_lum_contrast():- clip = get_test_video()+def test_lum_contrast(util, video):+ clip = video()clip1 = lum_contrast(clip)- clip1.write_videofile(os.path.join(TMP_DIR, "lum_contrast1.webm"))- close_all_clips(locals())+ clip1.write_videofile(os.path.join(util.TMP_DIR, "lum_contrast1.webm"))# what are the correct value ranges for function arguments lum,# contrast and contrast_thr? Maybe we should check for these in# lum_contrast.-def test_make_loopable():- clip = get_test_video()+def test_make_loopable(util, video):+ clip = video()clip1 = make_loopable(clip, 0.4)- clip1.write_videofile(os.path.join(TMP_DIR, "make_loopable1.webm"))- close_all_clips(locals())+ clip1.write_videofile(os.path.join(util.TMP_DIR, "make_loopable1.webm"))@pytest.mark.parametrize(@@ -1005,11 +996,11 @@ def test_rotate(assert rotated_clip.to_bitmap() == expected_clip.to_bitmap()-def test_rotate_nonstandard_angles():+def test_rotate_nonstandard_angles(util):# Test rotate with color clipclip = ColorClip([600, 400], [150, 250, 100]).with_duration(1).with_fps(5)clip = rotate(clip, 20)- clip.write_videofile(os.path.join(TMP_DIR, "color_rotate.webm"))+ clip.write_videofile(os.path.join(util.TMP_DIR, "color_rotate.webm"))def test_rotate_mask():@@ -1188,7 +1179,6 @@ def test_audio_normalize():clip = AudioFileClip("media/crunching.mp3")clip = audio_normalize(clip)assert clip.max_volume() == 1- close_all_clips(locals())def test_audio_normalize_muted():@@ -1198,8 +1188,6 @@ def test_audio_normalize_muted():clip = audio_normalize(clip)assert np.array_equal(clip.to_soundarray(), z_array)- close_all_clips(locals())-@pytest.mark.parametrize(("sound_type", "factor", "duration", "start_time", "end_time"),@@ -1448,8 +1436,6 @@ def test_multiply_stereo_volume():d_channel = mono_clip.to_soundarray() * 2assert np.array_equal(mono_channel_doubled, d_channel)- close_all_clips(locals())-@pytest.mark.parametrize(("duration", "offset", "n_repeats", "decay"),@@ -1460,7 +1446,7 @@ def test_multiply_stereo_volume():(0.3, 1, 7, 4),),)-def test_audio_delay(duration, offset, n_repeats, decay):+def test_audio_delay(stereo_wave, duration, offset, n_repeats, decay):"""Check that creating a short pulse of audio, the delay converts to a soundwith the volume level in the form `-_-_-_-_-`, being `-` pulses expressed by`duration` argument and `_` being chunks of muted audio. Keep in mind that this@@ -1477,7 +1463,7 @@ def test_audio_delay(duration, offset, n_repeats, decay):# stereo audio clipclip = AudioClip(- make_frame=get_stereo_wave(left_freq=440, right_freq=880),+ make_frame=stereo_wave(left_freq=440, right_freq=880),duration=duration,fps=44100,)@@ -1546,11 +1532,13 @@ def test_audio_delay(duration, offset, n_repeats, decay):)),)-def test_audio_fadein(sound_type, fps, clip_duration, fadein_duration):+def test_audio_fadein(+ mono_wave, stereo_wave, sound_type, fps, clip_duration, fadein_duration+):if sound_type == "stereo":- make_frame = get_stereo_wave(left_freq=440, right_freq=160)+ make_frame = stereo_wave(left_freq=440, right_freq=160)else:- make_frame = get_mono_wave(440)+ make_frame = mono_wave(440)clip = AudioClip(make_frame, duration=clip_duration, fps=fps)new_clip = audio_fadein(clip, fadein_duration)@@ -1605,11 +1593,13 @@ def test_audio_fadein(sound_type, fps, clip_duration, fadein_duration):)),)-def test_audio_fadeout(sound_type, fps, clip_duration, fadeout_duration):+def test_audio_fadeout(+ mono_wave, stereo_wave, sound_type, fps, clip_duration, fadeout_duration+):if sound_type == "stereo":- make_frame = get_stereo_wave(left_freq=440, right_freq=160)+ make_frame = stereo_wave(left_freq=440, right_freq=160)else:- make_frame = get_mono_wave(440)+ make_frame = mono_wave(440)clip = AudioClip(make_frame, duration=clip_duration, fps=fps)new_clip = audio_fadeout(clip, fadeout_duration)diff --git a/tests/test_issues.py b/tests/test_issues.pyindex aba6daf7..02bf32b1 100644--- a/tests/test_issues.py+++ b/tests/test_issues.py@@ -5,7 +5,6 @@ import osimport pytestfrom moviepy.audio.io.AudioFileClip import AudioFileClip-from moviepy.utils import close_all_clipsfrom moviepy.video.compositing.CompositeVideoClip import CompositeVideoClipfrom moviepy.video.compositing.concatenate import concatenate_videoclipsfrom moviepy.video.compositing.transitions import crossfadein, crossfadeout@@ -13,8 +12,6 @@ from moviepy.video.fx.resize import resizefrom moviepy.video.io.VideoFileClip import VideoFileClipfrom moviepy.video.VideoClip import ColorClip, ImageClip, VideoClip-from tests.test_helper import TMP_DIR-try:import matplotlib.pyplot@@ -32,18 +29,19 @@ def test_issue_145():def test_issue_190():# from PIL import Image- # Image.new('L', (800,600), 'white').save(os.path.join(TMP_DIR, "issue_190.png"))-+ #+ # filename = os.path.join(util.TMP_DIR, "issue_190.png")+ # Image.new('L', (800,600), 'white').save(filename)+ ## from imageio import imread- # image = imread(os.path.join(TMP_DIR, "issue_190.png"))-+ # image = imread(filename)+ ## clip = ImageSequenceClip([image, image], fps=1)- # clip.write_videofile(os.path.join(TMP_DIR, "issue_190.mp4"))+ # clip.write_videofile(os.path.splitext(filename)[0] + ".mp4"))passdef test_issue_285():-clip_1, clip_2, clip_3 = (ImageClip("media/python_logo.png", duration=10),ImageClip("media/python_logo.png", duration=10),@@ -51,10 +49,9 @@ def test_issue_285():)merged_clip = concatenate_videoclips([clip_1, clip_2, clip_3])assert merged_clip.duration == 30- close_all_clips(locals())-def test_issue_334():+def test_issue_334(util):# NOTE: this is horrible. Any simpler version ?last_move = Nonelast_move1 = None@@ -243,7 +240,7 @@ def test_issue_334():# .with_mask(maskclip).resize(size)])final = CompositeVideoClip([tt, concatenated.with_position(posi).fx(resize, size)])final.duration = tt.duration- final.write_videofile(os.path.join(TMP_DIR, "issue_334.mp4"), fps=10)+ final.write_videofile(os.path.join(util.TMP_DIR, "issue_334.mp4"), fps=10)def test_issue_354():@@ -264,14 +261,16 @@ def test_issue_354():CompositeVideoClip([clip, fadecaption]).close()-def test_issue_359():+def test_issue_359(util):with ColorClip((800, 600), color=(255, 0, 0)).with_duration(0.2) as video:video.fps = 30- video.write_gif(filename=os.path.join(TMP_DIR, "issue_359.gif"), tempfiles=True)+ video.write_gif(+ filename=os.path.join(util.TMP_DIR, "issue_359.gif"), tempfiles=True+ )@pytest.mark.skipif(not matplotlib, reason="no matplotlib")-def test_issue_368():+def test_issue_368(util):import matplotlib.pyplot as pltimport numpy as npfrom sklearn import svm@@ -313,7 +312,7 @@ def test_issue_368():return mplfig_to_npimage(fig)animation = VideoClip(make_frame, duration=0.2)- animation.write_gif(os.path.join(TMP_DIR, "svm.gif"), fps=20)+ animation.write_gif(os.path.join(util.TMP_DIR, "svm.gif"), fps=20)def test_issue_407():@@ -358,20 +357,20 @@ def test_issue_417():# final.with_duration(7).write_videofile("test.mp4", fps=30)-def test_issue_470():+def test_issue_470(util):+ wav_filename = os.path.join(util.TMP_DIR, "moviepy_issue_470.wav")+audio_clip = AudioFileClip("media/crunching.mp3")# end_time is out of boundssubclip = audio_clip.subclip(start_time=6, end_time=9)with pytest.raises(IOError):- subclip.write_audiofile(- os.path.join(TMP_DIR, "issue_470.wav"), write_logfile=True- )+ subclip.write_audiofile(wav_filename, write_logfile=True)# but this one should work..subclip = audio_clip.subclip(start_time=6, end_time=8)- subclip.write_audiofile(os.path.join(TMP_DIR, "issue_470.wav"), write_logfile=True)+ subclip.write_audiofile(wav_filename, write_logfile=True)def test_issue_547():diff --git a/tests/test_tools.py b/tests/test_tools.pyindex 7c4f7764..ca5883b8 100644--- a/tests/test_tools.py+++ b/tests/test_tools.py@@ -13,13 +13,6 @@ import pytestimport moviepy.tools as toolsfrom moviepy.video.io.downloader import download_webfile-from tests.test_helper import (- TMP_DIR,- get_functions_with_decorator_defined,- get_moviepy_modules,- static_files_server,-)-@pytest.mark.parametrize(("given", "expected"),@@ -113,8 +106,8 @@ def test_deprecated_version_of(old_name):("foobarbazimpossiblecode", OSError),),)-def test_download_webfile(url, expected_result):- filename = os.path.join(TMP_DIR, "moviepy_downloader_test.mp4")+def test_download_webfile(static_files_server, util, url, expected_result):+ filename = os.path.join(util.TMP_DIR, "moviepy_downloader_test.mp4")if os.path.isfile(filename):os.remove(filename)@@ -197,6 +190,7 @@ def test_download_webfile(url, expected_result):),)def test_config(+ util,ffmpeg_binary,ffmpeg_binary_error,imagemagick_binary,@@ -214,11 +208,11 @@ def test_config(prev_imagemagick_binary = os.environ.get("IMAGEMAGICK_BINARY")if imagemagick_binary_isfile:- imagemagick_binary = os.path.join(TMP_DIR, imagemagick_binary)+ imagemagick_binary = os.path.join(util.TMP_DIR, imagemagick_binary)with open(imagemagick_binary, "w") as f:f.write("foo")elif imagemagick_binary_isdir:- imagemagick_binary = os.path.join(TMP_DIR, imagemagick_binary)+ imagemagick_binary = os.path.join(util.TMP_DIR, imagemagick_binary)if os.path.isdir(imagemagick_binary):shutil.rmtree(imagemagick_binary)os.mkdir(imagemagick_binary)@@ -284,7 +278,9 @@ def test_config_check():"decorator_name",("convert_parameter_to_seconds", "convert_path_to_string"),)-def test_decorators_argument_converters_consistency(decorator_name):+def test_decorators_argument_converters_consistency(+ moviepy_modules, functions_with_decorator_defined, decorator_name+):"""Checks that for all functions that have a decorator defined (like``@convert_parameter_to_seconds``), the parameters passed to the decoratorcorrespond to the parameters taken by the function.@@ -300,7 +296,7 @@ def test_decorators_argument_converters_consistency(decorator_name):added."""with contextlib.redirect_stdout(io.StringIO()):- for modname, ispkg in get_moviepy_modules():+ for modname, ispkg in moviepy_modules():if ispkg:continue@@ -309,7 +305,7 @@ def test_decorators_argument_converters_consistency(decorator_name):except ImportError:continue- functions_with_decorator = get_functions_with_decorator_defined(+ functions_with_decorator = functions_with_decorator_defined(module,decorator_name,)diff --git a/tests/test_videotools.py b/tests/test_videotools.pyindex 45b2d8e1..d480420e 100644--- a/tests/test_videotools.py+++ b/tests/test_videotools.py@@ -7,6 +7,7 @@ import shutilimport sysimport numpy as np+import pytestfrom moviepy.audio.AudioClip import AudioClip, CompositeAudioClip@@ -36,8 +37,6 @@ else:from moviepy.video.VideoClip import BitmapClip, ColorClip, ImageClip, VideoClip-from tests.test_helper import FONT, TMP_DIR, get_mono_wave, get_stereo_wave-try:importlib.import_module("ipython.display")@@ -48,7 +47,7 @@ else:del sys.modules["ipython.display"]-def test_credits():+def test_credits(util):credit_file = ("# This is a comment\n""# The next line says : leave 4 blank lines\n"@@ -67,13 +66,13 @@ def test_credits():"JEAN DIDIER\n")- file_location = os.path.join(TMP_DIR, "credits.txt")- vid_location = os.path.join(TMP_DIR, "credits.mp4")+ file_location = os.path.join(util.TMP_DIR, "credits.txt")+ vid_location = os.path.join(util.TMP_DIR, "credits.mp4")with open(file_location, "w") as file:file.write(credit_file)image = CreditsClip(- file_location, 600, gap=100, stroke_color="blue", stroke_width=5, font=FONT+ file_location, 600, gap=100, stroke_color="blue", stroke_width=5, font=util.FONT)image = image.with_duration(3)image.write_videofile(vid_location, fps=24, logger=None)@@ -221,7 +220,7 @@ def test_FramesMatches_filter():assert frames_match == expected_matching_frames[i]-def test_FramesMatches_save_load():+def test_FramesMatches_save_load(util):input_matching_frames = [FramesMatch(1, 2, 0, 0),FramesMatch(1, 2, 0.8, 0),@@ -232,7 +231,7 @@ def test_FramesMatches_save_load():1.000 2.000 0.800 0.800"""- outputfile = os.path.join(TMP_DIR, "moviepy_FramesMatches_save_load.txt")+ outputfile = os.path.join(util.TMP_DIR, "moviepy_FramesMatches_save_load.txt")# saveFramesMatches(input_matching_frames).save(outputfile)@@ -327,7 +326,7 @@ def test_FramesMatches_select_scenes(assert result == expected_result-def test_FramesMatches_write_gifs():+def test_FramesMatches_write_gifs(util):video_clip = VideoFileClip("media/chaplin.mp4").subclip(0, 0.2)clip = concatenate_videoclips([video_clip.fx(time_mirror), video_clip])@@ -340,7 +339,7 @@ def test_FramesMatches_write_gifs():nomatch_threshold=0,)- gifs_dir = os.path.join(TMP_DIR, "moviepy_FramesMatches_write_gifs")+ gifs_dir = os.path.join(util.TMP_DIR, "moviepy_FramesMatches_write_gifs")if os.path.isdir(gifs_dir):shutil.rmtree(gifs_dir)os.mkdir(gifs_dir)@@ -905,8 +904,8 @@ def test_Trajectory_addy():assert trajectory.yy[1] == 2-def test_Trajectory_from_to_file():- filename = os.path.join(TMP_DIR, "moviepy_Trajectory_from_to_file.txt")+def test_Trajectory_from_to_file(util):+ filename = os.path.join(util.TMP_DIR, "moviepy_Trajectory_from_to_file.txt")if os.path.isfile(filename):os.remove(filename)@@ -979,7 +978,13 @@ def test_find_objects(filename, expected_screenpos):("clip", "filetype", "fps", "maxduration", "t", "expected_error"),(pytest.param(- AudioClip(get_stereo_wave(), duration=0.2, fps=44100),+ AudioClip(+ lambda t: np.array(+ [np.sin(440 * 2 * np.pi * t), np.sin(220 * 2 * np.pi * t)]+ ).T.copy(order="C"),+ duration=0.2,+ fps=44100,+ ),None,None,None,@@ -1042,7 +1047,7 @@ def test_find_objects(filename, expected_screenpos):id="filename(.jpg)",),pytest.param(- os.path.join(TMP_DIR, "moviepy_ipython_display.foo"),+ os.path.join("{tempdir}", "moviepy_ipython_display.foo"),None, # unknown filetypeNone,None,@@ -1051,7 +1056,7 @@ def test_find_objects(filename, expected_screenpos):id="filename(.foo)",),pytest.param(- os.path.join(TMP_DIR, "moviepy_ipython_display.foo"),+ os.path.join("{tempdir}", "moviepy_ipython_display.foo"),"video", # unsupported filetype for '.foo' extensionNone,None,@@ -1104,7 +1109,7 @@ def test_find_objects(filename, expected_screenpos):),)def test_ipython_display(- clip, filetype, fps, maxduration, t, expected_error, monkeypatch+ util, clip, filetype, fps, maxduration, t, expected_error, monkeypatch):# patch module to use it without ipython installedvideo_io_html_tools_module = importlib.import_module("moviepy.video.io.html_tools")@@ -1119,6 +1124,9 @@ def test_ipython_display(if t is not None:kwargs["t"] = t+ if isinstance(clip, str):+ clip = clip.replace("{tempdir}", util.TMP_DIR)+if expected_error is None:html_content = video_io_html_tools_module.ipython_display(clip,@@ -1185,14 +1193,14 @@ def test_ipython_display_not_available():del sys.modules["moviepy.video.io.html_tools"][email protected]("wave", ("mono", "stereo"))-def test_find_audio_period(wave):- if wave == "mono":- wave1 = get_mono_wave(freq=400)- wave2 = get_mono_wave(freq=100)[email protected]("wave_type", ("mono", "stereo"))+def test_find_audio_period(mono_wave, stereo_wave, wave_type):+ if wave_type == "mono":+ wave1 = mono_wave(freq=400)+ wave2 = mono_wave(freq=100)else:- wave1 = get_stereo_wave(left_freq=400, right_freq=220)- wave2 = get_stereo_wave(left_freq=100, right_freq=200)+ wave1 = stereo_wave(left_freq=400, right_freq=220)+ wave2 = stereo_wave(left_freq=100, right_freq=200)clip = CompositeAudioClip([AudioClip(make_frame=wave1, duration=0.3, fps=22050),