运行时错误:在应用程序上下文之外工作

2024-04-25 05:05:17 发布

您现在位置:Python中文网/ 问答频道 /正文

应用程序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()

测试.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"  

我正在将app导入test.py以进行单元测试。在将'u request函数调用到test.py之前,它将抛出RuntimeError:working out of application context 调用“input_info()”时也会发生同样的情况


Tags: frompytestimportappconnectorrequestdef
2条回答

Flask有一个Application Context,看起来你需要做如下事情:

def test_connection(self):
    with app.app_context():
        #test code

您也可以将app.app_context()调用推送到测试设置方法中。希望这有帮助。

当我在使用pytest时遇到类似的问题时,我遵循了@brenns10的答案。

我遵循了将其放入测试设置的建议,这是有效的:

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>

相关问题 更多 >