示例#1
0
def test_replace_hash_password_method():
    """Can the library work the same with custom ``has_password`` and
    ``password_is_valid`` methods?
    """

    class CustomAuth(authcode.Auth):
        def hash_password(self, secret):
            secret = self.prepare_password(secret)
            return secret[::-1]

        def password_is_valid(self, secret, hashed):
            secret = self.prepare_password(secret)
            if secret is None or hashed is None:
                return False
            return self.hash_password(secret) == hashed

    db = SQLAlchemy('sqlite:///:memory:')
    auth = CustomAuth(SECRET_KEY, db=db)
    User = auth.User
    db.create_all()

    credentials = {'login': u'meh', 'password': '******'}
    user = User(**credentials)
    db.session.add(user)
    db.session.commit()

    assert user.password == 'foobar'[::-1]
    assert user.has_password('foobar')

    auth_user = auth.authenticate(credentials)
    assert user.login == auth_user.login

    auth_user = auth.authenticate({})
    assert not auth_user
示例#2
0
def test_user_has_empty_password():
    db = SQLAlchemy('sqlite:///:memory:')
    auth = authcode.Auth(SECRET_KEY, db=db, password_minlen=0)

    User = auth.User

    db.create_all()
    user = User(login=u'meh', password=u'')
    db.session.add(user)
    db.session.commit()

    assert user.password != u''

    auth_user = auth.authenticate({'login': u'meh', 'password': u''})
    assert auth_user

    auth_user = auth.authenticate({})
    assert not auth_user

    auth_user = auth.authenticate({'login': u'meh', 'password': None})
    assert not auth_user

    auth_user = auth.authenticate({'login': u'meh'})
    assert not auth_user

    auth_user = auth.authenticate({'login': u'wtf', 'password': ''})
    assert not auth_user

    auth_user = auth.authenticate({'login': u'meh', 'password': '******'})
    assert not auth_user
示例#3
0
def test_authenticate_with_token():
    from time import time
    db = SQLAlchemy('sqlite:///:memory:')
    auth = authcode.Auth(SECRET_KEY, db=db, token_life=3 * 60)

    User = auth.User

    db.create_all()
    user = User(login=u'meh', password='******')
    db.session.add(user)
    db.session.commit()

    token = user.get_token()
    auth_user = auth.authenticate({'token': token})
    assert auth_user

    token = '555' + user.get_token()
    auth_user = auth.authenticate({'token': token})
    assert not auth_user

    auth_user = auth.authenticate({'token': ''})
    assert not auth_user

    timestamp = int(time()) - auth.token_life + 1
    token = user.get_token(timestamp)
    auth_user = auth.authenticate({'token': token})
    assert auth_user

    timestamp = int(time()) - auth.token_life - 1
    token = user.get_token(timestamp)
    auth_user = auth.authenticate({'token': token})
    assert not auth_user
示例#4
0
def test_define_table():
    db = SQLAlchemy(URI1)
    db.Table('foobar', db.Column('foo', db.UnicodeText),
             db.Column('bar', db.UnicodeText))
    db.Table('fizzbuzz', db.metadata, db.Column('fizz', db.Integer),
             db.Column('buzz', db.Integer))
    db.create_all()
示例#5
0
def test_models_mixins():
    db = SQLAlchemy('sqlite:///:memory:')

    class UserMixin(object):
        email = db.Column(db.Unicode(300))

        def __repr__(self):
            return 'overwrited'

    class RoleMixin(object):
        description = db.Column(db.UnicodeText)

    auth = authcode.Auth(SECRET_KEY, db=db, UserMixin=UserMixin, RoleMixin=RoleMixin)
    User = auth.User
    Role = auth.Role

    db.create_all()
    user = User(login=u'meh', password='******', email=u'*****@*****.**')
    db.session.add(user)
    db.flush()

    assert User.__tablename__ == 'users'
    assert user.login == u'meh'
    assert user.email == u'*****@*****.**'
    assert hasattr(user, 'password')
    assert hasattr(user, 'last_sign_in')
    assert repr(user) == 'overwrited'

    assert hasattr(Role, 'description')
示例#6
0
def test_authenticate_with_password():
    db = SQLAlchemy('sqlite:///:memory:')
    auth = authcode.Auth(SECRET_KEY, db=db)

    User = auth.User

    db.create_all()
    credentials = {'login': u'meh', 'password': '******'}
    user = User(**credentials)
    db.session.add(user)
    db.session.commit()

    auth_user = auth.authenticate(credentials)
    assert user.login == auth_user.login

    auth_user = auth.authenticate({})
    assert not auth_user

    auth_user = auth.authenticate({'login': u'meh'})
    assert not auth_user

    auth_user = auth.authenticate({'login': u'wtf', 'password': '******'})
    assert not auth_user

    auth_user = auth.authenticate({'login': u'meh', 'password': '******'})
    assert not auth_user
