Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions audio_processing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down
Empty file added helpers/__init__.py
Empty file.
6 changes: 3 additions & 3 deletions helpers/url_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
2 changes: 2 additions & 0 deletions pytest.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[pytest]
pythonpath = .
4 changes: 2 additions & 2 deletions router.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
Empty file added tests/__init__.py
Empty file.
Empty file added tests/helpers/__init__.py
Empty file.
85 changes: 85 additions & 0 deletions tests/helpers/test_cache_helpers.py
Original file line number Diff line number Diff line change
@@ -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
42 changes: 42 additions & 0 deletions tests/helpers/test_file_helpers.py
Original file line number Diff line number Diff line change
@@ -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'
35 changes: 35 additions & 0 deletions tests/helpers/test_url_helpers.py
Original file line number Diff line number Diff line change
@@ -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") == ""