diff --git a/audio_processing.py b/audio_processing.py index ad0f8ee..27dc493 100644 --- a/audio_processing.py +++ b/audio_processing.py @@ -110,7 +110,7 @@ def detect_ads(transcript): logger.info(ad_segments) return ad_segments - except Expeception as e: + except Exception as e: logger.error("Error in detect_ads (attempt %d/%d): %s", attempt + 1, retries, str(e)) raise @@ -177,9 +177,10 @@ def remove_ads(file_path, ad_segments): duration = len(new_audio) logger.error(duration) - + logger.info(f"filepath: {file_path}") # Save the new audio file file_title = extract_title(file_path) + print(f"file_title={file_title}") new_audio_path = f"{file_title}_no_ads.mp3" new_audio.export(new_audio_path, format="mp3") return new_audio_path diff --git a/helpers/__init__.py b/helpers/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/helpers/url_helpers.py b/helpers/url_helpers.py index a43da01..bd27ce4 100644 --- a/helpers/url_helpers.py +++ b/helpers/url_helpers.py @@ -18,9 +18,9 @@ def extract_name(url): return file_extension # Return only "mp3", "wav", etc. -def extract_title(url): - """Extracts the title from the given URL.""" - base, ext = os.path.splitext(url) +def extract_title(path): + """Extracts the title from the directory path.""" + base, ext = os.path.splitext(path) return base def extract_extension(url): diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000..03f586d --- /dev/null +++ b/pytest.ini @@ -0,0 +1,2 @@ +[pytest] +pythonpath = . \ No newline at end of file diff --git a/router.py b/router.py index 50b01e9..3df8902 100644 --- a/router.py +++ b/router.py @@ -134,8 +134,8 @@ def check_rss(): @audio_bp.route('/cache_test', methods=['POST']) def cache_test(): key = "hei::rss" - source_url = "nei" - rss_url = "nei" + source_url = "rss" + rss_url = "hei" initiate_key(key) diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/helpers/__init__.py b/tests/helpers/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/helpers/test_cache_helpers.py b/tests/helpers/test_cache_helpers.py new file mode 100644 index 0000000..8ccee9f --- /dev/null +++ b/tests/helpers/test_cache_helpers.py @@ -0,0 +1,85 @@ +import pytest +import logging +from unittest.mock import MagicMock, patch +from flask import Flask + +from helpers.cache_helpers import ( + setup_cache, initiate_key, cache_audio, + retrieve_audio, cached_rss_url, cached_source_url +) + +@pytest.fixture +def mock_redis(): + """Creates a mock Redis client.""" + mock = MagicMock() + mock.scan_iter.return_value = iter([]) # Default: No cached data + return mock + + +@pytest.fixture +def mock_app(): + """Creates a mock Flask app.""" + app = Flask(__name__) + return app + +def test_setup_cache(mock_app, mock_redis): + """Test that cache is properly set up.""" + with patch("helpers.cache_helpers.redis_client", mock_redis): + mock_app.config["CACHE_TYPE"] = "simple" # ✅ Use in-memory cache for testing + setup_cache(mock_app, mock_redis) + assert mock_redis is not None # Ensure redis_client is set + + +def test_initiate_key(mock_redis, caplog): + """Test that initiate_key sets a value in Redis.""" + with patch("helpers.cache_helpers.redis_client", mock_redis): + with caplog.at_level(logging.ERROR): + initiate_key("test_key") + mock_redis.set.assert_called_with("test_key", "INIT") # Fix: Ensure this call actually happens + assert "Error initializing key in cache" not in caplog.text + + +def test_cache_audio(mock_redis): + """Test that cache_audio stores the file path in Redis.""" + with patch("helpers.cache_helpers.redis_client", mock_redis): + cache_audio("audio_key", "/path/to/audio.mp3") + mock_redis.set.assert_called_with("audio_key", "/path/to/audio.mp3") + + +def test_retrieve_audio_found(mock_redis): + """Test that retrieve_audio returns the correct path if found.""" + with patch("helpers.cache_helpers.redis_client", mock_redis): + mock_redis.scan_iter.side_effect = lambda pattern: iter(["audio_key"]) + mock_redis.get.return_value = b"/path/to/audio.mp3" + + result = retrieve_audio("audio.mp3") + assert result == b"/path/to/audio.mp3" + + +def test_retrieve_audio_not_found(mock_redis): + """Test that retrieve_audio returns None if not found.""" + with patch("helpers.cache_helpers.redis_client", mock_redis): + mock_redis.scan_iter.return_value = iter([]) + + result = retrieve_audio("audio.mp3") + assert result is None + + +def test_cached_rss_url(mock_redis): + """Test that cached_rss_url checks if an RSS URL is cached.""" + with patch("helpers.cache_helpers.redis_client", mock_redis): + mock_redis.scan_iter.return_value = iter(["rss_url::source_url"]) + assert cached_rss_url("rss_url") is True # rss_url should be found + + mock_redis.scan_iter.return_value = iter([]) + assert cached_rss_url("rss_url") is False + + +def test_cached_source_url(mock_redis): + """Test that cached_source_url checks if a source URL is cached.""" + with patch("helpers.cache_helpers.redis_client", mock_redis): + mock_redis.scan_iter.return_value = iter(["rss_url::source_url"]) + assert cached_source_url("source_url") is True # source_url should be found + + mock_redis.scan_iter.return_value = iter([]) + assert cached_source_url("source_url") is False \ No newline at end of file diff --git a/tests/helpers/test_file_helpers.py b/tests/helpers/test_file_helpers.py new file mode 100644 index 0000000..cdbee4a --- /dev/null +++ b/tests/helpers/test_file_helpers.py @@ -0,0 +1,42 @@ +import os +import pytest +from helpers.file_helpers import allowed_file, save_file, sanitize_filename # Bytt ut "your_module" med riktig filnavn + + +def test_allowed_file(): + """Test allowed_file function with valid and invalid file extensions.""" + allowed_extensions = {"wav", "flacc", "mp3"} + + # Valid file-types + assert allowed_file("image.wav", allowed_extensions) is True + assert allowed_file("audio.mp3", allowed_extensions) is True + + # invalid file-types + assert allowed_file("document.pdf", allowed_extensions) is False + assert allowed_file("script.exe", allowed_extensions) is False + + # files with no extension + assert allowed_file("nofileextension", allowed_extensions) is False + + +def test_save_file(): + """Test that save_file returns the correct file path.""" + upload_folder = "/uploads" + + expected_path = os.path.abspath(os.path.normpath("/uploads/testfile.txt")) + result_path = os.path.abspath(save_file("testfile.txt", upload_folder)) + assert result_path == expected_path + + expected_path = os.path.abspath(os.path.normpath("/uploads/audio.mp3")) + result_path = os.path.abspath(save_file("audio.mp3", upload_folder)) + assert result_path == expected_path +def test_sanitize_filename(): + """Test sanitize_filename function to ensure invalid characters are removed.""" + + # Remove invalid char in files + assert sanitize_filename('test<>file.txt') == 'test__file.txt' + assert sanitize_filename('my|file?.mp3') == 'my_file_.mp3' + + # Not change anything if file name is normal + assert sanitize_filename('normal_file.txt') == 'normal_file.txt' + assert sanitize_filename('audio.mp3') == 'audio.mp3' \ No newline at end of file diff --git a/tests/helpers/test_url_helpers.py b/tests/helpers/test_url_helpers.py new file mode 100644 index 0000000..bbc7659 --- /dev/null +++ b/tests/helpers/test_url_helpers.py @@ -0,0 +1,35 @@ +from helpers.url_helpers import ( + normalize_url, generate_cache_url, + extract_name, extract_title, extract_extension +) + + +def test_normalize_url(): + """Ensures that URLs are normalized to end with .mp3.""" + assert normalize_url("https://example.com/audio.mp3?param=value") == "https://example.com/audio.mp3" + + +def test_generate_cache_url(): + """Tests that the cache URL is generated correctly.""" + assert generate_cache_url("rss_url", "source_url") == "rss_url::source_url" + + +def test_extract_name(): + """Tests that the file extension is extracted correctly from the URL.""" + assert extract_name("https://example.com/audio.mp3") == "mp3" + assert extract_name("https://example.com/path/to/song.wav") == "wav" + assert extract_name("https://example.com/no-extension") == "" + + +def test_extract_title(): + """Tests that the title (filename without extension) is correctly extracted.""" + assert extract_title("./uploads/audio.mp3") == "./uploads/audio" + assert extract_title("./uploads/song.wav") == "./uploads/song" + assert extract_title("./uploads/no-extension") == "./uploads/no-extension" + + +def test_extract_extension(): + """Tests that the file extension is extracted correctly.""" + assert extract_extension("https://example.com/audio.mp3") == ".mp3" + assert extract_extension("https://example.com/song.WAV") == ".wav" + assert extract_extension("https://example.com/no-extension") == "" \ No newline at end of file