Skip to content

Commit 30d1f9d

Browse files
committed
PYTHON-4834 Add __repr__ to IndexModel
- Fix __repr__ and test - use assertRepr function from test_connection_monitoring
1 parent ca90e39 commit 30d1f9d

File tree

2 files changed

+16
-5
lines changed

2 files changed

+16
-5
lines changed

pymongo/operations.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -774,7 +774,12 @@ def document(self) -> dict[str, Any]:
774774
return self.__document
775775

776776
def __repr__(self) -> str:
777-
return f"{self.__class__.__name__}({self.document})"
777+
return "%s(%s%s%s)" % (
778+
self.__class__.__name__,
779+
"" if not self.document.get("name") else "name='%s'" % self.document["name"],
780+
"" if not self.document.get("key") else ", keys=%s" % self.document["key"],
781+
"" if not self.document.get("unique") else ", unique='%s'" % self.document["unique"],
782+
)
778783

779784

780785
class SearchIndexModel:

test/test_collection.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2253,10 +2253,16 @@ def afind(*args, **kwargs):
22532253
for helper, args in helpers:
22542254
helper(*args, let={}) # type: ignore
22552255

2256-
def test_repr(self):
2257-
im = IndexModel("hello")
2258-
self.assertEqual(im.__repr__(), f"{im.__class__.__name__}({im.document})")
2259-
2256+
def assertRepr(self, obj):
2257+
new_obj = eval(repr(obj))
2258+
self.assertEqual(type(new_obj), type(obj))
2259+
self.assertEqual(repr(new_obj), repr(obj))
2260+
2261+
def test_index_model_repr(self):
2262+
self.assertRepr(IndexModel("hello", unique=False))
2263+
self.assertRepr(IndexModel("world", unique=True))
2264+
self.assertRepr(IndexModel([("hello", DESCENDING)], unique=True))
2265+
self.assertRepr(IndexModel([("world", DESCENDING)], name="world", unique=True))
22602266

22612267
if __name__ == "__main__":
22622268
unittest.main()

0 commit comments

Comments
 (0)