# Path: gengine/app/tests/base.py
# class BaseDBTest(unittest.TestCase):
# 
#     @classmethod
#     def setUpClass(cls):
#         if cls is BaseDBTest:
#             raise unittest.SkipTest("Skip BaseTest tests, it's a base class")
#         super(BaseDBTest, cls).setUpClass()
# 
#     def setUp(self):
#         from gengine.app.cache import clear_all_caches
#         clear_all_caches()
# 
#         if os.path.exists("/tmp/test_pgdata"):
#             shutil.rmtree("/tmp/test_pgdata")
# 
#         self.db = testDB.db()
#         dsn = self.db.dsn()
#         self.engine =  create_engine(
#             "postgresql://%(user)s@%(host)s:%(port)s/%(database)s" % {
#                 "user": dsn["user"],
#                 "host": dsn["host"],
#                 "port": dsn["port"],
#                 "database": dsn["database"],
#             }
#         )
#         init_session(override_session=scoped_session(get_sessionmaker(bind=self.engine)), replace=True)
#         from gengine.metadata import Base
#         Base.metadata.bind = self.engine
# 
#         Base.metadata.drop_all(self.engine)
#         self.engine.execute("DROP SCHEMA IF EXISTS public CASCADE")
#         self.engine.execute("CREATE SCHEMA IF NOT EXISTS public")
# 
#         from alembic.config import Config
#         from alembic import command
# 
#         alembic_cfg = Config(attributes={
#             'engine': self.engine,
#             'schema': 'public'
#         })
#         script_location = os.path.join(
#             os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
#             'app/alembic'
#         )
#         alembic_cfg.set_main_option("script_location", script_location)
# 
#         from gengine.app import model
# 
#         tables = [t for name, t in model.__dict__.items() if isinstance(t, Table)]
#         Base.metadata.create_all(self.engine, tables=tables)
# 
#         command.stamp(alembic_cfg, "head")
# 
#     def tearDown(self):
#         self.db.stop()
#         shutil.rmtree("/tmp/test_pgdata")
# 
# Path: gengine/app/tests/helpers.py
# class Undefined():
# def randrange_float(f1,f2):
# def create_subjecttypes():
# def get_user_subjecttype():
# def create_subjects():
# def create_variables():
# def create_achievements():
# def create_subject(
#         name,
#         type,
#         lat=None,
#         lng=None,
#         timezone=None,
#         language=None,
#         additional_public_data={},
#     ):
# def get_or_create_language(name):
# def create_device(
#         subject_id=undefined,
#         device_id=undefined,
#         device_os=undefined,
#         push_id=undefined,
#         app_version=undefined,
#         gen_data=default_device_data
#     ):
# def create_achievement_rewards(achievement):
# def create_variable(name, increase_permission="admin"):
# def default_dt():
# def next_day(dt):
# def next_month(dt):
# def next_week(dt):
# def last_month(dt):
# 
# Path: gengine/metadata.py
# class MySession(Session):
#     def commit(self,*args,**kw):
#     def rollback(self, *args, **kw):
# def get_sessionmaker(bind=None):
# def init_session(override_session=None, replace=False):
# def init_declarative_base(override_base=None):
# def init_db(engine):
# 
# Path: gengine/app/model.py
# class AuthUser(ABase):
# 
#     @hybrid_property
#     def password(self):
#         return self.password_hash
# 
#     @password.setter
#     def password(self,new_pw):
#         if new_pw!=self.password_hash:
#             import argon2
#             import crypt
#             import base64
#             self.password_salt = crypt.mksalt()+crypt.mksalt()+crypt.mksalt()+crypt.mksalt()+crypt.mksalt()
#             hash = argon2.argon2_hash(new_pw, self.password_salt)
#             self.password_hash = base64.b64encode(hash).decode("UTF-8")
# 
#     def verify_password(self, pw):
#         import argon2
#         import base64
#         check = base64.b64encode(argon2.argon2_hash(pw, self.password_salt)).decode("UTF-8")
#         orig = self.password_hash
#         is_valid = check == orig
#         return is_valid
# 
#     @classmethod
#     def check_password_strength(cls, password):
#         length_error = len(password) < 8
#         return not length_error
# 
#     def get_or_create_token(self):
#         tokenObj = DBSession.query(AuthToken).filter(and_(
#             AuthToken.valid_until >= dt_now(),
#             AuthToken.auth_user_id == self.id,
#         )).first()
# 
#         if not tokenObj:
#             token = AuthToken.generate_token()
#             tokenObj = AuthToken(
#                 auth_user_id=self.id,
#                 token=token
#             )
# 
#             DBSession.add(tokenObj)
# 
#         return tokenObj
# 
#     @classmethod
#     def may_increase(cls, variable_row, request, subject_id):
#         if not asbool(get_settings().get("enable_user_authentication", False)):
#             #Authentication deactivated
#             return True
#         if request.has_perm(perm_global_increase_value):
#             # I'm the global admin
#             return True
#         if variable_row["increase_permission"] == "own" and request.subject and str(request.subject.id) == str(subject_id):
#             #The variable may be updated for myself
#             return True
#         return False


from gengine.app.tests.base import BaseDBTest
from gengine.app.tests.helpers import create_user, update_user, delete_user, get_or_create_language
from gengine.metadata import DBSession
from gengine.app.model import AuthUser
# -*- coding: utf-8 -*-


class TestUserCreation(BaseDBTest):

    def test_user_creation(self):

        lang = get_or_create_language("en")

# Path: gengine/app/tests/base.py
# class BaseDBTest(unittest.TestCase):
# 
#     @classmethod
#     def setUpClass(cls):
#         if cls is BaseDBTest:
#             raise unittest.SkipTest("Skip BaseTest tests, it's a base class")
#         super(BaseDBTest, cls).setUpClass()
# 
#     def setUp(self):
#         from gengine.app.cache import clear_all_caches
#         clear_all_caches()
# 
#         if os.path.exists("/tmp/test_pgdata"):
#             shutil.rmtree("/tmp/test_pgdata")
# 
#         self.db = testDB.db()
#         dsn = self.db.dsn()
#         self.engine =  create_engine(
#             "postgresql://%(user)s@%(host)s:%(port)s/%(database)s" % {
#                 "user": dsn["user"],
#                 "host": dsn["host"],
#                 "port": dsn["port"],
#                 "database": dsn["database"],
#             }
#         )
#         init_session(override_session=scoped_session(get_sessionmaker(bind=self.engine)), replace=True)
#         from gengine.metadata import Base
#         Base.metadata.bind = self.engine
# 
#         Base.metadata.drop_all(self.engine)
#         self.engine.execute("DROP SCHEMA IF EXISTS public CASCADE")
#         self.engine.execute("CREATE SCHEMA IF NOT EXISTS public")
# 
#         from alembic.config import Config
#         from alembic import command
# 
#         alembic_cfg = Config(attributes={
#             'engine': self.engine,
#             'schema': 'public'
#         })
#         script_location = os.path.join(
#             os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
#             'app/alembic'
#         )
#         alembic_cfg.set_main_option("script_location", script_location)
# 
#         from gengine.app import model
# 
#         tables = [t for name, t in model.__dict__.items() if isinstance(t, Table)]
#         Base.metadata.create_all(self.engine, tables=tables)
# 
#         command.stamp(alembic_cfg, "head")
# 
#     def tearDown(self):
#         self.db.stop()
#         shutil.rmtree("/tmp/test_pgdata")
# 
# Path: gengine/app/tests/helpers.py
# class Undefined():
# def randrange_float(f1,f2):
# def create_subjecttypes():
# def get_user_subjecttype():
# def create_subjects():
# def create_variables():
# def create_achievements():
# def create_subject(
#         name,
#         type,
#         lat=None,
#         lng=None,
#         timezone=None,
#         language=None,
#         additional_public_data={},
#     ):
# def get_or_create_language(name):
# def create_device(
#         subject_id=undefined,
#         device_id=undefined,
#         device_os=undefined,
#         push_id=undefined,
#         app_version=undefined,
#         gen_data=default_device_data
#     ):
# def create_achievement_rewards(achievement):
# def create_variable(name, increase_permission="admin"):
# def default_dt():
# def next_day(dt):
# def next_month(dt):
# def next_week(dt):
# def last_month(dt):
# 
# Path: gengine/metadata.py
# class MySession(Session):
#     def commit(self,*args,**kw):
#     def rollback(self, *args, **kw):
# def get_sessionmaker(bind=None):
# def init_session(override_session=None, replace=False):
# def init_declarative_base(override_base=None):
# def init_db(engine):
# 
# Path: gengine/app/model.py
# class AuthUser(ABase):
# 
#     @hybrid_property
#     def password(self):
#         return self.password_hash
# 
#     @password.setter
#     def password(self,new_pw):
#         if new_pw!=self.password_hash:
#             import argon2
#             import crypt
#             import base64
#             self.password_salt = crypt.mksalt()+crypt.mksalt()+crypt.mksalt()+crypt.mksalt()+crypt.mksalt()
#             hash = argon2.argon2_hash(new_pw, self.password_salt)
#             self.password_hash = base64.b64encode(hash).decode("UTF-8")
# 
#     def verify_password(self, pw):
#         import argon2
#         import base64
#         check = base64.b64encode(argon2.argon2_hash(pw, self.password_salt)).decode("UTF-8")
#         orig = self.password_hash
#         is_valid = check == orig
#         return is_valid
# 
#     @classmethod
#     def check_password_strength(cls, password):
#         length_error = len(password) < 8
#         return not length_error
# 
#     def get_or_create_token(self):
#         tokenObj = DBSession.query(AuthToken).filter(and_(
#             AuthToken.valid_until >= dt_now(),
#             AuthToken.auth_user_id == self.id,
#         )).first()
# 
#         if not tokenObj:
#             token = AuthToken.generate_token()
#             tokenObj = AuthToken(
#                 auth_user_id=self.id,
#                 token=token
#             )
# 
#             DBSession.add(tokenObj)
# 
#         return tokenObj
# 
#     @classmethod
#     def may_increase(cls, variable_row, request, subject_id):
#         if not asbool(get_settings().get("enable_user_authentication", False)):
#             #Authentication deactivated
#             return True
#         if request.has_perm(perm_global_increase_value):
#             # I'm the global admin
#             return True
#         if variable_row["increase_permission"] == "own" and request.subject and str(request.subject.id) == str(subject_id):
#             #The variable may be updated for myself
#             return True
#         return False


# Path: gengine/app/tests_old/test_groups.py
from gengine.app.tests.base import BaseDBTest
from gengine.app.tests.helpers import create_user, update_user, delete_user, get_or_create_language
from gengine.metadata import DBSession
from gengine.app.model import AuthUser

# -*- coding: utf-8 -*-


class TestUserCreation(BaseDBTest):

    def test_user_creation(self):

        lang = get_or_create_language("en")

        user = create_user(