'Test the automatic backup of changed metadata'

def test_backup(self):

    cl = self.cloned_library
    cache = self.init_cache(cl)
    (ae, af, sf) = (self.assertEqual, self.assertFalse, cache.set_field)
    cache.dump_metadata()
    af(cache.dirtied_cache)
    from calibre.db.backup import MetadataBackup
    interval = 0.01
    mb = MetadataBackup(cache, interval=interval, scheduling_interval=0)
    mb.start()
    try:
        ae(sf(u'title', {1: u'title1', 2: u'title2', 3: u'title3'}), {1, 2, 3})
        ae(sf(u'authors', {1: u'author1    &    author2', 2: u'author1    &    author2', 3: u'author1    &    author2'}), {1, 2, 3})
        count = 6
        while (cache.dirty_queue_length() and (count > 0)):
            mb.join(2)
            count -= 1
        af(cache.dirty_queue_length())
    finally:
        mb.stop()
    mb.join(2)
    af(mb.is_alive())
    from calibre.ebooks.metadata.opf2 import OPF
    for book_id in (1, 2, 3):
        raw = cache.read_backup(book_id)
        opf = OPF(BytesIO(raw))
        ae(opf.title, (u'title%d' % book_id))
        ae(opf.authors, [u'author1', u'author2'])
