I have a flask application which uses a global object data_loader
.
The main flask file (let's call it main.py
) starts as follow:
app = Flask('my app')
...
data_loader = DataLoader(...)
Later on, this global data_loader
object is called in the route methods of the webserver:
class MyClass(Resource):
def get(self):
data_loader.load_some_data()
# ... process data, etc
Using unittest, I want to be able to patch the load_some_data()
method. I'm using the flask test_client:
from my_module.main import app
class MyTest(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
cls.client = app.test_client('my test client')
How can I patch the data_loader
method in subsequent tests in MyTest
? I have tried this approach, but it does not work (although the data_loader
seems to be replaced at some point):
@unittest.mock.patch('my_module.main.DataLoader')
def my_test(self, DataLoaderMock):
data_loader = DataLoaderMock.return_value
data_loader.my_method.return_value = 'new results (patched)'
with app.test_client() as client:
response = client.get(f'/some/http/get/request/to/MyTest/route',
query_string={...})
# ... some assertions to be tested ...
It seems the data_loader
is never truly replaced in the Flask app.
Also, is this considered "good practice" to have a global variable in the Flask server, or is the app supposed to have it stored inside?
Thanks