def test_custom_poolclass():
    class _CustomPool(pool.StaticPool):
        _do_return_conn = mock.MagicMock()

    db = SQLAlchemy(URI1, poolclass=_CustomPool)
    db.create_all()

    _CustomPool._do_return_conn.assert_called_once()
示例#8
0
def test_define_table():
    db = SQLAlchemy(URI1)
    db.Table('foobar',
             db.Column('foo', db.UnicodeText),
             db.Column('bar', db.UnicodeText))
    db.Table('fizzbuzz', db.metadata,
             db.Column('fizz', db.Integer),
             db.Column('buzz', db.Integer))
    db.create_all()
示例#9
0
def test_init_app():
    class FakeApp(object):
        pass

    app = FakeApp()
    db = SQLAlchemy(URI1, app)
    assert app.databases
    db.init_app(app)
    assert len(app.databases) == 1
示例#10
0
def test_init_app():
    class FakeApp(object):
        pass

    app = FakeApp()
    db = SQLAlchemy(URI1, app)
    assert app.databases
    db.init_app(app)
    assert len(app.databases) == 1
示例#11
0
def test_get_engine():
    class FakeApp(object):
        pass

    app1 = FakeApp()
    app2 = FakeApp()
    db = SQLAlchemy(URI1, app=app1)

    assert SQLAlchemy().get_engine(app1) == db.engine
    assert SQLAlchemy().get_engine(app2) is None
示例#12
0
def _get_flask_app(roles=False, **kwargs):
    db = SQLAlchemy('sqlite:///:memory:')
    auth = authcode.Auth(
        SECRET_KEY, db=db, roles=roles, password_minlen=3, **kwargs)
    User = auth.User

    db.create_all()
    user = User(login=u'meh', password='******')
    db.add(user)

    user2 = User(login=u'foo', password='******')
    db.add(user2)
    db.commit()

    app = Flask('test')
    app.secret_key = os.urandom(32)
    app.testing = True

    @app.route('/protected/')
    @auth.protected()
    def protected():
        return u'Welcome'

    authcode.setup_for_flask(auth, app)
    auth.session = {}
    return auth, app, user
示例#13
0
def test_automatic_case_insensitiveness():
    db = SQLAlchemy('sqlite:///:memory:')
    auth = authcode.Auth(SECRET_KEY, db=db)
    User = auth.User
    db.create_all()
    user = User(login=u'MeH', password='******')
    db.session.add(user)
    db.session.commit()

    assert user.login == u'meh'
    assert User.by_login(u'MEH') == User.by_login(u'MeH') == user
示例#14
0
def test_user_model_to_dict():
    db = SQLAlchemy('sqlite:///:memory:')
    auth = authcode.Auth(SECRET_KEY, db=db, roles=True)
    User = auth.User
    db.create_all()
    user = User(login=u'meh', password='******')
    db.session.add(user)
    db.commit()

    user_dict = user.to_dict()
    assert user_dict
示例#15
0
def test_role_model():
    db = SQLAlchemy('sqlite:///:memory:')
    auth = authcode.Auth(SECRET_KEY, db=db, roles=True)
    Role = auth.Role
    db.create_all()
    role = Role(name=u'admin')
    db.session.add(role)
    db.commit()

    assert role.name == u'admin'
    assert repr(role) == '<Role admin>'
示例#16
0
def test_set_raw_password():
    db = SQLAlchemy('sqlite:///:memory:')
    auth = authcode.Auth(SECRET_KEY, db=db, roles=True)
    User = auth.User
    db.create_all()
    user = User(login=u'meh', password='******')
    db.session.add(user)
    db.session.commit()

    assert user.password != 'foobar'
    user.set_raw_password('foobar')
    assert user.password == 'foobar'
示例#17
0
def test_backwards_compatibility():
    db = SQLAlchemy('sqlite:///:memory:')
    auth = authcode.Auth(SECRET_KEY, db=db)
    User = auth.User
    db.create_all()
    user = User(login=u'meh', password='******')
    db.session.add(user)
    db.commit()

    assert user._password == user.password
    user._password = '******'
    assert user.password == 'raw'
示例#18
0
def test_id_mixin():
    db = SQLAlchemy(URI1)

    class IDMixin(object):
        id = db.Column(db.Integer, primary_key=True)

    class Model(db.Model, IDMixin):
        field = db.Column(db.String)

    db.create_all()

    assert Model.__tablename__ == 'models'
    assert hasattr(Model, 'id')
