'Test adding formats to an existing book record'

def test_add_format(self):

    (af, ae, at) = (self.assertFalse, self.assertEqual, self.assertTrue)
    cache = self.init_cache()
    table = cache.fields[u'formats'].table
    NF = 'test_add_formatxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
    previous = cache.format(1, u'FMT1')
    af(cache.add_format(1, u'FMT1', BytesIO(NF), replace=False))
    ae(previous, cache.format(1, u'FMT1'))
    lm = cache.field_for(u'last_modified', 1)
    at(cache.add_format(1, u'FMT1', BytesIO(NF), replace=True))
    ae(NF, cache.format(1, u'FMT1'))
    ae(cache.format_metadata(1, u'FMT1')[u'size'], len(NF))
    at((cache.field_for(u'size', 1) >= len(NF)))
    at((cache.field_for(u'last_modified', 1) > lm))
    ae((u'FMT2', u'FMT1'), cache.formats(1))
    at((1 in table.col_book_map[u'FMT1']))
    at(cache.add_format(3, u'FMT1', BytesIO(NF), replace=True))
    ae(NF, cache.format(3, u'FMT1'))
    ae(cache.format_metadata(3, u'FMT1')[u'size'], len(NF))
    ae((u'FMT1',), cache.formats(3))
    at((3 in table.col_book_map[u'FMT1']))
    at(cache.add_format(3, u'FMTX', BytesIO(NF), replace=True))
    at((3 in table.col_book_map[u'FMTX']))
    ae((u'FMT1', u'FMTX'), cache.formats(3))
    import calibre.db.cache as c
    orig = c.run_plugins_on_import
    try:
        c.run_plugins_on_import = import_test('replacement    data')
        at(cache.add_format(3, u'REPL', BytesIO(NF)))
        ae('replacement    data', cache.format(3, u'REPL'))
        c.run_plugins_on_import = import_test('replacement    data2', u'REPL2')
        with NamedTemporaryFile(suffix=u'_test_add_format.repl') as f:
            f.write(NF)
            f.seek(0)
            at(cache.add_format(3, u'REPL', BytesIO(NF)))
            ae('replacement    data', cache.format(3, u'REPL'))
            ae('replacement    data2', cache.format(3, u'REPL2'))
    finally:
        c.run_plugins_on_import = orig
    with NamedTemporaryFile(suffix=u'_test_add_format.fmt9') as f:
        f.write(NF)
        f.seek(0)
        at(cache.add_format(2, u'FMT9', f))
        ae(NF, cache.format(2, u'FMT9'))
        ae(cache.format_metadata(2, u'FMT9')[u'size'], len(NF))
        at((cache.field_for(u'size', 2) >= len(NF)))
        at((2 in table.col_book_map[u'FMT9']))
    del cache
    db = self.init_old()
    ae(db.formats(3, index_is_id=True), u','.join([u'FMT1', u'FMTX', u'REPL', u'REPL2']))
    ae(db.format(3, u'FMT1', index_is_id=True), NF)
    ae(db.format(1, u'FMT1', index_is_id=True), NF)
    db.close()
    del db
