Skip to content

Commit

Permalink
Error handling for 'filesize' field
Browse files Browse the repository at this point in the history
- Logs a warning and returns 0 if getsize fails
- Add tests for this

Fix #1326
  • Loading branch information
tomjaspers committed Feb 13, 2015
1 parent e1e46df commit 9cdd541
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
9 changes: 8 additions & 1 deletion beets/library.py
Original file line number Diff line number Diff line change
Expand Up @@ -421,7 +421,7 @@ def _getters(cls):
getters = plugins.item_field_getters()
getters['singleton'] = lambda i: i.album_id is None
# Filesize is given in bytes
getters['filesize'] = lambda i: os.path.getsize(syspath(i.path))
getters['filesize'] = lambda i: i.try_filesize()

This comment has been minimized.

Copy link
@sampsyo

sampsyo Feb 14, 2015

Member

Instead of lambda i: i.try_filesize(), Item.try_filesize should work fine. I'll make this tiny change.

This comment has been minimized.

Copy link
@tomjaspers

tomjaspers Feb 14, 2015

Author Contributor

Oh yeah, haha, my bad. Thanks.

return getters

@classmethod
Expand Down Expand Up @@ -605,6 +605,13 @@ def current_mtime(self):
"""
return int(os.path.getmtime(syspath(self.path)))

def try_filesize(self):
try:
return os.path.getsize(syspath(self.path))
except (OSError, Exception) as exc:
log.warning(u'could not get filesize: {0}', exc)
return 0

# Model methods.

def remove(self, delete=False, with_album=True):
Expand Down
16 changes: 16 additions & 0 deletions test/test_library.py
Original file line number Diff line number Diff line change
Expand Up @@ -1172,6 +1172,22 @@ def test_nonexistent_raise_read_error(self):
item.read('/thisfiledoesnotexist')


class FilesizeTest(unittest.TestCase, TestHelper):
def setUp(self):
self.setup_beets()

def tearDown(self):
self.teardown_beets()

def test_filesize(self):
item = self.add_item_fixture()
self.assertNotEquals(item.filesize, 0)

def test_nonexistent_file(self):
item = beets.library.Item()
self.assertEqual(item.filesize, 0)


class ParseQueryTest(unittest.TestCase):
def test_parse_invalid_query_string(self):
with self.assertRaises(beets.dbcore.InvalidQueryError) as raised:
Expand Down

0 comments on commit 9cdd541

Please sign in to comment.