Skip to content

Commit 55091f1

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 f7d757d commit 55091f1

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
@@ -505,7 +505,7 @@ def object_hook(dct, json_options=DEFAULT_JSON_OPTIONS):
505505
def _parse_legacy_regex(doc):
506506
pattern = doc["$regex"]
507507
# Check if this is the $regex query operator.
508-
if isinstance(pattern, Regex):
508+
if not isinstance(pattern, (text_type, bytes)):
509509
return doc
510510
flags = 0
511511
# PyMongo always adds $options but some other tools may not.

test/test_json_util.py

+9
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,15 @@ def test_regex(self):
262262
'{"$regex": ".*", "$options": "mx"}',
263263
json_util.dumps(re.compile(b'.*', re.M | re.X)))
264264

265+
def test_regex_validation(self):
266+
non_str_types = [10, {}, []]
267+
docs = [{"$regex": i} for i in non_str_types]
268+
for doc in docs:
269+
self.assertEqual(doc, json_util.loads(json.dumps(doc)))
270+
271+
doc = {"$regex": ""}
272+
self.assertIsInstance(json_util.loads(json.dumps(doc)), Regex)
273+
265274
def test_minkey(self):
266275
self.round_trip({"m": MinKey()})
267276

0 commit comments

Comments
 (0)