1

Im writing test code with pytest for testing API written with python 3. But Im struggling with the below error message. The python code correctly works without pytest but the error message comes out only when executing pytest code. I dont think that the problems came from low level issues although it seems to be. To be honest, the real meaning behind this error does not make sense for me. The context also does not seem to be related with this problem this time. (http://flask-sqlalchemy.pocoo.org/contexts/)

Would anyone please give me some tips or hints for the solution ?

* I already tried to solve the issue based on this question('No application found. Either work inside a view function or push an application context.') but it did not work on this code.

The part of codes that might be related with the issue. (test_auth.py)

    app = Flask(__name__)
    app.config.from_object(test)
    db_acs.init_app(app)
    logger = logging.getLogger(__name__)
    init_app(app, db_acs, logger)

Error

=========================================================================================== FAILURES ============================================================================================
____________________________________________________________________________________ test______________________________________________________________________________________

    def test():
        sqlpath = app.config['SQL_PATH']['getid']
        input_id = 'xxx'

>       rows = db_acs.dba(sqlpath, s1=input_id)

test_auth.py:68: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
../xxx/xxx/db/dba.py:33: in dba
    connection = db.engine.connect()
../../../.pyenv/versions/3.6.5/lib/python3.6/site-packages/flask_sqlalchemy/__init__.py:877: in engine
    return self.get_engine()
../../../.pyenv/versions/3.6.5/lib/python3.6/site-packages/flask_sqlalchemy/__init__.py:886: in get_engine
    app = self.get_app(app)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <SQLAlchemy engine=None>, reference_app = None

    def get_app(self, reference_app=None):
        """Helper method that implements the logic to look up an
            application."""

        if reference_app is not None:
            return reference_app

        if current_app:
            return current_app._get_current_object()

        if self.app is not None:
            return self.app

        raise RuntimeError(
>           'No application found. Either work inside a view function or push'
            ' an application context. See'
            ' http://flask-sqlalchemy.pocoo.org/contexts/.'
        )
E       RuntimeError: No application found. Either work inside a view function or push an application context. See http://flask-sqlalchemy.pocoo.org/contexts/.
fpersyn
  • 1,045
  • 1
  • 12
  • 19
Nana
  • 57
  • 8

2 Answers2

4

In the file conftest.py, you can write this:

@pytest.fixture(scope="session")
def app():
    app = create_app()  # Or app = Flask(__name__)
    return app

And in your test_function:

def test_f(app):
    with app.app_context():
         # do your test
huang
  • 521
  • 3
  • 11
0

From the App Context page in the Flask documentation:

The application context keeps track of the application-level data during a request, CLI command, or other activity. […] An application context is pushed when a request context is pushed.

You can push an application context by: (1) Manually pushing a context with app.app_context() and accessing it within a with block (as huang has demonstrated already); (2) or creating an arbitrary request with test_client() – see my example below.

In conftest.py:

@pytest.fixture
def client(app):
    """A test client for the app."""
    return app.test_client()

In your test file (e.g. test_auth.py):

def test_something(client):
    with client:
        client.get("/")  # arbitrary request to push the app context
        # test/access the app context here

I can also recommend having a look at the official Flask test examples (test_blog.py has many relevant examples) and Testing Flask Applications in the Flask documentation (in particular the "Accessing and Modifying Sessions” section).

fpersyn
  • 1,045
  • 1
  • 12
  • 19