示例#19
0
def test_get_uhmac():
    db = SQLAlchemy('sqlite:///:memory:')
    auth = authcode.Auth(SECRET_KEY, db=db)

    User = auth.User

    db.create_all()
    user = User(login=u'meh', password='******')
    db.session.add(user)
    db.session.commit()

    assert user.get_uhmac()
    assert user.get_uhmac() == user.get_uhmac()
示例#20
0
def test_id_mixin():
    db = SQLAlchemy(URI1)

    class IDMixin(object):
        id = db.Column(db.Integer, primary_key=True)

    class Model(db.Model, IDMixin):
        field = db.Column(db.String)

    db.create_all()

    assert Model.__tablename__ == 'models'
    assert hasattr(Model, 'id')
示例#21
0
def test_automatic_password_hashing():
    db = SQLAlchemy('sqlite:///:memory:')
    auth = authcode.Auth(SECRET_KEY, db=db, hash='pbkdf2_sha512', rounds=10)

    User = auth.User

    db.create_all()
    user = User(login=u'meh', password='******')
    db.session.add(user)
    db.session.commit()

    assert user.password
    assert user.password != 'foobar'
    assert user.has_password('foobar')
示例#22
0
def test_flask_sqlalchemy_query():
    db = SQLAlchemy(URI1)
    ToDo = create_test_model(db)
    db.create_all()

    db.add(ToDo('First', 'The text'))
    db.add(ToDo('Second', 'The text'))
    db.flush()

    titles = ' '.join(x.title for x in ToDo.query.all())
    assert titles == 'First Second'

    data = ToDo.query.filter(ToDo.title == 'First').all()
    assert len(data) == 1
示例#23
0
def test_custom_metaclass():
    class _CustomMeta(_BoundDeclarativeMeta):
        def __init__(self, name, bases, dic):
            _BoundDeclarativeMeta.__init__(self, name, bases, dic)
            if hasattr(self, 'id'):
                setattr(self, 'test', 1)

    db = SQLAlchemy(URI1, metaclass=_CustomMeta)

    class Model(db.Model):
        id = db.Column(db.Integer, primary_key=True)

    db.create_all()

    assert Model.test == 1
示例#24
0
def test_sti_auto_tablename():
    """Test Single Table Inheritance with an autonatically
    asigned table name.
    """
    db = SQLAlchemy('sqlite://')

    class SaEmployee(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(50))
        manager_data = db.Column(db.String(50))
        engineer_info = db.Column(db.String(50))
        type = db.Column(db.String(20))

        __mapper_args__ = {
            'polymorphic_on': type,
            'polymorphic_identity': 'employee'
        }

    class SaManager(SaEmployee):
        __mapper_args__ = {
            'polymorphic_identity': 'manager'
        }

    class SaEngineer(SaEmployee):
        __mapper_args__ = {
            'polymorphic_identity': 'engineer'
        }

    assert SaEmployee.__tablename__ == 'sa_employees'
    assert SaManager.__tablename__ == 'sa_employees'
    assert SaEngineer.__tablename__ == 'sa_employees'
    db.session.expunge_all()
示例#25
0
def test_cti_auto_tablename():
    """Test Concrete Table Inheritance with an autonatically
    asigned table name.
    """
    db = SQLAlchemy('sqlite://')

    class Person(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(50))

    class Engineer(Person):
        __mapper_args__ = {'concrete': True}
        id = db.Column(db.Integer, primary_key=True)
        primary_language = db.Column(db.String(50))
        name = db.Column(db.String(50))

    class Teacher(Person):
        __tablename__ = 'cti_auto_teachers'
        __mapper_args__ = {'concrete': True}
        id = db.Column(db.Integer, primary_key=True)
        primary_language = db.Column(db.String(50))
        name = db.Column(db.String(50))

    assert Person.__tablename__ == 'people'
    assert Engineer.__tablename__ == 'engineers'
    assert Teacher.__tablename__ == 'cti_auto_teachers'
    db.session.expunge_all()
示例#26
0
def test_acti_auto_tablename():
    """Test Abstract Concrete Table Inheritance with an autonatically
    asigned table name.
    """
    db = SQLAlchemy('sqlite://')

    class Employee(AbstractConcreteBase, db.Model):
        pass

    class Manager(Employee):
        __tablename__ = 'acti_auto_managers'
        employee_id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(50))
        manager_data = db.Column(db.String(40))
        __mapper_args__ = {
            'polymorphic_identity': 'manager',
            'concrete': True
        }

    class AaEngineer(Employee):
        employee_id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(50))
        engineer_info = db.Column(db.String(40))
        __mapper_args__ = {
            'polymorphic_identity': 'engineer',
            'concrete': True
        }

    assert Manager.__tablename__ == 'acti_auto_managers'
    assert AaEngineer.__tablename__ == 'aa_engineers'
    db.session.expunge_all()
