def tearDown(self):
        from invenio_records.api import get_record
        from invenio_search.api import Query
        import time

        # clear cache
        inspire_cache.clear()

        # undo changes in the record
        record = get_record(self.changed_record_id)
        record['references'] = self.old_references
        record['titles'][0]['title'] = self.old_title
        record.commit()

        # make sure changes have been applied to ES and all citation_counts have been recalculated
        timeout = 15  # [seconds]
        timeout_start = time.time()
        while time.time() < timeout_start + timeout:
            es_record = Query('control_number:' + self.changed_record_id).search().records().pop()
            references = [unicode(ref['recid']) for ref in es_record['references'] if ref.get('recid')]
            title = es_record['titles'][0]['title']

            if self.removed_reference in references \
                    and self.added_reference not in references \
                    and title == self.old_title:
                break
            else:
                time.sleep(1)

        update_citation_count_for_records.delay([int(self.removed_reference), int(self.added_reference)])

        # make sure citation_counts have been updated
        time.sleep(4)
    def tearDown(self):
        from invenio_ext.es import es
        self._transaction.rollback()
        es.delete(index='hep', doc_type='record', id=self.new_recid)

        # we need to make sure the new record has been deleted from elasticsearch
        timeout = 15  # [seconds]
        timeout_start = time.time()
        while time.time() < timeout_start + timeout:
            if len(Query('control_number:' + self.new_recid).search()) == 0:
                break
            else:
                time.sleep(1)
        update_citation_count_for_records.delay(self.expected_citation_counts_after_insert.keys())
    def tearDown(self):
        from invenio_search.api import Query
        from invenio_records.api import get_record

        record = get_record(recid=self.test_recid)
        record['references'] = self.references_before_update
        record.commit()

        # we need to make sure the record has been already restored to initial state also in es
        timeout = 15  # [seconds]
        timeout_start = time.time()
        while time.time() < timeout_start + timeout:
            es_record = Query('control_number:' + self.test_recid).search().records().pop()
            references = [ref['recid'] for ref in es_record['references'] if ref.get('recid')]

            if self.removed_reference_recid in references:
                break
            else:
                time.sleep(1)

        update_citation_count_for_records.delay([self.removed_reference_recid])