Skip to content

Commit 455f2bd

Browse files
author
Shrikant Giri
committed
Use platform-specific path escaping with test evidence
Windows requires manual backslash replacement for repr() matching: - repr() displays C:\Users as 'C:\Users' (double backslashes) - Regex needs \\ to match \ (four backslashes in pattern) - re.escape() only produces \ (matches single backslash) Test evidence on Windows: re.escape(path) in repr(path): None (fails) path.replace('\', r'\\') in repr(path): Match (works) Solution: - Windows: Manual replacement for repr() double-escaping - Unix: re.escape() for special character handling Addresses @auvipy's review with detailed testing and explanation.
1 parent 3400651 commit 455f2bd

File tree

1 file changed

+27
-1
lines changed

1 file changed

+27
-1
lines changed

tests/test_model_serializer.py

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,32 @@ class Meta:
168168
model = RegularFieldsModel
169169
fields = '__all__'
170170

171+
# Cross-platform path handling for regex matching against repr() output
172+
#
173+
# Challenge: repr() output escapes backslashes, so Windows paths like
174+
# C:\Users become 'C:\\Users' in the repr string. To match \\ in regex,
175+
# we need \\\\ in the pattern.
176+
#
177+
# Why re.escape() doesn't work for Windows:
178+
# - re.escape(r'C:\Users') → 'C:\\Users' (matches single \)
179+
# - But repr() shows 'C:\\Users' (double \\)
180+
# - We need pattern 'C:\\\\Users' (to match double \\)
181+
#
182+
# Testing on Windows confirms:
183+
# >>> path = r'C:\Users\Temp'
184+
# >>> re.search(re.escape(path), repr(path))
185+
# None # Fails
186+
# >>> re.search(path.replace('\\', r'\\\\'), repr(path))
187+
# <re.Match object...> # Works
188+
#
189+
# For Unix paths (no backslashes), re.escape() works correctly.
190+
temp_path = tempfile.gettempdir()
191+
if '\\' in temp_path:
192+
# Windows: Manual replacement needed for repr() matching
193+
escaped_temp_path = temp_path.replace('\\', r'\\\\')
194+
else:
195+
# Unix: re.escape() handles any special regex characters
196+
escaped_temp_path = re.escape(temp_path)
171197
expected = dedent(r"""
172198
TestSerializer\(\):
173199
auto_field = IntegerField\(read_only=True\)
@@ -192,7 +218,7 @@ class Meta:
192218
url_field = URLField\(max_length=100\)
193219
custom_field = ModelField\(model_field=<.*CustomField: custom_field>\)
194220
file_path_field = FilePathField\(path='%s'\)
195-
""" % tempfile.gettempdir().replace('\\', r'\\\\'))
221+
""") % escaped_temp_path
196222

197223
assert re.search(expected, repr(TestSerializer()), re.DOTALL) is not None
198224

0 commit comments

Comments
 (0)