4
root rather than on a directory the input helped build.
5
"""
6
7
+import re
8
import sys
9
from pathlib import Path
10
140
assert is_inside_dir(Path("C:\\Foo\\Bar"), Path("c:\\foo"))
141
142
143
+TAG_BYTES = 17
144
+"""Bytes a changed name gains: ``-`` and 16 hex digits of the original's
145
+digest."""
146
+
147
+
148
+def tagged(stem: str, extension: str = "") -> "re.Pattern[str]":
149
+ """Match ``stem``, the digest tag of a changed name, then ``extension``."""
150
+ return re.compile(re.escape(stem) + "-[0-9a-f]{16}" + re.escape(extension))
151
+
152
+
153
class TestSafeBasename:
154
@pytest.mark.parametrize(
155
("value", "expected"),
160
(".gitignore", ".gitignore"),
161
("..\\..\\evil", "evil"),
162
(" report.pdf", "report.pdf"),
163
+ ("report.pdf ", "report.pdf"),
164
+ ("\x1creport.txt\x1f", "report.txt"),
165
("café.txt", "café.txt"),
166
("C:report.txt", "report.txt"),
167
("\ufeffreport.txt", "\ufeffreport.txt"),
196
safe_basename("report\x00.pdf")
197
198
@pytest.mark.parametrize(
186
- ("value", "expected"),
199
+ ("value", "stem", "extension"),
200
[
188
- ("report_2026-09-29T10:30:00.csv", "report_2026-09-29T10_30_00.csv"),
189
- ("What is this?.png", "What is this_.png"),
190
- ('invoice "final".pdf', "invoice _final_.pdf"),
191
- ("report.txt:payload", "report.txt_payload"),
192
- ("report<1>.txt", "report_1_.txt"),
193
- ("a|b*.txt", "a_b_.txt"),
194
- ("tab\there.txt", "tab_here.txt"),
195
- ("\x1creport.txt\x1f", "report.txt"),
196
- ("output/C:report.txt", "C_report.txt"),
201
+ ("report_2026-09-29T10:30:00.csv", "report_2026-09-29T10_30_00", ".csv"),
202
+ ("What is this?.png", "What is this_", ".png"),
203
+ ('invoice "final".pdf', "invoice _final_", ".pdf"),
204
+ ("report.txt:payload", "report", ".txt_payload"),
205
+ ("report<1>.txt", "report_1_", ".txt"),
206
+ ("a|b*.txt", "a_b_", ".txt"),
207
+ ("tab\there.txt", "tab_here", ".txt"),
208
+ ("output/C:report.txt", "C_report", ".txt"),
209
],
210
)
199
- def test_replaces_windows_reserved_characters(self, value, expected):
200
- assert safe_basename(value) == expected
211
+ def test_replaces_windows_reserved_characters(self, value, stem, extension):
212
+ assert tagged(stem, extension).fullmatch(safe_basename(value))
213
214
@pytest.mark.parametrize(
203
- ("value", "expected"),
215
+ ("value", "stem", "extension"),
216
[
205
- ("report.txt.", "report.txt"),
206
- ("report.txt ", "report.txt"),
207
- ("report. .", "report"),
208
- ("report.\u00a0", "report"),
209
- ("report.\u0085", "report"),
210
- ("\ufeff..", "\ufeff"),
217
+ ("report.txt.", "report", ".txt"),
218
+ ("report. .", "report", ""),
219
+ ("report.\u00a0", "report", ""),
220
+ ("report.\u0085", "report", ""),
221
+ ("\ufeff..", "\ufeff", ""),
222
],
223
)
213
- def test_drops_trailing_spaces_and_dots(self, value, expected):
214
- assert safe_basename(value) == expected
224
+ def test_drops_trailing_spaces_and_dots(self, value, stem, extension):
225
+ assert tagged(stem, extension).fullmatch(safe_basename(value))
226
227
@pytest.mark.parametrize(
217
- ("value", "expected"),
228
+ ("value", "stem", "extension"),
229
[
219
- ("NUL", "_NUL"),
220
- ("nul", "_nul"),
221
- ("NUL.tar.gz", "_NUL.tar.gz"),
222
- ("COM1.log.bak", "_COM1.log.bak"),
223
- ("COM¹.txt", "_COM¹.txt"),
224
- ("LPT³.data", "_LPT³.data"),
225
- ("aux.txt", "_aux.txt"),
226
- ("CON .txt", "_CON .txt"),
227
- ("COM1:.txt", "COM1_.txt"),
230
+ ("NUL", "_NUL", ""),
231
+ ("nul", "_nul", ""),
232
+ ("NUL.tar.gz", "_NUL.tar", ".gz"),
233
+ ("COM1.log.bak", "_COM1.log", ".bak"),
234
+ ("COM¹.txt", "_COM¹", ".txt"),
235
+ ("LPT³.data", "_LPT³", ".data"),
236
+ ("aux.txt", "_aux", ".txt"),
237
+ ("CON .txt", "_CON ", ".txt"),
238
+ ("COM1:.txt", "COM1_", ".txt"),
239
],
240
)
230
- def test_prefixes_windows_device_names_with_any_extension(self, value, expected):
231
- assert safe_basename(value) == expected
241
+ def test_prefixes_windows_device_names_with_any_extension(
242
+ self, value, stem, extension
243
+ ):
244
+ assert tagged(stem, extension).fullmatch(safe_basename(value))
245
246
def test_prefixes_a_device_name_exposed_by_truncation(self):
247
# Truncation keeps `NUL` plus spaces before `.txt`, and Windows ignores
248
# the spaces, so the checked name must be the fitted one.
236
- assert safe_basename("NUL" + " " * 200 + "x.txt") == "_NUL" + " " * 120 + ".txt"
237
- assert safe_basename("CON" + " " * 200 + "x") == "_CON"
249
+ spaces = " " * (MAX_COMPONENT_LENGTH - TAG_BYTES - 8)
250
+ assert tagged("_NUL" + spaces, ".txt").fullmatch(
251
+ safe_basename("NUL" + " " * 200 + "x.txt")
252
+ )
253
+ assert tagged("_CON").fullmatch(safe_basename("CON" + " " * 200 + "x"))
254
255
def test_keeps_a_filename_at_the_byte_limit(self):
256
name = "x" * MAX_COMPONENT_LENGTH
257
assert safe_basename(name) == name
258
259
def test_truncates_to_the_byte_limit_and_keeps_the_extension(self):
244
- assert (
245
- safe_basename("x" * 200 + ".pdf")
246
- == "x" * (MAX_COMPONENT_LENGTH - 4) + ".pdf"
260
+ result = safe_basename("x" * 200 + ".pdf")
261
+ assert tagged("x" * (MAX_COMPONENT_LENGTH - TAG_BYTES - 4), ".pdf").fullmatch(
262
+ result
263
)
264
+ assert len(result) == MAX_COMPONENT_LENGTH
265
266
def test_truncates_by_whole_code_points_measured_in_bytes(self):
267
cjk = safe_basename("請" * 70 + ".pdf")
251
- assert cjk == "請" * 41 + ".pdf"
268
+ assert tagged("請" * 35, ".pdf").fullmatch(cjk)
269
assert len(cjk.encode()) <= MAX_COMPONENT_LENGTH
253
- assert safe_basename("😀" * 33) == "😀" * 32
270
+ assert tagged("😀" * 27).fullmatch(safe_basename("😀" * 33))
271
272
def test_truncates_an_over_long_extension_with_the_rest(self):
256
- assert safe_basename("report." + "x" * 200) == "report." + "x" * (
257
- MAX_COMPONENT_LENGTH - 7
258
- )
273
+ stem = "report." + "x" * (MAX_COMPONENT_LENGTH - TAG_BYTES - 7)
274
+ assert tagged(stem).fullmatch(safe_basename("report." + "x" * 200))
275
276
def test_drops_a_trailing_dot_exposed_by_truncation(self):
277
name = "x" * (MAX_COMPONENT_LENGTH - 1) + "." + "y" * 40
262
- assert safe_basename(name) == "x" * (MAX_COMPONENT_LENGTH - 1)
278
+ assert tagged("x" * (MAX_COMPONENT_LENGTH - TAG_BYTES)).fullmatch(
279
+ safe_basename(name)
280
+ )
281
+
282
+ @pytest.mark.parametrize(
283
+ ("value", "expected"),
284
+ [
285
+ # safePath.test.ts asserts the same vectors, so both SDKs write a
286
+ # given server name to the same file.
287
+ ("report?.png", "report_-05fcb95aa5b918e9.png"),
288
+ ("report*.png", "report_-aa921bdab2b33292.png"),
289
+ (
290
+ "report_2026-09-29T10:30:00.csv",
291
+ "report_2026-09-29T10_30_00-d7211bb25cb815fe.csv",
292
+ ),
293
+ ("NUL.txt", "_NUL-d0848f78ce05ded6.txt"),
294
+ ],
295
+ )
296
+ def test_tags_a_changed_name_with_a_digest_of_the_original(self, value, expected):
297
+ assert safe_basename(value) == expected
298
+
299
+ def test_distinct_names_that_normalize_alike_stay_distinct(self):
300
+ names = ["report?.png", "report*.png", "report:.png", "report_.png"]
301
+ assert len({safe_basename(name) for name in names}) == len(names)
302
+
303
+ def test_distinct_long_names_sharing_a_truncated_prefix_stay_distinct(self):
304
+ prefix = "a" * 200
305
+ assert safe_basename(prefix + "-1.txt") != safe_basename(prefix + "-2.txt")
306
+
307
+ def test_returns_an_already_portable_name_unchanged(self):
308
+ assert safe_basename("report_.png") == "report_.png"
309
+
310
+ def test_treats_a_tagged_name_as_already_portable(self):
311
+ written = safe_basename("report?.png")
312
+ assert safe_basename(written) == written
313
314
def test_rejects_unencodable_filename(self):
315
with pytest.raises(UnsafePathComponentError, match="invalid Unicode"):