Limit name byte length

This commit is contained in:
Serene-Arc
2021-03-13 12:39:54 +10:00
committed by Ali Parlakci
parent f9809caa42
commit 36b6aafbc1
2 changed files with 7 additions and 3 deletions

View File

@@ -59,9 +59,10 @@ class FileNameFormatter:
@staticmethod
def _limit_file_name_length(filename: str, ending: str) -> str:
max_length = 255 - len(ending)
if len(filename) > max_length:
filename = filename[:max_length]
max_length_chars = 255 - len(ending)
max_length_bytes = 255 - len(ending.encode('utf-8'))
while len(filename) > max_length_chars or len(filename.encode('utf-8')) > max_length_bytes:
filename = filename[:-1]
return filename + ending
def format_resource_paths(self, resources: list[Resource],

View File

@@ -131,10 +131,13 @@ def test_format_multiple_resources():
('A' * 300, '.png'),
('A' * 300, '_1.png'),
('a' * 300, '_1000.jpeg'),
('😍💕✨' * 100, '_1.png'),
))
def test_limit_filename_length(test_filename: str, test_ending: str):
result = FileNameFormatter._limit_file_name_length(test_filename, test_ending)
assert len(result) <= 255
assert len(result.encode('utf-8')) <= 255
assert isinstance(result, str)
@pytest.mark.online