Skip to main content
 首页 » 编程设计

python之为什么我指定的 flask 单元测试不使用临时文件数据库

2025年05月04日10落叶无声

测试仍然写入我的 MySQL 数据库而不是 sqlite 临时文件数据库。为什么会这样?谢谢!

这是我的代码:

class UserTests(unittest.TestCase): 
 
    def setUp(self): 
        self.app = get_app() 
        #declare testing state 
        self.app.config["TESTING"] = True 
        self.db, self.app.config["DATABASE"] = tempfile.mkstemp() 
        #spawn test client 
        self.client = self.app.test_client() 
        #temp db 
        init_db() 
 
    def tearDown(self): 
        os.close(self.db) 
        os.unlink(self.app.config["DATABASE"]) 
 
    def test_save_user(self): 
        #create test user with 3 friends 
        app_xs_token = get_app_access_token(APP_ID, APP_SECRET) 
        test_user = create_test_user(APP_ID, app_xs_token) 
        friend_1 = create_test_user(APP_ID, app_xs_token) 
        friend_2 = create_test_user(APP_ID, app_xs_token) 
        friend_3 = create_test_user(APP_ID, app_xs_token) 
        make_friend_connection(test_user["id"], friend_1["id"], test_user["access_token"], friend_1["access_token"]) 
        make_friend_connection(test_user["id"], friend_2["id"], test_user["access_token"], friend_2["access_token"]) 
        make_friend_connection(test_user["id"], friend_3["id"], test_user["access_token"], friend_3["access_token"]) 
 
        save_user(test_user["access_token"])  

请您参考如下方法:

这一行可能是问题所在:

self.db, self.app.config["DATABASE"] = tempfile.mkstemp() 

打印 self.db 和 self.app.config["DATABASE"] 的值并确保它们是你的期望他们是。