Replace all mentions of 'str' with 'bytes'

This commit is contained in:
Bruno Cauet 2015-01-20 12:48:15 +01:00
parent 9c41c39913
commit 02d8e88ef1
33 changed files with 65 additions and 63 deletions

View file

@ -112,7 +112,7 @@ class AlbumInfo(object):
'catalognum', 'script', 'language', 'country',
'albumstatus', 'albumdisambig', 'artist_credit', 'media']:
value = getattr(self, fld)
if isinstance(value, str):
if isinstance(value, bytes):
setattr(self, fld, value.decode(codec, 'ignore'))
if self.tracks:
@ -171,7 +171,7 @@ class TrackInfo(object):
for fld in ['title', 'artist', 'medium', 'artist_sort', 'disctitle',
'artist_credit', 'media']:
value = getattr(self, fld)
if isinstance(value, str):
if isinstance(value, bytes):
setattr(self, fld, value.decode(codec, 'ignore'))

View file

@ -407,7 +407,7 @@ def tag_album(items, search_artist=None, search_album=None,
if id_info:
_add_candidate(items, candidates, id_info)
rec = _recommendation(candidates.values())
log.debug(u'Album ID match recommendation is {0}', str(rec))
log.debug(u'Album ID match recommendation is {0}', rec)
if candidates and not config['import']['timid']:
# If we have a very good MBID match, return immediately.
# Otherwise, this match will compete against metadata-based
@ -426,7 +426,7 @@ def tag_album(items, search_artist=None, search_album=None,
va_likely = ((not consensus['artist']) or
(search_artist.lower() in VA_ARTISTS) or
any(item.comp for item in items))
log.debug(u'Album might be VA: {0}', str(va_likely))
log.debug(u'Album might be VA: {0}', va_likely)
# Get the results from the data sources.
search_cands = hooks.album_candidates(items, search_artist,

View file

@ -319,7 +319,7 @@ def match_album(artist, album, tracks=None):
# Various Artists search.
criteria['arid'] = VARIOUS_ARTISTS_ID
if tracks is not None:
criteria['tracks'] = str(tracks)
criteria['tracks'] = bytes(tracks)
# Abort if we have no search terms.
if not any(criteria.itervalues()):

View file

@ -181,7 +181,7 @@ class BooleanQuery(MatchQuery):
class BytesQuery(MatchQuery):
"""Match a raw bytes field (i.e., a path). This is a necessary hack
to work around the `sqlite3` module's desire to treat `str` and
to work around the `sqlite3` module's desire to treat `bytes` and
`unicode` equivalently in Python 2. Always use this query instead of
`MatchQuery` when matching on BLOB values.
"""
@ -426,7 +426,7 @@ class Period(object):
precision (a string, one of "year", "month", or "day").
"""
if precision not in Period.precisions:
raise ValueError('Invalid precision ' + str(precision))
raise ValueError('Invalid precision {0}'.format(precision))
self.date = date
self.precision = precision
@ -466,7 +466,7 @@ class Period(object):
elif 'day' == precision:
return date + timedelta(days=1)
else:
raise ValueError('unhandled precision ' + str(precision))
raise ValueError('unhandled precision {0}'.format(precision))
class DateInterval(object):

View file

@ -121,7 +121,7 @@ class PathType(types.Type):
return self.normalize(sql_value)
def to_sql(self, value):
if isinstance(value, str):
if isinstance(value, bytes):
value = buffer(value)
return value
@ -410,7 +410,7 @@ class Item(LibModel):
if isinstance(value, unicode):
value = bytestring_path(value)
elif isinstance(value, buffer):
value = str(value)
value = bytes(value)
if key in MediaFile.fields():
self.mtime = 0 # Reset mtime on dirty.
@ -513,7 +513,7 @@ class Item(LibModel):
self.write(path)
return True
except FileOperationError as exc:
log.error(str(exc))
log.error("{0}", exc)
return False
def try_sync(self, write=None):

View file

@ -144,7 +144,7 @@ def _safe_cast(out_type, val):
return False
elif out_type == unicode:
if isinstance(val, str):
if isinstance(val, bytes):
return val.decode('utf8', 'ignore')
elif isinstance(val, unicode):
return val
@ -450,7 +450,7 @@ class StorageStyle(object):
if isinstance(value, bool):
# Store bools as 1/0 instead of True/False.
value = unicode(int(bool(value)))
elif isinstance(value, str):
elif isinstance(value, bytes):
value = value.decode('utf8', 'ignore')
else:
value = unicode(value)
@ -738,7 +738,7 @@ class MP3DescStorageStyle(MP3StorageStyle):
# need to make a new frame?
if not found:
frame = mutagen.id3.Frames[self.key](
desc=str(self.description),
desc=bytes(self.description),
text=value,
encoding=3
)
@ -811,7 +811,7 @@ class MP3ImageStorageStyle(ListStorageStyle, MP3StorageStyle):
"""
def __init__(self):
super(MP3ImageStorageStyle, self).__init__(key='APIC')
self.as_type = str
self.as_type = bytes
def deserialize(self, apic_frame):
"""Convert APIC frame into Image."""
@ -880,7 +880,7 @@ class VorbisImageStorageStyle(ListStorageStyle):
super(VorbisImageStorageStyle, self).__init__(
key='metadata_block_picture'
)
self.as_type = str
self.as_type = bytes
def fetch(self, mutagen_file):
images = []

View file

@ -219,11 +219,11 @@ def input_options(options, require=False, prompt=None, fallback_prompt=None,
prompt_part_lengths = []
if numrange:
if isinstance(default, int):
default_name = str(default)
default_name = unicode(default)
default_name = colorize('turquoise', default_name)
tmpl = '# selection (default %s)'
prompt_parts.append(tmpl % default_name)
prompt_part_lengths.append(len(tmpl % str(default)))
prompt_part_lengths.append(len(tmpl % unicode(default)))
else:
prompt_parts.append('# selection')
prompt_part_lengths.append(len(prompt_parts[-1]))

View file

@ -312,7 +312,7 @@ def _fsencoding():
def bytestring_path(path):
"""Given a path, which is either a str or a unicode, returns a str
"""Given a path, which is either a bytes or a unicode, returns a str
path (ensuring that we never deal with Unicode pathnames).
"""
# Pass through bytestrings.

View file

@ -43,7 +43,7 @@ def resize_url(url, maxwidth):
"""
return '{0}?{1}'.format(PROXY_URL, urllib.urlencode({
'url': url.replace('http://', ''),
'w': str(maxwidth),
'w': bytes(maxwidth),
}))

View file

@ -553,7 +553,7 @@ def spawn(coro):
and child coroutines run concurrently.
"""
if not isinstance(coro, types.GeneratorType):
raise ValueError('%s is not a coroutine' % str(coro))
raise ValueError('%s is not a coroutine' % coro)
return SpawnEvent(coro)
@ -563,7 +563,7 @@ def call(coro):
returns a value using end(), then this event returns that value.
"""
if not isinstance(coro, types.GeneratorType):
raise ValueError('%s is not a coroutine' % str(coro))
raise ValueError('%s is not a coroutine' % coro)
return DelegationEvent(coro)

View file

@ -247,7 +247,7 @@ class ConfigView(object):
def __str__(self):
"""Gets the value for this view as a byte string."""
return str(self.get())
return bytes(self.get())
def __unicode__(self):
"""Gets the value for this view as a unicode string. (Python 2

View file

@ -89,7 +89,7 @@ class GstPlayer(object):
# error
self.player.set_state(gst.STATE_NULL)
err, debug = message.parse_error()
print("Error: " + str(err))
print("Error: {0}".format(err))
self.playing = False
def _set_volume(self, volume):

View file

@ -133,9 +133,9 @@ def str2fmt(s):
def format_span(fmt, yearfrom, yearto, fromnchars, tonchars):
"""Return a span string representation.
"""
args = (str(yearfrom)[-fromnchars:])
args = (bytes(yearfrom)[-fromnchars:])
if tonchars:
args = (str(yearfrom)[-fromnchars:], str(yearto)[-tonchars:])
args = (bytes(yearfrom)[-fromnchars:], bytes(yearto)[-tonchars:])
return fmt % args

View file

@ -64,7 +64,7 @@ def acoustid_match(log, path):
duration, fp = acoustid.fingerprint_file(util.syspath(path))
except acoustid.FingerprintGenerationError as exc:
log.error(u'fingerprinting of {0} failed: {1}',
util.displayable_path(repr(path)), str(exc))
util.displayable_path(repr(path)), exc)
return None
_fingerprints[path] = fp
try:

View file

@ -65,7 +65,7 @@ def get_format(format=None):
.format(format)
)
except ConfigTypeError:
command = config['convert']['formats'][format].get(str)
command = config['convert']['formats'][format].get(bytes)
extension = format
# Convenience and backwards-compatibility shortcuts.

View file

@ -87,7 +87,7 @@ def _group_by(objs, keys, log):
counts[key].append(obj)
else:
log.debug(u'{0}: all keys {1} on item {2} are null: skipping',
PLUGIN, str(keys), displayable_path(obj.path))
PLUGIN, keys, displayable_path(obj.path))
return counts

View file

@ -107,8 +107,8 @@ def fetch_tracks(user, page, limit):
'method': 'library.gettracks',
'user': user,
'api_key': plugins.LASTFM_KEY,
'page': str(page),
'limit': str(limit),
'page': bytes(page),
'limit': bytes(limit),
'format': 'json',
}).json()

View file

@ -56,7 +56,7 @@ URL_CHARACTERS = {
def unescape(text):
"""Resolves &#xxx; HTML entities (and some others)."""
if isinstance(text, str):
if isinstance(text, bytes):
text = text.decode('utf8', 'ignore')
out = text.replace(u' ', u' ')

View file

@ -16,7 +16,7 @@ def convert_perm(perm):
to an oct int. Else it just converts it to oct.
"""
if isinstance(perm, int):
return int(str(perm), 8)
return int(bytes(perm), 8)
else:
return int(perm, 8)

View file

@ -179,7 +179,7 @@ class CommandBackend(Backend):
# Disable clipping warning.
cmd = cmd + ['-c']
cmd = cmd + ['-a' if is_album else '-r']
cmd = cmd + ['-d', str(self.gain_offset)]
cmd = cmd + ['-d', bytes(self.gain_offset)]
cmd = cmd + [syspath(i.path) for i in items]
self._log.debug(u'analyzing {0} files', len(items))

View file

@ -277,7 +277,7 @@ def prep():
# FIXME It should be possible to specify this as an argument.
version_parts = [int(n) for n in cur_version.split('.')]
version_parts[-1] += 1
next_version = '.'.join(map(str, version_parts))
next_version = u'.'.join(map(unicode, version_parts))
bump_version(next_version)

View file

@ -75,7 +75,7 @@ def item(lib=None):
comments=u'the comments',
bpm=8,
comp=True,
path='somepath' + str(_item_ident),
path='somepath{0}'.format(_item_ident),
length=60.0,
bitrate=128000,
format='FLAC',

View file

@ -62,7 +62,7 @@ class LogCapture(logging.Handler):
self.messages = []
def emit(self, record):
self.messages.append(str(record.msg))
self.messages.append(unicode(record.msg))
@contextmanager
@ -326,7 +326,7 @@ class TestHelper(object):
items = []
path = os.path.join(_common.RSRC, 'full.' + ext)
for i in range(count):
item = Item.from_path(str(path))
item = Item.from_path(bytes(path))
item.album = u'\u00e4lbum {0}'.format(i) # Check unicode paths
item.title = u't\u00eftle {0}'.format(i)
item.add(self.lib)
@ -341,7 +341,7 @@ class TestHelper(object):
items = []
path = os.path.join(_common.RSRC, 'full.' + ext)
for i in range(track_count):
item = Item.from_path(str(path))
item = Item.from_path(bytes(path))
item.album = u'\u00e4lbum' # Check unicode paths
item.title = u't\u00eftle {0}'.format(i)
item.add(self.lib)

View file

@ -572,7 +572,7 @@ class AssignmentTest(unittest.TestCase):
return Item(
artist=u'ben harper',
album=u'burn to shine',
title=u'ben harper - Burn to Shine ' + str(i),
title=u'ben harper - Burn to Shine {0}'.format(i),
track=i,
length=length,
mb_trackid='', mb_albumid='', mb_artistid='',

View file

@ -106,7 +106,7 @@ class ConfigCommandTest(unittest.TestCase, TestHelper):
execlp.side_effect = OSError()
self.run_command('config', '-e')
self.assertIn('Could not edit configuration',
str(user_error.exception.args[0]))
unicode(user_error.exception.args[0]))
def test_edit_invalid_config_file(self):
self.lib = Library(':memory:')

View file

@ -924,22 +924,22 @@ class PathStringTest(_common.TestCase):
self.i = item(self.lib)
def test_item_path_is_bytestring(self):
self.assert_(isinstance(self.i.path, str))
self.assert_(isinstance(self.i.path, bytes))
def test_fetched_item_path_is_bytestring(self):
i = list(self.lib.items())[0]
self.assert_(isinstance(i.path, str))
self.assert_(isinstance(i.path, bytes))
def test_unicode_path_becomes_bytestring(self):
self.i.path = u'unicodepath'
self.assert_(isinstance(self.i.path, str))
self.assert_(isinstance(self.i.path, bytes))
def test_unicode_in_database_becomes_bytestring(self):
self.lib._connection().execute("""
update items set path=? where id=?
""", (self.i.id, u'somepath'))
i = list(self.lib.items())[0]
self.assert_(isinstance(i.path, str))
self.assert_(isinstance(i.path, bytes))
def test_special_chars_preserved_in_database(self):
path = 'b\xe1r'.encode('utf8')
@ -960,13 +960,13 @@ class PathStringTest(_common.TestCase):
def test_destination_returns_bytestring(self):
self.i.artist = u'b\xe1r'
dest = self.i.destination()
self.assert_(isinstance(dest, str))
self.assert_(isinstance(dest, bytes))
def test_art_destination_returns_bytestring(self):
self.i.artist = u'b\xe1r'
alb = self.lib.add_album([self.i])
dest = alb.art_destination(u'image.jpg')
self.assert_(isinstance(dest, str))
self.assert_(isinstance(dest, bytes))
def test_artpath_stores_special_chars(self):
path = b'b\xe1r'
@ -989,7 +989,7 @@ class PathStringTest(_common.TestCase):
def test_unicode_artpath_becomes_bytestring(self):
alb = self.lib.add_album([self.i])
alb.artpath = u'somep\xe1th'
self.assert_(isinstance(alb.artpath, str))
self.assert_(isinstance(alb.artpath, bytes))
def test_unicode_artpath_in_database_decoded(self):
alb = self.lib.add_album([self.i])
@ -998,7 +998,7 @@ class PathStringTest(_common.TestCase):
(u'somep\xe1th', alb.id)
)
alb = self.lib.get_album(alb.id)
self.assert_(isinstance(alb.artpath, str))
self.assert_(isinstance(alb.artpath, bytes))
class PathTruncationTest(_common.TestCase):

View file

@ -65,7 +65,7 @@ class MBAlbumInfoTest(_common.TestCase):
for i, recording in enumerate(tracks):
track = {
'recording': recording,
'position': str(i + 1),
'position': bytes(i + 1),
}
if track_length:
# Track lengths are distinct from recording lengths.

View file

@ -340,12 +340,14 @@ class ExtendedFieldTestMixin(object):
def test_invalid_descriptor(self):
with self.assertRaises(ValueError) as cm:
MediaFile.add_field('somekey', True)
self.assertIn('must be an instance of MediaField', str(cm.exception))
self.assertIn('must be an instance of MediaField',
unicode(cm.exception))
def test_overwrite_property(self):
with self.assertRaises(ValueError) as cm:
MediaFile.add_field('artist', MediaField())
self.assertIn('property "artist" already exists', str(cm.exception))
self.assertIn('property "artist" already exists',
unicode(cm.exception))
class ReadWriteTestBase(ArtTestMixin, GenreListTestMixin,

View file

@ -292,7 +292,7 @@ class ID3v23Test(unittest.TestCase, TestHelper):
mf.year = 2013
mf.save()
frame = mf.mgfile['TDRC']
self.assertTrue('2013' in str(frame))
self.assertTrue('2013' in unicode(frame))
self.assertTrue('TYER' not in mf.mgfile)
finally:
self._delete_test()
@ -303,7 +303,7 @@ class ID3v23Test(unittest.TestCase, TestHelper):
mf.year = 2013
mf.save()
frame = mf.mgfile['TYER']
self.assertTrue('2013' in str(frame))
self.assertTrue('2013' in unicode(frame))
self.assertTrue('TDRC' not in mf.mgfile)
finally:
self._delete_test()

View file

@ -281,12 +281,12 @@ class GetTest(DummyDataTestCase):
def test_invalid_query(self):
with self.assertRaises(InvalidQueryError) as raised:
dbcore.query.NumericQuery('year', '199a')
self.assertIn('not an int', str(raised.exception))
self.assertIn('not an int', unicode(raised.exception))
with self.assertRaises(InvalidQueryError) as raised:
dbcore.query.RegexpQuery('year', '199(')
self.assertIn('not a regular expression', str(raised.exception))
self.assertIn('unbalanced parenthesis', str(raised.exception))
self.assertIn('not a regular expression', unicode(raised.exception))
self.assertIn('unbalanced parenthesis', unicode(raised.exception))
class MatchTest(_common.TestCase):

View file

@ -47,7 +47,7 @@ class SpotifyPluginTest(_common.TestCase, TestHelper):
@responses.activate
def test_missing_request(self):
response_body = str(
response_body = bytes(
'{'
'"tracks" : {'
'"href" : "https://api.spotify.com/v1/search?query=duifhjslkef'
@ -83,7 +83,7 @@ class SpotifyPluginTest(_common.TestCase, TestHelper):
@responses.activate
def test_track_request(self):
response_body = str(
response_body = bytes(
'{'
'"tracks" : {'
'"href" : "https://api.spotify.com/v1/search?query=Happy+album%3A'

View file

@ -650,7 +650,7 @@ class ConfigTest(unittest.TestCase, TestHelper):
ui._raw_main(['test'])
replacements = self.test_cmd.lib.replacements
self.assertEqual(replacements, [(re.compile(ur'[xy]'), u'z')])
self.assertEqual(replacements, [(re.compile(r'[xy]'), b'z')])
def test_multiple_replacements_parsed(self):
with self.write_config_file() as config:
@ -659,8 +659,8 @@ class ConfigTest(unittest.TestCase, TestHelper):
ui._raw_main(['test'])
replacements = self.test_cmd.lib.replacements
self.assertEqual(replacements, [
(re.compile(ur'[xy]'), u'z'),
(re.compile(ur'foo'), u'bar'),
(re.compile(r'[xy]'), 'z'),
(re.compile(r'foo'), 'bar'),
])
def test_cli_config_option(self):

View file

@ -67,7 +67,7 @@ class TestTerminalImportSession(TerminalImportSession):
self.io.addinput('S')
elif isinstance(choice, int):
self.io.addinput('M')
self.io.addinput(str(choice))
self.io.addinput(unicode(choice))
self._add_choice_input()
else:
raise Exception('Unknown choice %s' % choice)