In the provided code, an exception is encountered when accessing database methods from the unit test file. Specifically, the "RuntimeError: working outside of application context" error is thrown when calling the "before_request" function and the "input_info" route from the test.py file.
To address this issue and enable database interactions within the unit tests, it is necessary to ensure that the Flask application context is set up correctly. The Flask application context manages request-specific state, including database connections. When running tests outside the context of a request, it is required to manually set up the application context.
Here's a modified version of your test code in test.py that includes the necessary changes:
from app import app from app import TestMySQL class Test(unittest.TestCase): def test_connection(self): with app.app_context(): object = TestMySQL() object.before_request() cursor = g.db.cursor() cursor.execute ('CREATE TABLE IF NOT EXISTS testmysql (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(40) NOT NULL, \ email VARCHAR(40) NOT NULL UNIQUE)') cursor.close()
By wrapping the test code inside the app.app_context() call, we establish the application context and ensure that the required database connection objects are available. This will resolve the "RuntimeError: working outside of application context" exception and allow the database methods to be accessed successfully during the unit tests.
The above is the detailed content of Why Am I Getting "RuntimeError: working outside of application context" When Testing My Flask App?. For more information, please follow other related articles on the PHP Chinese website!