Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I mock a file object with a set size?

I have a function that raises an exception if the size of a file is too big (> 1MB). I would like to test this function without using a real image. I know it is possible to mock file objects with mock_open but how do I give this fake file a size?

Here is the function I want to test:

def _check_image_size(img_path):
    megabyte = 1048576

    if os.path.getsize(img_path) > megabyte:
        raise ValueError("Image must be less than or equal to 1MB in size.")

So just to reiterate the question in a different way: how to I test this function without using a real file greater than 1MB in size?

P.S. Should I even write a test for this function? I am very much a new developer who doesn't have much experience. Am I going overboard by wanting to test this?

like image 919
C_Rod_27 Avatar asked Oct 16 '25 17:10

C_Rod_27


1 Answers

It's simpler to mock the function itself.

with mock.patch('os.path.getsize', return_value=2*1024*1024)
    try:
        _check_image_size("any arbitrary string")
    except ValueError:
        print "Successfully raised ValueError"
    else:
        print "Did not raise ValueError"

Or, without using the mock library (or something similar), monkey patch the function directly.

import os.path

os.path.getsize = lambda path: return 2*1024*1024
try:
    _check_image_size("any arbitrary string")
except ValueError:
    print "Successfully raised ValueError"
else:
    print "Did not raise ValueError"
like image 114
chepner Avatar answered Oct 19 '25 09:10

chepner