Runtime Error: 응용 프로그램 컨텍스트 외부에서 작업
app.py
from flask import Flask, render_template, request,jsonify,json,g
import mysql.connector
app = Flask(__name__)
**class TestMySQL():**
@app.before_request
def before_request():
try:
g.db = mysql.connector.connect(user='root', password='root', database='mysql')
except mysql.connector.errors.Error as err:
resp = jsonify({'status': 500, 'error': "Error:{}".format(err)})
resp.status_code = 500
return resp
@app.route('/')
def input_info(self):
try:
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()
test.py
from app import *
class Test(unittest.TestCase):
def test_connection1(self):
with patch('__main__.mysql.connector.connect') as mock_mysql_connector_connect:
object=TestMySQL()
object.before_request() """Runtime error on calling this"
유닛 테스트를 위해 test.py에 앱을 Import합니다.test.py에 'before_request' 함수를 호출하면 RuntimeError가 발생합니다.애플리케이션 컨텍스트 외부에서 작업하면 'input_info()' 호출 시 동일한 작업이 발생합니다.
Flask에는 애플리케이션 컨텍스트가 있으며 다음과 같은 작업을 수행해야 할 것 같습니다.
def test_connection(self):
with app.app_context():
#test code
그리고 아마 넌 이 모든것들을 밀어넣을 수 있을 거야app.app_context()테스트 셋업 메서드도 호출합니다.이게 도움이 됐으면 좋겠다.
@brenns10의 답변에 따라 사용 중 비슷한 문제가 발생했을 때pytest.
테스트 셋업에 넣자는 제안을 따랐습니다.이 방법은 다음과 같습니다.
import pytest
from src.app import app
@pytest.fixture
def app_context():
with app.app_context():
yield
def some_test(app_context):
# <test code that needs the app context>
언급URL : https://stackoverflow.com/questions/31444036/runtimeerror-working-outside-of-application-context
'programing' 카테고리의 다른 글
| Java 옵션 -Xmx는 무엇을 나타냅니까? (0) | 2022.12.20 |
|---|---|
| 플레인 JavaScript로 div 높이 가져오기 (0) | 2022.12.20 |
| 숫자 범위를 다른 범위로 매핑 (0) | 2022.12.20 |
| JavaScript에서 여러 변수 선언 (0) | 2022.12.20 |
| python 목록에는 pop()이 있지만 push()는 없는 이유는 무엇입니까? (0) | 2022.12.20 |