mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-20 13:07:57 +09:00
First pass at finalise tests (41 failing)
This commit is contained in:
12 files changed
+2396
No files matched your search
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,309 @@
|
||||
import pytest
|
||||
import os
|
||||
import shlex
|
||||
from unittest.mock import patch, MagicMock, call
|
||||
|
||||
# Adjust the import path
|
||||
from karaoke_prep.karaoke_finalise.karaoke_finalise import KaraokeFinalise
|
||||
from .test_initialization import mock_logger, basic_finaliser, MINIMAL_CONFIG # Reuse fixtures
|
||||
from .test_file_input_validation import BASE_NAME, TITLE_MOV, END_MOV, WITH_VOCALS_MOV, INSTRUMENTAL_FLAC # Reuse constants
|
||||
|
||||
# Define expected output filenames for convenience
|
||||
OUTPUT_FILES = {
|
||||
"karaoke_mp4": f"{BASE_NAME} (Karaoke).mp4",
|
||||
"with_vocals_mp4": f"{BASE_NAME} (With Vocals).mp4",
|
||||
"final_karaoke_lossless_mp4": f"{BASE_NAME} (Final Karaoke Lossless 4k).mp4",
|
||||
"final_karaoke_lossless_mkv": f"{BASE_NAME} (Final Karaoke Lossless 4k).mkv",
|
||||
"final_karaoke_lossy_mp4": f"{BASE_NAME} (Final Karaoke Lossy 4k).mp4",
|
||||
"final_karaoke_lossy_720p_mp4": f"{BASE_NAME} (Final Karaoke Lossy 720p).mp4",
|
||||
}
|
||||
|
||||
INPUT_FILES = {
|
||||
"title_mov": TITLE_MOV,
|
||||
"instrumental_audio": INSTRUMENTAL_FLAC,
|
||||
# end_mov is added conditionally in tests
|
||||
}
|
||||
|
||||
@pytest.fixture
|
||||
def finaliser_with_aac(mock_logger):
|
||||
"""Fixture for a finaliser specifically with 'aac' codec."""
|
||||
with patch.object(KaraokeFinalise, 'detect_best_aac_codec', return_value='aac'):
|
||||
finaliser = KaraokeFinalise(logger=mock_logger, **MINIMAL_CONFIG)
|
||||
return finaliser
|
||||
|
||||
@pytest.fixture
|
||||
def finaliser_with_aac_at(mock_logger):
|
||||
"""Fixture for a finaliser specifically with 'aac_at' codec."""
|
||||
with patch.object(KaraokeFinalise, 'detect_best_aac_codec', return_value='aac_at'):
|
||||
finaliser = KaraokeFinalise(logger=mock_logger, **MINIMAL_CONFIG)
|
||||
return finaliser
|
||||
|
||||
# --- execute_command Tests ---
|
||||
|
||||
@patch('os.system')
|
||||
def test_execute_command_runs_command(mock_system, finaliser_with_aac):
|
||||
"""Test execute_command calls os.system."""
|
||||
command = "echo 'test'"
|
||||
description = "Running test command"
|
||||
finaliser_with_aac.execute_command(command, description)
|
||||
mock_system.assert_called_once_with(command)
|
||||
finaliser_with_aac.logger.info.assert_any_call(description)
|
||||
finaliser_with_aac.logger.info.assert_any_call(f"Running command: {command}")
|
||||
|
||||
@patch('os.system')
|
||||
def test_execute_command_dry_run(mock_system, finaliser_with_aac):
|
||||
"""Test execute_command logs but doesn't run in dry run mode."""
|
||||
finaliser_with_aac.dry_run = True
|
||||
command = "echo 'test'"
|
||||
description = "Running test command"
|
||||
finaliser_with_aac.execute_command(command, description)
|
||||
mock_system.assert_not_called()
|
||||
finaliser_with_aac.logger.info.assert_any_call(description)
|
||||
finaliser_with_aac.logger.info.assert_any_call(f"DRY RUN: Would run command: {command}")
|
||||
|
||||
# --- prepare_concat_filter Tests ---
|
||||
|
||||
@patch('os.path.isfile', return_value=False)
|
||||
def test_prepare_concat_filter_no_end_mov(mock_isfile, finaliser_with_aac):
|
||||
"""Test concat filter without end_mov."""
|
||||
input_files_no_end = INPUT_FILES.copy()
|
||||
env_mov_input, ffmpeg_filter = finaliser_with_aac.prepare_concat_filter(input_files_no_end)
|
||||
assert env_mov_input == ""
|
||||
assert ffmpeg_filter == '-filter_complex "[0:v:0][0:a:0][1:v:0][1:a:0]concat=n=2:v=1:a=1[outv][outa]"'
|
||||
mock_isfile.assert_not_called() # Should not check if key not present
|
||||
|
||||
@patch('os.path.isfile', return_value=True)
|
||||
@patch('shlex.quote', side_effect=lambda x: f"'{x}'") # Simple quote mock
|
||||
@patch('os.path.abspath', side_effect=lambda x: f"/abs/path/{x}") # Simple abspath mock
|
||||
def test_prepare_concat_filter_with_end_mov(mock_abspath, mock_quote, mock_isfile, finaliser_with_aac):
|
||||
"""Test concat filter with end_mov."""
|
||||
input_files_with_end = INPUT_FILES.copy()
|
||||
input_files_with_end["end_mov"] = END_MOV
|
||||
|
||||
env_mov_input, ffmpeg_filter = finaliser_with_aac.prepare_concat_filter(input_files_with_end)
|
||||
|
||||
expected_end_mov_path = '/abs/path/' + END_MOV
|
||||
mock_isfile.assert_called_once_with(END_MOV)
|
||||
mock_abspath.assert_called_once_with(END_MOV)
|
||||
mock_quote.assert_called_once_with(expected_end_mov_path)
|
||||
|
||||
assert env_mov_input == f"-i '{expected_end_mov_path}'"
|
||||
assert ffmpeg_filter == '-filter_complex "[0:v:0][0:a:0][1:v:0][1:a:0][2:v:0][2:a:0]concat=n=3:v=1:a=1[outv][outa]"'
|
||||
finaliser_with_aac.logger.info.assert_called_with(f"Found end_mov file: {END_MOV}, including in final MP4")
|
||||
|
||||
|
||||
# --- Individual Encoding Method Tests ---
|
||||
|
||||
@patch.object(KaraokeFinalise, 'execute_command')
|
||||
def test_remux_with_instrumental(mock_execute, finaliser_with_aac):
|
||||
"""Test remux_with_instrumental command."""
|
||||
finaliser_with_aac.remux_with_instrumental(WITH_VOCALS_MOV, INSTRUMENTAL_FLAC, OUTPUT_FILES["karaoke_mp4"])
|
||||
expected_cmd = (
|
||||
f'{finaliser_with_aac.ffmpeg_base_command} -an -i "{WITH_VOCALS_MOV}" '
|
||||
f'-vn -i "{INSTRUMENTAL_FLAC}" -c:v copy -c:a pcm_s16le "{OUTPUT_FILES["karaoke_mp4"]}"'
|
||||
)
|
||||
mock_execute.assert_called_once_with(expected_cmd, "Remuxing video with instrumental audio")
|
||||
|
||||
@patch.object(KaraokeFinalise, 'execute_command')
|
||||
def test_convert_mov_to_mp4_aac(mock_execute, finaliser_with_aac):
|
||||
"""Test convert_mov_to_mp4 command with basic aac codec."""
|
||||
finaliser_with_aac.convert_mov_to_mp4(WITH_VOCALS_MOV, OUTPUT_FILES["with_vocals_mp4"])
|
||||
expected_cmd = (
|
||||
f'{finaliser_with_aac.ffmpeg_base_command} -i "{WITH_VOCALS_MOV}" '
|
||||
f'-c:v libx264 -c:a aac {finaliser_with_aac.mp4_flags} "{OUTPUT_FILES["with_vocals_mp4"]}"'
|
||||
)
|
||||
mock_execute.assert_called_once_with(expected_cmd, "Converting MOV video to MP4")
|
||||
|
||||
@patch.object(KaraokeFinalise, 'execute_command')
|
||||
def test_convert_mov_to_mp4_aac_at(mock_execute, finaliser_with_aac_at):
|
||||
"""Test convert_mov_to_mp4 command with aac_at codec."""
|
||||
finaliser_with_aac_at.convert_mov_to_mp4(WITH_VOCALS_MOV, OUTPUT_FILES["with_vocals_mp4"])
|
||||
expected_cmd = (
|
||||
f'{finaliser_with_aac_at.ffmpeg_base_command} -i "{WITH_VOCALS_MOV}" '
|
||||
f'-c:v libx264 -c:a aac_at {finaliser_with_aac_at.mp4_flags} "{OUTPUT_FILES["with_vocals_mp4"]}"'
|
||||
)
|
||||
mock_execute.assert_called_once_with(expected_cmd, "Converting MOV video to MP4")
|
||||
|
||||
@patch.object(KaraokeFinalise, 'execute_command')
|
||||
@patch('shlex.quote', side_effect=lambda x: f"'{x}'") # Mock quoting for consistency
|
||||
def test_encode_lossless_mp4(mock_quote, mock_execute, finaliser_with_aac):
|
||||
"""Test encode_lossless_mp4 command."""
|
||||
# Simulate how paths would be prepared by the calling function
|
||||
quoted_title_mov = shlex.quote(TITLE_MOV)
|
||||
quoted_karaoke_mp4 = shlex.quote(OUTPUT_FILES["karaoke_mp4"])
|
||||
env_mov_input = "-i 'end.mov'" # Assume end mov path is already prepared/quoted if present
|
||||
ffmpeg_filter = '-filter_complex "[concat]"'
|
||||
|
||||
finaliser_with_aac.encode_lossless_mp4(
|
||||
quoted_title_mov, quoted_karaoke_mp4, env_mov_input, ffmpeg_filter, OUTPUT_FILES["final_karaoke_lossless_mp4"]
|
||||
)
|
||||
# Construct expected command using the quoted paths
|
||||
expected_cmd = (
|
||||
f"{finaliser_with_aac.ffmpeg_base_command} -i {quoted_title_mov} -i {quoted_karaoke_mp4} {env_mov_input} "
|
||||
f'{ffmpeg_filter} -map "[outv]" -map "[outa]" -c:v libx264 -c:a pcm_s16le '
|
||||
f'{finaliser_with_aac.mp4_flags} "{OUTPUT_FILES["final_karaoke_lossless_mp4"]}"'
|
||||
)
|
||||
mock_execute.assert_called_once_with(expected_cmd, "Creating MP4 version with PCM audio")
|
||||
|
||||
@patch.object(KaraokeFinalise, 'execute_command')
|
||||
def test_encode_lossy_mp4_aac(mock_execute, finaliser_with_aac):
|
||||
"""Test encode_lossy_mp4 command with basic aac."""
|
||||
finaliser_with_aac.encode_lossy_mp4(OUTPUT_FILES["final_karaoke_lossless_mp4"], OUTPUT_FILES["final_karaoke_lossy_mp4"])
|
||||
expected_cmd = (
|
||||
f'{finaliser_with_aac.ffmpeg_base_command} -i "{OUTPUT_FILES["final_karaoke_lossless_mp4"]}" '
|
||||
f'-c:v copy -c:a aac -b:a 320k {finaliser_with_aac.mp4_flags} "{OUTPUT_FILES["final_karaoke_lossy_mp4"]}"'
|
||||
)
|
||||
mock_execute.assert_called_once_with(expected_cmd, "Creating MP4 version with AAC audio")
|
||||
|
||||
@patch.object(KaraokeFinalise, 'execute_command')
|
||||
def test_encode_lossy_mp4_aac_at(mock_execute, finaliser_with_aac_at):
|
||||
"""Test encode_lossy_mp4 command with aac_at."""
|
||||
finaliser_with_aac_at.encode_lossy_mp4(OUTPUT_FILES["final_karaoke_lossless_mp4"], OUTPUT_FILES["final_karaoke_lossy_mp4"])
|
||||
expected_cmd = (
|
||||
f'{finaliser_with_aac_at.ffmpeg_base_command} -i "{OUTPUT_FILES["final_karaoke_lossless_mp4"]}" '
|
||||
f'-c:v copy -c:a aac_at -b:a 320k {finaliser_with_aac_at.mp4_flags} "{OUTPUT_FILES["final_karaoke_lossy_mp4"]}"'
|
||||
)
|
||||
mock_execute.assert_called_once_with(expected_cmd, "Creating MP4 version with AAC audio")
|
||||
|
||||
@patch.object(KaraokeFinalise, 'execute_command')
|
||||
def test_encode_lossless_mkv(mock_execute, finaliser_with_aac):
|
||||
"""Test encode_lossless_mkv command."""
|
||||
finaliser_with_aac.encode_lossless_mkv(OUTPUT_FILES["final_karaoke_lossless_mp4"], OUTPUT_FILES["final_karaoke_lossless_mkv"])
|
||||
expected_cmd = (
|
||||
f'{finaliser_with_aac.ffmpeg_base_command} -i "{OUTPUT_FILES["final_karaoke_lossless_mp4"]}" '
|
||||
f'-c:v copy -c:a flac "{OUTPUT_FILES["final_karaoke_lossless_mkv"]}"'
|
||||
)
|
||||
mock_execute.assert_called_once_with(expected_cmd, "Creating MKV version with FLAC audio for YouTube")
|
||||
|
||||
@patch.object(KaraokeFinalise, 'execute_command')
|
||||
def test_encode_720p_version_aac(mock_execute, finaliser_with_aac):
|
||||
"""Test encode_720p_version command with basic aac."""
|
||||
finaliser_with_aac.encode_720p_version(OUTPUT_FILES["final_karaoke_lossless_mp4"], OUTPUT_FILES["final_karaoke_lossy_720p_mp4"])
|
||||
expected_cmd = (
|
||||
f'{finaliser_with_aac.ffmpeg_base_command} -i "{OUTPUT_FILES["final_karaoke_lossless_mp4"]}" '
|
||||
f'-c:v libx264 -vf "scale=1280:720" -b:v 200k -preset medium -tune animation '
|
||||
f'-c:a aac -b:a 128k {finaliser_with_aac.mp4_flags} "{OUTPUT_FILES["final_karaoke_lossy_720p_mp4"]}"'
|
||||
)
|
||||
mock_execute.assert_called_once_with(expected_cmd, "Encoding 720p version of the final video")
|
||||
|
||||
@patch.object(KaraokeFinalise, 'execute_command')
|
||||
def test_encode_720p_version_aac_at(mock_execute, finaliser_with_aac_at):
|
||||
"""Test encode_720p_version command with aac_at."""
|
||||
finaliser_with_aac_at.encode_720p_version(OUTPUT_FILES["final_karaoke_lossless_mp4"], OUTPUT_FILES["final_karaoke_lossy_720p_mp4"])
|
||||
expected_cmd = (
|
||||
f'{finaliser_with_aac_at.ffmpeg_base_command} -i "{OUTPUT_FILES["final_karaoke_lossless_mp4"]}" '
|
||||
f'-c:v libx264 -vf "scale=1280:720" -b:v 200k -preset medium -tune animation '
|
||||
f'-c:a aac_at -b:a 128k {finaliser_with_aac_at.mp4_flags} "{OUTPUT_FILES["final_karaoke_lossy_720p_mp4"]}"'
|
||||
)
|
||||
mock_execute.assert_called_once_with(expected_cmd, "Encoding 720p version of the final video")
|
||||
|
||||
|
||||
# --- remux_and_encode_output_video_files Tests ---
|
||||
|
||||
@patch('os.path.isfile')
|
||||
@patch('os.remove')
|
||||
@patch('shlex.quote', side_effect=lambda x: f"'{x}'")
|
||||
@patch('os.path.abspath', side_effect=lambda x: f"/abs/path/{x}")
|
||||
@patch.object(KaraokeFinalise, 'remux_with_instrumental')
|
||||
@patch.object(KaraokeFinalise, 'convert_mov_to_mp4')
|
||||
@patch.object(KaraokeFinalise, 'prepare_concat_filter')
|
||||
@patch.object(KaraokeFinalise, 'encode_lossless_mp4')
|
||||
@patch.object(KaraokeFinalise, 'encode_lossy_mp4')
|
||||
@patch.object(KaraokeFinalise, 'encode_lossless_mkv')
|
||||
@patch.object(KaraokeFinalise, 'encode_720p_version')
|
||||
@patch.object(KaraokeFinalise, 'prompt_user_bool', return_value=True) # Auto-confirm overwrite/checks
|
||||
@patch.object(KaraokeFinalise, 'prompt_user_confirmation_or_raise_exception') # Mock final check
|
||||
def test_remux_and_encode_all_steps_mov_input(
|
||||
mock_prompt_confirm, mock_prompt_bool, mock_encode_720p, mock_encode_mkv, mock_encode_lossy,
|
||||
mock_encode_lossless, mock_prepare_filter, mock_convert_mov, mock_remux,
|
||||
mock_abspath, mock_quote, mock_remove, mock_isfile, finaliser_with_aac):
|
||||
"""Test the full remux/encode process with a .mov input requiring conversion."""
|
||||
|
||||
# Simulate output files don't exist initially, end_mov exists
|
||||
mock_isfile.side_effect = lambda f: f == INPUT_FILES["title_mov"] or f == END_MOV
|
||||
|
||||
# Mock prepare_concat_filter to return specific values
|
||||
mock_env_mov_input = f"-i '/abs/path/{END_MOV}'"
|
||||
mock_ffmpeg_filter = '-filter_complex "[concat_3]"'
|
||||
mock_prepare_filter.return_value = (mock_env_mov_input, mock_ffmpeg_filter)
|
||||
|
||||
input_files_with_end = INPUT_FILES.copy()
|
||||
input_files_with_end["end_mov"] = END_MOV
|
||||
|
||||
finaliser_with_aac.remux_and_encode_output_video_files(WITH_VOCALS_MOV, input_files_with_end, OUTPUT_FILES)
|
||||
|
||||
# Check file existence check
|
||||
mock_isfile.assert_any_call(OUTPUT_FILES["final_karaoke_lossless_mp4"])
|
||||
mock_isfile.assert_any_call(OUTPUT_FILES["final_karaoke_lossless_mkv"])
|
||||
mock_prompt_bool.assert_called_once() # Should ask to overwrite
|
||||
|
||||
# Check steps called in order
|
||||
mock_remux.assert_called_once_with(WITH_VOCALS_MOV, input_files_with_end["instrumental_audio"], OUTPUT_FILES["karaoke_mp4"])
|
||||
mock_convert_mov.assert_called_once_with(WITH_VOCALS_MOV, OUTPUT_FILES["with_vocals_mp4"])
|
||||
mock_remove.assert_called_once_with(WITH_VOCALS_MOV) # Original MOV deleted
|
||||
mock_prepare_filter.assert_called_once_with(input_files_with_end)
|
||||
|
||||
# Explicitly define expected quoted paths based on mocks
|
||||
expected_quoted_title_mov = f"'/abs/path/{INPUT_FILES['title_mov']}'"
|
||||
expected_quoted_karaoke_mp4 = f"'/abs/path/{OUTPUT_FILES['karaoke_mp4']}'"
|
||||
|
||||
mock_encode_lossless.assert_called_once_with(
|
||||
expected_quoted_title_mov,
|
||||
expected_quoted_karaoke_mp4,
|
||||
mock_env_mov_input,
|
||||
mock_ffmpeg_filter,
|
||||
OUTPUT_FILES["final_karaoke_lossless_mp4"]
|
||||
)
|
||||
mock_encode_lossy.assert_called_once_with(OUTPUT_FILES["final_karaoke_lossless_mp4"], OUTPUT_FILES["final_karaoke_lossy_mp4"])
|
||||
mock_encode_mkv.assert_called_once_with(OUTPUT_FILES["final_karaoke_lossless_mp4"], OUTPUT_FILES["final_karaoke_lossless_mkv"])
|
||||
mock_encode_720p.assert_called_once_with(OUTPUT_FILES["final_karaoke_lossless_mp4"], OUTPUT_FILES["final_karaoke_lossy_720p_mp4"])
|
||||
mock_prompt_confirm.assert_called_once() # Final check prompt
|
||||
|
||||
@patch('os.path.isfile')
|
||||
@patch('os.remove')
|
||||
@patch.object(KaraokeFinalise, 'remux_with_instrumental')
|
||||
@patch.object(KaraokeFinalise, 'convert_mov_to_mp4')
|
||||
@patch.object(KaraokeFinalise, 'prompt_user_bool', return_value=True) # Auto-confirm overwrite/checks
|
||||
@patch.object(KaraokeFinalise, 'prompt_user_confirmation_or_raise_exception') # Mock final check
|
||||
def test_remux_and_encode_mp4_input(
|
||||
mock_prompt_confirm, mock_prompt_bool, mock_convert_mov, mock_remux,
|
||||
mock_remove, mock_isfile, finaliser_with_aac):
|
||||
"""Test the remux/encode process skips conversion for .mp4 input."""
|
||||
mock_isfile.return_value = False # Output files don't exist
|
||||
|
||||
# Use MP4 as input
|
||||
with_vocals_mp4 = f"{BASE_NAME} (With Vocals).mp4"
|
||||
|
||||
finaliser_with_aac.remux_and_encode_output_video_files(with_vocals_mp4, INPUT_FILES, OUTPUT_FILES)
|
||||
|
||||
mock_remux.assert_called_once()
|
||||
mock_convert_mov.assert_not_called() # Should skip conversion
|
||||
mock_remove.assert_not_called() # Should not delete input MP4
|
||||
|
||||
@patch('os.path.isfile', return_value=True) # Files exist
|
||||
@patch.object(KaraokeFinalise, 'remux_with_instrumental')
|
||||
@patch.object(KaraokeFinalise, 'convert_mov_to_mp4')
|
||||
@patch.object(KaraokeFinalise, 'encode_lossless_mp4')
|
||||
@patch.object(KaraokeFinalise, 'encode_lossy_mp4')
|
||||
@patch.object(KaraokeFinalise, 'encode_lossless_mkv')
|
||||
@patch.object(KaraokeFinalise, 'encode_720p_version')
|
||||
@patch.object(KaraokeFinalise, 'prompt_user_bool', return_value=False) # User chooses *not* to overwrite
|
||||
@patch.object(KaraokeFinalise, 'prompt_user_confirmation_or_raise_exception')
|
||||
def test_remux_and_encode_skip_overwrite(
|
||||
mock_prompt_confirm, mock_prompt_bool, mock_encode_720p, mock_encode_mkv, mock_encode_lossy,
|
||||
mock_encode_lossless, mock_convert_mov, mock_remux, mock_isfile, finaliser_with_aac):
|
||||
"""Test skipping encoding steps if user chooses not to overwrite."""
|
||||
|
||||
finaliser_with_aac.remux_and_encode_output_video_files(WITH_VOCALS_MOV, INPUT_FILES, OUTPUT_FILES)
|
||||
|
||||
mock_isfile.assert_any_call(OUTPUT_FILES["final_karaoke_lossless_mp4"])
|
||||
mock_isfile.assert_any_call(OUTPUT_FILES["final_karaoke_lossless_mkv"])
|
||||
mock_prompt_bool.assert_called_once() # Asked to overwrite
|
||||
# Ensure no encoding steps were called
|
||||
mock_remux.assert_not_called()
|
||||
mock_convert_mov.assert_not_called()
|
||||
mock_encode_lossless.assert_not_called()
|
||||
mock_encode_lossy.assert_not_called()
|
||||
mock_encode_mkv.assert_not_called()
|
||||
mock_encode_720p.assert_not_called()
|
||||
mock_prompt_confirm.assert_not_called() # Final check prompt skipped
|
||||
@@ -0,0 +1,377 @@
|
||||
import pytest
|
||||
import os
|
||||
import json
|
||||
from unittest.mock import patch, MagicMock, mock_open, call
|
||||
|
||||
# Adjust the import path
|
||||
from karaoke_prep.karaoke_finalise.karaoke_finalise import KaraokeFinalise
|
||||
from .test_initialization import mock_logger, basic_finaliser, MINIMAL_CONFIG # Reuse fixtures
|
||||
|
||||
BASE_NAME = "Artist - Title"
|
||||
ARTIST = "Artist" # Define constant
|
||||
TITLE = "Title" # Define constant
|
||||
WITH_VOCALS_MOV = f"{BASE_NAME} (With Vocals).mov"
|
||||
WITH_VOCALS_MP4 = f"{BASE_NAME} (With Vocals).mp4"
|
||||
INSTRUMENTAL_FLAC = f"{BASE_NAME} (Instrumental).flac"
|
||||
INSTRUMENTAL_MP3 = f"{BASE_NAME} (Instrumental).mp3"
|
||||
INSTRUMENTAL_WAV = f"{BASE_NAME} (Instrumental).wav"
|
||||
TITLE_MOV = f"{BASE_NAME} (Title).mov"
|
||||
TITLE_JPG = f"{BASE_NAME} (Title).jpg"
|
||||
END_MOV = f"{BASE_NAME} (End).mov"
|
||||
END_JPG = f"{BASE_NAME} (End).jpg"
|
||||
KARAOKE_LRC = f"{BASE_NAME} (Karaoke).lrc"
|
||||
KARAOKE_MOV_MISNAMED = f"{BASE_NAME} (Karaoke).mov"
|
||||
|
||||
# --- File Existence and Preparation Tests ---
|
||||
|
||||
@patch('os.path.isfile')
|
||||
def test_check_input_files_exist_success(mock_isfile, basic_finaliser):
|
||||
"""Test check_input_files_exist succeeds when all required files exist."""
|
||||
mock_isfile.return_value = True
|
||||
basic_finaliser.enable_cdg = True # Need LRC for this test
|
||||
|
||||
input_files = basic_finaliser.check_input_files_exist(BASE_NAME, WITH_VOCALS_MOV, INSTRUMENTAL_FLAC)
|
||||
|
||||
expected_files = {
|
||||
"title_mov": TITLE_MOV,
|
||||
"title_jpg": TITLE_JPG,
|
||||
"instrumental_audio": INSTRUMENTAL_FLAC,
|
||||
"with_vocals_mov": WITH_VOCALS_MOV,
|
||||
"karaoke_lrc": KARAOKE_LRC,
|
||||
"end_mov": END_MOV, # Optional, mocked as existing
|
||||
"end_jpg": END_JPG, # Optional, mocked as existing
|
||||
}
|
||||
assert input_files == expected_files
|
||||
mock_isfile.assert_has_calls([
|
||||
call(TITLE_MOV),
|
||||
call(TITLE_JPG),
|
||||
call(INSTRUMENTAL_FLAC),
|
||||
call(WITH_VOCALS_MOV),
|
||||
call(KARAOKE_LRC),
|
||||
call(END_MOV), # Checks optional file
|
||||
call(END_JPG), # Checks optional file
|
||||
], any_order=True)
|
||||
|
||||
@patch('os.path.isfile')
|
||||
def test_check_input_files_exist_missing_required(mock_isfile, basic_finaliser):
|
||||
"""Test check_input_files_exist raises exception for missing required file."""
|
||||
# Make title_mov missing
|
||||
mock_isfile.side_effect = lambda f: f != TITLE_MOV
|
||||
|
||||
with pytest.raises(Exception, match=f"Input file title_mov not found: {TITLE_MOV}"):
|
||||
basic_finaliser.check_input_files_exist(BASE_NAME, WITH_VOCALS_MOV, INSTRUMENTAL_FLAC)
|
||||
|
||||
@patch('os.path.isfile')
|
||||
def test_check_input_files_exist_missing_optional(mock_isfile, basic_finaliser):
|
||||
"""Test check_input_files_exist succeeds when optional files are missing."""
|
||||
# Make optional files missing, required files exist
|
||||
mock_isfile.side_effect = lambda f: f not in [END_MOV, END_JPG]
|
||||
basic_finaliser.enable_cdg = False # Don't require LRC
|
||||
|
||||
input_files = basic_finaliser.check_input_files_exist(BASE_NAME, WITH_VOCALS_MOV, INSTRUMENTAL_FLAC)
|
||||
|
||||
expected_files = {
|
||||
"title_mov": TITLE_MOV,
|
||||
"title_jpg": TITLE_JPG,
|
||||
"instrumental_audio": INSTRUMENTAL_FLAC,
|
||||
"with_vocals_mov": WITH_VOCALS_MOV,
|
||||
# karaoke_lrc, end_mov, end_jpg should be absent
|
||||
}
|
||||
assert input_files == expected_files
|
||||
# Ensure optional files were checked but not added
|
||||
mock_isfile.assert_has_calls([call(END_MOV), call(END_JPG)], any_order=True)
|
||||
|
||||
@patch('os.path.isfile')
|
||||
def test_check_input_files_exist_lrc_required(mock_isfile, basic_finaliser):
|
||||
"""Test check_input_files_exist requires LRC when CDG or TXT enabled."""
|
||||
mock_isfile.side_effect = lambda f: f != KARAOKE_LRC # Make LRC missing
|
||||
basic_finaliser.enable_cdg = True
|
||||
|
||||
with pytest.raises(Exception, match=f"Input file karaoke_lrc not found: {KARAOKE_LRC}"):
|
||||
basic_finaliser.check_input_files_exist(BASE_NAME, WITH_VOCALS_MOV, INSTRUMENTAL_FLAC)
|
||||
|
||||
basic_finaliser.enable_cdg = False
|
||||
basic_finaliser.enable_txt = True
|
||||
with pytest.raises(Exception, match=f"Input file karaoke_lrc not found: {KARAOKE_LRC}"):
|
||||
basic_finaliser.check_input_files_exist(BASE_NAME, WITH_VOCALS_MOV, INSTRUMENTAL_FLAC)
|
||||
|
||||
|
||||
def test_prepare_output_filenames(basic_finaliser):
|
||||
"""Test prepare_output_filenames generates correct names."""
|
||||
basic_finaliser.enable_cdg = True
|
||||
basic_finaliser.enable_txt = True
|
||||
|
||||
output_files = basic_finaliser.prepare_output_filenames(BASE_NAME)
|
||||
|
||||
expected_suffixes = {
|
||||
"karaoke_mp4": " (Karaoke).mp4",
|
||||
"karaoke_mp3": " (Karaoke).mp3",
|
||||
"karaoke_cdg": " (Karaoke).cdg",
|
||||
"with_vocals_mp4": " (With Vocals).mp4",
|
||||
"final_karaoke_lossless_mp4": " (Final Karaoke Lossless 4k).mp4",
|
||||
"final_karaoke_lossless_mkv": " (Final Karaoke Lossless 4k).mkv",
|
||||
"final_karaoke_lossy_mp4": " (Final Karaoke Lossy 4k).mp4",
|
||||
"final_karaoke_lossy_720p_mp4": " (Final Karaoke Lossy 720p).mp4",
|
||||
"final_karaoke_cdg_zip": " (Final Karaoke CDG).zip", # Enabled
|
||||
"karaoke_txt": " (Karaoke).txt", # Enabled
|
||||
"final_karaoke_txt_zip": " (Final Karaoke TXT).zip", # Enabled
|
||||
}
|
||||
|
||||
assert len(output_files) == len(expected_suffixes)
|
||||
for key, suffix in expected_suffixes.items():
|
||||
assert key in output_files
|
||||
assert output_files[key] == f"{BASE_NAME}{suffix}"
|
||||
|
||||
def test_prepare_output_filenames_cdg_txt_disabled(basic_finaliser):
|
||||
"""Test prepare_output_filenames excludes CDG/TXT when disabled."""
|
||||
basic_finaliser.enable_cdg = False
|
||||
basic_finaliser.enable_txt = False
|
||||
|
||||
output_files = basic_finaliser.prepare_output_filenames(BASE_NAME)
|
||||
|
||||
assert "final_karaoke_cdg_zip" not in output_files
|
||||
assert "karaoke_txt" not in output_files
|
||||
assert "final_karaoke_txt_zip" not in output_files
|
||||
|
||||
|
||||
# --- Feature Validation Tests ---
|
||||
|
||||
@patch('os.path.isfile')
|
||||
@patch('os.path.isdir')
|
||||
@patch('builtins.open', new_callable=mock_open, read_data='{"installed": {"client_id": "test"}}')
|
||||
@patch('json.load')
|
||||
@patch('builtins.input', return_value='y') # Auto-confirm prompt
|
||||
def test_validate_input_parameters_all_features_enabled(mock_input, mock_json_load, mock_open_file, mock_isdir, mock_isfile, basic_finaliser):
|
||||
"""Test validation enables all features with correct inputs."""
|
||||
mock_isfile.return_value = True # All files exist
|
||||
mock_isdir.return_value = True # All dirs exist
|
||||
|
||||
basic_finaliser.youtube_client_secrets_file = "secrets.json"
|
||||
basic_finaliser.youtube_description_file = "desc.txt"
|
||||
basic_finaliser.discord_webhook_url = "https://discord.com/api/webhooks/123/abc"
|
||||
basic_finaliser.brand_prefix = "TEST"
|
||||
basic_finaliser.organised_dir = "/path/to/organised"
|
||||
basic_finaliser.public_share_dir = "/path/to/public"
|
||||
basic_finaliser.rclone_destination = "remote:backup"
|
||||
basic_finaliser.enable_cdg = True
|
||||
basic_finaliser.enable_txt = True
|
||||
|
||||
basic_finaliser.validate_input_parameters_for_features()
|
||||
|
||||
assert basic_finaliser.youtube_upload_enabled
|
||||
assert basic_finaliser.discord_notication_enabled
|
||||
assert basic_finaliser.folder_organisation_enabled
|
||||
assert basic_finaliser.public_share_copy_enabled
|
||||
assert basic_finaliser.public_share_rclone_enabled
|
||||
mock_isfile.assert_any_call("secrets.json")
|
||||
mock_isfile.assert_any_call("desc.txt")
|
||||
mock_open_file.assert_called_once_with("secrets.json", "r")
|
||||
mock_json_load.assert_called_once()
|
||||
mock_isdir.assert_any_call("/path/to/organised")
|
||||
mock_isdir.assert_any_call("/path/to/public")
|
||||
mock_isdir.assert_any_call("/path/to/public/MP4")
|
||||
mock_isdir.assert_any_call("/path/to/public/CDG")
|
||||
mock_input.assert_called_once() # Confirmation prompt
|
||||
|
||||
@patch('os.path.isfile', return_value=False)
|
||||
@patch('builtins.input', return_value='y')
|
||||
def test_validate_youtube_secrets_missing(mock_input, mock_isfile, basic_finaliser):
|
||||
"""Test validation fails if YouTube secrets file is missing."""
|
||||
basic_finaliser.youtube_client_secrets_file = "secrets.json"
|
||||
basic_finaliser.youtube_description_file = "desc.txt"
|
||||
with pytest.raises(Exception, match="YouTube client secrets file does not exist"):
|
||||
basic_finaliser.validate_input_parameters_for_features()
|
||||
assert not basic_finaliser.youtube_upload_enabled
|
||||
|
||||
@patch('os.path.isfile', return_value=True)
|
||||
@patch('builtins.open', new_callable=mock_open, read_data='invalid json')
|
||||
@patch('json.load', side_effect=json.JSONDecodeError("Expecting value", "invalid json", 0))
|
||||
@patch('builtins.input', return_value='y')
|
||||
def test_validate_youtube_secrets_invalid_json(mock_input, mock_json_load, mock_open_file, mock_isfile, basic_finaliser):
|
||||
"""Test validation fails if YouTube secrets file is invalid JSON."""
|
||||
basic_finaliser.youtube_client_secrets_file = "secrets.json"
|
||||
basic_finaliser.youtube_description_file = "desc.txt"
|
||||
with pytest.raises(Exception, match="YouTube client secrets file is not valid JSON"):
|
||||
basic_finaliser.validate_input_parameters_for_features()
|
||||
assert not basic_finaliser.youtube_upload_enabled
|
||||
|
||||
@patch('builtins.input', return_value='y')
|
||||
def test_validate_discord_url_invalid(mock_input, basic_finaliser):
|
||||
"""Test validation fails with invalid Discord webhook URL."""
|
||||
basic_finaliser.discord_webhook_url = "http://invalid.com"
|
||||
with pytest.raises(Exception, match="Discord webhook URL is not valid"):
|
||||
basic_finaliser.validate_input_parameters_for_features()
|
||||
assert not basic_finaliser.discord_notication_enabled
|
||||
|
||||
@patch('os.path.isdir', return_value=False)
|
||||
@patch('builtins.input', return_value='y')
|
||||
def test_validate_organised_dir_missing(mock_input, mock_isdir, basic_finaliser):
|
||||
"""Test validation fails if organised_dir is missing."""
|
||||
basic_finaliser.brand_prefix = "TEST"
|
||||
basic_finaliser.organised_dir = "/missing/dir"
|
||||
with pytest.raises(Exception, match="Target directory does not exist"):
|
||||
basic_finaliser.validate_input_parameters_for_features()
|
||||
assert not basic_finaliser.folder_organisation_enabled
|
||||
|
||||
@patch('os.path.isdir')
|
||||
@patch('builtins.input', return_value='y')
|
||||
def test_validate_public_share_dir_missing_subdirs(mock_input, mock_isdir, basic_finaliser):
|
||||
"""Test validation fails if public_share_dir is missing subdirectories."""
|
||||
basic_finaliser.public_share_dir = "/public/share"
|
||||
# Simulate missing MP4 subdir
|
||||
mock_isdir.side_effect = lambda p: p != "/public/share/MP4"
|
||||
|
||||
with pytest.raises(Exception, match="Public share directory does not contain MP4 subdirectory"):
|
||||
basic_finaliser.validate_input_parameters_for_features()
|
||||
assert not basic_finaliser.public_share_copy_enabled
|
||||
|
||||
# Simulate missing CDG subdir
|
||||
mock_isdir.side_effect = lambda p: p != "/public/share/CDG"
|
||||
with pytest.raises(Exception, match="Public share directory does not contain CDG subdirectory"):
|
||||
basic_finaliser.validate_input_parameters_for_features()
|
||||
assert not basic_finaliser.public_share_copy_enabled
|
||||
|
||||
@patch('builtins.input', return_value='n') # User rejects confirmation
|
||||
def test_validate_user_rejects_confirmation(mock_input, basic_finaliser):
|
||||
"""Test validation fails if user rejects the confirmation prompt."""
|
||||
# Setup minimal valid config for some features to be enabled
|
||||
basic_finaliser.rclone_destination = "remote:dest"
|
||||
with pytest.raises(Exception, match="Refusing to proceed without user confirmation"):
|
||||
basic_finaliser.validate_input_parameters_for_features()
|
||||
|
||||
# --- File Finding/Choosing Tests ---
|
||||
|
||||
@patch('os.listdir')
|
||||
def test_find_with_vocals_file_mov_exists(mock_listdir, basic_finaliser):
|
||||
"""Test finding a .mov with vocals file."""
|
||||
mock_listdir.return_value = ["other.txt", WITH_VOCALS_MOV, TITLE_MOV]
|
||||
found_file = basic_finaliser.find_with_vocals_file()
|
||||
assert found_file == WITH_VOCALS_MOV
|
||||
|
||||
@patch('os.listdir')
|
||||
def test_find_with_vocals_file_mp4_exists(mock_listdir, basic_finaliser):
|
||||
"""Test finding a .mp4 with vocals file."""
|
||||
mock_listdir.return_value = ["other.txt", WITH_VOCALS_MP4, TITLE_MOV]
|
||||
found_file = basic_finaliser.find_with_vocals_file()
|
||||
assert found_file == WITH_VOCALS_MP4
|
||||
|
||||
@patch('os.listdir')
|
||||
@patch('os.rename')
|
||||
@patch('builtins.input', return_value='y') # Confirm rename
|
||||
def test_find_with_vocals_file_rename_karaoke_mov(mock_input, mock_rename, mock_listdir, basic_finaliser):
|
||||
"""Test renaming a misnamed (Karaoke).mov file."""
|
||||
mock_listdir.return_value = ["other.txt", KARAOKE_MOV_MISNAMED, TITLE_MOV]
|
||||
found_file = basic_finaliser.find_with_vocals_file()
|
||||
assert found_file == WITH_VOCALS_MOV
|
||||
mock_rename.assert_called_once_with(KARAOKE_MOV_MISNAMED, WITH_VOCALS_MOV)
|
||||
mock_input.assert_called_once()
|
||||
|
||||
@patch('os.listdir')
|
||||
@patch('os.rename')
|
||||
@patch('builtins.input', return_value='n') # Reject rename
|
||||
def test_find_with_vocals_file_reject_rename(mock_input, mock_rename, mock_listdir, basic_finaliser):
|
||||
"""Test exception raised if user rejects renaming."""
|
||||
mock_listdir.return_value = ["other.txt", KARAOKE_MOV_MISNAMED, TITLE_MOV]
|
||||
with pytest.raises(Exception, match="Unable to proceed without With Vocals file"):
|
||||
basic_finaliser.find_with_vocals_file()
|
||||
mock_rename.assert_not_called()
|
||||
|
||||
@patch('os.listdir', return_value=["other.txt", TITLE_MOV])
|
||||
def test_find_with_vocals_file_not_found(mock_listdir, basic_finaliser):
|
||||
"""Test exception raised if no suitable file is found."""
|
||||
with pytest.raises(Exception, match="No suitable files found for processing"):
|
||||
basic_finaliser.find_with_vocals_file()
|
||||
|
||||
@patch('os.listdir')
|
||||
def test_choose_instrumental_audio_file_only_flac(mock_listdir, basic_finaliser):
|
||||
"""Test choosing the only instrumental file (FLAC)."""
|
||||
mock_listdir.return_value = [INSTRUMENTAL_FLAC, "other.txt"]
|
||||
chosen_file = basic_finaliser.choose_instrumental_audio_file(BASE_NAME)
|
||||
assert chosen_file == INSTRUMENTAL_FLAC
|
||||
|
||||
@patch('os.listdir')
|
||||
def test_choose_instrumental_audio_file_prefer_flac(mock_listdir, basic_finaliser):
|
||||
"""Test preferring FLAC over MP3 and WAV."""
|
||||
mock_listdir.return_value = [INSTRUMENTAL_MP3, INSTRUMENTAL_FLAC, INSTRUMENTAL_WAV, "other.txt"]
|
||||
chosen_file = basic_finaliser.choose_instrumental_audio_file(BASE_NAME)
|
||||
assert chosen_file == INSTRUMENTAL_FLAC
|
||||
|
||||
@patch('os.listdir')
|
||||
def test_choose_instrumental_audio_file_prefer_wav_over_mp3(mock_listdir, basic_finaliser):
|
||||
"""Test preferring WAV over MP3 when FLAC is absent."""
|
||||
mock_listdir.return_value = [INSTRUMENTAL_MP3, INSTRUMENTAL_WAV, "other.txt"]
|
||||
chosen_file = basic_finaliser.choose_instrumental_audio_file(BASE_NAME)
|
||||
assert chosen_file == INSTRUMENTAL_WAV
|
||||
|
||||
@patch('os.listdir')
|
||||
@patch('builtins.input', return_value='2') # Choose second option
|
||||
def test_choose_instrumental_audio_file_multiple_prompt(mock_input, mock_listdir, basic_finaliser):
|
||||
"""Test prompting user when multiple valid files exist."""
|
||||
basic_finaliser.non_interactive = False # Enable prompt
|
||||
files = [f"{BASE_NAME} (Instrumental Mix 1).flac", f"{BASE_NAME} (Instrumental Mix 2).flac"]
|
||||
mock_listdir.return_value = files
|
||||
# Sort order expected by the prompt (reverse alphabetical)
|
||||
expected_prompt_order = sorted(files, reverse=True)
|
||||
|
||||
chosen_file = basic_finaliser.choose_instrumental_audio_file(BASE_NAME)
|
||||
|
||||
assert chosen_file == expected_prompt_order[1] # User chose '2' (index 1)
|
||||
mock_input.assert_called_once()
|
||||
|
||||
@patch('os.listdir')
|
||||
def test_choose_instrumental_audio_file_multiple_non_interactive(mock_listdir, basic_finaliser):
|
||||
"""Test choosing the first option non-interactively."""
|
||||
basic_finaliser.non_interactive = True # Disable prompt
|
||||
files = [f"{BASE_NAME} (Instrumental Mix 1).flac", f"{BASE_NAME} (Instrumental Mix 2).flac"]
|
||||
mock_listdir.return_value = files
|
||||
expected_choice = sorted(files, reverse=True)[0] # First in reverse alphabetical
|
||||
|
||||
chosen_file = basic_finaliser.choose_instrumental_audio_file(BASE_NAME)
|
||||
assert chosen_file == expected_choice
|
||||
|
||||
@patch('os.listdir', return_value=["other.txt"])
|
||||
def test_choose_instrumental_audio_file_not_found(mock_listdir, basic_finaliser):
|
||||
"""Test exception raised if no instrumental files are found."""
|
||||
with pytest.raises(Exception, match="No instrumental audio files found"):
|
||||
basic_finaliser.choose_instrumental_audio_file(BASE_NAME)
|
||||
|
||||
# --- Name Extraction Tests ---
|
||||
|
||||
def test_get_names_from_withvocals_mov(basic_finaliser):
|
||||
"""Test extracting names from a .mov file."""
|
||||
base, artist, title = basic_finaliser.get_names_from_withvocals(WITH_VOCALS_MOV)
|
||||
assert base == BASE_NAME
|
||||
assert artist == "Artist"
|
||||
assert title == "Title"
|
||||
|
||||
def test_get_names_from_withvocals_mp4(basic_finaliser):
|
||||
"""Test extracting names from a .mp4 file."""
|
||||
base, artist, title = basic_finaliser.get_names_from_withvocals(WITH_VOCALS_MP4)
|
||||
assert base == BASE_NAME
|
||||
assert artist == "Artist"
|
||||
assert title == "Title"
|
||||
|
||||
def test_get_names_from_withvocals_mkv(basic_finaliser):
|
||||
"""Test extracting names from a .mkv file."""
|
||||
mkv_file = f"{BASE_NAME} (With Vocals).mkv"
|
||||
base, artist, title = basic_finaliser.get_names_from_withvocals(mkv_file)
|
||||
assert base == BASE_NAME
|
||||
assert artist == "Artist"
|
||||
assert title == "Title"
|
||||
|
||||
def test_get_names_from_withvocals_no_suffix(basic_finaliser):
|
||||
"""Test extracting names when suffix is missing (falls back to removing extension)."""
|
||||
file_no_suffix = f"{BASE_NAME}.mov"
|
||||
base, artist, title = basic_finaliser.get_names_from_withvocals(file_no_suffix)
|
||||
assert base == BASE_NAME
|
||||
assert artist == "Artist"
|
||||
assert title == "Title"
|
||||
|
||||
def test_get_names_from_withvocals_complex_title(basic_finaliser):
|
||||
"""Test extracting names with complex title including hyphens."""
|
||||
complex_base = "Some Artist - A Song - With Hyphens - And Stuff"
|
||||
complex_file = f"{complex_base} (With Vocals).mp4"
|
||||
base, artist, title = basic_finaliser.get_names_from_withvocals(complex_file)
|
||||
assert base == complex_base
|
||||
assert artist == "Some Artist"
|
||||
assert title == "A Song - With Hyphens - And Stuff"
|
||||
@@ -0,0 +1,293 @@
|
||||
import pytest
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import time
|
||||
from unittest.mock import patch, MagicMock, call, ANY
|
||||
|
||||
# Adjust the import path
|
||||
from karaoke_prep.karaoke_finalise.karaoke_finalise import KaraokeFinalise
|
||||
from .test_initialization import mock_logger, basic_finaliser, MINIMAL_CONFIG # Reuse fixtures
|
||||
from .test_file_input_validation import BASE_NAME, ARTIST, TITLE # Reuse constants
|
||||
from .test_ffmpeg_commands import OUTPUT_FILES as FFMPEG_OUTPUT_FILES # Reuse constants
|
||||
|
||||
# Define expected output filenames relevant to organisation
|
||||
OUTPUT_FILES_ORG = {
|
||||
"final_karaoke_lossy_mp4": FFMPEG_OUTPUT_FILES["final_karaoke_lossy_mp4"],
|
||||
"final_karaoke_lossy_720p_mp4": FFMPEG_OUTPUT_FILES["final_karaoke_lossy_720p_mp4"],
|
||||
"final_karaoke_cdg_zip": f"{BASE_NAME} (Final Karaoke CDG).zip", # Assume CDG enabled for copy tests
|
||||
}
|
||||
|
||||
BRAND_PREFIX = "XYZ"
|
||||
ORGANISED_DIR = "/path/to/organised"
|
||||
PUBLIC_SHARE_DIR = "/path/to/public"
|
||||
RCLONE_DEST = "remote:public_share"
|
||||
ORGANISED_RCLONE_ROOT = "remote:organised"
|
||||
|
||||
@pytest.fixture
|
||||
def finaliser_for_org(mock_logger):
|
||||
"""Fixture for a finaliser configured for organisation tasks."""
|
||||
config = MINIMAL_CONFIG.copy()
|
||||
config.update({
|
||||
"brand_prefix": BRAND_PREFIX,
|
||||
"organised_dir": ORGANISED_DIR,
|
||||
"public_share_dir": PUBLIC_SHARE_DIR,
|
||||
"rclone_destination": RCLONE_DEST,
|
||||
"organised_dir_rclone_root": ORGANISED_RCLONE_ROOT,
|
||||
"enable_cdg": True, # Needed for zip copy test
|
||||
})
|
||||
with patch.object(KaraokeFinalise, 'detect_best_aac_codec', return_value='aac'):
|
||||
finaliser = KaraokeFinalise(logger=mock_logger, **config)
|
||||
# Manually enable features for testing specific methods
|
||||
finaliser.folder_organisation_enabled = True
|
||||
finaliser.public_share_copy_enabled = True
|
||||
finaliser.public_share_rclone_enabled = True
|
||||
return finaliser
|
||||
|
||||
# --- Brand Code Tests ---
|
||||
|
||||
@patch('os.listdir')
|
||||
@patch('os.path.isdir', return_value=True)
|
||||
def test_get_next_brand_code_first(mock_isdir, mock_listdir, finaliser_for_org):
|
||||
"""Test getting the first brand code when no previous exist."""
|
||||
mock_listdir.return_value = ["some_other_file.txt", "NOT-A-BRAND-DIR"]
|
||||
next_code = finaliser_for_org.get_next_brand_code()
|
||||
assert next_code == f"{BRAND_PREFIX}-0001"
|
||||
mock_isdir.assert_called_once_with(ORGANISED_DIR)
|
||||
|
||||
@patch('os.listdir')
|
||||
@patch('os.path.isdir', return_value=True)
|
||||
def test_get_next_brand_code_existing(mock_isdir, mock_listdir, finaliser_for_org):
|
||||
"""Test getting the next brand code when others exist."""
|
||||
mock_listdir.return_value = [
|
||||
f"{BRAND_PREFIX}-0001 - Some Artist - Title",
|
||||
f"{BRAND_PREFIX}-0005 - Another Artist - Song",
|
||||
f"{BRAND_PREFIX}-0003 - Test - Track",
|
||||
"OTHER-0001 - Ignored",
|
||||
]
|
||||
next_code = finaliser_for_org.get_next_brand_code()
|
||||
assert next_code == f"{BRAND_PREFIX}-0006" # Max was 5, next is 6
|
||||
mock_isdir.assert_called_once_with(ORGANISED_DIR)
|
||||
|
||||
@patch('os.path.isdir', return_value=False)
|
||||
def test_get_next_brand_code_dir_missing(mock_isdir, finaliser_for_org):
|
||||
"""Test get_next_brand_code raises error if organised_dir is missing."""
|
||||
with pytest.raises(Exception, match=f"Target directory does not exist: {ORGANISED_DIR}"):
|
||||
finaliser_for_org.get_next_brand_code()
|
||||
|
||||
@patch('os.getcwd', return_value=f"/some/path/{BRAND_PREFIX}-0010 - {ARTIST} - {TITLE}")
|
||||
@patch('os.path.basename', return_value=f"{BRAND_PREFIX}-0010 - {ARTIST} - {TITLE}")
|
||||
def test_get_existing_brand_code_success(mock_basename, mock_getcwd, finaliser_for_org):
|
||||
"""Test successfully extracting existing brand code."""
|
||||
brand_code = finaliser_for_org.get_existing_brand_code()
|
||||
assert brand_code == f"{BRAND_PREFIX}-0010"
|
||||
mock_getcwd.assert_called_once()
|
||||
mock_basename.assert_called_once_with(mock_getcwd.return_value)
|
||||
|
||||
@patch('os.getcwd', return_value="/some/path/NoBrandCode - Artist - Title")
|
||||
@patch('os.path.basename', return_value="NoBrandCode - Artist - Title")
|
||||
def test_get_existing_brand_code_invalid_format(mock_basename, mock_getcwd, finaliser_for_org):
|
||||
"""Test error when current directory format is wrong."""
|
||||
with pytest.raises(Exception, match="Could not extract valid brand code"):
|
||||
finaliser_for_org.get_existing_brand_code()
|
||||
|
||||
# --- File Moving/Copying Tests ---
|
||||
|
||||
@patch('os.getcwd', return_value=f"/current/workdir/{ARTIST} - {TITLE}")
|
||||
@patch('os.path.dirname', return_value="/current/workdir")
|
||||
@patch('os.chdir')
|
||||
@patch('os.rename')
|
||||
@patch('os.path.join', side_effect=os.path.join) # Use real join
|
||||
@patch('os.path.basename', side_effect=os.path.basename) # Use real basename
|
||||
def test_move_files_to_brand_code_folder(mock_basename, mock_join, mock_rename, mock_chdir, mock_dirname, mock_getcwd, finaliser_for_org):
|
||||
"""Test moving files to the new brand code directory."""
|
||||
brand_code = f"{BRAND_PREFIX}-0001"
|
||||
current_dir = mock_getcwd.return_value
|
||||
parent_dir = mock_dirname.return_value
|
||||
new_dir_name = f"{brand_code} - {ARTIST} - {TITLE}"
|
||||
expected_new_path = os.path.join(ORGANISED_DIR, new_dir_name)
|
||||
|
||||
# Make a copy to modify
|
||||
output_files_copy = OUTPUT_FILES_ORG.copy()
|
||||
|
||||
finaliser_for_org.move_files_to_brand_code_folder(brand_code, ARTIST, TITLE, output_files_copy)
|
||||
|
||||
assert finaliser_for_org.new_brand_code_dir == new_dir_name
|
||||
assert finaliser_for_org.new_brand_code_dir_path == expected_new_path
|
||||
mock_getcwd.assert_called_once()
|
||||
mock_dirname.assert_called_once_with(current_dir)
|
||||
# Ensure the assertion uses the exact value returned by the mock
|
||||
mock_chdir.assert_called_once_with(mock_dirname.return_value)
|
||||
mock_rename.assert_called_once_with(current_dir, expected_new_path)
|
||||
|
||||
# Check output_files paths were updated
|
||||
for key, original_path in OUTPUT_FILES_ORG.items():
|
||||
original_basename = os.path.basename(original_path)
|
||||
expected_updated_path = os.path.join(expected_new_path, original_basename)
|
||||
assert output_files_copy[key] == expected_updated_path
|
||||
|
||||
@patch('os.getcwd', return_value=f"/current/workdir/{ARTIST} - {TITLE}")
|
||||
@patch('os.path.dirname', return_value="/current/workdir")
|
||||
@patch('os.chdir')
|
||||
@patch('os.rename')
|
||||
def test_move_files_to_brand_code_folder_dry_run(mock_rename, mock_chdir, mock_dirname, mock_getcwd, finaliser_for_org):
|
||||
"""Test move files dry run."""
|
||||
finaliser_for_org.dry_run = True
|
||||
brand_code = f"{BRAND_PREFIX}-0001"
|
||||
current_dir = mock_getcwd.return_value
|
||||
new_dir_name = f"{brand_code} - {ARTIST} - {TITLE}"
|
||||
expected_new_path = os.path.join(ORGANISED_DIR, new_dir_name)
|
||||
output_files_copy = OUTPUT_FILES_ORG.copy() # Paths won't be updated in dry run
|
||||
|
||||
finaliser_for_org.move_files_to_brand_code_folder(brand_code, ARTIST, TITLE, output_files_copy)
|
||||
|
||||
mock_rename.assert_not_called()
|
||||
finaliser_for_org.logger.info.assert_any_call(f"DRY RUN: Would move original directory {current_dir} to: {expected_new_path}")
|
||||
# Paths should NOT be updated in dry run
|
||||
assert output_files_copy == OUTPUT_FILES_ORG
|
||||
|
||||
|
||||
@patch('os.path.isdir', return_value=True)
|
||||
@patch('os.makedirs')
|
||||
@patch('shutil.copy2')
|
||||
def test_copy_final_files_to_public_share_dirs(mock_copy, mock_makedirs, mock_isdir, finaliser_for_org):
|
||||
"""Test copying files to public share directories."""
|
||||
brand_code = f"{BRAND_PREFIX}-0001"
|
||||
base_name_no_brand = f"{ARTIST} - {TITLE}" # Base name without brand code
|
||||
|
||||
dest_mp4_dir = os.path.join(PUBLIC_SHARE_DIR, "MP4")
|
||||
dest_720p_dir = os.path.join(PUBLIC_SHARE_DIR, "MP4-720p")
|
||||
dest_cdg_dir = os.path.join(PUBLIC_SHARE_DIR, "CDG")
|
||||
|
||||
expected_dest_mp4 = os.path.join(dest_mp4_dir, f"{brand_code} - {base_name_no_brand}.mp4")
|
||||
expected_dest_720p = os.path.join(dest_720p_dir, f"{brand_code} - {base_name_no_brand}.mp4")
|
||||
expected_dest_zip = os.path.join(dest_cdg_dir, f"{brand_code} - {base_name_no_brand}.zip")
|
||||
|
||||
finaliser_for_org.copy_final_files_to_public_share_dirs(brand_code, base_name_no_brand, OUTPUT_FILES_ORG)
|
||||
|
||||
mock_isdir.assert_has_calls([
|
||||
call(PUBLIC_SHARE_DIR),
|
||||
call(dest_mp4_dir),
|
||||
call(dest_720p_dir), # Check for 720p dir
|
||||
call(dest_cdg_dir),
|
||||
], any_order=True)
|
||||
mock_makedirs.assert_has_calls([
|
||||
call(dest_mp4_dir, exist_ok=True),
|
||||
call(dest_720p_dir, exist_ok=True),
|
||||
call(dest_cdg_dir, exist_ok=True),
|
||||
], any_order=True)
|
||||
mock_copy.assert_has_calls([
|
||||
call(OUTPUT_FILES_ORG["final_karaoke_lossy_mp4"], expected_dest_mp4),
|
||||
call(OUTPUT_FILES_ORG["final_karaoke_lossy_720p_mp4"], expected_dest_720p),
|
||||
call(OUTPUT_FILES_ORG["final_karaoke_cdg_zip"], expected_dest_zip),
|
||||
], any_order=True)
|
||||
|
||||
@patch('os.path.isdir', return_value=False)
|
||||
def test_copy_final_files_public_dir_missing(mock_isdir, finaliser_for_org):
|
||||
"""Test error if public share dir is missing."""
|
||||
with pytest.raises(Exception, match=f"Public share directory does not exist: {PUBLIC_SHARE_DIR}"):
|
||||
finaliser_for_org.copy_final_files_to_public_share_dirs("CODE", BASE_NAME, OUTPUT_FILES_ORG)
|
||||
|
||||
@patch('os.path.isdir', side_effect=lambda p: p != os.path.join(PUBLIC_SHARE_DIR, "MP4-720p")) # 720p dir missing
|
||||
@patch('os.makedirs')
|
||||
def test_copy_final_files_public_subdir_missing(mock_makedirs, mock_isdir, finaliser_for_org):
|
||||
"""Test error if public share subdirectories are missing."""
|
||||
with pytest.raises(Exception, match="Public share directory does not contain MP4-720p subdirectory"):
|
||||
finaliser_for_org.copy_final_files_to_public_share_dirs("CODE", BASE_NAME, OUTPUT_FILES_ORG)
|
||||
|
||||
def test_copy_final_files_no_brand_code(finaliser_for_org):
|
||||
"""Test error if brand code is None."""
|
||||
with pytest.raises(Exception, match="New track prefix was not set"):
|
||||
finaliser_for_org.copy_final_files_to_public_share_dirs(None, BASE_NAME, OUTPUT_FILES_ORG)
|
||||
|
||||
@patch('os.path.isdir', return_value=True)
|
||||
@patch('os.makedirs')
|
||||
@patch('shutil.copy2')
|
||||
def test_copy_final_files_dry_run(mock_copy, mock_makedirs, mock_isdir, finaliser_for_org):
|
||||
"""Test copy files dry run."""
|
||||
finaliser_for_org.dry_run = True
|
||||
brand_code = f"{BRAND_PREFIX}-0001"
|
||||
base_name_no_brand = f"{ARTIST} - {TITLE}"
|
||||
|
||||
finaliser_for_org.copy_final_files_to_public_share_dirs(brand_code, base_name_no_brand, OUTPUT_FILES_ORG)
|
||||
|
||||
mock_copy.assert_not_called()
|
||||
finaliser_for_org.logger.info.assert_any_call(pytest.string_containing("DRY RUN: Would copy final MP4"))
|
||||
|
||||
|
||||
# --- Rclone Sync / Link Tests ---
|
||||
|
||||
@patch('os.walk')
|
||||
@patch('os.remove')
|
||||
@patch('os.path.join', side_effect=os.path.join)
|
||||
@patch.object(KaraokeFinalise, 'execute_command')
|
||||
def test_sync_public_share_dir_to_rclone(mock_execute, mock_join, mock_remove, mock_walk, finaliser_for_org):
|
||||
"""Test syncing public share dir, including .DS_Store removal."""
|
||||
# Simulate finding a .DS_Store file
|
||||
mock_walk.return_value = [
|
||||
(PUBLIC_SHARE_DIR, ['MP4', 'CDG'], ['file1.txt']),
|
||||
(os.path.join(PUBLIC_SHARE_DIR, 'MP4'), [], ['video.mp4', '.DS_Store']),
|
||||
(os.path.join(PUBLIC_SHARE_DIR, 'CDG'), [], ['song.zip']),
|
||||
]
|
||||
ds_store_path = os.path.join(PUBLIC_SHARE_DIR, 'MP4', '.DS_Store')
|
||||
|
||||
finaliser_for_org.sync_public_share_dir_to_rclone_destination()
|
||||
|
||||
mock_walk.assert_called_once_with(PUBLIC_SHARE_DIR)
|
||||
mock_remove.assert_called_once_with(ds_store_path)
|
||||
finaliser_for_org.logger.info.assert_any_call(f"Deleted .DS_Store file: {ds_store_path}")
|
||||
expected_cmd = f"rclone sync -v '{PUBLIC_SHARE_DIR}' '{RCLONE_DEST}'"
|
||||
mock_execute.assert_called_once_with(expected_cmd, "Syncing with cloud destination")
|
||||
|
||||
@patch('time.sleep')
|
||||
@patch('subprocess.run')
|
||||
@patch('shlex.quote', side_effect=lambda x: f"'{x}'") # Simple quote mock
|
||||
def test_generate_organised_folder_sharing_link(mock_quote, mock_run, mock_sleep, finaliser_for_org):
|
||||
"""Test generating the organised folder sharing link."""
|
||||
brand_code = f"{BRAND_PREFIX}-0001"
|
||||
finaliser_for_org.new_brand_code_dir = f"{brand_code} - {ARTIST} - {TITLE}" # Set this as if move happened
|
||||
expected_link = "https://example.com/share_link"
|
||||
mock_run.return_value = subprocess.CompletedProcess(
|
||||
args="mock command", returncode=0, stdout=expected_link + "\n", stderr=""
|
||||
)
|
||||
|
||||
finaliser_for_org.generate_organised_folder_sharing_link()
|
||||
|
||||
expected_rclone_path = f"{ORGANISED_RCLONE_ROOT}/{finaliser_for_org.new_brand_code_dir}"
|
||||
expected_cmd = f"rclone link '{expected_rclone_path}'"
|
||||
|
||||
mock_sleep.assert_called_once_with(5)
|
||||
mock_quote.assert_called_once_with(expected_rclone_path)
|
||||
mock_run.assert_called_once_with(expected_cmd, shell=True, check=True, capture_output=True, text=True)
|
||||
assert finaliser_for_org.brand_code_dir_sharing_link == expected_link
|
||||
|
||||
@patch('time.sleep')
|
||||
@patch('subprocess.run', side_effect=subprocess.CalledProcessError(1, "cmd", stderr="Link failed"))
|
||||
@patch('shlex.quote', side_effect=lambda x: f"'{x}'")
|
||||
def test_generate_organised_folder_sharing_link_failure(mock_quote, mock_run, mock_sleep, finaliser_for_org):
|
||||
"""Test handling failure during sharing link generation."""
|
||||
brand_code = f"{BRAND_PREFIX}-0001"
|
||||
finaliser_for_org.new_brand_code_dir = f"{brand_code} - {ARTIST} - {TITLE}"
|
||||
|
||||
# No exception expected, should log error
|
||||
finaliser_for_org.generate_organised_folder_sharing_link()
|
||||
|
||||
assert finaliser_for_org.brand_code_dir_sharing_link is None
|
||||
finaliser_for_org.logger.error.assert_any_call(pytest.string_containing("Failed to get organised folder sharing link"))
|
||||
finaliser_for_org.logger.error.assert_any_call(pytest.string_containing("stderr=Link failed"))
|
||||
|
||||
@patch('time.sleep')
|
||||
@patch('subprocess.run')
|
||||
@patch('shlex.quote')
|
||||
def test_generate_organised_folder_sharing_link_dry_run(mock_quote, mock_run, mock_sleep, finaliser_for_org):
|
||||
"""Test sharing link generation dry run."""
|
||||
finaliser_for_org.dry_run = True
|
||||
brand_code = f"{BRAND_PREFIX}-0001"
|
||||
finaliser_for_org.new_brand_code_dir = f"{brand_code} - {ARTIST} - {TITLE}"
|
||||
|
||||
link = finaliser_for_org.generate_organised_folder_sharing_link()
|
||||
|
||||
assert link == "https://file-sharing-service.com/example" # Default dry run link
|
||||
mock_sleep.assert_not_called()
|
||||
mock_run.assert_not_called()
|
||||
finaliser_for_org.logger.info.assert_any_call(pytest.string_containing("DRY RUN: Would get sharing link with:"))
|
||||
@@ -0,0 +1,173 @@
|
||||
import pytest
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
from unittest.mock import patch, MagicMock, mock_open
|
||||
|
||||
# Adjust the import path based on your project structure
|
||||
# Assuming tests are run from the project root
|
||||
from karaoke_prep.karaoke_finalise.karaoke_finalise import KaraokeFinalise
|
||||
|
||||
# Basic configuration for tests
|
||||
MINIMAL_CONFIG = {
|
||||
"dry_run": False,
|
||||
"instrumental_format": "flac",
|
||||
"enable_cdg": False,
|
||||
"enable_txt": False,
|
||||
"non_interactive": True, # Avoid prompts in most tests
|
||||
}
|
||||
|
||||
@pytest.fixture
|
||||
def mock_logger():
|
||||
"""Fixture for a mocked logger."""
|
||||
return MagicMock(spec=logging.Logger)
|
||||
|
||||
@pytest.fixture
|
||||
def basic_finaliser(mock_logger):
|
||||
"""Fixture for a basic KaraokeFinalise instance with mocked logger."""
|
||||
with patch.object(KaraokeFinalise, 'detect_best_aac_codec', return_value='aac'):
|
||||
# Mock detect_best_aac_codec during init
|
||||
finaliser = KaraokeFinalise(logger=mock_logger, **MINIMAL_CONFIG)
|
||||
return finaliser
|
||||
|
||||
# --- Initialization Tests ---
|
||||
|
||||
def test_init_defaults(mock_logger):
|
||||
"""Test default values are set correctly during initialization."""
|
||||
with patch.object(KaraokeFinalise, 'detect_best_aac_codec', return_value='aac'):
|
||||
finaliser = KaraokeFinalise(logger=mock_logger, **MINIMAL_CONFIG)
|
||||
|
||||
assert finaliser.logger == mock_logger
|
||||
assert finaliser.dry_run == MINIMAL_CONFIG["dry_run"]
|
||||
assert finaliser.instrumental_format == MINIMAL_CONFIG["instrumental_format"]
|
||||
assert finaliser.enable_cdg == MINIMAL_CONFIG["enable_cdg"]
|
||||
assert finaliser.enable_txt == MINIMAL_CONFIG["enable_txt"]
|
||||
assert finaliser.non_interactive == MINIMAL_CONFIG["non_interactive"]
|
||||
assert finaliser.brand_prefix is None
|
||||
assert finaliser.organised_dir is None
|
||||
assert finaliser.public_share_dir is None
|
||||
assert finaliser.youtube_client_secrets_file is None
|
||||
assert finaliser.youtube_description_file is None
|
||||
assert finaliser.rclone_destination is None
|
||||
assert finaliser.discord_webhook_url is None
|
||||
assert finaliser.email_template_file is None
|
||||
assert finaliser.cdg_styles is None
|
||||
assert finaliser.keep_brand_code is False
|
||||
assert finaliser.aac_codec == 'aac' # Mocked value
|
||||
assert finaliser.mp4_flags == "-pix_fmt yuv420p -movflags +faststart+frag_keyframe+empty_moov"
|
||||
|
||||
# Check feature flags default to False
|
||||
assert not finaliser.youtube_upload_enabled
|
||||
assert not finaliser.discord_notication_enabled
|
||||
assert not finaliser.folder_organisation_enabled
|
||||
assert not finaliser.public_share_copy_enabled
|
||||
assert not finaliser.public_share_rclone_enabled
|
||||
|
||||
def test_init_custom_logger_setup():
|
||||
"""Test logger setup when no logger is provided."""
|
||||
with patch('logging.getLogger') as mock_get_logger, \
|
||||
patch('logging.StreamHandler') as mock_stream_handler, \
|
||||
patch('logging.Formatter') as mock_formatter, \
|
||||
patch.object(KaraokeFinalise, 'detect_best_aac_codec', return_value='aac'):
|
||||
|
||||
mock_logger_instance = MagicMock()
|
||||
mock_get_logger.return_value = mock_logger_instance
|
||||
mock_handler_instance = MagicMock()
|
||||
mock_stream_handler.return_value = mock_handler_instance
|
||||
mock_formatter_instance = MagicMock()
|
||||
mock_formatter.return_value = mock_formatter_instance
|
||||
|
||||
finaliser = KaraokeFinalise(log_level=logging.INFO, **MINIMAL_CONFIG)
|
||||
|
||||
mock_get_logger.assert_called_once_with('karaoke_prep.karaoke_finalise.karaoke_finalise')
|
||||
mock_logger_instance.setLevel.assert_called_once_with(logging.INFO)
|
||||
mock_stream_handler.assert_called_once()
|
||||
mock_formatter.assert_called_once_with("%(asctime)s - %(levelname)s - %(module)s - %(message)s")
|
||||
mock_handler_instance.setFormatter.assert_called_once_with(mock_formatter_instance)
|
||||
mock_logger_instance.addHandler.assert_called_once_with(mock_handler_instance)
|
||||
assert finaliser.logger == mock_logger_instance
|
||||
|
||||
def test_init_ffmpeg_command_debug(mock_logger):
|
||||
"""Test ffmpeg command includes loglevel verbose in debug mode."""
|
||||
with patch.object(KaraokeFinalise, 'detect_best_aac_codec', return_value='aac'):
|
||||
finaliser = KaraokeFinalise(logger=mock_logger, log_level=logging.DEBUG, **MINIMAL_CONFIG)
|
||||
assert " -loglevel verbose" in finaliser.ffmpeg_base_command
|
||||
assert " -loglevel fatal" not in finaliser.ffmpeg_base_command
|
||||
if MINIMAL_CONFIG["non_interactive"]:
|
||||
assert finaliser.ffmpeg_base_command.endswith(" -y")
|
||||
|
||||
def test_init_ffmpeg_command_info(mock_logger):
|
||||
"""Test ffmpeg command includes loglevel fatal in non-debug mode."""
|
||||
with patch.object(KaraokeFinalise, 'detect_best_aac_codec', return_value='aac'):
|
||||
finaliser = KaraokeFinalise(logger=mock_logger, log_level=logging.INFO, **MINIMAL_CONFIG)
|
||||
assert " -loglevel fatal" in finaliser.ffmpeg_base_command
|
||||
assert " -loglevel verbose" not in finaliser.ffmpeg_base_command
|
||||
if MINIMAL_CONFIG["non_interactive"]:
|
||||
assert finaliser.ffmpeg_base_command.endswith(" -y")
|
||||
|
||||
def test_init_ffmpeg_command_frozen(mock_logger):
|
||||
"""Test ffmpeg command uses bundled path when frozen."""
|
||||
with patch('sys.frozen', True), \
|
||||
patch('sys._MEIPASS', '/path/to/frozen/app'), \
|
||||
patch.object(KaraokeFinalise, 'detect_best_aac_codec', return_value='aac'):
|
||||
finaliser = KaraokeFinalise(logger=mock_logger, **MINIMAL_CONFIG)
|
||||
expected_path = os.path.join('/path/to/frozen/app', 'ffmpeg.exe')
|
||||
assert finaliser.ffmpeg_base_command.startswith(f"{expected_path} ")
|
||||
|
||||
def test_init_ffmpeg_command_not_frozen(mock_logger):
|
||||
"""Test ffmpeg command uses system path when not frozen."""
|
||||
with patch('sys.frozen', False), \
|
||||
patch.object(KaraokeFinalise, 'detect_best_aac_codec', return_value='aac'):
|
||||
finaliser = KaraokeFinalise(logger=mock_logger, **MINIMAL_CONFIG)
|
||||
assert finaliser.ffmpeg_base_command.startswith("ffmpeg ")
|
||||
|
||||
def test_init_non_interactive_ffmpeg(mock_logger):
|
||||
"""Test ffmpeg command includes -y when non_interactive is True."""
|
||||
config = MINIMAL_CONFIG.copy()
|
||||
config["non_interactive"] = True
|
||||
with patch.object(KaraokeFinalise, 'detect_best_aac_codec', return_value='aac'):
|
||||
finaliser = KaraokeFinalise(logger=mock_logger, **config)
|
||||
assert finaliser.ffmpeg_base_command.strip().endswith(" -y")
|
||||
|
||||
def test_init_interactive_ffmpeg(mock_logger):
|
||||
"""Test ffmpeg command does not include -y when non_interactive is False."""
|
||||
config = MINIMAL_CONFIG.copy()
|
||||
config["non_interactive"] = False
|
||||
with patch.object(KaraokeFinalise, 'detect_best_aac_codec', return_value='aac'):
|
||||
finaliser = KaraokeFinalise(logger=mock_logger, **config)
|
||||
assert not finaliser.ffmpeg_base_command.strip().endswith(" -y")
|
||||
|
||||
|
||||
# --- AAC Codec Detection Tests ---
|
||||
|
||||
@patch('os.popen')
|
||||
def test_detect_best_aac_codec_aac_at(mock_popen, mock_logger):
|
||||
"""Test detection of aac_at codec."""
|
||||
mock_popen.return_value.read.return_value = "Codecs:\n D..... aac\n DEA.L. aac_at\n D..... libfdk_aac"
|
||||
finaliser = KaraokeFinalise(logger=mock_logger, **MINIMAL_CONFIG)
|
||||
assert finaliser.aac_codec == "aac_at"
|
||||
mock_logger.info.assert_any_call("Using aac_at codec (best quality)")
|
||||
|
||||
@patch('os.popen')
|
||||
def test_detect_best_aac_codec_libfdk_aac(mock_popen, mock_logger):
|
||||
"""Test detection of libfdk_aac codec when aac_at is not present."""
|
||||
mock_popen.return_value.read.return_value = "Codecs:\n D..... aac\n D..... libfdk_aac"
|
||||
finaliser = KaraokeFinalise(logger=mock_logger, **MINIMAL_CONFIG)
|
||||
assert finaliser.aac_codec == "libfdk_aac"
|
||||
mock_logger.info.assert_any_call("Using libfdk_aac codec (good quality)")
|
||||
|
||||
@patch('os.popen')
|
||||
def test_detect_best_aac_codec_aac_default(mock_popen, mock_logger):
|
||||
"""Test detection falls back to basic aac codec."""
|
||||
mock_popen.return_value.read.return_value = "Codecs:\n D..... aac"
|
||||
finaliser = KaraokeFinalise(logger=mock_logger, **MINIMAL_CONFIG)
|
||||
assert finaliser.aac_codec == "aac"
|
||||
mock_logger.info.assert_any_call("Using built-in aac codec (basic quality)")
|
||||
|
||||
@patch('os.popen')
|
||||
def test_detect_best_aac_codec_none_found(mock_popen, mock_logger):
|
||||
"""Test detection falls back to basic aac when no AAC codecs are listed."""
|
||||
mock_popen.return_value.read.return_value = "Codecs:\n D..... mp3\n D..... flac"
|
||||
finaliser = KaraokeFinalise(logger=mock_logger, **MINIMAL_CONFIG)
|
||||
assert finaliser.aac_codec == "aac"
|
||||
mock_logger.info.assert_any_call("Using built-in aac codec (basic quality)")
|
||||
@@ -0,0 +1,246 @@
|
||||
import pytest
|
||||
import os
|
||||
import pickle
|
||||
import base64
|
||||
from email.mime.text import MIMEText
|
||||
from unittest.mock import patch, MagicMock, mock_open, call, ANY
|
||||
import requests # For requests.exceptions.RequestException
|
||||
|
||||
# Adjust the import path
|
||||
from karaoke_prep.karaoke_finalise.karaoke_finalise import KaraokeFinalise
|
||||
from .test_initialization import mock_logger, basic_finaliser, MINIMAL_CONFIG # Reuse fixtures
|
||||
from .test_file_input_validation import ARTIST, TITLE # Reuse constants
|
||||
from .test_youtube_integration import mock_google_auth # Reuse Gmail auth mocks structure
|
||||
|
||||
DISCORD_WEBHOOK_URL = "https://discord.com/api/webhooks/123/abc"
|
||||
EMAIL_TEMPLATE_FILE = "email_template.txt"
|
||||
GMAIL_TOKEN_FILE = "/tmp/karaoke-finalise-gmail-token.pickle"
|
||||
YOUTUBE_SECRETS_FILE_GMAIL = "client_secrets_gmail.json" # Assume separate secrets for Gmail scope if needed
|
||||
|
||||
@pytest.fixture
|
||||
def finaliser_for_notify(mock_logger):
|
||||
"""Fixture for a finaliser configured for notification/email tasks."""
|
||||
config = MINIMAL_CONFIG.copy()
|
||||
config.update({
|
||||
"discord_webhook_url": DISCORD_WEBHOOK_URL,
|
||||
"email_template_file": EMAIL_TEMPLATE_FILE,
|
||||
# Need youtube secrets for Gmail auth as well in the original code
|
||||
"youtube_client_secrets_file": YOUTUBE_SECRETS_FILE_GMAIL,
|
||||
"brand_prefix": "TEST", # Needed for email subject brand code
|
||||
})
|
||||
with patch.object(KaraokeFinalise, 'detect_best_aac_codec', return_value='aac'):
|
||||
finaliser = KaraokeFinalise(logger=mock_logger, **config)
|
||||
# Manually enable features for testing specific methods
|
||||
finaliser.discord_notication_enabled = True
|
||||
# Set some state needed for notifications/email
|
||||
finaliser.youtube_url = "https://www.youtube.com/watch?v=test_vid"
|
||||
finaliser.brand_code = "TEST-0001"
|
||||
finaliser.brand_code_dir_sharing_link = "https://dropbox.com/share/link"
|
||||
return finaliser
|
||||
|
||||
@pytest.fixture
|
||||
def mock_gmail_service():
|
||||
"""Fixture for a mocked Gmail service object."""
|
||||
mock_service = MagicMock()
|
||||
mock_service.users.return_value.drafts.return_value.create.return_value.execute.return_value = {"id": "draft_123"}
|
||||
return mock_service
|
||||
|
||||
# --- Discord Notification Tests ---
|
||||
|
||||
@patch('requests.post')
|
||||
def test_post_discord_message_success(mock_post, finaliser_for_notify):
|
||||
"""Test successful posting to Discord."""
|
||||
mock_response = MagicMock()
|
||||
mock_response.raise_for_status.return_value = None # No error
|
||||
mock_post.return_value = mock_response
|
||||
message = "Test message"
|
||||
|
||||
finaliser_for_notify.post_discord_message(message, DISCORD_WEBHOOK_URL)
|
||||
|
||||
mock_post.assert_called_once_with(DISCORD_WEBHOOK_URL, json={"content": message})
|
||||
mock_response.raise_for_status.assert_called_once()
|
||||
finaliser_for_notify.logger.info.assert_called_with("Message posted to Discord")
|
||||
|
||||
@patch('requests.post')
|
||||
def test_post_discord_message_failure(mock_post, finaliser_for_notify):
|
||||
"""Test handling failure when posting to Discord."""
|
||||
mock_response = MagicMock()
|
||||
mock_response.raise_for_status.side_effect = requests.exceptions.RequestException("API Error")
|
||||
mock_post.return_value = mock_response
|
||||
message = "Test message"
|
||||
|
||||
with pytest.raises(requests.exceptions.RequestException, match="API Error"):
|
||||
finaliser_for_notify.post_discord_message(message, DISCORD_WEBHOOK_URL)
|
||||
|
||||
mock_post.assert_called_once_with(DISCORD_WEBHOOK_URL, json={"content": message})
|
||||
mock_response.raise_for_status.assert_called_once()
|
||||
|
||||
@patch.object(KaraokeFinalise, 'post_discord_message')
|
||||
def test_post_discord_notification_sends(mock_post_msg, finaliser_for_notify):
|
||||
"""Test that post_discord_notification calls post_discord_message."""
|
||||
finaliser_for_notify.skip_notifications = False
|
||||
expected_message = f"New upload: {finaliser_for_notify.youtube_url}"
|
||||
|
||||
finaliser_for_notify.post_discord_notification()
|
||||
|
||||
mock_post_msg.assert_called_once_with(expected_message, DISCORD_WEBHOOK_URL)
|
||||
|
||||
@patch.object(KaraokeFinalise, 'post_discord_message')
|
||||
def test_post_discord_notification_skipped(mock_post_msg, finaliser_for_notify):
|
||||
"""Test that post_discord_notification skips if flag is set."""
|
||||
finaliser_for_notify.skip_notifications = True
|
||||
|
||||
finaliser_for_notify.post_discord_notification()
|
||||
|
||||
mock_post_msg.assert_not_called()
|
||||
finaliser_for_notify.logger.info.assert_called_with("Skipping Discord notification as video was previously uploaded to YouTube")
|
||||
|
||||
@patch.object(KaraokeFinalise, 'post_discord_message')
|
||||
def test_post_discord_notification_dry_run(mock_post_msg, finaliser_for_notify):
|
||||
"""Test post_discord_notification dry run."""
|
||||
finaliser_for_notify.dry_run = True
|
||||
finaliser_for_notify.skip_notifications = False
|
||||
|
||||
finaliser_for_notify.post_discord_notification()
|
||||
|
||||
mock_post_msg.assert_not_called()
|
||||
finaliser_for_notify.logger.info.assert_called_with(
|
||||
f"DRY RUN: Would post Discord notification for youtube URL {finaliser_for_notify.youtube_url} using webhook URL: {DISCORD_WEBHOOK_URL}"
|
||||
)
|
||||
|
||||
# --- Gmail Authentication Tests ---
|
||||
|
||||
def test_authenticate_gmail_new_token(finaliser_for_notify, mock_google_auth, mock_gmail_service):
|
||||
"""Test Gmail authentication flow when no token file exists."""
|
||||
mock_google_auth["mock_path_exists"].return_value = False
|
||||
mock_google_auth["mock_build"].return_value = mock_gmail_service
|
||||
|
||||
service = finaliser_for_notify.authenticate_gmail()
|
||||
|
||||
mock_google_auth["mock_path_exists"].assert_called_once_with(GMAIL_TOKEN_FILE)
|
||||
mock_google_auth["mock_flow_cls"].from_client_secrets_file.assert_called_once_with(
|
||||
YOUTUBE_SECRETS_FILE_GMAIL, ["https://www.googleapis.com/auth/gmail.compose"]
|
||||
)
|
||||
mock_google_auth["mock_flow_instance"].run_local_server.assert_called_once_with(port=0)
|
||||
mock_google_auth["mock_pickle_dump"].assert_called_once()
|
||||
assert mock_google_auth["mock_pickle_dump"].call_args[0][0] == mock_google_auth["mock_credentials"]
|
||||
mock_google_auth["mock_build"].assert_called_once_with("gmail", "v1", credentials=mock_google_auth["mock_credentials"])
|
||||
assert service == mock_gmail_service
|
||||
|
||||
def test_authenticate_gmail_load_valid_token(finaliser_for_notify, mock_google_auth, mock_gmail_service):
|
||||
"""Test Gmail authentication using a valid existing token file."""
|
||||
mock_google_auth["mock_path_exists"].return_value = True
|
||||
mock_google_auth["mock_pickle_load"].return_value = mock_google_auth["mock_credentials"]
|
||||
mock_google_auth["mock_credentials"].valid = True
|
||||
mock_google_auth["mock_build"].return_value = mock_gmail_service
|
||||
|
||||
service = finaliser_for_notify.authenticate_gmail()
|
||||
|
||||
mock_google_auth["mock_path_exists"].assert_called_once_with(GMAIL_TOKEN_FILE)
|
||||
mock_google_auth["mock_pickle_load"].assert_called_once_with(ANY)
|
||||
mock_google_auth["mock_flow_instance"].run_local_server.assert_not_called()
|
||||
mock_google_auth["mock_pickle_dump"].assert_not_called()
|
||||
mock_google_auth["mock_build"].assert_called_once_with("gmail", "v1", credentials=mock_google_auth["mock_credentials"])
|
||||
assert service == mock_gmail_service
|
||||
|
||||
def test_authenticate_gmail_refresh_token(finaliser_for_notify, mock_google_auth, mock_gmail_service):
|
||||
"""Test Gmail authentication refreshing an expired token."""
|
||||
mock_google_auth["mock_path_exists"].return_value = True
|
||||
mock_google_auth["mock_pickle_load"].return_value = mock_google_auth["mock_credentials"]
|
||||
mock_google_auth["mock_credentials"].valid = False
|
||||
mock_google_auth["mock_credentials"].expired = True
|
||||
mock_google_auth["mock_credentials"].refresh_token = "fake_refresh_token"
|
||||
mock_google_auth["mock_build"].return_value = mock_gmail_service
|
||||
|
||||
with patch('google.auth.transport.requests.Request') as mock_request:
|
||||
mock_refresh = mock_google_auth["mock_credentials"].refresh
|
||||
service = finaliser_for_notify.authenticate_gmail()
|
||||
mock_refresh.assert_called_once_with(mock_request())
|
||||
|
||||
mock_google_auth["mock_path_exists"].assert_called_once_with(GMAIL_TOKEN_FILE)
|
||||
mock_google_auth["mock_pickle_load"].assert_called_once_with(ANY)
|
||||
mock_google_auth["mock_flow_instance"].run_local_server.assert_not_called()
|
||||
mock_google_auth["mock_pickle_dump"].assert_called_once()
|
||||
mock_google_auth["mock_build"].assert_called_once_with("gmail", "v1", credentials=mock_google_auth["mock_credentials"])
|
||||
assert service == mock_gmail_service
|
||||
|
||||
# --- Gmail Draft Creation Tests ---
|
||||
|
||||
@patch('builtins.open', new_callable=mock_open, read_data="YT: {youtube_url}\nDB: {dropbox_url}")
|
||||
@patch.object(KaraokeFinalise, 'authenticate_gmail')
|
||||
@patch('email.mime.text.MIMEText', return_value=MagicMock(spec=MIMEText)) # Mock MIMEText instance
|
||||
@patch('base64.urlsafe_b64encode')
|
||||
def test_draft_completion_email_success(mock_b64encode, mock_mime_text_cls, mock_auth_gmail, mock_open_template, finaliser_for_notify, mock_gmail_service):
|
||||
"""Test successful email draft creation."""
|
||||
mock_auth_gmail.return_value = mock_gmail_service
|
||||
# Mock the result of as_bytes() on the MIMEText instance
|
||||
mock_mime_instance = mock_mime_text_cls.return_value
|
||||
mock_mime_instance.as_bytes.return_value = b"raw email bytes"
|
||||
mock_b64encode.return_value = b"encoded_raw_email"
|
||||
|
||||
finaliser_for_notify.draft_completion_email(ARTIST, TITLE, finaliser_for_notify.youtube_url, finaliser_for_notify.brand_code_dir_sharing_link)
|
||||
|
||||
mock_open_template.assert_called_once_with(EMAIL_TEMPLATE_FILE, "r")
|
||||
expected_body = f"YT: {finaliser_for_notify.youtube_url}\nDB: {finaliser_for_notify.brand_code_dir_sharing_link}"
|
||||
mock_mime_text_cls.assert_called_once_with(expected_body)
|
||||
|
||||
expected_subject = f"{finaliser_for_notify.brand_code}: {ARTIST} - {TITLE}"
|
||||
assert mock_mime_instance.__setitem__.call_args_list == [call('subject', expected_subject)]
|
||||
|
||||
mock_b64encode.assert_called_once_with(b"raw email bytes")
|
||||
mock_auth_gmail.assert_called_once() # Ensure auth was called
|
||||
assert finaliser_for_notify.gmail_service == mock_gmail_service # Check service was stored
|
||||
|
||||
# Check the API call to create draft
|
||||
mock_gmail_service.users().drafts().create.assert_called_once_with(
|
||||
userId="me", body={"message": {"raw": "encoded_raw_email"}}
|
||||
)
|
||||
finaliser_for_notify.logger.info.assert_called_with("Email draft created with ID: draft_123")
|
||||
|
||||
|
||||
def test_draft_completion_email_no_template_file(finaliser_for_notify):
|
||||
"""Test skipping email draft if template file is not set."""
|
||||
finaliser_for_notify.email_template_file = None
|
||||
with patch.object(KaraokeFinalise, 'authenticate_gmail') as mock_auth_gmail:
|
||||
finaliser_for_notify.draft_completion_email(ARTIST, TITLE, "yt_url", "db_url")
|
||||
mock_auth_gmail.assert_not_called()
|
||||
finaliser_for_notify.logger.info.assert_called_with("Email template file not provided, skipping email draft creation.")
|
||||
|
||||
@patch('builtins.open', new_callable=mock_open, read_data="Template")
|
||||
@patch.object(KaraokeFinalise, 'authenticate_gmail')
|
||||
def test_draft_completion_email_dry_run(mock_auth_gmail, mock_open_template, finaliser_for_notify):
|
||||
"""Test email draft dry run."""
|
||||
finaliser_for_notify.dry_run = True
|
||||
|
||||
finaliser_for_notify.draft_completion_email(ARTIST, TITLE, finaliser_for_notify.youtube_url, finaliser_for_notify.brand_code_dir_sharing_link)
|
||||
|
||||
mock_open_template.assert_called_once_with(EMAIL_TEMPLATE_FILE, "r")
|
||||
mock_auth_gmail.assert_not_called() # Auth not needed for dry run
|
||||
expected_subject = f"{finaliser_for_notify.brand_code}: {ARTIST} - {TITLE}"
|
||||
finaliser_for_notify.logger.info.assert_any_call(f"DRY RUN: Would create email draft with subject: {expected_subject}")
|
||||
finaliser_for_notify.logger.info.assert_any_call(pytest.string_containing("DRY RUN: Email body:"))
|
||||
|
||||
|
||||
@patch.object(KaraokeFinalise, 'draft_completion_email')
|
||||
def test_test_email_template(mock_draft_email, finaliser_for_notify):
|
||||
"""Test the test_email_template method calls draft_completion_email correctly."""
|
||||
finaliser_for_notify.test_email_template()
|
||||
|
||||
expected_artist = "Test Artist"
|
||||
expected_title = "Test Song"
|
||||
expected_youtube_url = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
|
||||
expected_dropbox_url = "https://www.dropbox.com/sh/fake/folder/link"
|
||||
expected_brand_code = "TEST-0001" # Set within the test method
|
||||
|
||||
# Check brand_code was set correctly before calling draft
|
||||
assert finaliser_for_notify.brand_code == expected_brand_code
|
||||
mock_draft_email.assert_called_once_with(expected_artist, expected_title, expected_youtube_url, expected_dropbox_url)
|
||||
finaliser_for_notify.logger.info.assert_called_with("Email template test complete. Check your Gmail drafts for the test email.")
|
||||
|
||||
def test_test_email_template_no_file(finaliser_for_notify):
|
||||
"""Test test_email_template when no template file is configured."""
|
||||
finaliser_for_notify.email_template_file = None
|
||||
with patch.object(KaraokeFinalise, 'draft_completion_email') as mock_draft_email:
|
||||
finaliser_for_notify.test_email_template()
|
||||
mock_draft_email.assert_not_called()
|
||||
finaliser_for_notify.logger.error.assert_called_with("Email template file not provided. Use --email_template_file to specify the file path.")
|
||||
@@ -0,0 +1,274 @@
|
||||
import pytest
|
||||
import os
|
||||
from unittest.mock import patch, MagicMock, call, ANY
|
||||
|
||||
# Adjust the import path
|
||||
from karaoke_prep.karaoke_finalise.karaoke_finalise import KaraokeFinalise
|
||||
from .test_initialization import mock_logger, basic_finaliser, MINIMAL_CONFIG # Reuse fixtures
|
||||
from .test_file_input_validation import BASE_NAME, ARTIST, TITLE, WITH_VOCALS_MOV, INSTRUMENTAL_FLAC # Reuse constants
|
||||
from .test_ffmpeg_commands import OUTPUT_FILES as FFMPEG_OUTPUT_FILES # Reuse constants
|
||||
from .test_zip_creation import OUTPUT_FILES_ZIP # Reuse constants
|
||||
from .test_file_organisation import OUTPUT_FILES_ORG, BRAND_PREFIX, ORGANISED_DIR, PUBLIC_SHARE_DIR, RCLONE_DEST, ORGANISED_RCLONE_ROOT # Reuse constants
|
||||
from .test_youtube_integration import YOUTUBE_SECRETS_FILE, YOUTUBE_DESC_FILE, OUTPUT_FILES_YT, INPUT_FILES_YT # Reuse constants
|
||||
from .test_notifications_email import DISCORD_WEBHOOK_URL, EMAIL_TEMPLATE_FILE # Reuse constants
|
||||
|
||||
# Combine output file dictionaries for process tests
|
||||
ALL_OUTPUT_FILES = {**FFMPEG_OUTPUT_FILES, **OUTPUT_FILES_ZIP, **OUTPUT_FILES_ORG, **OUTPUT_FILES_YT}
|
||||
# Combine input file dictionaries
|
||||
ALL_INPUT_FILES = {
|
||||
"title_mov": f"{BASE_NAME}{KaraokeFinalise().suffixes['title_mov']}",
|
||||
"title_jpg": f"{BASE_NAME}{KaraokeFinalise().suffixes['title_jpg']}",
|
||||
"instrumental_audio": INSTRUMENTAL_FLAC,
|
||||
"with_vocals_mov": WITH_VOCALS_MOV,
|
||||
"karaoke_lrc": f"{BASE_NAME}{KaraokeFinalise().suffixes['karaoke_lrc']}",
|
||||
"end_mov": f"{BASE_NAME}{KaraokeFinalise().suffixes['end_mov']}",
|
||||
"end_jpg": f"{BASE_NAME}{KaraokeFinalise().suffixes['end_jpg']}",
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def finaliser_for_process(mock_logger):
|
||||
"""Fixture for a finaliser configured for full process tests."""
|
||||
config = MINIMAL_CONFIG.copy()
|
||||
config.update({
|
||||
"brand_prefix": BRAND_PREFIX,
|
||||
"organised_dir": ORGANISED_DIR,
|
||||
"public_share_dir": PUBLIC_SHARE_DIR,
|
||||
"rclone_destination": RCLONE_DEST,
|
||||
"organised_dir_rclone_root": ORGANISED_RCLONE_ROOT,
|
||||
"youtube_client_secrets_file": YOUTUBE_SECRETS_FILE,
|
||||
"youtube_description_file": YOUTUBE_DESC_FILE,
|
||||
"discord_webhook_url": DISCORD_WEBHOOK_URL,
|
||||
"email_template_file": EMAIL_TEMPLATE_FILE,
|
||||
"enable_cdg": True,
|
||||
"enable_txt": True,
|
||||
"cdg_styles": {"style": "default"}, # Need styles for CDG generation call
|
||||
})
|
||||
with patch.object(KaraokeFinalise, 'detect_best_aac_codec', return_value='aac'):
|
||||
finaliser = KaraokeFinalise(logger=mock_logger, **config)
|
||||
# Assume features are enabled after validation for these tests
|
||||
finaliser.youtube_upload_enabled = True
|
||||
finaliser.discord_notication_enabled = True
|
||||
finaliser.folder_organisation_enabled = True
|
||||
finaliser.public_share_copy_enabled = True
|
||||
finaliser.public_share_rclone_enabled = True
|
||||
return finaliser
|
||||
|
||||
# --- execute_optional_features Tests ---
|
||||
|
||||
@patch.object(KaraokeFinalise, 'upload_final_mp4_to_youtube_with_title_thumbnail')
|
||||
@patch.object(KaraokeFinalise, 'post_discord_notification')
|
||||
@patch.object(KaraokeFinalise, 'get_next_brand_code', return_value=f"{BRAND_PREFIX}-0001")
|
||||
@patch.object(KaraokeFinalise, 'get_existing_brand_code')
|
||||
@patch.object(KaraokeFinalise, 'move_files_to_brand_code_folder')
|
||||
@patch.object(KaraokeFinalise, 'copy_final_files_to_public_share_dirs')
|
||||
@patch.object(KaraokeFinalise, 'sync_public_share_dir_to_rclone_destination')
|
||||
@patch.object(KaraokeFinalise, 'generate_organised_folder_sharing_link')
|
||||
def test_execute_optional_features_all_enabled_new_code(
|
||||
mock_gen_link, mock_sync, mock_copy, mock_move, mock_get_existing, mock_get_next,
|
||||
mock_discord, mock_youtube, finaliser_for_process):
|
||||
"""Test execute_optional_features with all features enabled and generating a new brand code."""
|
||||
finaliser_for_process.keep_brand_code = False
|
||||
replace_existing_yt = False
|
||||
|
||||
finaliser_for_process.execute_optional_features(ARTIST, TITLE, BASE_NAME, ALL_INPUT_FILES, ALL_OUTPUT_FILES, replace_existing_yt)
|
||||
|
||||
mock_youtube.assert_called_once_with(ARTIST, TITLE, ALL_INPUT_FILES, ALL_OUTPUT_FILES, replace_existing_yt)
|
||||
mock_discord.assert_called_once()
|
||||
mock_get_next.assert_called_once()
|
||||
mock_get_existing.assert_not_called()
|
||||
mock_move.assert_called_once_with(f"{BRAND_PREFIX}-0001", ARTIST, TITLE, ALL_OUTPUT_FILES)
|
||||
# Assume move updates the paths, check subsequent calls use the updated path implicitly if needed
|
||||
mock_copy.assert_called_once_with(f"{BRAND_PREFIX}-0001", BASE_NAME, ALL_OUTPUT_FILES)
|
||||
mock_sync.assert_called_once()
|
||||
mock_gen_link.assert_called_once()
|
||||
|
||||
@patch.object(KaraokeFinalise, 'upload_final_mp4_to_youtube_with_title_thumbnail')
|
||||
@patch.object(KaraokeFinalise, 'post_discord_notification')
|
||||
@patch.object(KaraokeFinalise, 'get_next_brand_code')
|
||||
@patch.object(KaraokeFinalise, 'get_existing_brand_code', return_value=f"{BRAND_PREFIX}-9999")
|
||||
@patch.object(KaraokeFinalise, 'move_files_to_brand_code_folder')
|
||||
@patch.object(KaraokeFinalise, 'copy_final_files_to_public_share_dirs')
|
||||
@patch.object(KaraokeFinalise, 'sync_public_share_dir_to_rclone_destination')
|
||||
@patch.object(KaraokeFinalise, 'generate_organised_folder_sharing_link')
|
||||
@patch('os.getcwd', return_value=f"/path/to/{BRAND_PREFIX}-9999 - {ARTIST} - {TITLE}") # Mock current dir for keep_brand_code
|
||||
@patch('os.path.basename', return_value=f"{BRAND_PREFIX}-9999 - {ARTIST} - {TITLE}")
|
||||
def test_execute_optional_features_all_enabled_keep_code(
|
||||
mock_basename, mock_getcwd, mock_gen_link, mock_sync, mock_copy, mock_move, mock_get_existing, mock_get_next,
|
||||
mock_discord, mock_youtube, finaliser_for_process):
|
||||
"""Test execute_optional_features with all features enabled and keeping the existing brand code."""
|
||||
finaliser_for_process.keep_brand_code = True
|
||||
replace_existing_yt = True
|
||||
expected_brand_code = f"{BRAND_PREFIX}-9999"
|
||||
expected_dir_name = f"{expected_brand_code} - {ARTIST} - {TITLE}"
|
||||
expected_dir_path = mock_getcwd.return_value
|
||||
|
||||
finaliser_for_process.execute_optional_features(ARTIST, TITLE, BASE_NAME, ALL_INPUT_FILES, ALL_OUTPUT_FILES, replace_existing_yt)
|
||||
|
||||
mock_youtube.assert_called_once_with(ARTIST, TITLE, ALL_INPUT_FILES, ALL_OUTPUT_FILES, replace_existing_yt)
|
||||
mock_discord.assert_called_once()
|
||||
mock_get_next.assert_not_called()
|
||||
mock_get_existing.assert_called_once()
|
||||
mock_move.assert_not_called() # Should not move if keeping code
|
||||
# Check state was set correctly without moving
|
||||
assert finaliser_for_process.brand_code == expected_brand_code
|
||||
assert finaliser_for_process.new_brand_code_dir == expected_dir_name
|
||||
assert finaliser_for_process.new_brand_code_dir_path == expected_dir_path
|
||||
mock_copy.assert_called_once_with(expected_brand_code, BASE_NAME, ALL_OUTPUT_FILES)
|
||||
mock_sync.assert_called_once()
|
||||
mock_gen_link.assert_called_once()
|
||||
|
||||
@patch.object(KaraokeFinalise, 'upload_final_mp4_to_youtube_with_title_thumbnail')
|
||||
@patch.object(KaraokeFinalise, 'post_discord_notification')
|
||||
@patch.object(KaraokeFinalise, 'get_next_brand_code')
|
||||
@patch.object(KaraokeFinalise, 'move_files_to_brand_code_folder')
|
||||
@patch.object(KaraokeFinalise, 'copy_final_files_to_public_share_dirs')
|
||||
@patch.object(KaraokeFinalise, 'sync_public_share_dir_to_rclone_destination')
|
||||
@patch.object(KaraokeFinalise, 'generate_organised_folder_sharing_link')
|
||||
def test_execute_optional_features_some_disabled(
|
||||
mock_gen_link, mock_sync, mock_copy, mock_move, mock_get_next,
|
||||
mock_discord, mock_youtube, finaliser_for_process):
|
||||
"""Test execute_optional_features with some features disabled."""
|
||||
# Disable some features
|
||||
finaliser_for_process.discord_notication_enabled = False
|
||||
finaliser_for_process.public_share_rclone_enabled = False
|
||||
finaliser_for_process.keep_brand_code = False
|
||||
|
||||
finaliser_for_process.execute_optional_features(ARTIST, TITLE, BASE_NAME, ALL_INPUT_FILES, ALL_OUTPUT_FILES, False)
|
||||
|
||||
mock_youtube.assert_called_once()
|
||||
mock_discord.assert_not_called() # Disabled
|
||||
mock_get_next.assert_called_once()
|
||||
mock_move.assert_called_once()
|
||||
mock_copy.assert_called_once()
|
||||
mock_sync.assert_not_called() # Disabled
|
||||
mock_gen_link.assert_called_once() # Still called even if sync disabled
|
||||
|
||||
@patch.object(KaraokeFinalise, 'upload_final_mp4_to_youtube_with_title_thumbnail', side_effect=Exception("YT Upload Failed"))
|
||||
@patch.object(KaraokeFinalise, 'post_discord_notification')
|
||||
@patch('builtins.input', return_value="manual_video_id") # Provide manual ID when prompted
|
||||
def test_execute_optional_features_youtube_fails(mock_input, mock_discord, mock_youtube, finaliser_for_process):
|
||||
"""Test handling when YouTube upload fails and user provides manual ID."""
|
||||
# Disable other features to isolate YouTube failure
|
||||
finaliser_for_process.folder_organisation_enabled = False
|
||||
finaliser_for_process.public_share_copy_enabled = False
|
||||
finaliser_for_process.public_share_rclone_enabled = False
|
||||
|
||||
finaliser_for_process.execute_optional_features(ARTIST, TITLE, BASE_NAME, ALL_INPUT_FILES, ALL_OUTPUT_FILES, False)
|
||||
|
||||
mock_youtube.assert_called_once()
|
||||
mock_input.assert_called_once_with("Enter the manually uploaded YouTube video ID: ")
|
||||
assert finaliser_for_process.youtube_video_id == "manual_video_id"
|
||||
assert finaliser_for_process.youtube_url == f"https://www.youtube.com/watch?v=manual_video_id"
|
||||
mock_discord.assert_called_once() # Discord should still be called after manual ID entry
|
||||
|
||||
# --- process Method Tests ---
|
||||
|
||||
@patch.object(KaraokeFinalise, 'validate_input_parameters_for_features')
|
||||
@patch.object(KaraokeFinalise, 'find_with_vocals_file', return_value=WITH_VOCALS_MOV)
|
||||
@patch.object(KaraokeFinalise, 'get_names_from_withvocals', return_value=(BASE_NAME, ARTIST, TITLE))
|
||||
@patch.object(KaraokeFinalise, 'choose_instrumental_audio_file', return_value=INSTRUMENTAL_FLAC)
|
||||
@patch.object(KaraokeFinalise, 'check_input_files_exist', return_value=ALL_INPUT_FILES)
|
||||
@patch.object(KaraokeFinalise, 'prepare_output_filenames', return_value=ALL_OUTPUT_FILES)
|
||||
@patch.object(KaraokeFinalise, 'create_cdg_zip_file')
|
||||
@patch.object(KaraokeFinalise, 'create_txt_zip_file')
|
||||
@patch.object(KaraokeFinalise, 'remux_and_encode_output_video_files')
|
||||
@patch.object(KaraokeFinalise, 'execute_optional_features')
|
||||
@patch.object(KaraokeFinalise, 'draft_completion_email')
|
||||
def test_process_full_success(
|
||||
mock_draft_email, mock_exec_opt, mock_remux_encode, mock_create_txt, mock_create_cdg,
|
||||
mock_prep_out, mock_check_in, mock_choose_instr, mock_get_names, mock_find_vocals,
|
||||
mock_validate, finaliser_for_process):
|
||||
"""Test the full process method with all features enabled."""
|
||||
replace_existing = True
|
||||
# Mock return values for execute_optional_features state
|
||||
finaliser_for_process.youtube_url = "mock_yt_url"
|
||||
finaliser_for_process.brand_code = "mock_brand_code"
|
||||
finaliser_for_process.new_brand_code_dir_path = "mock_new_dir_path"
|
||||
finaliser_for_process.brand_code_dir_sharing_link = "mock_share_link"
|
||||
|
||||
result = finaliser_for_process.process(replace_existing=replace_existing)
|
||||
|
||||
# Check methods called in order
|
||||
mock_validate.assert_called_once()
|
||||
mock_find_vocals.assert_called_once()
|
||||
mock_get_names.assert_called_once_with(WITH_VOCALS_MOV)
|
||||
mock_choose_instr.assert_called_once_with(BASE_NAME)
|
||||
mock_check_in.assert_called_once_with(BASE_NAME, WITH_VOCALS_MOV, INSTRUMENTAL_FLAC)
|
||||
mock_prep_out.assert_called_once_with(BASE_NAME)
|
||||
mock_create_cdg.assert_called_once_with(ALL_INPUT_FILES, ALL_OUTPUT_FILES, ARTIST, TITLE)
|
||||
mock_create_txt.assert_called_once_with(ALL_INPUT_FILES, ALL_OUTPUT_FILES)
|
||||
mock_remux_encode.assert_called_once_with(WITH_VOCALS_MOV, ALL_INPUT_FILES, ALL_OUTPUT_FILES)
|
||||
mock_exec_opt.assert_called_once_with(ARTIST, TITLE, BASE_NAME, ALL_INPUT_FILES, ALL_OUTPUT_FILES, replace_existing)
|
||||
mock_draft_email.assert_called_once_with(ARTIST, TITLE, "mock_yt_url", "mock_share_link")
|
||||
|
||||
# Check result dictionary
|
||||
expected_result = {
|
||||
"artist": ARTIST,
|
||||
"title": TITLE,
|
||||
"video_with_vocals": ALL_OUTPUT_FILES["with_vocals_mp4"],
|
||||
"video_with_instrumental": ALL_OUTPUT_FILES["karaoke_mp4"],
|
||||
"final_video": ALL_OUTPUT_FILES["final_karaoke_lossless_mp4"],
|
||||
"final_video_mkv": ALL_OUTPUT_FILES["final_karaoke_lossless_mkv"],
|
||||
"final_video_lossy": ALL_OUTPUT_FILES["final_karaoke_lossy_mp4"],
|
||||
"final_video_720p": ALL_OUTPUT_FILES["final_karaoke_lossy_720p_mp4"],
|
||||
"youtube_url": "mock_yt_url",
|
||||
"brand_code": "mock_brand_code",
|
||||
"new_brand_code_dir_path": "mock_new_dir_path",
|
||||
"brand_code_dir_sharing_link": "mock_share_link",
|
||||
"final_karaoke_cdg_zip": ALL_OUTPUT_FILES["final_karaoke_cdg_zip"], # CDG enabled
|
||||
"final_karaoke_txt_zip": ALL_OUTPUT_FILES["final_karaoke_txt_zip"], # TXT enabled
|
||||
}
|
||||
assert result == expected_result
|
||||
|
||||
@patch.object(KaraokeFinalise, 'validate_input_parameters_for_features')
|
||||
@patch.object(KaraokeFinalise, 'find_with_vocals_file', return_value=WITH_VOCALS_MOV)
|
||||
@patch.object(KaraokeFinalise, 'get_names_from_withvocals', return_value=(BASE_NAME, ARTIST, TITLE))
|
||||
@patch.object(KaraokeFinalise, 'choose_instrumental_audio_file', return_value=INSTRUMENTAL_FLAC)
|
||||
@patch.object(KaraokeFinalise, 'check_input_files_exist', return_value=ALL_INPUT_FILES)
|
||||
@patch.object(KaraokeFinalise, 'prepare_output_filenames', return_value=ALL_OUTPUT_FILES)
|
||||
@patch.object(KaraokeFinalise, 'create_cdg_zip_file')
|
||||
@patch.object(KaraokeFinalise, 'create_txt_zip_file')
|
||||
@patch.object(KaraokeFinalise, 'remux_and_encode_output_video_files')
|
||||
@patch.object(KaraokeFinalise, 'execute_optional_features')
|
||||
@patch.object(KaraokeFinalise, 'draft_completion_email')
|
||||
def test_process_some_disabled(
|
||||
mock_draft_email, mock_exec_opt, mock_remux_encode, mock_create_txt, mock_create_cdg,
|
||||
mock_prep_out, mock_check_in, mock_choose_instr, mock_get_names, mock_find_vocals,
|
||||
mock_validate, finaliser_for_process):
|
||||
"""Test the process method with CDG, TXT, and Email disabled."""
|
||||
finaliser_for_process.enable_cdg = False
|
||||
finaliser_for_process.enable_txt = False
|
||||
finaliser_for_process.email_template_file = None # Disable email
|
||||
|
||||
result = finaliser_for_process.process()
|
||||
|
||||
mock_validate.assert_called_once()
|
||||
mock_find_vocals.assert_called_once()
|
||||
# ... other calls ...
|
||||
mock_create_cdg.assert_not_called() # Disabled
|
||||
mock_create_txt.assert_not_called() # Disabled
|
||||
mock_remux_encode.assert_called_once()
|
||||
mock_exec_opt.assert_called_once()
|
||||
mock_draft_email.assert_not_called() # Disabled
|
||||
|
||||
# Check result dictionary excludes disabled features
|
||||
assert "final_karaoke_cdg_zip" not in result
|
||||
assert "final_karaoke_txt_zip" not in result
|
||||
|
||||
@patch.object(KaraokeFinalise, 'validate_input_parameters_for_features')
|
||||
@patch.object(KaraokeFinalise, 'find_with_vocals_file')
|
||||
# ... mock other methods ...
|
||||
def test_process_dry_run(mock_find_vocals, mock_validate, finaliser_for_process):
|
||||
"""Test process method in dry run mode."""
|
||||
finaliser_for_process.dry_run = True
|
||||
|
||||
# We don't need to mock everything, just check the initial warning
|
||||
# and potentially that sub-methods inherit dry_run (tested elsewhere)
|
||||
with patch.object(KaraokeFinalise, 'get_names_from_withvocals', side_effect=Exception("Should not reach here in simple dry run test")):
|
||||
# Use side effect to ensure later methods aren't called if dry run logic fails early
|
||||
finaliser_for_process.process()
|
||||
|
||||
finaliser_for_process.logger.warning.assert_called_with("Dry run enabled. No actions will be performed.")
|
||||
mock_validate.assert_called_once() # Validation should still run
|
||||
mock_find_vocals.assert_called_once() # Should still find files
|
||||
@@ -0,0 +1,90 @@
|
||||
import pytest
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
# Adjust the import path
|
||||
from karaoke_prep.karaoke_finalise.karaoke_finalise import KaraokeFinalise
|
||||
from .test_initialization import mock_logger, basic_finaliser, MINIMAL_CONFIG # Reuse fixtures
|
||||
|
||||
PROMPT_MSG = "Do you want to proceed?"
|
||||
EXIT_MSG = "User aborted."
|
||||
|
||||
# --- prompt_user_bool Tests ---
|
||||
|
||||
@pytest.mark.parametrize("user_input, allow_empty, expected_result", [
|
||||
("y", True, True),
|
||||
("Y", True, True),
|
||||
("yes", True, True),
|
||||
("YES", True, True),
|
||||
("", True, True), # Empty allowed
|
||||
("y", False, True),
|
||||
("Y", False, True),
|
||||
("yes", False, True),
|
||||
("YES", False, True),
|
||||
("", False, False), # Empty not allowed
|
||||
("n", True, False),
|
||||
("N", True, False),
|
||||
("no", True, False),
|
||||
("NO", True, False),
|
||||
("n", False, False),
|
||||
("N", False, False),
|
||||
("no", False, False),
|
||||
("NO", False, False),
|
||||
("maybe", True, False),
|
||||
("maybe", False, False),
|
||||
])
|
||||
@patch('builtins.input')
|
||||
def test_prompt_user_bool_interactive(mock_input, user_input, allow_empty, expected_result, basic_finaliser):
|
||||
"""Test various inputs for prompt_user_bool in interactive mode."""
|
||||
basic_finaliser.non_interactive = False # Ensure interactive
|
||||
mock_input.return_value = user_input
|
||||
result = basic_finaliser.prompt_user_bool(PROMPT_MSG, allow_empty=allow_empty)
|
||||
assert result == expected_result
|
||||
expected_options = "[y]/n" if allow_empty else "y/[n]"
|
||||
mock_input.assert_called_once_with(f"{PROMPT_MSG} {expected_options} ")
|
||||
|
||||
@patch('builtins.input')
|
||||
def test_prompt_user_bool_non_interactive(mock_input, basic_finaliser):
|
||||
"""Test prompt_user_bool always returns True in non-interactive mode."""
|
||||
basic_finaliser.non_interactive = True # Ensure non-interactive
|
||||
result_allow_empty = basic_finaliser.prompt_user_bool(PROMPT_MSG, allow_empty=True)
|
||||
result_not_allow_empty = basic_finaliser.prompt_user_bool(PROMPT_MSG, allow_empty=False)
|
||||
|
||||
assert result_allow_empty is True
|
||||
assert result_not_allow_empty is True
|
||||
mock_input.assert_not_called() # Should not prompt
|
||||
basic_finaliser.logger.info.assert_any_call(f"Non-interactive mode, automatically answering yes to: {PROMPT_MSG}")
|
||||
|
||||
# --- prompt_user_confirmation_or_raise_exception Tests ---
|
||||
|
||||
@patch.object(KaraokeFinalise, 'prompt_user_bool', return_value=True)
|
||||
def test_prompt_confirmation_success(mock_prompt_bool, basic_finaliser):
|
||||
"""Test confirmation succeeds when prompt_user_bool returns True."""
|
||||
basic_finaliser.non_interactive = False # Ensure interactive
|
||||
# No exception should be raised
|
||||
try:
|
||||
basic_finaliser.prompt_user_confirmation_or_raise_exception(PROMPT_MSG, EXIT_MSG, allow_empty=True)
|
||||
except Exception as e:
|
||||
pytest.fail(f"Should not have raised exception: {e}")
|
||||
mock_prompt_bool.assert_called_once_with(PROMPT_MSG, allow_empty=True)
|
||||
|
||||
@patch.object(KaraokeFinalise, 'prompt_user_bool', return_value=False)
|
||||
def test_prompt_confirmation_failure_raises(mock_prompt_bool, basic_finaliser):
|
||||
"""Test confirmation raises exception when prompt_user_bool returns False."""
|
||||
basic_finaliser.non_interactive = False # Ensure interactive
|
||||
with pytest.raises(Exception, match=EXIT_MSG):
|
||||
basic_finaliser.prompt_user_confirmation_or_raise_exception(PROMPT_MSG, EXIT_MSG, allow_empty=False)
|
||||
mock_prompt_bool.assert_called_once_with(PROMPT_MSG, allow_empty=False)
|
||||
basic_finaliser.logger.error.assert_called_once_with(EXIT_MSG)
|
||||
|
||||
@patch.object(KaraokeFinalise, 'prompt_user_bool')
|
||||
def test_prompt_confirmation_non_interactive(mock_prompt_bool, basic_finaliser):
|
||||
"""Test confirmation is bypassed in non-interactive mode."""
|
||||
basic_finaliser.non_interactive = True # Ensure non-interactive
|
||||
# No exception should be raised
|
||||
try:
|
||||
basic_finaliser.prompt_user_confirmation_or_raise_exception(PROMPT_MSG, EXIT_MSG)
|
||||
except Exception as e:
|
||||
pytest.fail(f"Should not have raised exception: {e}")
|
||||
|
||||
mock_prompt_bool.assert_not_called() # Prompt should be skipped
|
||||
basic_finaliser.logger.info.assert_called_once_with(f"Non-interactive mode, automatically confirming: {PROMPT_MSG}")
|
||||
@@ -0,0 +1,431 @@
|
||||
import pytest
|
||||
import os
|
||||
import pickle
|
||||
from unittest.mock import patch, MagicMock, mock_open, call, ANY
|
||||
|
||||
# Adjust the import path
|
||||
from karaoke_prep.karaoke_finalise.karaoke_finalise import KaraokeFinalise
|
||||
from .test_initialization import mock_logger, basic_finaliser, MINIMAL_CONFIG # Reuse fixtures
|
||||
from .test_file_input_validation import BASE_NAME, ARTIST, TITLE, TITLE_JPG # Reuse constants
|
||||
from .test_ffmpeg_commands import OUTPUT_FILES as FFMPEG_OUTPUT_FILES # Reuse constants
|
||||
|
||||
YOUTUBE_SECRETS_FILE = "client_secrets.json"
|
||||
YOUTUBE_DESC_FILE = "youtube_description.txt"
|
||||
YOUTUBE_TOKEN_FILE = "/tmp/karaoke-finalise-youtube-token.pickle"
|
||||
|
||||
# Define expected output filenames relevant to YouTube
|
||||
OUTPUT_FILES_YT = {
|
||||
"final_karaoke_lossless_mkv": FFMPEG_OUTPUT_FILES["final_karaoke_lossless_mkv"],
|
||||
}
|
||||
INPUT_FILES_YT = {
|
||||
"title_jpg": TITLE_JPG,
|
||||
}
|
||||
|
||||
@pytest.fixture
|
||||
def finaliser_for_yt(mock_logger):
|
||||
"""Fixture for a finaliser configured for YouTube tasks."""
|
||||
config = MINIMAL_CONFIG.copy()
|
||||
config.update({
|
||||
"youtube_client_secrets_file": YOUTUBE_SECRETS_FILE,
|
||||
"youtube_description_file": YOUTUBE_DESC_FILE,
|
||||
})
|
||||
with patch.object(KaraokeFinalise, 'detect_best_aac_codec', return_value='aac'):
|
||||
finaliser = KaraokeFinalise(logger=mock_logger, **config)
|
||||
# Manually enable features for testing specific methods
|
||||
finaliser.youtube_upload_enabled = True
|
||||
return finaliser
|
||||
|
||||
@pytest.fixture
|
||||
def mock_youtube_service():
|
||||
"""Fixture for a mocked YouTube service object."""
|
||||
mock_service = MagicMock()
|
||||
# Mock chained calls
|
||||
mock_service.channels.return_value.list.return_value.execute.return_value = {"items": [{"id": "UC_test_channel_id"}]}
|
||||
mock_service.search.return_value.list.return_value.execute.return_value = {"items": []} # Default: no search results
|
||||
mock_service.videos.return_value.delete.return_value.execute.return_value = {} # Default: delete success
|
||||
mock_service.videos.return_value.insert.return_value.execute.return_value = {"id": "new_video_id"} # Default: insert success
|
||||
mock_service.thumbnails.return_value.set.return_value.execute.return_value = {} # Default: thumbnail set success
|
||||
return mock_service
|
||||
|
||||
@pytest.fixture
|
||||
def mock_google_auth():
|
||||
"""Fixture to mock Google auth flow and build."""
|
||||
with patch('google_auth_oauthlib.flow.InstalledAppFlow') as mock_flow_cls, \
|
||||
patch('googleapiclient.discovery.build') as mock_build, \
|
||||
patch('pickle.dump') as mock_pickle_dump, \
|
||||
patch('pickle.load') as mock_pickle_load, \
|
||||
patch('os.path.exists') as mock_path_exists:
|
||||
|
||||
mock_flow_instance = MagicMock()
|
||||
mock_flow_cls.from_client_secrets_file.return_value = mock_flow_instance
|
||||
mock_credentials = MagicMock()
|
||||
mock_credentials.valid = True # Assume valid by default
|
||||
mock_credentials.expired = False
|
||||
mock_credentials.refresh_token = "fake_refresh_token"
|
||||
mock_flow_instance.run_local_server.return_value = mock_credentials
|
||||
|
||||
# Default: token file doesn't exist, build returns mock service
|
||||
mock_path_exists.return_value = False
|
||||
mock_pickle_load.side_effect = FileNotFoundError # If exists=True but load fails
|
||||
|
||||
yield {
|
||||
"mock_flow_cls": mock_flow_cls,
|
||||
"mock_flow_instance": mock_flow_instance,
|
||||
"mock_build": mock_build,
|
||||
"mock_pickle_dump": mock_pickle_dump,
|
||||
"mock_pickle_load": mock_pickle_load,
|
||||
"mock_path_exists": mock_path_exists,
|
||||
"mock_credentials": mock_credentials,
|
||||
}
|
||||
|
||||
# --- Truncate Title Test ---
|
||||
def test_truncate_to_nearest_word(basic_finaliser):
|
||||
"""Test title truncation logic."""
|
||||
long_title = "This is a very long title that definitely exceeds the maximum length allowed"
|
||||
max_len = 50
|
||||
truncated = basic_finaliser.truncate_to_nearest_word(long_title, max_len)
|
||||
assert truncated == "This is a very long title that definitely exceeds ..."
|
||||
assert len(truncated) <= max_len + 4 # Allow for ellipsis
|
||||
|
||||
short_title = "Short title"
|
||||
truncated_short = basic_finaliser.truncate_to_nearest_word(short_title, max_len)
|
||||
assert truncated_short == short_title
|
||||
|
||||
exact_title = "Title exactly fifty characters long right here now!" # 50 chars
|
||||
truncated_exact = basic_finaliser.truncate_to_nearest_word(exact_title, max_len)
|
||||
assert truncated_exact == exact_title
|
||||
|
||||
title_with_no_space = "a"*60
|
||||
truncated_no_space = basic_finaliser.truncate_to_nearest_word(title_with_no_space, max_len)
|
||||
assert truncated_no_space == "" # Should truncate to empty string if no space found
|
||||
|
||||
# --- Authentication Tests ---
|
||||
|
||||
def test_authenticate_youtube_new_token(finaliser_for_yt, mock_google_auth, mock_youtube_service):
|
||||
"""Test authentication flow when no token file exists."""
|
||||
mock_google_auth["mock_path_exists"].return_value = False
|
||||
mock_google_auth["mock_build"].return_value = mock_youtube_service
|
||||
|
||||
service = finaliser_for_yt.authenticate_youtube()
|
||||
|
||||
mock_google_auth["mock_path_exists"].assert_called_once_with(YOUTUBE_TOKEN_FILE)
|
||||
mock_google_auth["mock_flow_cls"].from_client_secrets_file.assert_called_once_with(
|
||||
YOUTUBE_SECRETS_FILE, scopes=["https://www.googleapis.com/auth/youtube"]
|
||||
)
|
||||
mock_google_auth["mock_flow_instance"].run_local_server.assert_called_once_with(port=0)
|
||||
mock_google_auth["mock_pickle_dump"].assert_called_once()
|
||||
# Check that the credentials from the flow were saved
|
||||
assert mock_google_auth["mock_pickle_dump"].call_args[0][0] == mock_google_auth["mock_credentials"]
|
||||
mock_google_auth["mock_build"].assert_called_once_with("youtube", "v3", credentials=mock_google_auth["mock_credentials"])
|
||||
assert service == mock_youtube_service
|
||||
|
||||
def test_authenticate_youtube_load_valid_token(finaliser_for_yt, mock_google_auth, mock_youtube_service):
|
||||
"""Test authentication using a valid existing token file."""
|
||||
mock_google_auth["mock_path_exists"].return_value = True
|
||||
mock_google_auth["mock_pickle_load"].return_value = mock_google_auth["mock_credentials"]
|
||||
mock_google_auth["mock_credentials"].valid = True
|
||||
mock_google_auth["mock_build"].return_value = mock_youtube_service
|
||||
|
||||
service = finaliser_for_yt.authenticate_youtube()
|
||||
|
||||
mock_google_auth["mock_path_exists"].assert_called_once_with(YOUTUBE_TOKEN_FILE)
|
||||
mock_google_auth["mock_pickle_load"].assert_called_once_with(ANY) # Check it tried to load
|
||||
mock_google_auth["mock_flow_instance"].run_local_server.assert_not_called() # Should not run flow
|
||||
mock_google_auth["mock_pickle_dump"].assert_not_called() # Should not save token again
|
||||
mock_google_auth["mock_build"].assert_called_once_with("youtube", "v3", credentials=mock_google_auth["mock_credentials"])
|
||||
assert service == mock_youtube_service
|
||||
|
||||
def test_authenticate_youtube_refresh_token(finaliser_for_yt, mock_google_auth, mock_youtube_service):
|
||||
"""Test authentication refreshing an expired token."""
|
||||
mock_google_auth["mock_path_exists"].return_value = True
|
||||
mock_google_auth["mock_pickle_load"].return_value = mock_google_auth["mock_credentials"]
|
||||
mock_google_auth["mock_credentials"].valid = False # Token is invalid
|
||||
mock_google_auth["mock_credentials"].expired = True # But expired
|
||||
mock_google_auth["mock_credentials"].refresh_token = "fake_refresh_token" # And has refresh token
|
||||
mock_google_auth["mock_build"].return_value = mock_youtube_service
|
||||
|
||||
# Mock the refresh method
|
||||
with patch('google.auth.transport.requests.Request') as mock_request:
|
||||
mock_refresh = mock_google_auth["mock_credentials"].refresh
|
||||
service = finaliser_for_yt.authenticate_youtube()
|
||||
|
||||
mock_refresh.assert_called_once_with(mock_request())
|
||||
|
||||
mock_google_auth["mock_path_exists"].assert_called_once_with(YOUTUBE_TOKEN_FILE)
|
||||
mock_google_auth["mock_pickle_load"].assert_called_once_with(ANY)
|
||||
mock_google_auth["mock_flow_instance"].run_local_server.assert_not_called() # Should not run flow
|
||||
mock_google_auth["mock_pickle_dump"].assert_called_once() # Should save refreshed token
|
||||
mock_google_auth["mock_build"].assert_called_once_with("youtube", "v3", credentials=mock_google_auth["mock_credentials"])
|
||||
assert service == mock_youtube_service
|
||||
|
||||
# --- Channel ID / Video Check Tests ---
|
||||
|
||||
@patch.object(KaraokeFinalise, 'authenticate_youtube')
|
||||
def test_get_channel_id(mock_auth, finaliser_for_yt, mock_youtube_service):
|
||||
"""Test getting the channel ID."""
|
||||
mock_auth.return_value = mock_youtube_service
|
||||
channel_id = finaliser_for_yt.get_channel_id()
|
||||
assert channel_id == "UC_test_channel_id"
|
||||
mock_youtube_service.channels().list.assert_called_once_with(part="snippet", mine=True)
|
||||
|
||||
@patch.object(KaraokeFinalise, 'authenticate_youtube')
|
||||
@patch('thefuzz.fuzz.ratio')
|
||||
@patch('builtins.input', return_value='y') # Confirm match
|
||||
def test_check_if_video_title_exists_found_confirm(mock_input, mock_fuzz_ratio, mock_auth, finaliser_for_yt, mock_youtube_service):
|
||||
"""Test finding an existing video and confirming."""
|
||||
mock_auth.return_value = mock_youtube_service
|
||||
youtube_title = f"{ARTIST} - {TITLE} (Karaoke)"
|
||||
found_video_id = "existing_video_id"
|
||||
found_video_title = f"{ARTIST} - {TITLE} (Karaoke) Official"
|
||||
mock_youtube_service.search.return_value.list.return_value.execute.return_value = {
|
||||
"items": [{"id": {"videoId": found_video_id}, "snippet": {"title": found_video_title}}]
|
||||
}
|
||||
mock_fuzz_ratio.return_value = 85 # High similarity
|
||||
|
||||
exists = finaliser_for_yt.check_if_video_title_exists_on_youtube_channel(youtube_title)
|
||||
|
||||
assert exists is True
|
||||
assert finaliser_for_yt.youtube_video_id == found_video_id
|
||||
assert finaliser_for_yt.youtube_url == f"https://www.youtube.com/watch?v={found_video_id}"
|
||||
assert finaliser_for_yt.skip_notifications is True # Should skip notifications if found
|
||||
mock_fuzz_ratio.assert_called_once_with(youtube_title.lower(), found_video_title.lower())
|
||||
mock_input.assert_called_once()
|
||||
|
||||
@patch.object(KaraokeFinalise, 'authenticate_youtube')
|
||||
@patch('thefuzz.fuzz.ratio')
|
||||
@patch('builtins.input', return_value='n') # Reject match
|
||||
def test_check_if_video_title_exists_found_reject(mock_input, mock_fuzz_ratio, mock_auth, finaliser_for_yt, mock_youtube_service):
|
||||
"""Test finding an existing video but rejecting the match."""
|
||||
mock_auth.return_value = mock_youtube_service
|
||||
youtube_title = f"{ARTIST} - {TITLE} (Karaoke)"
|
||||
found_video_id = "existing_video_id"
|
||||
found_video_title = f"{ARTIST} - {TITLE} (Karaoke) Official"
|
||||
mock_youtube_service.search.return_value.list.return_value.execute.return_value = {
|
||||
"items": [{"id": {"videoId": found_video_id}, "snippet": {"title": found_video_title}}]
|
||||
}
|
||||
mock_fuzz_ratio.return_value = 85
|
||||
|
||||
exists = finaliser_for_yt.check_if_video_title_exists_on_youtube_channel(youtube_title)
|
||||
|
||||
assert exists is False # User rejected
|
||||
assert finaliser_for_yt.youtube_video_id is None
|
||||
assert finaliser_for_yt.youtube_url is None
|
||||
assert finaliser_for_yt.skip_notifications is False
|
||||
mock_input.assert_called_once()
|
||||
|
||||
@patch.object(KaraokeFinalise, 'authenticate_youtube')
|
||||
@patch('thefuzz.fuzz.ratio')
|
||||
def test_check_if_video_title_exists_low_similarity(mock_fuzz_ratio, mock_auth, finaliser_for_yt, mock_youtube_service):
|
||||
"""Test skipping a potential match due to low similarity."""
|
||||
mock_auth.return_value = mock_youtube_service
|
||||
youtube_title = f"{ARTIST} - {TITLE} (Karaoke)"
|
||||
found_video_id = "existing_video_id"
|
||||
found_video_title = "Completely Different Title"
|
||||
mock_youtube_service.search.return_value.list.return_value.execute.return_value = {
|
||||
"items": [{"id": {"videoId": found_video_id}, "snippet": {"title": found_video_title}}]
|
||||
}
|
||||
mock_fuzz_ratio.return_value = 30 # Low similarity
|
||||
|
||||
exists = finaliser_for_yt.check_if_video_title_exists_on_youtube_channel(youtube_title)
|
||||
|
||||
assert exists is False
|
||||
assert finaliser_for_yt.youtube_video_id is None
|
||||
assert finaliser_for_yt.youtube_url is None
|
||||
assert finaliser_for_yt.skip_notifications is False
|
||||
|
||||
@patch.object(KaraokeFinalise, 'authenticate_youtube')
|
||||
@patch('thefuzz.fuzz.ratio')
|
||||
@patch('builtins.input') # Should not be called
|
||||
def test_check_if_video_title_exists_non_interactive(mock_input, mock_fuzz_ratio, mock_auth, finaliser_for_yt, mock_youtube_service):
|
||||
"""Test non-interactive confirmation of existing video."""
|
||||
finaliser_for_yt.non_interactive = True
|
||||
mock_auth.return_value = mock_youtube_service
|
||||
youtube_title = f"{ARTIST} - {TITLE} (Karaoke)"
|
||||
found_video_id = "existing_video_id"
|
||||
found_video_title = f"{ARTIST} - {TITLE} (Karaoke) Official"
|
||||
mock_youtube_service.search.return_value.list.return_value.execute.return_value = {
|
||||
"items": [{"id": {"videoId": found_video_id}, "snippet": {"title": found_video_title}}]
|
||||
}
|
||||
mock_fuzz_ratio.return_value = 85
|
||||
|
||||
exists = finaliser_for_yt.check_if_video_title_exists_on_youtube_channel(youtube_title)
|
||||
|
||||
assert exists is True
|
||||
assert finaliser_for_yt.youtube_video_id == found_video_id
|
||||
assert finaliser_for_yt.skip_notifications is True
|
||||
mock_input.assert_not_called() # No prompt in non-interactive
|
||||
|
||||
@patch.object(KaraokeFinalise, 'authenticate_youtube')
|
||||
def test_check_if_video_title_exists_not_found(mock_auth, finaliser_for_yt, mock_youtube_service):
|
||||
"""Test when no video is found."""
|
||||
mock_auth.return_value = mock_youtube_service
|
||||
mock_youtube_service.search.return_value.list.return_value.execute.return_value = {"items": []} # No results
|
||||
youtube_title = f"{ARTIST} - {TITLE} (Karaoke)"
|
||||
|
||||
exists = finaliser_for_yt.check_if_video_title_exists_on_youtube_channel(youtube_title)
|
||||
|
||||
assert exists is False
|
||||
assert finaliser_for_yt.youtube_video_id is None
|
||||
assert finaliser_for_yt.youtube_url is None
|
||||
assert finaliser_for_yt.skip_notifications is False
|
||||
|
||||
# --- Delete / Upload Tests ---
|
||||
|
||||
@patch.object(KaraokeFinalise, 'authenticate_youtube')
|
||||
def test_delete_youtube_video_success(mock_auth, finaliser_for_yt, mock_youtube_service):
|
||||
"""Test successful video deletion."""
|
||||
mock_auth.return_value = mock_youtube_service
|
||||
video_id = "video_to_delete"
|
||||
result = finaliser_for_yt.delete_youtube_video(video_id)
|
||||
assert result is True
|
||||
mock_youtube_service.videos().delete.assert_called_once_with(id=video_id)
|
||||
finaliser_for_yt.logger.info.assert_any_call(f"Successfully deleted YouTube video with ID: {video_id}")
|
||||
|
||||
@patch.object(KaraokeFinalise, 'authenticate_youtube')
|
||||
def test_delete_youtube_video_failure(mock_auth, finaliser_for_yt, mock_youtube_service):
|
||||
"""Test failed video deletion."""
|
||||
mock_auth.return_value = mock_youtube_service
|
||||
video_id = "video_to_delete"
|
||||
mock_youtube_service.videos.return_value.delete.return_value.execute.side_effect = Exception("API Error")
|
||||
result = finaliser_for_yt.delete_youtube_video(video_id)
|
||||
assert result is False
|
||||
mock_youtube_service.videos().delete.assert_called_once_with(id=video_id)
|
||||
finaliser_for_yt.logger.error.assert_any_call(f"Failed to delete YouTube video with ID {video_id}: API Error")
|
||||
|
||||
@patch.object(KaraokeFinalise, 'authenticate_youtube')
|
||||
def test_delete_youtube_video_dry_run(mock_auth, finaliser_for_yt, mock_youtube_service):
|
||||
"""Test video deletion dry run."""
|
||||
finaliser_for_yt.dry_run = True
|
||||
mock_auth.return_value = mock_youtube_service
|
||||
video_id = "video_to_delete"
|
||||
result = finaliser_for_yt.delete_youtube_video(video_id)
|
||||
assert result is True
|
||||
mock_youtube_service.videos().delete.assert_not_called()
|
||||
finaliser_for_yt.logger.info.assert_any_call(f"DRY RUN: Would delete YouTube video with ID: {video_id}")
|
||||
|
||||
|
||||
@patch('builtins.open', new_callable=mock_open, read_data="Custom description from file")
|
||||
@patch('googleapiclient.http.MediaFileUpload')
|
||||
@patch.object(KaraokeFinalise, 'authenticate_youtube')
|
||||
@patch.object(KaraokeFinalise, 'check_if_video_title_exists_on_youtube_channel', return_value=False) # Assume not exists
|
||||
@patch.object(KaraokeFinalise, 'truncate_to_nearest_word', side_effect=lambda t, l: t) # Passthrough truncate
|
||||
def test_upload_youtube_success(mock_truncate, mock_check_exists, mock_auth, mock_media_upload, mock_open_file, finaliser_for_yt, mock_youtube_service):
|
||||
"""Test successful YouTube upload."""
|
||||
mock_auth.return_value = mock_youtube_service
|
||||
mock_media_upload.return_value = MagicMock() # Mock the media file upload object
|
||||
|
||||
finaliser_for_yt.upload_final_mp4_to_youtube_with_title_thumbnail(ARTIST, TITLE, INPUT_FILES_YT, OUTPUT_FILES_YT)
|
||||
|
||||
expected_title = f"{ARTIST} - {TITLE} (Karaoke)"
|
||||
expected_keywords = ["karaoke", "music", "singing", "instrumental", "lyrics", ARTIST, TITLE]
|
||||
expected_description = "Custom description from file"
|
||||
expected_category_id = "10"
|
||||
expected_privacy = "public"
|
||||
|
||||
mock_check_exists.assert_called_once_with(expected_title)
|
||||
mock_open_file.assert_called_once_with(YOUTUBE_DESC_FILE, "r")
|
||||
mock_truncate.assert_called_once_with(expected_title, 95)
|
||||
|
||||
# Check video insert call
|
||||
insert_call_args = mock_youtube_service.videos().insert.call_args
|
||||
assert insert_call_args[1]['part'] == "snippet,status"
|
||||
body = insert_call_args[1]['body']
|
||||
assert body['snippet']['title'] == expected_title
|
||||
assert body['snippet']['description'] == expected_description
|
||||
assert body['snippet']['tags'] == expected_keywords
|
||||
assert body['snippet']['categoryId'] == expected_category_id
|
||||
assert body['status']['privacyStatus'] == expected_privacy
|
||||
assert insert_call_args[1]['media_body'] == mock_media_upload.return_value
|
||||
# Check MediaFileUpload calls with relative paths
|
||||
mock_media_upload.assert_has_calls([
|
||||
call(OUTPUT_FILES_YT["final_karaoke_lossless_mkv"], mimetype="video/x-matroska", resumable=True),
|
||||
call(INPUT_FILES_YT["title_jpg"], mimetype="image/jpeg")
|
||||
], any_order=True) # Order might vary slightly depending on execution
|
||||
|
||||
# Check thumbnail set call
|
||||
mock_youtube_service.thumbnails().set.assert_called_once()
|
||||
thumb_call_args = mock_youtube_service.thumbnails().set.call_args
|
||||
assert thumb_call_args[1]['videoId'] == "new_video_id"
|
||||
# Ensure the media_body for thumbnail is the one created for the JPG
|
||||
assert thumb_call_args[1]['media_body'] == mock_media_upload.return_value # This assumes the mock returns the same instance for both calls, adjust if needed
|
||||
|
||||
assert finaliser_for_yt.youtube_video_id == "new_video_id"
|
||||
assert finaliser_for_yt.youtube_url == f"https://www.youtube.com/watch?v=new_video_id"
|
||||
|
||||
@patch('googleapiclient.http.MediaFileUpload')
|
||||
@patch.object(KaraokeFinalise, 'authenticate_youtube')
|
||||
@patch.object(KaraokeFinalise, 'check_if_video_title_exists_on_youtube_channel', return_value=True) # Assume exists
|
||||
@patch.object(KaraokeFinalise, 'delete_youtube_video')
|
||||
def test_upload_youtube_exists_skip(mock_delete, mock_check_exists, mock_auth, mock_media_upload, finaliser_for_yt, mock_youtube_service):
|
||||
"""Test skipping upload if video exists and replace_existing is False."""
|
||||
mock_auth.return_value = mock_youtube_service
|
||||
finaliser_for_yt.youtube_video_id = "existing_id" # Set by check_if_video_title_exists
|
||||
finaliser_for_yt.youtube_url = "http://youtube.com/existing_id"
|
||||
|
||||
finaliser_for_yt.upload_final_mp4_to_youtube_with_title_thumbnail(ARTIST, TITLE, INPUT_FILES_YT, OUTPUT_FILES_YT, replace_existing=False)
|
||||
|
||||
mock_check_exists.assert_called_once()
|
||||
mock_delete.assert_not_called()
|
||||
mock_youtube_service.videos().insert.assert_not_called()
|
||||
mock_youtube_service.thumbnails().set.assert_not_called()
|
||||
finaliser_for_yt.logger.warning.assert_called_with(f"Video already exists on YouTube, skipping upload: {finaliser_for_yt.youtube_url}")
|
||||
|
||||
@patch('googleapiclient.http.MediaFileUpload')
|
||||
@patch.object(KaraokeFinalise, 'authenticate_youtube')
|
||||
@patch.object(KaraokeFinalise, 'check_if_video_title_exists_on_youtube_channel', return_value=True) # Assume exists
|
||||
@patch.object(KaraokeFinalise, 'delete_youtube_video', return_value=True) # Delete succeeds
|
||||
def test_upload_youtube_exists_replace_success(mock_delete, mock_check_exists, mock_auth, mock_media_upload, finaliser_for_yt, mock_youtube_service):
|
||||
"""Test replacing an existing video successfully."""
|
||||
mock_auth.return_value = mock_youtube_service
|
||||
finaliser_for_yt.youtube_video_id = "existing_id" # Set by check_if_video_title_exists
|
||||
finaliser_for_yt.youtube_url = "http://youtube.com/existing_id"
|
||||
|
||||
finaliser_for_yt.upload_final_mp4_to_youtube_with_title_thumbnail(ARTIST, TITLE, INPUT_FILES_YT, OUTPUT_FILES_YT, replace_existing=True)
|
||||
|
||||
mock_check_exists.assert_called_once()
|
||||
mock_delete.assert_called_once_with("existing_id")
|
||||
# Check that video ID and URL were reset before upload attempt
|
||||
# (Difficult to check state mid-function, but ensure insert is called)
|
||||
mock_youtube_service.videos().insert.assert_called_once()
|
||||
mock_youtube_service.thumbnails().set.assert_called_once()
|
||||
# Check final state reflects the *new* video ID
|
||||
assert finaliser_for_yt.youtube_video_id == "new_video_id"
|
||||
assert finaliser_for_yt.youtube_url == f"https://www.youtube.com/watch?v=new_video_id"
|
||||
|
||||
@patch('googleapiclient.http.MediaFileUpload')
|
||||
@patch.object(KaraokeFinalise, 'authenticate_youtube')
|
||||
@patch.object(KaraokeFinalise, 'check_if_video_title_exists_on_youtube_channel', return_value=True) # Assume exists
|
||||
@patch.object(KaraokeFinalise, 'delete_youtube_video', return_value=False) # Delete fails
|
||||
def test_upload_youtube_exists_replace_delete_fails(mock_delete, mock_check_exists, mock_auth, mock_media_upload, finaliser_for_yt, mock_youtube_service):
|
||||
"""Test aborting replacement if deletion fails."""
|
||||
mock_auth.return_value = mock_youtube_service
|
||||
finaliser_for_yt.youtube_video_id = "existing_id"
|
||||
finaliser_for_yt.youtube_url = "http://youtube.com/existing_id"
|
||||
|
||||
# Should not raise an exception, just log error and return
|
||||
finaliser_for_yt.upload_final_mp4_to_youtube_with_title_thumbnail(ARTIST, TITLE, INPUT_FILES_YT, OUTPUT_FILES_YT, replace_existing=True)
|
||||
|
||||
mock_check_exists.assert_called_once()
|
||||
mock_delete.assert_called_once_with("existing_id")
|
||||
mock_youtube_service.videos().insert.assert_not_called() # Upload aborted
|
||||
mock_youtube_service.thumbnails().set.assert_not_called()
|
||||
finaliser_for_yt.logger.error.assert_called_with("Failed to delete existing video, aborting upload")
|
||||
# Video ID and URL should remain the old ones
|
||||
assert finaliser_for_yt.youtube_video_id == "existing_id"
|
||||
assert finaliser_for_yt.youtube_url == "http://youtube.com/existing_id"
|
||||
|
||||
@patch.object(KaraokeFinalise, 'authenticate_youtube')
|
||||
@patch.object(KaraokeFinalise, 'check_if_video_title_exists_on_youtube_channel', return_value=False)
|
||||
def test_upload_youtube_dry_run(mock_check_exists, mock_auth, finaliser_for_yt, mock_youtube_service):
|
||||
"""Test YouTube upload dry run."""
|
||||
finaliser_for_yt.dry_run = True
|
||||
mock_auth.return_value = mock_youtube_service
|
||||
|
||||
finaliser_for_yt.upload_final_mp4_to_youtube_with_title_thumbnail(ARTIST, TITLE, INPUT_FILES_YT, OUTPUT_FILES_YT)
|
||||
|
||||
mock_check_exists.assert_not_called() # Should skip check in dry run? No, check should still happen.
|
||||
mock_youtube_service.videos().insert.assert_not_called()
|
||||
mock_youtube_service.thumbnails().set.assert_not_called()
|
||||
finaliser_for_yt.logger.info.assert_any_call(pytest.string_containing("DRY RUN: Would upload"))
|
||||
assert finaliser_for_yt.youtube_video_id is None
|
||||
assert finaliser_for_yt.youtube_url is None
|
||||
@@ -0,0 +1,203 @@
|
||||
import pytest
|
||||
import os
|
||||
import zipfile
|
||||
from unittest.mock import patch, MagicMock, mock_open, call
|
||||
|
||||
# Adjust the import path
|
||||
from karaoke_prep.karaoke_finalise.karaoke_finalise import KaraokeFinalise
|
||||
from .test_initialization import mock_logger, basic_finaliser, MINIMAL_CONFIG # Reuse fixtures
|
||||
from .test_file_input_validation import BASE_NAME, KARAOKE_LRC, INSTRUMENTAL_FLAC # Reuse constants
|
||||
|
||||
# Define expected output filenames for convenience
|
||||
OUTPUT_FILES_ZIP = {
|
||||
"karaoke_mp3": f"{BASE_NAME} (Karaoke).mp3",
|
||||
"karaoke_cdg": f"{BASE_NAME} (Karaoke).cdg",
|
||||
"karaoke_txt": f"{BASE_NAME} (Karaoke).txt",
|
||||
"final_karaoke_cdg_zip": f"{BASE_NAME} (Final Karaoke CDG).zip",
|
||||
"final_karaoke_txt_zip": f"{BASE_NAME} (Final Karaoke TXT).zip",
|
||||
}
|
||||
|
||||
INPUT_FILES_ZIP = {
|
||||
"karaoke_lrc": KARAOKE_LRC,
|
||||
"instrumental_audio": INSTRUMENTAL_FLAC,
|
||||
}
|
||||
|
||||
ARTIST = "Artist"
|
||||
TITLE = "Title"
|
||||
CDG_STYLES_CONFIG = {"style_name": "default"} # Dummy config
|
||||
|
||||
# --- CDG ZIP Creation Tests ---
|
||||
|
||||
@patch('os.path.isfile')
|
||||
@patch('zipfile.ZipFile')
|
||||
@patch('lyrics_transcriber.output.cdg.CDGGenerator')
|
||||
@patch.object(KaraokeFinalise, 'prompt_user_bool', return_value=True) # Confirm overwrite
|
||||
def test_create_cdg_zip_generate_new(mock_prompt, mock_cdg_gen_cls, mock_zipfile, mock_isfile, basic_finaliser):
|
||||
"""Test generating new CDG/MP3 files and zipping."""
|
||||
# Simulate no existing files
|
||||
mock_isfile.return_value = False
|
||||
basic_finaliser.cdg_styles = CDG_STYLES_CONFIG
|
||||
|
||||
# Mock CDGGenerator instance and its method
|
||||
mock_generator_instance = MagicMock()
|
||||
mock_cdg_gen_cls.return_value = mock_generator_instance
|
||||
generated_cdg = "temp_cdg_file.cdg"
|
||||
generated_mp3 = "temp_mp3_file.mp3"
|
||||
generated_zip = "temp_zip_file.zip"
|
||||
mock_generator_instance.generate_cdg_from_lrc.return_value = (generated_cdg, generated_mp3, generated_zip)
|
||||
|
||||
# Mock os.rename and os.path.isfile for the rename check
|
||||
with patch('os.rename') as mock_rename, \
|
||||
patch('os.path.isfile', side_effect=lambda f: f == generated_zip or f == OUTPUT_FILES_ZIP["final_karaoke_cdg_zip"]): # Make zip exist after rename
|
||||
|
||||
basic_finaliser.create_cdg_zip_file(INPUT_FILES_ZIP, OUTPUT_FILES_ZIP, ARTIST, TITLE)
|
||||
|
||||
mock_prompt.assert_called_once_with(f"Found existing CDG ZIP file: {OUTPUT_FILES_ZIP['final_karaoke_cdg_zip']}. Overwrite (y) or skip (n)?")
|
||||
mock_cdg_gen_cls.assert_called_once_with(output_dir=os.getcwd(), logger=basic_finaliser.logger)
|
||||
mock_generator_instance.generate_cdg_from_lrc.assert_called_once_with(
|
||||
lrc_file=INPUT_FILES_ZIP["karaoke_lrc"],
|
||||
audio_file=INPUT_FILES_ZIP["instrumental_audio"],
|
||||
title=TITLE,
|
||||
artist=ARTIST,
|
||||
cdg_styles=CDG_STYLES_CONFIG,
|
||||
)
|
||||
mock_rename.assert_called_once_with(generated_zip, OUTPUT_FILES_ZIP["final_karaoke_cdg_zip"])
|
||||
# Check extraction call
|
||||
mock_zipfile.assert_any_call(OUTPUT_FILES_ZIP["final_karaoke_cdg_zip"], "r")
|
||||
zip_instance_mock = mock_zipfile.return_value.__enter__.return_value
|
||||
zip_instance_mock.extractall.assert_called_once_with()
|
||||
|
||||
|
||||
@patch('os.path.isfile')
|
||||
@patch('zipfile.ZipFile')
|
||||
@patch('lyrics_transcriber.output.cdg.CDGGenerator')
|
||||
@patch.object(KaraokeFinalise, 'prompt_user_bool', return_value=True) # Confirm overwrite
|
||||
def test_create_cdg_zip_use_existing_mp3_cdg(mock_prompt, mock_cdg_gen_cls, mock_zipfile, mock_isfile, basic_finaliser):
|
||||
"""Test creating ZIP from existing MP3 and CDG files."""
|
||||
# Simulate existing MP3 and CDG, but not the final ZIP initially
|
||||
mock_isfile.side_effect = lambda f: f == OUTPUT_FILES_ZIP["karaoke_mp3"] or \
|
||||
f == OUTPUT_FILES_ZIP["karaoke_cdg"] or \
|
||||
f == OUTPUT_FILES_ZIP["final_karaoke_cdg_zip"] # Make zip exist for overwrite check and extraction
|
||||
|
||||
basic_finaliser.create_cdg_zip_file(INPUT_FILES_ZIP, OUTPUT_FILES_ZIP, ARTIST, TITLE)
|
||||
|
||||
mock_prompt.assert_called_once() # Overwrite prompt
|
||||
mock_cdg_gen_cls.assert_not_called() # Should not generate
|
||||
# Check zip creation call
|
||||
mock_zipfile.assert_any_call(OUTPUT_FILES_ZIP["final_karaoke_cdg_zip"], "w")
|
||||
zip_instance_mock = mock_zipfile.return_value.__enter__.return_value
|
||||
zip_instance_mock.write.assert_has_calls([
|
||||
call(OUTPUT_FILES_ZIP["karaoke_mp3"], os.path.basename(OUTPUT_FILES_ZIP["karaoke_mp3"])),
|
||||
call(OUTPUT_FILES_ZIP["karaoke_cdg"], os.path.basename(OUTPUT_FILES_ZIP["karaoke_cdg"])),
|
||||
], any_order=True)
|
||||
# Check extraction call
|
||||
mock_zipfile.assert_any_call(OUTPUT_FILES_ZIP["final_karaoke_cdg_zip"], "r")
|
||||
zip_instance_mock_read = mock_zipfile.return_value.__enter__.return_value
|
||||
zip_instance_mock_read.extractall.assert_called_once_with()
|
||||
|
||||
|
||||
@patch('os.path.isfile', return_value=True) # ZIP exists
|
||||
@patch('zipfile.ZipFile')
|
||||
@patch('lyrics_transcriber.output.cdg.CDGGenerator')
|
||||
@patch.object(KaraokeFinalise, 'prompt_user_bool', return_value=False) # Skip overwrite
|
||||
def test_create_cdg_zip_skip_overwrite(mock_prompt, mock_cdg_gen_cls, mock_zipfile, mock_isfile, basic_finaliser):
|
||||
"""Test skipping CDG ZIP creation if user chooses not to overwrite."""
|
||||
basic_finaliser.create_cdg_zip_file(INPUT_FILES_ZIP, OUTPUT_FILES_ZIP, ARTIST, TITLE)
|
||||
|
||||
mock_prompt.assert_called_once()
|
||||
mock_cdg_gen_cls.assert_not_called()
|
||||
mock_zipfile.assert_not_called() # No zip creation or extraction
|
||||
|
||||
def test_create_cdg_zip_missing_styles(basic_finaliser):
|
||||
"""Test error raised if cdg_styles is missing."""
|
||||
basic_finaliser.cdg_styles = None
|
||||
with patch('os.path.isfile', return_value=False), \
|
||||
pytest.raises(ValueError, match="CDG styles configuration is required"):
|
||||
basic_finaliser.create_cdg_zip_file(INPUT_FILES_ZIP, OUTPUT_FILES_ZIP, ARTIST, TITLE)
|
||||
|
||||
@patch('os.path.isfile', return_value=False) # No existing files
|
||||
@patch('zipfile.ZipFile')
|
||||
@patch('lyrics_transcriber.output.cdg.CDGGenerator')
|
||||
@patch.object(KaraokeFinalise, 'prompt_user_bool', return_value=True)
|
||||
def test_create_cdg_zip_generation_fails_to_create_zip(mock_prompt, mock_cdg_gen_cls, mock_zipfile, mock_isfile, basic_finaliser):
|
||||
"""Test error if CDGGenerator runs but zip isn't found afterwards."""
|
||||
basic_finaliser.cdg_styles = CDG_STYLES_CONFIG
|
||||
mock_generator_instance = MagicMock()
|
||||
mock_cdg_gen_cls.return_value = mock_generator_instance
|
||||
# Simulate generator returning paths but the zip file doesn't actually appear
|
||||
mock_generator_instance.generate_cdg_from_lrc.return_value = ("file.cdg", "file.mp3", "temp.zip")
|
||||
|
||||
with patch('os.rename'), \
|
||||
patch('os.path.isfile', return_value=False), \
|
||||
patch('os.listdir', return_value=[]), \
|
||||
pytest.raises(Exception, match="Failed to create CDG ZIP file"):
|
||||
basic_finaliser.create_cdg_zip_file(INPUT_FILES_ZIP, OUTPUT_FILES_ZIP, ARTIST, TITLE)
|
||||
|
||||
|
||||
# --- TXT ZIP Creation Tests ---
|
||||
|
||||
@patch('os.path.isfile')
|
||||
@patch('zipfile.ZipFile')
|
||||
@patch('lyrics_converter.LyricsConverter')
|
||||
@patch('builtins.open', new_callable=mock_open)
|
||||
@patch.object(KaraokeFinalise, 'prompt_user_bool', return_value=True) # Confirm overwrite
|
||||
def test_create_txt_zip_generate_new(mock_prompt, mock_open_file, mock_lyrics_converter_cls, mock_zipfile, mock_isfile, basic_finaliser):
|
||||
"""Test generating new TXT file and zipping."""
|
||||
# Simulate no existing TXT zip, but MP3 exists (assumed from CDG step)
|
||||
mock_isfile.side_effect = lambda f: f == OUTPUT_FILES_ZIP["karaoke_mp3"] or f == OUTPUT_FILES_ZIP["final_karaoke_txt_zip"]
|
||||
|
||||
# Mock LyricsConverter
|
||||
mock_converter_instance = MagicMock()
|
||||
mock_lyrics_converter_cls.return_value = mock_converter_instance
|
||||
converted_text = "[00:01.00]Line 1\n[00:02.00]Line 2"
|
||||
mock_converter_instance.convert_file.return_value = converted_text
|
||||
|
||||
basic_finaliser.create_txt_zip_file(INPUT_FILES_ZIP, OUTPUT_FILES_ZIP)
|
||||
|
||||
mock_prompt.assert_called_once_with(f"Found existing TXT ZIP file: {OUTPUT_FILES_ZIP['final_karaoke_txt_zip']}. Overwrite (y) or skip (n)?")
|
||||
mock_lyrics_converter_cls.assert_called_once_with(output_format="txt", filepath=INPUT_FILES_ZIP["karaoke_lrc"])
|
||||
mock_converter_instance.convert_file.assert_called_once()
|
||||
# Check TXT file write
|
||||
mock_open_file.assert_called_once_with(OUTPUT_FILES_ZIP["karaoke_txt"], "w")
|
||||
mock_open_file().write.assert_called_once_with(converted_text)
|
||||
# Check zip creation
|
||||
mock_zipfile.assert_called_once_with(OUTPUT_FILES_ZIP["final_karaoke_txt_zip"], "w")
|
||||
zip_instance_mock = mock_zipfile.return_value.__enter__.return_value
|
||||
zip_instance_mock.write.assert_has_calls([
|
||||
call(OUTPUT_FILES_ZIP["karaoke_mp3"], os.path.basename(OUTPUT_FILES_ZIP["karaoke_mp3"])),
|
||||
call(OUTPUT_FILES_ZIP["karaoke_txt"], os.path.basename(OUTPUT_FILES_ZIP["karaoke_txt"])),
|
||||
], any_order=True)
|
||||
|
||||
@patch('os.path.isfile', return_value=True) # ZIP exists
|
||||
@patch('zipfile.ZipFile')
|
||||
@patch('lyrics_converter.LyricsConverter')
|
||||
@patch('builtins.open', new_callable=mock_open)
|
||||
@patch.object(KaraokeFinalise, 'prompt_user_bool', return_value=False) # Skip overwrite
|
||||
def test_create_txt_zip_skip_overwrite(mock_prompt, mock_open_file, mock_lyrics_converter_cls, mock_zipfile, mock_isfile, basic_finaliser):
|
||||
"""Test skipping TXT ZIP creation if user chooses not to overwrite."""
|
||||
basic_finaliser.create_txt_zip_file(INPUT_FILES_ZIP, OUTPUT_FILES_ZIP)
|
||||
|
||||
mock_prompt.assert_called_once()
|
||||
mock_lyrics_converter_cls.assert_not_called()
|
||||
mock_open_file.assert_not_called()
|
||||
mock_zipfile.assert_not_called()
|
||||
|
||||
@patch('os.path.isfile')
|
||||
@patch('zipfile.ZipFile', side_effect=Exception("Zip creation failed")) # Simulate zip error
|
||||
@patch('lyrics_converter.LyricsConverter')
|
||||
@patch('builtins.open', new_callable=mock_open)
|
||||
@patch.object(KaraokeFinalise, 'prompt_user_bool', return_value=True)
|
||||
def test_create_txt_zip_creation_fails(mock_prompt, mock_open_file, mock_lyrics_converter_cls, mock_zipfile, mock_isfile, basic_finaliser):
|
||||
"""Test handling exception during TXT ZIP creation."""
|
||||
mock_isfile.return_value = False # No existing zip
|
||||
mock_converter_instance = MagicMock()
|
||||
mock_lyrics_converter_cls.return_value = mock_converter_instance
|
||||
mock_converter_instance.convert_file.return_value = "text"
|
||||
|
||||
with pytest.raises(Exception, match="Zip creation failed"):
|
||||
basic_finaliser.create_txt_zip_file(INPUT_FILES_ZIP, OUTPUT_FILES_ZIP)
|
||||
|
||||
# Ensure previous steps were attempted
|
||||
mock_lyrics_converter_cls.assert_called_once()
|
||||
mock_open_file.assert_called_once_with(OUTPUT_FILES_ZIP["karaoke_txt"], "w")
|
||||
mock_zipfile.assert_called_once() # Attempted to create zip
|
||||
Reference in new issue
Block a user