首页 > 解决方案 > 在单元测试数据库中为 FLASK sqlalchemy 应用程序添加一行

问题描述

我正在尝试为我的烧瓶应用程序编写一些单元测试,但由于某种原因,我的数据库总是空的。

import os
import unittest
import json
from flask_sqlalchemy import SQLAlchemy

from flaskr import create_app
from models import setup_db, Question, Category, db


class TriviaTestCase(unittest.TestCase):
    """This class represents the trivia test case"""

    def setUp(self):
        """Define test variables and initialize app."""
        self.app = create_app()
        self.client = self.app.test_client
        self.database_name = "trivia_test"
        self.database_path = "postgres://{}/{}".format('localhost:5432', self.database_name)
        setup_db(self.app, self.database_path)

        self.question = {
            'question': 'is Yaser amazing?',
            'answer': 'of course, are you crazy?',
            'difficulty': 1 ,
            'category': 'all'
        }
        # binds the app to the current context
        with self.app.app_context():
            self.db = SQLAlchemy()
            self.db.init_app(self.app)
            # create all tables
            self.db.create_all()



    def tearDown(self):
        """Executed after reach test"""
        pass
    def test_get_questions(self):
        res = self.client().get('/questions')
        data = json.loads(res.data)
        print(data)

        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'],True)
        self.assertTrue(data['totalQuestions'])
        self.assertTrue(data['all_categories'])

我认为这self.question{}会在我的数据库中添加一行,但事实并非如此。我不确定语法是否正确,或者是否应该是别的东西。我正在关注一个课堂示例,我很困惑。

标签: unit-testingflasksqlalchemyflask-sqlalchemy

解决方案


看起来您正在将数据添加到您的测试类对象,但没有添加到您的数据库中。展示:

# The following adds a dictionary to `self.question`
self.question = {
    'question': 'is Yaser amazing?',
    'answer': 'of course, are you crazy?',
    'difficulty': 1 ,
    'category': 'all'
    }

# The following assertion should be true
assert isinstance(self.question, dict)

要添加到您的数据库,您需要执行以下操作:

def add_q(self, commit=True):
    """
    Unpack the stored dictionary into your db model,
    then add to your db.
    
    If you'd like to query this object from the db,
    you'll need to commit the session.
    --> Toggle this feature with the param `commit`
    """
    self.db.session.add(Question(**self.question))
    
    # You can also commit outside of the function execution
    # Helpful for batch processing  
    if commit:
        self.db.session.commit()

完成上述操作后,您应该能够在数据库中查询新添加的问题。如果您经常运行此测试,您可能希望删除新添加的 q。这是一个有用的功能:

def remove_q(self, commit=True):
    """
    Query your db for the previously added q. Then
    remove from db.
    
    To commit this change, set commit=True (default)
    """

    my_q = self.db.session.query(Question).filter_by(**self.question).first()
    
    # now delete
    self.db.session.delete(my_q)

    # You can also commit outside of the function execution
    # Helpful for batch processing  
    if commit:
        self.db.session.commit()

推荐阅读