db_tests.py 3.55 KB
import os
import unittest
from pprint import pprint

from app import create_app, db, User
from app.models import Project
from pdc_config import TestConfig
from tests.common_db_feed import resources_to_instancedb


class DbBaseTestCase(unittest.TestCase):
    def setUp(self, mode='memory'):
        """

        :param mode:  memory or btp
        :return:
        """
        self.app = create_app(TestConfig)
        self.mode = mode
        # Set uri based on called mode
        #
        if self.mode == 'memory':
            # force db uri to sqlite memory
            uri = 'sqlite:///:memory:'
        elif self.mode == 'btp':
            self.db_path = resources_to_instancedb(self.app)
            # force db path to newly create file
            uri = 'sqlite:///' + self.db_path
        self.app.config.update(
            SQLALCHEMY_DATABASE_URI=uri
        )
        # Push context
        #
        self.app_context = self.app.app_context()
        self.app_context.push()
        # Create and feed db if empty
        #
        if self.mode == 'memory':
            db.create_all()
            # TODO: to be rewriten for new category/label model
            # feed_projects()

    def tearDown(self):
        if self.mode == 'memory':
            db.session.remove()
            db.drop_all()
        elif self.mode == 'btp':
            if os.path.isfile(self.db_path):
                os.remove(self.db_path)
        self.app_context.pop()


class AnyModelTestCase(DbBaseTestCase):
    def setUp(self):
        DbBaseTestCase.setUp(self, 'btp')

    def tearDown(self):
        DbBaseTestCase.tearDown(self)

    def test_projects_struct(self):
        for project in Project.query.all():
            with self.subTest(project):
                categories = list(project.to_struct()['category_labels'].keys())
                self.assertEqual(['Domaine', 'Pôle'], categories,
                                 f"Failed on {project.name} categories: {categories}")


class ChargeModelTestCase(DbBaseTestCase):
    def setUp(self):
        DbBaseTestCase.setUp(self, 'btp')

    def tearDown(self):
        DbBaseTestCase.tearDown(self)

    def test_btp(self):
        projects = Project.query.all()
        self.assertEqual(101, len(projects))


class AuthModelTestCase(DbBaseTestCase):

    def skip_if_no_sqlitememory(self):
        if 'memory' not in self.app.config['SQLALCHEMY_DATABASE_URI']:
            self.skipTest("Needs in memory sqlite")

    def get_admin(self):
        return User.query.filter(User.name == 'admin').one()

    def setUp(self):
        DbBaseTestCase.setUp(self)
        self.skip_if_no_sqlitememory()
        db.create_all()
        admin = User(email='admin@nowhere.org', name='admin', login='admin', role='admin')
        db.session.add(admin)
        db.session.commit()

    def test_in_memory(self):
        self.app.logger.info("In memory Sqlite DB for tests")
        self.assertTrue(True)

    def test_setrole(self):
        admin = self.get_admin()
        admin.set_role("ADMIN")
        db.session.commit()
        admin = self.get_admin()
        self.assertTrue(admin is not None)
        self.assertTrue(admin.has_role("ADMIN"))
        self.assertFalse(admin.has_role("SERVICE"))

    def test_setrole_valueerror(self):
        admin = self.get_admin()
        with self.assertRaises(ValueError) as ve:
            admin.set_role("NOSUCHROLE")

    def test_setcheckpassword(self):
        admin = self.get_admin()
        admin.set_password("hahaha")
        db.session.commit()
        admin2 = self.get_admin()
        self.assertTrue(admin2.check_password("hahaha"))