From 803f0b52ccb7ee7d79121429c6e0dc4275409df6 Mon Sep 17 00:00:00 2001 From: Chris McCord Date: Tue, 14 Dec 2021 21:07:02 -0500 Subject: [PATCH] Test bad inputs --- lib/live_beats/mp3_stat.ex | 16 ++++++++++++---- test/live_beats/mp3_stat_test.exs | 8 ++++++++ 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/lib/live_beats/mp3_stat.ex b/lib/live_beats/mp3_stat.ex index 8b7e39c..1f788f5 100644 --- a/lib/live_beats/mp3_stat.ex +++ b/lib/live_beats/mp3_stat.ex @@ -36,11 +36,19 @@ defmodule LiveBeats.MP3Stat do def parse(path) do {tag_info, rest} = parse_tag(File.read!(path)) duration = parse_frame(rest, 0, 0, 0) - title = Enum.at(tag_info["TIT2"] || [], 0) - artist = Enum.at(tag_info["TPE1"] || [], 0) - {:ok, - %MP3Stat{duration: round(duration), path: path, tags: tag_info, title: title, artist: artist}} + case duration do + duration when is_float(duration) and duration > 0 -> + title = Enum.at(tag_info["TIT2"] || [], 0) + artist = Enum.at(tag_info["TPE1"] || [], 0) + seconds = round(duration) + + {:ok, + %MP3Stat{duration: seconds, path: path, tags: tag_info, title: title, artist: artist}} + + _other -> + {:error, :bad_file} + end rescue _ -> {:error, :bad_file} end diff --git a/test/live_beats/mp3_stat_test.exs b/test/live_beats/mp3_stat_test.exs index 382095f..63abf10 100644 --- a/test/live_beats/mp3_stat_test.exs +++ b/test/live_beats/mp3_stat_test.exs @@ -9,4 +9,12 @@ defmodule LiveBeats.MP3StatTest do assert stat.title == "Silence" assert stat.artist == "Anon" end + + test "parse/1 with invalid mp3" do + assert {:error, :bad_file} = MP3Stat.parse("mix.exs") + end + + test "parse/1 with missing file" do + assert {:error, :bad_file} = MP3Stat.parse("lsfjslkfjslkfjs") + end end