Skip to content

Flask-Testing using selenium and mock #153

@nekjir90

Description

@nekjir90

Hello
I have a problem when testing using mock

I need to go to the page and do some action. But at the same time, I want to mock the foo() function.

If I send a get request through the test client -- everything is OK; but when I open the page in the browser, the code does not mocked. How can I perform some actions on the page with selenium, and at the same time, so that have mock-code?

view.py

app = Flask(__name__)


def foo():
    print('\nNo mock!\n')


@app.route('/')
def hello_world():
    foo()
    return 'Hello, World!'

tests.py

from unittest import mock
from flask_testing import LiveServerTestCase
from selenium import webdriver


def foo():
    print('\nI am MOCK!!!\n')


class BaseClient(LiveServerTestCase):

    def create_app(self):
        from view import app

        self.test_client = app.test_client()
        return app

    def setUp(self):
        self.browser = webdriver.Firefox()

    def tearDown(self):
        self.browser.quit()

    @classmethod
    def get_server_url(cls):      
        return 'http://127.0.0.1:5000'

    @mock.patch('view.foo', side_effect=foo)
    def test_bad_mock(self, mock):
        self.browser.get(self.get_server_url())  # will be printed "No mock!", but I want to mock it!

    @mock.patch('view.foo', side_effect=foo)
    def test_correct_mock(self, mock):
        self.test_client.get('/')                # will be printed "I am MOCK!!!"

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions