'Test reading ebook formats using the format() method'

def test_get_formats(self):

    from calibre.library.database2 import LibraryDatabase2
    from calibre.db.cache import NoSuchFormat
    old = LibraryDatabase2(self.library_path)
    ids = old.all_ids()
    lf = {i: (set(old.formats(i, index_is_id=True).split(u',')) if old.formats(i, index_is_id=True) else set()) for i in ids}
    formats = {i: {f: old.format(i, f, index_is_id=True) for f in fmts} for (i, fmts) in lf.iteritems()}
    old.conn.close()
    old = None
    cache = self.init_cache(self.library_path)
    for (book_id, fmts) in lf.iteritems():
        self.assertEqual(fmts, set(cache.formats(book_id)), u'Set    of    formats    is    not    the    same')
        for fmt in fmts:
            old = formats[book_id][fmt]
            self.assertEqual(old, cache.format(book_id, fmt), u'Old    and    new    format    disagree')
            f = cache.format(book_id, fmt, as_file=True)
            self.assertEqual(old, f.read(), u'Failed    to    read    format    as    file')
            with open(cache.format(book_id, fmt, as_path=True, preserve_filename=True), u'rb') as f:
                self.assertEqual(old, f.read(), u'Failed    to    read    format    as    path')
            with open(cache.format(book_id, fmt, as_path=True), u'rb') as f:
                self.assertEqual(old, f.read(), u'Failed    to    read    format    as    path')
    buf = BytesIO()
    self.assertRaises(NoSuchFormat, cache.copy_format_to, 99999, u'X', buf, u'copy_format_to()    failed    to    raise    an    exception    for    non-existent    book')
    self.assertRaises(NoSuchFormat, cache.copy_format_to, 1, u'X', buf, u'copy_format_to()    failed    to    raise    an    exception    for    non-existent    format')
