Is it possible to mock SimpleUploadedFile?
Question:
I have a function like this:
def my_func():
[...]
with open(full_path, "rb") as file:
image.image = SimpleUploadedFile(
name=image.external_url,
content=file.read(),
content_type="image/jpeg",
)
image.save()
print(f"{file_name} - Saved!")
I would like mock the "SimpleUploadedFile" for a test (calling print…).
Is it possible?
A little bit of context: the function download and upload files. Maybe the test is not necessary…
Answers:
I suppose that SimpleUploadedFile
is defined in the module a
and the function my_func()
is defined in the module b
.
The test file can be defined as the following:
import unittest
from unittest.mock import patch
from b import my_func
def func_only_print():
# assign an image to some_image
some_image = ...
print("This function substitutes SimpleUploadedFile")
return some_image
class MyTestCase(unittest.TestCase):
def test_my_func(self):
# note in the patch the string 'a.SimpleUploadedFile' => SimpleUploadedFile is defined in 'a'
with patch('a.SimpleUploadedFile') as mock_SimpleUploadedFile:
mock_SimpleUploadedFile.side_effect = func_only_print
my_func()
if __name__ == '__main__':
unittest.main()
If you execute the test file you might to see the message "This function substitutes SimpleUploadedFile"
printed on the standard output.
I have a function like this:
def my_func():
[...]
with open(full_path, "rb") as file:
image.image = SimpleUploadedFile(
name=image.external_url,
content=file.read(),
content_type="image/jpeg",
)
image.save()
print(f"{file_name} - Saved!")
I would like mock the "SimpleUploadedFile" for a test (calling print…).
Is it possible?
A little bit of context: the function download and upload files. Maybe the test is not necessary…
I suppose that SimpleUploadedFile
is defined in the module a
and the function my_func()
is defined in the module b
.
The test file can be defined as the following:
import unittest
from unittest.mock import patch
from b import my_func
def func_only_print():
# assign an image to some_image
some_image = ...
print("This function substitutes SimpleUploadedFile")
return some_image
class MyTestCase(unittest.TestCase):
def test_my_func(self):
# note in the patch the string 'a.SimpleUploadedFile' => SimpleUploadedFile is defined in 'a'
with patch('a.SimpleUploadedFile') as mock_SimpleUploadedFile:
mock_SimpleUploadedFile.side_effect = func_only_print
my_func()
if __name__ == '__main__':
unittest.main()
If you execute the test file you might to see the message "This function substitutes SimpleUploadedFile"
printed on the standard output.