示例#27
0
def test_jti_auto_tablename():
    """Test Joined Table Inheritance with an autonatically
    asigned table name.
    """
    db = SQLAlchemy('sqlite://')

    class JaPerson(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        discriminator = db.Column('type', db.String(50))
        __mapper_args__ = {'polymorphic_on': discriminator}

    class JaEngineer(JaPerson):
        __mapper_args__ = {'polymorphic_identity': 'engineer'}
        id = db.Column(db.Integer, db.ForeignKey(JaPerson.id), primary_key=True)
        primary_language = db.Column(db.String(50))

    class JaTeacher(JaPerson):
        __tablename__ = 'jti_auto_teachers'
        __mapper_args__ = {'polymorphic_identity': 'teacher'}
        id = db.Column(db.Integer, db.ForeignKey(JaPerson.id), primary_key=True)
        primary_language = db.Column(db.String(50))

    assert JaPerson.__tablename__ == 'ja_people'
    assert JaEngineer.__tablename__ == 'ja_engineers'
    assert JaTeacher.__tablename__ == 'jti_auto_teachers'
    db.session.expunge_all()
示例#28
0
def test_sti_custom_tablename():
    """Test Single Table Inheritance with a custom table name.
    """
    db = SQLAlchemy('sqlite://')

    class Employee(db.Model):
        __tablename__ = 'sti_custom_employee'

        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(50))
        manager_data = db.Column(db.String(50))
        engineer_info = db.Column(db.String(50))
        type = db.Column(db.String(20))

        __mapper_args__ = {
            'polymorphic_on': type,
            'polymorphic_identity': 'employee'
        }

    class Manager(Employee):
        __mapper_args__ = {
            'polymorphic_identity': 'manager'
        }

    class Engineer(Employee):
        __mapper_args__ = {
            'polymorphic_identity': 'engineer'
        }

    assert Employee.__tablename__ == 'sti_custom_employee'
    assert Manager.__tablename__ == 'sti_custom_employee'
    assert Engineer.__tablename__ == 'sti_custom_employee'
    db.session.expunge_all()
示例#29
0
def test_custom_metaclass():

    class _CustomMeta(_BoundDeclarativeMeta):

        def __init__(self, name, bases, dic):
            _BoundDeclarativeMeta.__init__(self, name, bases, dic)
            if hasattr(self, 'id'):
                setattr(self, 'test', 1)

    db = SQLAlchemy(URI1, metaclass=_CustomMeta)

    class Model(db.Model):
        id = db.Column(db.Integer, primary_key=True)

    db.create_all()

    assert Model.test == 1
示例#30
0
def test_user_model():
    db = SQLAlchemy('sqlite:///:memory:')
    auth = authcode.Auth(SECRET_KEY, db=db, roles=True)
    assert auth.users_model_name == 'User'
    assert auth.roles_model_name == 'Role'

    User = auth.User
    db.create_all()
    user = User(login=u'meh', password='******')
    db.session.add(user)
    db.commit()

    assert user.login == u'meh'
    assert user.email == user.login
    assert hasattr(user, 'password')
    assert hasattr(user, 'last_sign_in')
    assert repr(user) == '<User meh>'
示例#31
0
def test_login_logout():
    db = SQLAlchemy('sqlite:///:memory:')
    auth = authcode.Auth(SECRET_KEY, db=db)

    User = auth.User

    db.create_all()
    user = User(login=u'meh', password='******')
    db.session.add(user)
    db.session.commit()

    session = {}
    auth.login(user, session=session)
    print(session)
    assert session[auth.session_key] == user.get_uhmac()
    auth.logout(session=session)
    assert auth.session_key not in session
示例#32
0
def test_sql_injection():
    db = SQLAlchemy('sqlite:///:memory:')
    auth = authcode.Auth(SECRET_KEY, db=db, roles=True)
    User = auth.User
    db.create_all()
    user = User(login=u'meh', password='******')
    db.session.add(user)
    db.session.commit()

    tests = [
        "1'; DELETE FROM users",
        '1"; DELETE FROM users',
        "1' --",
    ]
    for passw in tests:
        user.set_raw_password(passw)
        db.session.commit()
        assert user.password == passw
示例#33
0
def test_flask_hooks_0_8():
    teardown_request_spy = mock.Mock()

    class AppWithTearDownRequest(object):
        def teardown_request(self, f):
            teardown_request_spy()

    app = AppWithTearDownRequest()
    SQLAlchemy(URI1, app=app)
    assert teardown_request_spy.call_count
示例#34
0
def test_flask_hooks_0_9():
    teardown_appcontext_spy = mock.Mock()

    class AppWithTearDownAppContext(object):
        def teardown_appcontext(self, f):
            teardown_appcontext_spy()

    app = AppWithTearDownAppContext()
    SQLAlchemy(URI1, app=app)
    assert teardown_appcontext_spy.call_count
示例#35
0
def test_model_helpers():
    db = SQLAlchemy()

    class Row(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(60), nullable=False)
        created_at = db.Column(db.DateTime, nullable=False,
                               default=datetime.utcnow)

    db.create_all()
    db.add(Row(name='a'))
    db.flush()
    row = db.query(Row).first()

    assert str(row) == '<Row>'
    assert dict(row)['name'] == 'a'
示例#36
0
def test_user_model_methods():
    db = SQLAlchemy('sqlite:///:memory:')
    auth = authcode.Auth(SECRET_KEY, db=db)
    User = auth.User
    db.create_all()
    user = User(login=u'meh', password='******')
    db.session.add(user)
    db.commit()

    assert User.by_id(user.id) == user
    assert User.by_id(33) is None

    assert User.by_login(u'meh') == user
    assert User.by_login(u'foobar') is None

    assert user.has_password('foobar')
    assert not user.has_password('abracadabra')

    assert user.get_token()
    assert user.get_uhmac()
示例#37
0
def test_disable_update_on_authenticate():
    db = SQLAlchemy('sqlite:///:memory:')
    auth = authcode.Auth(SECRET_KEY, db=db, hash='pbkdf2_sha512',
                         update_hash=False)
    User = auth.User
    db.create_all()

    credentials = {'login': u'meh', 'password': '******'}
    user = User(**credentials)
    db.session.add(user)
    db.session.commit()

    deprecated_hash = ph.hex_sha1.encrypt(credentials['password'])
    assert user.password != deprecated_hash
    user.set_raw_password(deprecated_hash)
    db.session.commit()
    assert user.password == deprecated_hash

    auth_user = auth.authenticate(credentials)
    assert auth_user.password == deprecated_hash
示例#38
0
def test_bottle_hooks():
    hook_spy = mock.Mock()

    class App(object):
        def hook(self, name):
            def decorator(f):
                hook_spy()
            return decorator

    app = App()
    SQLAlchemy(URI1, app=app)
    assert hook_spy.call_count
示例#39
0
def test_get_token():
    from time import time, sleep
    db = SQLAlchemy('sqlite:///:memory:')
    auth = authcode.Auth(SECRET_KEY, db=db)

    User = auth.User

    db.create_all()
    user = User(login=u'meh', password='******')
    db.session.add(user)
    db.session.commit()

    token1 = user.get_token()
    sleep(1)
    token2 = user.get_token()
    assert token1 != token2

    timestamp = time()
    token1 = user.get_token(timestamp)
    token2 = user.get_token(timestamp)
    assert token1 == token2
示例#40
0
def test_init_app():

    class App(object):

        def after_request(self, f):
            f()

        def on_exception(self, f):
            f()

        def hook(self, name):
            def decorator(f):
                f()
            return decorator

    app = App()
    db = SQLAlchemy(URI1)
    db.init_app(app)
    assert app.databases

    app = App()
    db = SQLAlchemy(URI1, app)
    assert app.databases
    db.init_app(app)
    assert len(app.databases) == 1
示例#41
0
def test_dont_clear_session_on_logout():
    db = SQLAlchemy('sqlite:///:memory:')
    auth = authcode.Auth(SECRET_KEY, db=db, clear_session_on_logout=False)

    User = auth.User

    db.create_all()
    user = User(login=u'meh', password='******')
    db.session.add(user)
    db.session.commit()

    session = {}
    auth.login(user, session=session)
    session['foo'] = 'bar'

    print(session)
    assert auth.session_key in session
    assert 'foo' in session

    auth.logout(session=session)
    print(session)
    assert auth.session_key not in session
    assert session['foo'] == 'bar'
示例#42
0
def test_model_helpers():
    db = SQLAlchemy()

    class Row(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(60), nullable=False)
        created_at = db.Column(db.DateTime, nullable=False,
                               default=datetime.utcnow)

    db.create_all()
    db.add(Row(name='a'))
    db.flush()
    row = db.query(Row).first()

    assert str(row) == '<Row>'
    assert dict(row)['name'] == 'a'
