简体   繁体   English

如果将db连接存储在flask.g对象上,如何使Flask连接到测试数据库?

[英]How do I get Flask to connect to my test database if I'm storing the db connection on the flask.g object?

I have a Flask application using pymysql directly, no SQLAlchemy. 我有一个直接使用pymysql的Flask应用程序,没有SQLAlchemy。

In my db.py file, I have the following: 在我的db.py文件中,我具有以下内容:

from myns.my_db import db_connect

def has_db():
  return hasattr(flask.g, 'db')

def get_db(name):
  if not has_db():
    setattr(flask.g, 'db', db_connect())
  return getattr(flask.g, 'db')

As well as this in my main app.py: 以及在我的主app.py中:

@app.teardown_request
def close_db(ex):
  if has_db():
    conn = get_db()
    conn.close()

What I'm trying to do is "mock" the database in tests, using the example here: https://flask.palletsprojects.com/en/1.1.x/testing/#faking-resources-and-context 我想做的是使用此处的示例在测试中“模拟”数据库: https : //flask.palletsprojects.com/en/1.1.x/testing/#faking-resources-and-context

The error I'm getting when running my test is: 运行测试时出现的错误是:

pymysql.err.InterfaceError: (0, '')

Which I have encountered before with pymysql. 我以前在pymysql中遇到过。 I generally interpret this error to mean that there are multiple threads using a database cursor, or there is a global database cursor being used inside multiple modules. 我通常将此错误解释为意味着使用一个数据库游标有多个线程,或者在多个模块内部使用了一个全局数据库游标。 This seems to make sense, because I believe the flask.g object to be some kind of thred-local global object. 这似乎是有道理的,因为我相信flask.g对象是某种thred-local全局对象。

Is there a way to "mock" the database connection in my test, even if it involves re-architecting my Flask application? 有没有办法在我的测试中“模拟”数据库连接,即使它涉及重新架构Flask应用程序也是如此? Thanks! 谢谢!

The problem was that I had a self.db connection that I was trying to use to: 问题是我有一个self.db连接,我试图将其用于:

  1. Setup the database and install the schema 设置数据库并安装架构
  2. Run the tests against 针对运行测试
  3. And also teardown the database 还要拆除数据库

Once I separated those steps and used a new connection for steps 1, 2 and 3, I no longer had the issue. 一旦分离了这些步骤并为步骤1、2和3使用新的连接,我就不再遇到问题了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM