In my Django application there is an endpoint that handles file upload. In the serializer I define the file size validation like below
extra_kwargs = {
"image_file": {
"validators": [
get_file_size_validator(1e8),
],
},
The validator function looks like this
def get_file_size_validator(file_size):
def validator_func(file):
if file_size < file.size:
raise ValidationError(f"Maximum file size is {file_size}")
return validator_func
I would like to write a test where I want to test that user cannot upload large files.
What I have tried so far.
SimpleUploadedFile("foo.pdf", b"aaaaa" * (9**10), content_type="image/jpeg")
InMemoryUploadedFile(BytesIO(b"large_content"), None, "foo.jpg", "image/jpeg", lambda: 1e9, None, None)
- Used
mock.patch.object(InMemoryUploadedFile, "size", return_value=1e9):
- Mocked
os.path.getsize
as recommended here https://stackoverflow.com/a/35246275/1847898
The first solution gives me MemoryError and for all the others file size is returned as 13 in validator_func
Any ideas how I can achieve this?