Как настроить и создать тестовую базу данных sqlite в flask с Flask -тестированием - PullRequest
0 голосов
/ 09 июля 2020

это config.py:

import os

basedir = os.path.abspath(os.path.dirname(__file__))
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'datadb.sqlite')

class Config(object):
    DEBUG = False
    TESTING = False
    CSRF_ENABLED = True
    DEBUG = True

class ProductionConfig(Config):
    DEBUG = False


class StagingConfig(Config):
    DEVELOPMENT = True
    DEBUG = True


class DevelopmentConfig(Config):
    DEVELOPMENT = True
    DEBUG = True
    SQLALCHEMY_ECHO = True

class TestingConfig(Config):
    TESTING = True


app_config = {
    'development': DevelopmentConfig,
    'production': ProductionConfig,
    'testing': TestingConfig
}

init .py:

db = SQLAlchemy()
login_manager = LoginManager()
#==================================  GENERAL CONFIG======================================

def create_app(config_name):
    app = Flask(__name__, instance_relative_config=True)
    # security
    app.config['SECRET_KEY'] = SECRET_KEY
    # trace db modifications
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False


    # Ensure responses aren't cached
    @app.after_request
    def after_request(response):
        response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
        response.headers["Expires"] = 0
        response.headers["Pragma"] = "no-cache"
        return response

    # Ensure templates are auto-reloaded
    app.config["TEMPLATES_AUTO_RELOAD"] = True


    # define where is database
    app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI

    db.init_app(app)

    Bootstrap(app)

    # ==================================  DATABASE AND LOGIN APP ======================================
    # after the db variable initialization

    login_manager.init_app(app)
    login_manager.login_message = "You must be logged in to access this page."
    login_manager.login_view = "auth.login"

    # manage migrations
    migrate = Migrate(app, db)
    from application import models
#==================================  BLUEPRINTS ======================================

    # blueprints for each folder. Be sure to configure __init__.py of each folder

    from .admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint, url_prefix='/admin') #the views for this blueprint will be accessed in the browser with the url prefix admin

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint)

    from .home import home as home_blueprint
    app.register_blueprint(home_blueprint)

    return app

my app.py:

from application import create_app

config_name = os.getenv('FLASK_CONFIG')
app = create_app(config_name)

if __name__ == '__main__':
    app.run()

и test.py:

import unittest
import os
from flask import abort, url_for
from flask_testing import TestCase

from application import create_app, db
from application.models import Employee, Role, Department
from config import basedir

class TestBase(TestCase):

    def create_app(self):

        # pass in test configurations
        config_name = 'testing'
        app = create_app(config_name)
        app.config.update(
            TEST_SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'test.sqlite')
        )

        return app

    def setUp(self):
        """
        Will be called before every test
        """

        db.create_all()

        # create test admin user
        admin = Employee(username="admin", password="admin2016", is_admin=True)

        # create test non-admin user
        employee = Employee(username="test_user", password="test2016")

        # save users to database
        db.session.add(admin)
        db.session.add(employee)
        db.session.commit()

    def tearDown(self):
        """
        Will be called after every test
        """

        db.session.remove()
        db.drop_all()



class TestModels(TestBase):

    def test_employee_model(self):
        """
        Test number of records in Employee table
        """
        self.assertEqual(Employee.query.count(), 2)

    def test_department_model(self):
        """
        Test number of records in Department table
        """

Чтобы понять проблему, я уже удалил свою базу данных. Кажется, когда я запускаю test.py. Он создает datadb.sqlite, а не test.sqlite. Поэтому, когда тесты пытаются создать пользователя с правами администратора, у меня возникает эта ошибка:

sqlite3.IntegrityError: Ошибка ограничения UNIQUE: employee.username

Я почти уверен, что проблема в том, что мой тестовый код не создает тест db, но попробуйте протестировать мою производственную базу данных.

Как я могу это проверить и как решить эту проблему? спасибо

...