'Try importing a known good library archive, and verify that the
contents of the library have completely replaced the old contents.'

def test_library_import(self):

    library = LibraryFactory.create(modulestore=self.store)
    lib_key = library.location.library_key
    test_block = ItemFactory.create(category='vertical', parent_location=library.location, user_id=self.user.id, publish_item=False)
    test_block2 = ItemFactory.create(category='vertical', parent_location=library.location, user_id=self.user.id, publish_item=False)
    unchanged_lib = LibraryFactory.create()
    unchanged_key = unchanged_lib.location.library_key
    test_block3 = ItemFactory.create(category='vertical', parent_location=unchanged_lib.location, user_id=self.user.id, publish_item=False)
    test_block4 = ItemFactory.create(category='vertical', parent_location=unchanged_lib.location, user_id=self.user.id, publish_item=False)
    library = self.store.get_library(lib_key)
    children = [self.store.get_item(child).url_name for child in library.children]
    self.assertEqual(len(children), 2)
    self.assertIn(test_block.url_name, children)
    self.assertIn(test_block2.url_name, children)
    unchanged_lib = self.store.get_library(unchanged_key)
    children = [self.store.get_item(child).url_name for child in unchanged_lib.children]
    self.assertEqual(len(children), 2)
    self.assertIn(test_block3.url_name, children)
    self.assertIn(test_block4.url_name, children)
    extract_dir = path(tempfile.mkdtemp(dir=settings.DATA_DIR))
    extract_dir_relative = path.relpath(extract_dir, settings.DATA_DIR)
    try:
        with tarfile.open(((path(TEST_DATA_DIR) / 'imports') / 'library.HhJfPD.tar.gz')) as tar:
            safetar_extractall(tar, extract_dir)
        library_items = import_library_from_xml(self.store, self.user.id, settings.GITHUB_REPO_ROOT, [(extract_dir_relative / 'library')], load_error_modules=False, static_content_store=contentstore(), target_id=lib_key)
    finally:
        shutil.rmtree(extract_dir)
    self.assertEqual(lib_key, library_items[0].location.library_key)
    library = self.store.get_library(lib_key)
    children = [self.store.get_item(child).url_name for child in library.children]
    self.assertEqual(len(children), 3)
    self.assertNotIn(test_block.url_name, children)
    self.assertNotIn(test_block2.url_name, children)
    unchanged_lib = self.store.get_library(unchanged_key)
    children = [self.store.get_item(child).url_name for child in unchanged_lib.children]
    self.assertEqual(len(children), 2)
    self.assertIn(test_block3.url_name, children)
    self.assertIn(test_block4.url_name, children)
