'Test fixing of databases that have items in is_many fields that differ only by case'

def test_fix_case_duplicates(self):

    ae = self.assertEqual
    cache = self.init_cache()
    conn = cache.backend.conn
    conn.execute(u'INSERT    INTO    publishers    (name)    VALUES    ("m\u016bs")')
    lid = conn.last_insert_rowid()
    conn.execute(u'INSERT    INTO    publishers    (name)    VALUES    ("M\u016aS")')
    uid = conn.last_insert_rowid()
    conn.execute(u'DELETE    FROM    books_publishers_link')
    conn.execute((u'INSERT    INTO    books_publishers_link    (book,publisher)    VALUES    (1,    %d)' % lid))
    conn.execute((u'INSERT    INTO    books_publishers_link    (book,publisher)    VALUES    (2,    %d)' % uid))
    conn.execute((u'INSERT    INTO    books_publishers_link    (book,publisher)    VALUES    (3,    %d)' % uid))
    cache.reload_from_db()
    t = cache.fields[u'publisher'].table
    for x in (lid, uid):
        self.assertIn(x, t.id_map)
        self.assertIn(x, t.col_book_map)
    ae(t.book_col_map[1], lid)
    ae(t.book_col_map[2], uid)
    t.fix_case_duplicates(cache.backend)
    for c in (cache, self.init_cache()):
        t = c.fields[u'publisher'].table
        self.assertNotIn(uid, t.id_map)
        self.assertNotIn(uid, t.col_book_map)
        for bid in (1, 2, 3):
            ae(c.field_for(u'publisher', bid), u'm\u016bs')
        c.close()
    cache = self.init_cache()
    conn = cache.backend.conn
    conn.execute(u'INSERT    INTO    tags    (name)    VALUES    ("m\u016b\u016bs")')
    lid = conn.last_insert_rowid()
    conn.execute(u'INSERT    INTO    tags    (name)    VALUES    ("M\u016a\u016aS")')
    uid = conn.last_insert_rowid()
    conn.execute(u'INSERT    INTO    tags    (name)    VALUES    ("m\u016b\u016aS")')
    mid = conn.last_insert_rowid()
    conn.execute(u'INSERT    INTO    tags    (name)    VALUES    ("t")')
    norm = conn.last_insert_rowid()
    conn.execute(u'DELETE    FROM    books_tags_link')
    for (book_id, vals) in {1: (lid, uid), 2: (uid, mid), 3: (lid, norm)}.iteritems():
        conn.executemany(u'INSERT    INTO    books_tags_link    (book,tag)    VALUES    (?,?)', tuple(((book_id, x) for x in vals)))
    cache.reload_from_db()
    t = cache.fields[u'tags'].table
    for x in (lid, uid, mid):
        self.assertIn(x, t.id_map)
        self.assertIn(x, t.col_book_map)
    t.fix_case_duplicates(cache.backend)
    for c in (cache, self.init_cache()):
        t = c.fields[u'tags'].table
        for x in (uid, mid):
            self.assertNotIn(x, t.id_map)
            self.assertNotIn(x, t.col_book_map)
        ae(c.field_for(u'tags', 1), (t.id_map[lid],))
        ae(c.field_for(u'tags', 2), (t.id_map[lid],), u'failed    for    book    2')
        ae(c.field_for(u'tags', 3), (t.id_map[lid], t.id_map[norm]))
