MCPcopy Index your code
hub / github.com/mongodb/mongo-python-driver / test_sort

Method test_sort

test/test_cursor.py:766–819  ·  view source on GitHub ↗
(self)

Source from the content-addressed store, hash-verified

764 self.assertRaises(InvalidOperation, a.skip, 5)
765
766 def test_sort(self):
767 db = self.db
768
769 with self.assertRaises(TypeError):
770 db.test.find().sort(5) # type: ignore[arg-type]
771 with self.assertRaises(ValueError):
772 db.test.find().sort([]) # type: ignore[arg-type]
773 with self.assertRaises(TypeError):
774 db.test.find().sort([], ASCENDING) # type: ignore[arg-type]
775 with self.assertRaises(TypeError):
776 db.test.find().sort([("hello", DESCENDING)], DESCENDING) # type: ignore[arg-type]
777
778 db.test.drop()
779
780 unsort = list(range(10))
781 random.shuffle(unsort)
782
783 db.test.insert_many([{"x": i} for i in unsort])
784
785 asc = [i["x"] for i in db.test.find().sort("x", ASCENDING)]
786 self.assertEqual(asc, list(range(10)))
787 asc = [i["x"] for i in db.test.find().sort("x")]
788 self.assertEqual(asc, list(range(10)))
789 asc = [i["x"] for i in db.test.find().sort([("x", ASCENDING)])]
790 self.assertEqual(asc, list(range(10)))
791
792 expect = list(reversed(range(10)))
793 desc = [i["x"] for i in db.test.find().sort("x", DESCENDING)]
794 self.assertEqual(desc, expect)
795 desc = [i["x"] for i in db.test.find().sort([("x", DESCENDING)])]
796 self.assertEqual(desc, expect)
797 desc = [i["x"] for i in db.test.find().sort("x", ASCENDING).sort("x", DESCENDING)]
798 self.assertEqual(desc, expect)
799
800 expected = [(1, 5), (2, 5), (0, 3), (7, 3), (9, 2), (2, 1), (3, 1)]
801 shuffled = list(expected)
802 random.shuffle(shuffled)
803
804 db.test.drop()
805 for a, b in shuffled:
806 db.test.insert_one({"a": a, "b": b})
807
808 result = [
809 (i["a"], i["b"]) for i in db.test.find().sort([("b", DESCENDING), ("a", ASCENDING)])
810 ]
811 self.assertEqual(result, expected)
812 result = [(i["a"], i["b"]) for i in db.test.find().sort([("b", DESCENDING), "a"])]
813 self.assertEqual(result, expected)
814
815 a = db.test.find()
816 a.sort("x", ASCENDING)
817 for _ in a:
818 break
819 self.assertRaises(InvalidOperation, a.sort, "x", ASCENDING)
820
821 def test_where(self):
822 db = self.db

Callers

nothing calls this directly

Calls 5

sortMethod · 0.45
findMethod · 0.45
dropMethod · 0.45
insert_manyMethod · 0.45
insert_oneMethod · 0.45

Tested by

no test coverage detected