Skip to content

Commit f0d1563

Browse files
juliusgeoShaneHarvey
authored andcommitted
PYTHON-3028 $regex as a field name does not allow for non-string values (#807)
(cherry picked from commit 70f7fe7)
1 parent fd9a8bf commit f0d1563

File tree

2 files changed

+10
-1
lines changed

2 files changed

+10
-1
lines changed

bson/json_util.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -508,7 +508,7 @@ def object_hook(dct, json_options=DEFAULT_JSON_OPTIONS):
508508
def _parse_legacy_regex(doc):
509509
pattern = doc["$regex"]
510510
# Check if this is the $regex query operator.
511-
if isinstance(pattern, Regex):
511+
if not isinstance(pattern, (str, bytes)):
512512
return doc
513513
flags = 0
514514
# PyMongo always adds $options but some other tools may not.

test/test_json_util.py

+9
Original file line numberDiff line numberDiff line change
@@ -270,6 +270,15 @@ def test_regex(self):
270270
json_util.dumps(Regex('.*', re.M | re.X),
271271
json_options=LEGACY_JSON_OPTIONS))
272272

273+
def test_regex_validation(self):
274+
non_str_types = [10, {}, []]
275+
docs = [{"$regex": i} for i in non_str_types]
276+
for doc in docs:
277+
self.assertEqual(doc, json_util.loads(json.dumps(doc)))
278+
279+
doc = {"$regex": ""}
280+
self.assertIsInstance(json_util.loads(json.dumps(doc)), Regex)
281+
273282
def test_minkey(self):
274283
self.round_trip({"m": MinKey()})
275284

0 commit comments

Comments
 (0)