示例#43
0
def test_get_user():
    db = SQLAlchemy('sqlite:///:memory:')
    auth = authcode.Auth(SECRET_KEY, db=db)

    User = auth.User

    db.create_all()
    user = User(login=u'meh', password='******')
    db.session.add(user)
    db.session.commit()

    session = {}
    assert auth.get_user(session=session) is None

    session = {auth.session_key: user.get_uhmac()}
    assert auth.get_user(session=session)

    session = {auth.session_key: 'foobar'}
    assert auth.get_user(session=session) is None
    assert session.get(auth.session_key) is None

    session = {auth.session_key: 'foobar' + user.get_uhmac()}
    assert auth.get_user(session=session) is None
    assert session.get(auth.session_key) is None
示例#44
0
def test_flask_hooks_old():
    after_request_spy = mock.Mock()
    on_exception_spy = mock.Mock()

    class App(object):
        def after_request(self, f):
            after_request_spy()

        def on_exception(self, f):
            on_exception_spy()

    app = App()
    SQLAlchemy(URI1, app=app)
    assert after_request_spy.call_count
    assert on_exception_spy.call_count
示例#45
0
def test_mixin_no_tablename():
    """Test for a tablename defined in a mixin.
    """
    db = SQLAlchemy('sqlite://')

    class BaseMixin(object):
        @declared_attr
        def id(cls):
            return db.Column(db.Integer, primary_key=True)

    class MEngineer(BaseMixin, db.Model):
        name = db.Column(db.String(50))

    assert MEngineer.__tablename__ == 'm_engineers'
    db.session.expunge_all()
示例#46
0
def test_custom_templates():
    db = SQLAlchemy('sqlite:///:memory:')
    options = {
        'template_sign_in': 'sign-in.html',
        'template_sign_out': 'sign-out.html',
        'template_reset': 'reset-password.html',
        'template_reset_email': 'reset-password-email.html',
        'template_change_password': '******',
    }
    inbox = []

    def send_email(user, subject, msg):
        inbox.append(msg)

    auth = authcode.Auth(SECRET_KEY, db=db, **options)
    User = auth.User
    db.create_all()
    user = User(login=u'meh', password='******')
    db.add(user)
    db.commit()

    custom_templates = os.path.join(
        os.path.dirname(__file__),
        'custom_templates'
    )
    app = Flask('test', template_folder=custom_templates)
    app.secret_key = os.urandom(32)
    app.testing = True
    authcode.setup_for_flask(auth, app, send_email=send_email)
    auth.session = {}
    client = app.test_client()

    resp = client.get(auth.url_sign_in)
    assert resp.data == b'OK SIGN IN'

    resp = client.get(auth.url_reset_password)
    assert resp.data == b'OK RESET PASSWORD'

    data = dict(login=user.login, _csrf_token=auth.get_csrf_token())
    resp = client.post(auth.url_reset_password, data=data)
    assert inbox[0] == 'OK RESET PASSWORD EMAIL'

    auth.login(user)

    resp = client.get(auth.url_change_password)
    assert resp.data == b'OK CHANGE PASSWORD'

    url = '{0}?_csrf_token={1}'.format(auth.url_sign_out, auth.get_csrf_token())
    resp = client.get(url)
    assert resp.data == b'OK SIGN OUT'
示例#47
0
def test_mixin_overwritten_tablename():
    """Test for a tablename defined in a mixin but overwritten.
    """
    db = SQLAlchemy('sqlite://')

    class EmployeeMixin(object):
        __tablename__ = 'mixin_tablename'

        @declared_attr
        def id(cls):
            return db.Column(db.Integer, primary_key=True)

    class Engineer(EmployeeMixin, db.Model):
        __tablename__ = 'mixin_overwritten_tablename'
        name = db.Column(db.String(50))

    assert Engineer.__tablename__ == 'mixin_overwritten_tablename'
    db.session.expunge_all()
