3

We have a Flask app where most of the basic Flask setup code is in a file run.py at the root of our application. So basically a lot of this:

app = Flask(__name__)
app.debug = True
app.config(...)
app.config(...)

api = Api(app)
api.add_resource(resources.Registration, '/registration')
api.add_resource(...)
api.add_resource(...)

I'm trying to add unit testing to it, which we don't currently have. I'm roughly following the Flask tutorial project (https://github.com/pallets/flask/tree/1.0.2/examples/tutorial) as an example.

In that, basically you create your entire app as a module that can be imported - and the module is a factory. So __init__.py has a create_app function that creates your app (https://github.com/pallets/flask/blob/1.0.2/examples/tutorial/flaskr/init.py). I think this is automatically called when the module is imported by the main app during normal operation, but it can also be explicitly called in conftest.py (https://github.com/pallets/flask/blob/1.0.2/examples/tutorial/tests/conftest.py) which I think (?) is automatically called as part of the pytest launch.

So my question is actually pretty simple: Is there a decent way we can launch some pytest tests without refactoring our main app's code into a factory module? I don't want to touch the main app too much... I'd like to leave it as a really simple setup like my code at the top of this question.

In other words, this is the basic app setup in the tutorial's conftest.py once you remove the DB stuff:

@pytest.fixture
def app():

    app = create_app({
        'TESTING': True,
        'DATABASE': db_path,
    })

    yield app

And I want an app without create_app. But since all of our app code is just in our basic run.py, I can't think of a good way to do this other than copying everything and keeping it in sync. I can't import app from run.py since it's not a module I don't think.

Sorry that this is so basic - neither testing nor import statements are strengths of mine.

Stephen
  • 8,508
  • 12
  • 56
  • 96

1 Answers1

3

I think I found a way... just make it so that you can include modules from the parent folder (as per Importing modules from parent folder) and then import run and get the variable from that:

import os,sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir)

import run

@pytest.fixture
def app():
    app = run.app
    yield app

...of course I'll need to find a way to adjust the behavior there for testing purposes (i.e. the equivalent of the tutorial's passing 'Testing': True), so that's my next challenge.

Stephen
  • 8,508
  • 12
  • 56
  • 96