pytest-dev / pytest-flask

A set of pytest fixtures to test Flask applications

Home Page:http://pytest-flask.readthedocs.org/en/latest/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to go about mocking application functions when running app in Live Server

ndkv opened this issue · comments

Hello,

I realise this is a general Python question (how to mock functions running in other processes) but I couldn't find anything useful on the net and decided to ask here since it relates to pytest-flask.

I'm testing my application with Selenium and pytest-flask's Live Server and would like to mock (external) functions in my application. I'm using pytest-mock's mocker.patch() function.

The problem is that the functions are not mocked and mocked_function.assert_called_once() fails.

So: how do I go about mocking (external) functions in my application while it is served by Live Server? If this isn't possible, what is a good replacement for preventing some functions from executing during testing (in this case: the sending of an email)?

what is a good replacement for preventing some functions from executing during testing (in this case: the sending of an email)?

A common way of going about this by using the [factory pattern (https://flask.palletsprojects.com/en/1.1.x/tutorial/factory/#the-application-factory) and having something along the lines of:

from flask import Flask

def create_app(test_config=None):
    app = Flask(__name__, instance_relative_config=True)
    if test_config:
        # don't set up email handler
        # other testing configurations...
    else:
        # set up email handler

This way your application will behave differently when running in debug mode, you can even create multiple application instances with settings tailored to each one of your tests by passing different test_config objects to your app factory function create_app.

That being said, considering that the issue tracker is primarily meant to address bugs and feature requests in pytest-flask itself you will probably have better luck with such broad questions in places like stack overflow