示例#48
0
def test_save():
    db = SQLAlchemy()

    class Contact(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        subject = db.Column(db.Unicode, nullable=False)
        email = db.Column(db.Unicode)
        message = db.Column(db.UnicodeText, nullable=False)

    db.create_all()

    class MyContactForm(f.Form):
        _model = Contact

        subject = f.Text(validate=[f.Required])
        email = f.Text(validate=[f.ValidEmail])
        message = f.Text(validate=[
            f.Required(message=u'write something!')
        ])

    # Create new object
    data = {
        'subject': u'foo',
        'message': u'bar',
        'email': u'*****@*****.**',
    }
    form = MyContactForm(data)
    assert form.is_valid()
    contact = form.save()
    print('contact', contact.__dict__)
    assert isinstance(contact, Contact)
    assert contact.id is None
    assert contact.subject == data['subject']
    assert contact.message == data['message']
    assert contact.email == data['email']
    db.commit()

    # Update object
    data['message'] = u'lalala'
    form = MyContactForm(data, obj=contact)
    assert form.is_valid()
    contact = form.save()
    assert contact.id is not None
    assert contact.message == data['message']
    db.commit()
示例#49
0
def test_prefix_save():
    db = SQLAlchemy()

    class Contact(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        subject = db.Column(db.Unicode, nullable=False)
        email = db.Column(db.Unicode)
        message = db.Column(db.UnicodeText, nullable=False)

    db.create_all()

    class MyContactForm(f.Form):
        _model = Contact

        subject = f.Text(validate=[f.Required])
        email = f.Text(validate=[f.ValidEmail])
        message = f.Text(validate=[
            f.Required(message=u'write something!')
        ])

    data = {
        'meh-subject': u'Hello',
        'meh-message': u'Welcome',
    }
    form = MyContactForm(data, prefix='meh')
    assert form.is_valid()
    contact = form.save()
    assert isinstance(contact, Contact)
    db.commit()
    assert contact.subject == data['meh-subject']
    assert contact.message == data['meh-message']

    data = {
        'meh-subject': u'foo',
        'meh-message': u'bar',
    }
    form = MyContactForm(data, obj=contact, prefix='meh')
    assert form.is_valid()
    assert form.has_changed
    form.save()
    db.commit()
    assert contact.subject == data['meh-subject']
    assert contact.message == data['meh-message']
示例#50
0
from sqlalchemy_wrapper import SQLAlchemy

from .config import CONFIG

db_words_80_percent = SQLAlchemy(
    uri='sqlite:///server/databases/words80percent.db?check_same_thread=False',
    echo=CONFIG.ECHO_SQL)


class Level(db_words_80_percent.Model):  # type: ignore
    num = db_words_80_percent.Column('level_num',
                                     db_words_80_percent.Integer,
                                     primary_key=True)
    title = db_words_80_percent.Column('level_title',
                                       db_words_80_percent.Unicode)


class Verse(db_words_80_percent.Model):  # type: ignore
    sura_num = db_words_80_percent.Column('sura_num',
                                          db_words_80_percent.Integer,
                                          primary_key=True)
    ayah_num = db_words_80_percent.Column('ayah_num',
                                          db_words_80_percent.Integer,
                                          primary_key=True)
    text = db_words_80_percent.Column('text', db_words_80_percent.Unicode)


class Word(db_words_80_percent.Model):  # type: ignore
    level_num = db_words_80_percent.Column(
        'level_num',
        db_words_80_percent.Integer,
示例#51
0
from sqlalchemy import Column, Integer, ForeignKey, String
from sqlalchemy.orm import relationship
from sqlalchemy_wrapper import SQLAlchemy

db = SQLAlchemy('sqlite:///:memory:')


class Parent(db.Model):
    __tablename__ = 'parent'

    id = db.Column(Integer, primary_key=True)
    name = db.Column(String(20))


class Child(db.Model):
    __tablename__ = "child"

    id = Column(Integer, primary_key=True)
    parent_id = Column(Integer, ForeignKey('parent.id'))
    child_attr = db.Column(String(20))
    parent = relationship('Parent')


db.create_all()

p1 = Parent(name="Akshay")
db.add(p1)

c1 = Child(child_attr="Child1")
c1.parent_id = p1.id
db.add(c1)
from sqlalchemy_wrapper import SQLAlchemy

from sa_types import EnumChoiceType

config_name = 'coding_challenge_restful.settings.Config'
config = Config('')
config.from_object(config_name)

s3_client = boto3.client(
    's3',
    # Hard coded strings as credentials, not recommended.
    aws_access_key_id=config['AWS_ACCESS_KEY'],
    aws_secret_access_key=config['AWS_SECRET_KEY'])

isolation_level = 'READ COMMITTED'
db = SQLAlchemy(uri=config['DATABASE_URL'], isolation_level=isolation_level)
migrate = Migrate(compare_type=True)
# Create Models
Model = db.Model


# Models are defined here
class SurrogatePK(object):
    __table_args__ = {'extend_existing': True}

    id = Column(Integer, autoincrement=True, primary_key=True)


class HasTablename(object):
    @declared_attr
    def __tablename__(cls):
示例#53
0
from sqlalchemy_wrapper import SQLAlchemy

from .config import DATABASE_URI

db: SQLAlchemy = SQLAlchemy(DATABASE_URI)
from app import models  # noqa
示例#54
0
# -*- coding: utf-8 -*-
import requests, requesocks, BeautifulSoup, re, time, random, subprocess, telnetlib
from sqlalchemy_wrapper import SQLAlchemy
from stem import Signal
from stem.control import Controller

db = SQLAlchemy('sqlite:///Test_new.db')


class Product(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    product_id = db.Column(db.String(20), unique=True)
    product_cat_id = db.Column(db.String(10), unique=False)
    product_name = db.Column(db.String(200), unique=False)
    product_picture = db.Column(db.String(200), unique=False)
    product_other_picture = db.Column(db.Text, unique=False)
    product_test_one_flag = db.Column(db.Integer, unique=False)
    product_price_r = db.Column(db.Integer, unique=False)
    product_price_u = db.Column(db.Integer, unique=False)
    product_discount = db.Column(db.String(20), unique=False)
    product_store_id = db.Column(db.String(20), unique=False)
    product_store_title = db.Column(db.String(20), unique=False)
    partner_url = db.Column(db.String(200), unique=False)
    orders_count = db.Column(db.Integer, unique=False)
    score = db.Column(db.Integer, unique=False)

    def __init__(self, product_id, product_cat_id, product_name,
                 product_picture, product_other_picture, product_test_one_flag,
                 product_price_r, product_price_u, product_discount,
                 product_store_id, product_store_title, partner_url,
                 orders_count, score):
示例#55
0
from sqlalchemy_wrapper import SQLAlchemy

from .config import CONFIG


db_quran_arabic = SQLAlchemy(
    uri='sqlite:///server/databases/quran_arabic.db?check_same_thread=False',
    echo=CONFIG.ECHO_SQL)


class QuranArabic(db_quran_arabic.Model):  # type: ignore
    __tablename__ = 'verses'
    sura_num = db_quran_arabic.Column(
        'sura', db_quran_arabic.Integer, primary_key=True)
    ayah_num = db_quran_arabic.Column(
        'ayah', db_quran_arabic.Integer, primary_key=True)
    text = db_quran_arabic.Column('text', db_quran_arabic.Unicode)


if __name__ == '__main__':
    print(db_quran_arabic.session.query(QuranArabic).count())
示例#56
0
文件: main.py 项目: artakak/EXPbot
from sqlalchemy_wrapper import SQLAlchemy
import datetime
import time
import telegram
import logging
import sys
import re
import difflib

# Enable logging
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO)

logger = logging.getLogger(__name__)
db = SQLAlchemy('sqlite:///User.db')


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.String(20), unique=True)
    user_name = db.Column(db.String(200), unique=True)
    user_auth = db.Column(db.Integer, unique=False)

    def __init__(self, user_id, user_name, user_auth):
        self.user_id = user_id
        self.user_name = user_name
        self.user_auth = user_auth

    def __repr__(self):
        return '<User %r, %r>' % (self.user_id, self.user_name)
示例#57
0
import sqlalchemy

from sqlalchemy import Column, Integer, ForeignKey, String
from sqlalchemy.orm import relationship
from sqlalchemy_wrapper import SQLAlchemy

db = SQLAlchemy('sqlite:///mydatabase.db')


class Student(db.Model):
    __tablename__ = "student"

    roll_no = db.Column(Integer, primary_key=True)
    name = db.Column(String)
    address = db.Column(String)
    phone = db.Column(String)
    age = db.Column(Integer)

    def __repr__(self):
        return '    {}'.format(self.name)

    #result = relationship("StudentCourse")
    # , primaryjoin="and_(Student.roll_no==StudentCourse.roll_no,")


class StudentCourse(db.Model):
    __tablename__ = "studentcourse"

    id = db.Column(Integer, primary_key=True)
    course_id = db.Column(Integer)
    roll_no = db.Column(Integer, ForeignKey('student.roll_no'))
示例#58
0
from sqlalchemy_wrapper import SQLAlchemy

db = SQLAlchemy('sqlite:///:memory:')
示例#59
0
def test_repr():
    db = SQLAlchemy(URI1)
    assert str(db) == "<SQLAlchemy('%s')>" % URI1
示例#60
0
def test_aggregated_query():
    db = SQLAlchemy(URI1)

    class Unit(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(60))
        price = db.Column(db.Integer)

    db.create_all()
    db.add(Unit(price=25))
    db.add(Unit(price=5))
    db.add(Unit(price=10))
    db.add(Unit(price=3))
    db.commit()

    res = db.query(db.func.sum(Unit.price).label('price')).first()
    assert res.price == 43