Skip to content

Instantly share code, notes, and snippets.

@diegoquintanav
Created October 9, 2018 20:35
Show Gist options
  • Save diegoquintanav/00dddee63df644bb5acd8c8490145caf to your computer and use it in GitHub Desktop.
Save diegoquintanav/00dddee63df644bb5acd8c8490145caf to your computer and use it in GitHub Desktop.
migrate unittests to pytest in Flask

Migrate from python.unittest to pytest

Check http://flask.pocoo.org/docs/1.0/testing/

# test_stuff.py

class StuffTestCase(unittest.TestCase):
    def setUp(self):
        self.app = create_app('testing') # app factory
        self.app_context = self.app.app_context()
        self.app_context.push()

        db.create_all()

    def tearDown(self):
        db.session.remove()
        db.drop_all()
        self.app_context.pop()

    def test_dummy(self):
        with self.app.test_request_context('/'):
             self.assertTrue(False) # dummy test

with pytest and fixtures

# conftest.py

import pytest

@pytest.fixture()
def testing_app():
    """Prepares a testing app and populates the database with
    default values.

    Check http://flask.pocoo.org/docs/1.0/testing/ for details
    """

    # Set up app in testing mode
    app = create_app('testing')
    app_context = app.app_context()
    app_context.push()

    db.create_all()

    yield app # this is where the testing happens

    # Teardown app and DB
    db.session.remove()
    db.drop_all()
    app_context.pop()


# test_stuff.py

def test_dummy(testing_app):
    with testing_app.test_request_context('/'):
         assert False # dummy test
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment