'Test that DocManagers have proper state after a chunk migration
that resuts in orphaned documents.'

def test_with_orphan_documents(self):

    self.opman1.start()
    self.opman2.start()
    collection = self.mongos_conn['test']['mcsharded']
    collection.insert_many([{'i': (i + 500)} for i in range(1000)])
    self.assertEqual(self.shard1_conn['test']['mcsharded'].find().count(), 500)
    self.assertEqual(self.shard2_conn['test']['mcsharded'].find().count(), 500)
    assert_soon((lambda : (len(self.opman1.doc_managers[0]._search()) == 1000)))
    self.shard1_conn.admin.command('configureFailPoint', 'rsSyncApplyStop', mode='alwaysOn')
    def move_chunk():
        try:
            self.mongos_conn['admin'].command('moveChunk', 'test.mcsharded', find={'i': 1000}, to='demo-set-0')
        except pymongo.errors.OperationFailure:
            pass
    mover = threading.Thread(target=move_chunk)
    mover.start()
    assert_soon((lambda : (self.shard1_conn.test.mcsharded.count() > 500)))
    operations = self.mongos_conn.test.current_op()
    opid = None
    for op in operations['inprog']:
        if op.get('query', {}).get('moveChunk'):
            opid = op['opid']
    if (opid is None):
        raise SkipTest('could    not    find    moveChunk    operation,    cannot    test    failed    moveChunk')
    if (self.mongos_conn.server_info()['versionArray'][:3] >= [3, 1, 2]):
        self.mongos_conn.admin.command('killOp', op=opid)
    else:
        self.mongos_conn['test']['$cmd.sys.killop'].find_one({'op': opid})
    docs = self.opman1.doc_managers[0]._search()
    self.assertEqual(len(docs), 1000)
    self.assertEqual(sorted((d['i'] for d in docs)), list(range(500, 1500)))
    self.shard1_conn.admin.command('configureFailPoint', 'rsSyncApplyStop', mode='off')
    mover.join()
