def test_sort(self, test_db):
with pytest.raises(TypeError):
test_db.test.find().sort(5)
with pytest.raises(ValueError):
test_db.test.find().sort([])
with pytest.raises(TypeError):
test_db.test.find().sort([], ASCENDING)
with pytest.raises(TypeError):
test_db.test.find().sort([], [('hello', DESCENDING)], DESCENDING)
unsort = list(range(10))
random.shuffle(unsort)
await test_db.test.insert_many([{'x': i} for i in unsort])
asc = [i['x'] for i in await test_db.test.find().sort('x', ASCENDING).to_list()]
assert asc == list(range(10))
asc = [i['x'] for i in await test_db.test.find().sort('x').to_list()]
assert asc == list(range(10))
asc = [i['x'] for i in await test_db.test.find().sort([('x', ASCENDING)]).to_list()]
assert asc == list(range(10))
expect = list(reversed(range(10)))
desc = [i['x'] for i in await test_db.test.find().sort('x', DESCENDING).to_list()]
assert desc == expect
desc = [i['x'] for i in await test_db.test.find().sort([('x', DESCENDING)]).to_list()]
assert desc == expect
desc = [i['x'] for i in
await test_db.test.find().sort('x', ASCENDING).sort('x', DESCENDING).to_list()]
assert desc == expect
expected = [(1, 5), (2, 5), (0, 3), (7, 3), (9, 2), (2, 1), (3, 1)]
shuffled = list(expected)
random.shuffle(shuffled)
await test_db.test.drop()
for (a, b) in shuffled:
await test_db.test.insert_one({'a': a, 'b': b})
result = [(i['a'], i['b']) for i in
await test_db.test.find().sort([('b', DESCENDING),
('a', ASCENDING)]).to_list()]
assert result == expected
a = test_db.test.find()
a.sort('x', ASCENDING)
async for _ in a:
break
with pytest.raises(InvalidOperation):
a.sort('x', ASCENDING)
评论列表
文章目录