示例#1
0
def test_config_endpoint_2():
    app = Zask(__name__)
    endpoint = random_ipc_endpoint()
    app.config['ZERORPC_SOME_SERVICE'] = {
        '1.0': endpoint,
        'default': '1.0'
    }
    rpc = ZeroRPC(app, middlewares=[CONFIG_ENDPOINT_MIDDLEWARE])

    class Srv(object):
        __version__ = "1.0"
        __service_name__ = "some_service"

        def hello(self):
            return 'world'

    srv = rpc.Server(Srv())
    gevent.spawn(srv.run)

    client = rpc.Client('some_service')
    assert client.hello() == 'world'

    with pytest.raises(MissingConfigException):
        client = rpc.Client('some_service', version='2.0')

    client.close()
    srv.close()
示例#2
0
def test_config_endpoint_1():
    app = Zask(__name__)
    endpoint = random_ipc_endpoint()
    app.config['ZERORPC_SOME_SERVICE'] = {
        '1.0': endpoint,
    }
    rpc = ZeroRPC(app, middlewares=[CONFIG_ENDPOINT_MIDDLEWARE])

    class Srv(rpc.Server):
        __version__ = "1.0"
        __service_name__ = "some_service"

        def hello(self):
            return 'world'

    srv = Srv()
    gevent.spawn(srv.run)

    client = rpc.Client('some_service', version='1.0')
    assert client.hello() == 'world'

    with pytest.raises(ClientMissingVersionException):
        client = rpc.Client('some_service')

    client.close()
    srv.close()
示例#3
0
 def test_debug_mode(self):
     app = Zask(__name__)
     app.config = self.default_config
     app.logger.debug("debug")
     app.logger.info("info")
     app.logger.error("error")
     app.logger.exception("exception")
示例#4
0
def testing_scope_session():
    app = Zask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
    app.config['DEBUG'] = False
    db = sqlalchemy.SQLAlchemy(app)

    endpoint = random_ipc_endpoint()
    rpc = ZeroRPC(app, middlewares=None)
    rpc.register_middleware(sqlalchemy.SessionMiddleware(db))

    class Foo(object):
        def create_foo(self, ctx):
            ctx2 = _request_ctx.get_request_cxt()
            assert ctx == ctx2

    class Srv(rpc.Server):
        def get_session(self):
            ctx = _request_ctx.get_request_cxt()
            foo = Foo()
            foo.create_foo(ctx)

            return str(db.session())

    srv = Srv(pool_size=1)
    srv.bind(endpoint)
    gevent.spawn(srv.run)

    client = rpc.Client(endpoint)
    session1 = client.get_session(async=True)
    session2 = client.get_session(async=True)

    assert session1.get() != session2.get()
示例#5
0
def testing_scope_session():
    app = Zask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
    app.config['DEBUG'] = False
    db = sqlalchemy.SQLAlchemy(app)

    endpoint = random_ipc_endpoint()
    rpc = ZeroRPC(app, middlewares=None)
    rpc.register_middleware(sqlalchemy.SessionMiddleware(db))

    class Foo(object):

        def create_foo(self, ctx):
            ctx2 = _request_ctx.get_request_cxt()
            assert ctx == ctx2

    class Srv(rpc.Server):

        def get_session(self):
            ctx = _request_ctx.get_request_cxt()
            foo = Foo()
            foo.create_foo(ctx)

            return str(db.session())

    srv = Srv(pool_size=1)
    srv.bind(endpoint)
    gevent.spawn(srv.run)

    client = rpc.Client(endpoint)
    session1 = client.get_session(async=True)
    session2 = client.get_session(async=True)

    assert session1.get() != session2.get()
示例#6
0
 def test_default_config(self):
     clear_handlers()
     app = Zask(__name__)
     app.config = {
         "DEBUG": True,
         "ERROR_LOG": ""
     }
     init_zerorpc(app)
     assert app.config['ZERORPC_ACCESS_LOG'] == '/tmp/zerorpc.access.log'
示例#7
0
    def test_debug_mode(self):
        clear_handlers()
        app = Zask(__name__)
        app.config = self.default_config
        init_zerorpc(app)

        print ""
        channel_logger.error("error")
        gevent_logger.error("error")
        core_logger.error("error")
示例#8
0
    def test_debug_mode(self):
        clear_handlers()
        app = Zask(__name__)
        app.config = self.default_config
        init_zerorpc(app)

        print ""
        channel_logger.error("error")
        gevent_logger.error("error")
        core_logger.error("error")
示例#9
0
def test_config_multiple_endpoints():
    app = Zask(__name__)
    endpoint = random_ipc_endpoint()
    another_endpoint = random_ipc_endpoint()

    app.config['ZERORPC_SOME_SERVICE'] = {
        '1.0': endpoint,
    }
    app.config['ZERORPC_SOME_SERVICE_2'] = {
        '1.0': another_endpoint
    }
    app.config['ZERORPC_SOME_SERVICE_CLIENT'] = {
        '1.0': [
            endpoint,
            another_endpoint
        ],
        'default': '1.0'
    }
    rpc = ZeroRPC(app, middlewares=[CONFIG_ENDPOINT_MIDDLEWARE])

    class Srv(object):
        __version__ = "1.0"
        __service_name__ = "some_service"

        def hello(self):
            return 'i am server 1'

    class AnotherSrv(object):
        __version__ = "1.0"
        __service_name__ = "some_service_2"

        def hello(self):
            return 'i am server 2'

    srv = rpc.Server(Srv())
    another_srv = rpc.Server(AnotherSrv())
    gevent.spawn(srv.run)
    gevent.spawn(another_srv.run)

    client = rpc.Client('some_service_client')
    for i in range(5):
        who_i_am = client.hello()
        app.logger.debug(who_i_am)
        assert who_i_am == 'i am server 1' or who_i_am == 'i am server 2'

    with pytest.raises(MissingConfigException):
        client = rpc.Client('some_service_client', version='2.0')

    client.close()
    srv.close()
    another_srv.close()
示例#10
0
def test_config_multiple_endpoints():
    app = Zask(__name__)
    endpoint = random_ipc_endpoint()
    another_endpoint = random_ipc_endpoint()

    app.config['ZERORPC_SOME_SERVICE'] = {
        '1.0': endpoint,
    }
    app.config['ZERORPC_SOME_SERVICE_2'] = {
        '1.0': another_endpoint
    }
    app.config['ZERORPC_SOME_SERVICE_CLIENT'] = {
        '1.0': [
            endpoint,
            another_endpoint
        ],
        'default': '1.0'
    }
    rpc = ZeroRPC(app, middlewares=[CONFIG_ENDPOINT_MIDDLEWARE])

    class Srv(object):
        __version__ = "1.0"
        __service_name__ = "some_service"

        def hello(self):
            return 'i am server 1'

    class AnotherSrv(object):
        __version__ = "1.0"
        __service_name__ = "some_service_2"

        def hello(self):
            return 'i am server 2'

    srv = rpc.Server(Srv())
    another_srv = rpc.Server(AnotherSrv())
    gevent.spawn(srv.run)
    gevent.spawn(another_srv.run)

    client = rpc.Client('some_service_client')
    for i in range(5):
        who_i_am = client.hello()
        app.logger.debug(who_i_am)
        assert who_i_am == 'i am server 1' or who_i_am == 'i am server 2'

    with pytest.raises(MissingConfigException):
        client = rpc.Client('some_service_client', version='2.0')

    client.close()
    srv.close()
    another_srv.close()
示例#11
0
    def test_access_log(self):
        clear_handlers()
        app = Zask(__name__)
        app.config = self.default_config
        init_zerorpc(app)

        @access_log
        class MySrv(object):
            def sleep(self):
                time.sleep(1)

        srv = MySrv()
        print "Should print an access log:"
        srv.sleep()
示例#12
0
    def test_joined_name(self):
        """Model has a separate primary key; it should set a new name."""

        app = Zask(__name__)
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
        db = sqlalchemy.SQLAlchemy(app)

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

        class Donald(Duck):
            id = db.Column(db.Integer, db.ForeignKey(Duck.id), primary_key=True)

        self.assertEqual(Donald.__tablename__, 'donald')
示例#13
0
    def test_access_log(self):
        clear_handlers()
        app = Zask(__name__)
        app.config = self.default_config
        init_zerorpc(app)

        @access_log
        class MySrv(object):
            def sleep(self):
                time.sleep(1)

        srv = MySrv()
        print "Should print an access log:"
        srv.sleep()
示例#14
0
    def test_single_name(self):
        """Single table inheritance should not set a new name."""

        app = Zask(__name__)
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
        db = sqlalchemy.SQLAlchemy(app)

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

        class Mallard(Duck):
            pass

        self.assertEqual(Mallard.__tablename__, 'duck')
示例#15
0
    def test_single_name(self):
        """Single table inheritance should not set a new name."""

        app = Zask(__name__)
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
        db = sqlalchemy.SQLAlchemy(app)

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

        class Mallard(Duck):
            pass

        self.assertEqual(Mallard.__tablename__, 'duck')
示例#16
0
    def test_default_session_scoping(self):
        app = Zask(__name__)
        app.config['SQLALCHEMY_ENGINE'] = 'sqlite://'
        db = sqlalchemy.SQLAlchemy(app)

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

        db.create_all()

        fb = FOOBar()
        db.session.add(fb)
        assert fb in db.session

        db.drop_all()
示例#17
0
    def test_prod_mode(self):
        clear_handlers()
        app = Zask(__name__)
        app.config = self.default_config
        app.config['DEBUG'] = False
        init_zerorpc(app)

        channel_logger.error("error")
        gevent_logger.error("error")
        core_logger.error("error")

        print ""
        print "printing file:"
        with open(app.config['ERROR_LOG'], 'r') as fin:
            print fin.read()
示例#18
0
    def test_prod_mode(self):
        clear_handlers()
        app = Zask(__name__)
        app.config = self.default_config
        app.config['DEBUG'] = False
        init_zerorpc(app)

        channel_logger.error("error")
        gevent_logger.error("error")
        core_logger.error("error")

        print ""
        print "printing file:"
        with open(app.config['ERROR_LOG'], 'r') as fin:
            print fin.read()
示例#19
0
    def test_mixin_name(self):
        """Primary key provided by mixin should still allow model to set tablename."""

        app = Zask(__name__)
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
        db = sqlalchemy.SQLAlchemy(app)

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

        class Duck(Base, db.Model):
            pass

        self.assertFalse(hasattr(Base, '__tablename__'))
        self.assertEqual(Duck.__tablename__, 'duck')
示例#20
0
    def test_default_session_scoping(self):
        app = Zask(__name__)
        app.config['SQLALCHEMY_ENGINE'] = 'sqlite://'
        db = sqlalchemy.SQLAlchemy(app)

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

        db.create_all()

        fb = FOOBar()
        db.session.add(fb)
        assert fb in db.session

        db.drop_all()
示例#21
0
    def test_prod_mode(self):
        app = Zask(__name__)
        app.config = self.default_config
        app.config['DEBUG'] = False
        app.config['PRODUCTION_LOGGING_LEVEL'] = 'warning'
        app.logger.debug("debug")
        app.logger.info("info")
        app.logger.warning("warning")
        app.logger.error("error")
        app.logger.exception("exception")

        print ''
        print 'printing file:'
        with open(app.config['ERROR_LOG'], 'r') as fin:
            print fin.read()
示例#22
0
    def test_mixin_name(self):
        """Primary key provided by mixin should still allow model to set tablename."""

        app = Zask(__name__)
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
        db = sqlalchemy.SQLAlchemy(app)

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

        class Duck(Base, db.Model):
            pass

        self.assertFalse(hasattr(Base, '__tablename__'))
        self.assertEqual(Duck.__tablename__, 'duck')
示例#23
0
    def setUp(self):
        self.app = Zask(__name__)
        self.app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
        self.db = sqlalchemy.SQLAlchemy(self.app)

        self.Todo = make_todo_model(self.db)
        self.db.create_all()
示例#24
0
    def test_abstract_name(self):
        """Abstract model should not set a name.  Subclass should set a name."""

        app = Zask(__name__)
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
        db = sqlalchemy.SQLAlchemy(app)

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

        class Duck(Base):
            pass

        self.assertFalse(hasattr(Base, '__tablename__'))
        self.assertEqual(Duck.__tablename__, 'duck')
示例#25
0
    def test_joined_name(self):
        """Model has a separate primary key; it should set a new name."""

        app = Zask(__name__)
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
        db = sqlalchemy.SQLAlchemy(app)

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

        class Donald(Duck):
            id = db.Column(db.Integer,
                           db.ForeignKey(Duck.id),
                           primary_key=True)

        self.assertEqual(Donald.__tablename__, 'donald')
示例#26
0
    def test_abstract_name(self):
        """Abstract model should not set a name.  Subclass should set a name."""

        app = Zask(__name__)
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
        db = sqlalchemy.SQLAlchemy(app)

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

        class Duck(Base):
            pass

        self.assertFalse(hasattr(Base, '__tablename__'))
        self.assertEqual(Duck.__tablename__, 'duck')
示例#27
0
def test_custom_header():

    @access_log
    class Srv(object):
        __version__ = "2.0"
        __service_name__ = "some_service"

        def hello(self):
            return 'world'

    app = Zask(__name__)
    endpoint = random_ipc_endpoint()
    app.config['DEBUG'] = False # for testing accesslog
    app.config['ZERORPC_SOME_SERVICE'] = {
        '2.0': endpoint,
        '1.0': endpoint,
        'client_keys': ['key'],
        'access_key': 'key',
        'default': '2.0'
    }
    rpc = ZeroRPC(app, middlewares=[
        CONFIG_CUSTOME_HEADER_MIDDLEWARE,
        ACCESS_LOG_MIDDLEWARE
    ])

    srv = rpc.Server(Srv())
    gevent.spawn(srv.run)

    client = rpc.Client('some_service')
    channel = client._multiplexer.channel()
    hbchan = HeartBeatOnChannel(channel, freq=client._heartbeat_freq,
            passive=client._passive_heartbeat)
    bufchan = BufferedChannel(hbchan, inqueue_size=100)
    request_event = client._generate_request_event(bufchan, 'hello', None)
    assert request_event.header['access_key'] == 'key'
    assert request_event.header['service_version'] == '2.0'
    assert client.hello() == 'world'

    app.config['ZERORPC_SOME_SERVICE']['default'] = '1.0'
    with pytest.raises(zerorpc.RemoteError) as excinfo:
        client.hello()
    assert 'VersionNotMatchException' in str(excinfo.value)

    app.config['ZERORPC_SOME_SERVICE']['default'] = '2.0'
    app.config['ZERORPC_SOME_SERVICE']['access_key'] = 'key_error'
    with pytest.raises(zerorpc.RemoteError) as excinfo:
        client.hello()
    assert 'NoSuchAccessKeyException' in str(excinfo.value)

    app.config['ZERORPC_SOME_SERVICE']['client_keys'] = None
    client = rpc.Client('some_service')
    assert client.hello() == 'world'

    client.close()
    srv.close()
示例#28
0
    def test_default_query_class(self):
        app = Zask(__name__)
        app.config['SQLALCHEMY_ENGINE'] = 'sqlite://'
        app.config['TESTING'] = True
        db = sqlalchemy.SQLAlchemy(app)

        class Parent(db.Model):
            id = db.Column(db.Integer, primary_key=True)
            children = db.relationship("Child", backref = "parents", lazy='dynamic')
        class Child(db.Model):
            id = db.Column(db.Integer, primary_key=True)
            parent_id = db.Column(db.Integer, db.ForeignKey('parent.id'))
        p = Parent()
        c = Child()
        c.parent = p
        self.assertEqual(type(Parent.query), BaseQuery)
        self.assertEqual(type(Child.query), BaseQuery)
        self.assertTrue(isinstance(p.children, BaseQuery))
示例#29
0
    def test_name(self):
        app = Zask(__name__)
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
        db = sqlalchemy.SQLAlchemy(app)

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

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

        class Ham(db.Model):
            __tablename__ = 'spam'
            id = db.Column(db.Integer, primary_key=True)

        self.assertEqual(FOOBar.__tablename__, 'foo_bar')
        self.assertEqual(BazBar.__tablename__, 'baz_bar')
        self.assertEqual(Ham.__tablename__, 'spam')
示例#30
0
    def test_name(self):
        app = Zask(__name__)
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
        db = sqlalchemy.SQLAlchemy(app)

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

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

        class Ham(db.Model):
            __tablename__ = 'spam'
            id = db.Column(db.Integer, primary_key=True)

        self.assertEqual(FOOBar.__tablename__, 'foo_bar')
        self.assertEqual(BazBar.__tablename__, 'baz_bar')
        self.assertEqual(Ham.__tablename__, 'spam')
示例#31
0
    def test_complex_inheritance(self):
        """Joined table inheritance, but the new primary key is provided by a mixin, not directly on the class."""

        app = Zask(__name__)
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
        db = sqlalchemy.SQLAlchemy(app)

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

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

        class RubberDuck(IdMixin, Duck):
            pass

        self.assertEqual(RubberDuck.__tablename__, 'rubber_duck')
示例#32
0
    def test_session_scoping_changing(self):
        app = Zask(__name__)
        app.config['SQLALCHEMY_ENGINE'] = 'sqlite://'

        def scopefunc():
            return id(dict())

        db = sqlalchemy.SQLAlchemy(app, session_options=dict(scopefunc=scopefunc))

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

        db.create_all()

        fb = FOOBar()
        db.session.add(fb)
        assert fb not in db.session  # because a new scope is generated on each call

        db.drop_all()
示例#33
0
    def test_session_scoping_changing(self):
        app = Zask(__name__)
        app.config['SQLALCHEMY_ENGINE'] = 'sqlite://'

        def scopefunc():
            return id(dict())

        db = sqlalchemy.SQLAlchemy(app,
                                   session_options=dict(scopefunc=scopefunc))

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

        db.create_all()

        fb = FOOBar()
        db.session.add(fb)
        assert fb not in db.session  # because a new scope is generated on each call

        db.drop_all()
示例#34
0
def test_config_missing():
    app = Zask(__name__)
    try:
        app.config.from_pyfile('missing.cfg')
    except IOError as e:
        msg = str(e)
        assert msg.startswith('[Errno 2] Unable to load configuration '
                              'file (No such file or directory):')
        assert msg.endswith("missing.cfg'")
    else:
        assert 0, 'expected config'
    assert not app.config.from_pyfile('missing.cfg', silent=True)
示例#35
0
    def test_complex_inheritance(self):
        """Joined table inheritance, but the new primary key is provided by a mixin, not directly on the class."""

        app = Zask(__name__)
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
        db = sqlalchemy.SQLAlchemy(app)

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

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

        class RubberDuck(IdMixin, Duck):
            pass

        self.assertEqual(RubberDuck.__tablename__, 'rubber_duck')
示例#36
0
def test_custom_header():

    @access_log
    class Srv(object):
        __version__ = "2.0"
        __service_name__ = "some_service"

        def hello(self):
            return 'world'

    app = Zask(__name__)
    endpoint = random_ipc_endpoint()
    app.config['DEBUG'] = False  # for testing accesslog
    app.config['ZERORPC_SOME_SERVICE'] = {
        '2.0': endpoint,
        '1.0': endpoint,
        'client_keys': ['key'],
        'access_key': 'key',
        'default': '2.0'
    }
    rpc = ZeroRPC(app, middlewares=[
        CONFIG_CUSTOME_HEADER_MIDDLEWARE,
        ACCESS_LOG_MIDDLEWARE
    ])

    srv = rpc.Server(Srv())
    gevent.spawn(srv.run)

    client = rpc.Client('some_service')
    channel = client._multiplexer.channel()
    hbchan = HeartBeatOnChannel(channel, freq=client._heartbeat_freq,
                                passive=client._passive_heartbeat)
    bufchan = BufferedChannel(hbchan, inqueue_size=100)
    request_event = client._generate_request_event(bufchan, 'hello', None)
    assert request_event.header['access_key'] == 'key'
    assert request_event.header['service_version'] == '2.0'
    assert client.hello() == 'world'

    app.config['ZERORPC_SOME_SERVICE']['default'] = '1.0'
    with pytest.raises(zerorpc.RemoteError) as excinfo:
        client.hello()
    assert 'VersionNotMatchException' in str(excinfo.value)

    app.config['ZERORPC_SOME_SERVICE']['default'] = '2.0'
    app.config['ZERORPC_SOME_SERVICE']['access_key'] = 'key_error'
    with pytest.raises(zerorpc.RemoteError) as excinfo:
        client.hello()
    assert 'NoSuchAccessKeyException' in str(excinfo.value)

    app.config['ZERORPC_SOME_SERVICE']['client_keys'] = None
    client = rpc.Client('some_service')
    assert client.hello() == 'world'

    client.close()
    srv.close()
示例#37
0
    def test_default_query_class(self):
        app = Zask(__name__)
        app.config['SQLALCHEMY_ENGINE'] = 'sqlite://'
        app.config['TESTING'] = True
        db = sqlalchemy.SQLAlchemy(app)

        class Parent(db.Model):
            id = db.Column(db.Integer, primary_key=True)
            children = db.relationship("Child",
                                       backref="parents",
                                       lazy='dynamic')

        class Child(db.Model):
            id = db.Column(db.Integer, primary_key=True)
            parent_id = db.Column(db.Integer, db.ForeignKey('parent.id'))

        p = Parent()
        c = Child()
        c.parent = p
        self.assertEqual(type(Parent.query), BaseQuery)
        self.assertEqual(type(Child.query), BaseQuery)
        self.assertTrue(isinstance(p.children, BaseQuery))
示例#38
0
def test_get_namespace():
    app = Zask(__name__)
    app.config['FOO_OPTION_1'] = 'foo option 1'
    app.config['FOO_OPTION_2'] = 'foo option 2'
    app.config['BAR_STUFF_1'] = 'bar stuff 1'
    app.config['BAR_STUFF_2'] = 'bar stuff 2'
    foo_options = app.config.get_namespace('FOO_')
    assert 2 == len(foo_options)
    assert 'foo option 1' == foo_options['option_1']
    assert 'foo option 2' == foo_options['option_2']
    bar_options = app.config.get_namespace('BAR_', lowercase=False)
    assert 2 == len(bar_options)
    assert 'bar stuff 1' == bar_options['STUFF_1']
    assert 'bar stuff 2' == bar_options['STUFF_2']
    foo_options = app.config.get_namespace('FOO_', trim_namespace=False)
    assert 2 == len(foo_options)
    assert 'foo option 1' == foo_options['foo_option_1']
    assert 'foo option 2' == foo_options['foo_option_2']
    bar_options = app.config.get_namespace('BAR_', lowercase=False, trim_namespace=False)
    assert 2 == len(bar_options)
    assert 'bar stuff 1' == bar_options['BAR_STUFF_1']
    assert 'bar stuff 2' == bar_options['BAR_STUFF_2']
示例#39
0
def test_config_from_envvar_missing():
    env = os.environ
    try:
        os.environ = {'FOO_SETTINGS': 'missing.cfg'}
        try:
            app = Zask(__name__)
            app.config.from_envvar('FOO_SETTINGS')
        except IOError as e:
            msg = str(e)
            assert msg.startswith('[Errno 2] Unable to load configuration '
                                  'file (No such file or directory):')
            assert msg.endswith("missing.cfg'")
        else:
            assert False, 'expected IOError'
        assert not app.config.from_envvar('FOO_SETTINGS', silent=True)
    finally:
        os.environ = env
示例#40
0
def test_no_middleware_context():
    app = Zask(__name__)
    endpoint = random_ipc_endpoint()
    rpc = ZeroRPC(app, middlewares=None)

    class Srv(rpc.Server):
        __version__ = "1.0"
        __service_name__ = "some_service"

        def hello(self):
            return 'world'

    srv = Srv()
    assert srv._context._middlewares == []
    srv.bind(endpoint)
    gevent.spawn(srv.run)

    client = rpc.Client(endpoint)
    assert client.hello() == 'world'
示例#41
0
def test_config_from_envvar():
    env = os.environ
    try:
        os.environ = {}
        app = Zask(__name__)
        config = app.config
        try:
            app.config.from_envvar('FOO_SETTINGS')
        except RuntimeError as e:
            assert "'FOO_SETTINGS' is not set" in str(e)
        else:
            assert 0, 'expected exception'
        assert not app.config.from_envvar('FOO_SETTINGS', silent=True)

        os.environ = {'FOO_SETTINGS': __file__.rsplit('.', 1)[0] + '.py'}
        assert app.config.from_envvar('FOO_SETTINGS')
        common_object_test(app)
    finally:
        os.environ = env
示例#42
0
def test_no_middleware_runtime():
    app = Zask(__name__)
    endpoint = random_ipc_endpoint()
    rpc = ZeroRPC(app)

    class Srv(rpc.Server):
        __version__ = "1.0"
        __service_name__ = "some_service"

        def hello(self):
            return 'world'

    default_context = zerorpc.Context().get_instance()
    srv = Srv(context=default_context)
    assert srv._context._middlewares == []
    srv.bind(endpoint)
    gevent.spawn(srv.run)

    client = rpc.Client(endpoint, context=default_context)
    assert client.hello() == 'world'
示例#43
0
def test_get_namespace():
    app = Zask(__name__)
    app.config['FOO_OPTION_1'] = 'foo option 1'
    app.config['FOO_OPTION_2'] = 'foo option 2'
    app.config['BAR_STUFF_1'] = 'bar stuff 1'
    app.config['BAR_STUFF_2'] = 'bar stuff 2'
    foo_options = app.config.get_namespace('FOO_')
    assert 2 == len(foo_options)
    assert 'foo option 1' == foo_options['option_1']
    assert 'foo option 2' == foo_options['option_2']
    bar_options = app.config.get_namespace('BAR_', lowercase=False)
    assert 2 == len(bar_options)
    assert 'bar stuff 1' == bar_options['STUFF_1']
    assert 'bar stuff 2' == bar_options['STUFF_2']
    foo_options = app.config.get_namespace('FOO_', trim_namespace=False)
    assert 2 == len(foo_options)
    assert 'foo option 1' == foo_options['foo_option_1']
    assert 'foo option 2' == foo_options['foo_option_2']
    bar_options = app.config.get_namespace('BAR_',
                                           lowercase=False,
                                           trim_namespace=False)
    assert 2 == len(bar_options)
    assert 'bar stuff 1' == bar_options['BAR_STUFF_1']
    assert 'bar stuff 2' == bar_options['BAR_STUFF_2']
示例#44
0
 def test_default_config(self):
     clear_handlers()
     app = Zask(__name__)
     app.config = {"DEBUG": True, "ERROR_LOG": ""}
     init_zerorpc(app)
     assert app.config['ZERORPC_ACCESS_LOG'] == '/tmp/zerorpc.access.log'
示例#45
0
 def setUp(self):
     self.app = Zask(__name__)
     self.app.config['SQLALCHEMY_ENGINE'] = 'sqlite://'
示例#46
0
    def test_basic_binds(self):
        import tempfile
        _, db1 = tempfile.mkstemp()
        _, db2 = tempfile.mkstemp()

        def _remove_files():
            import os
            try:
                os.remove(db1)
                os.remove(db2)
            except IOError:
                pass
        atexit.register(_remove_files)

        app = Zask(__name__)
        app.config['SQLALCHEMY_ENGINE'] = 'sqlite://'
        app.config['SQLALCHEMY_BINDS'] = {
            'foo':      'sqlite:///' + db1,
            'bar':      'sqlite:///' + db2
        }
        db = sqlalchemy.SQLAlchemy(app)

        class Foo(db.Model):
            __bind_key__ = 'foo'
            __table_args__ = {"info": {"bind_key": "foo"}}
            id = db.Column(db.Integer, primary_key=True)

        class Bar(db.Model):
            __bind_key__ = 'bar'
            id = db.Column(db.Integer, primary_key=True)

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

        db.create_all()

        # simple way to check if the engines are looked up properly
        self.assertEqual(db.get_engine(app, None), db.engine)
        for key in 'foo', 'bar':
            engine = db.get_engine(app, key)
            connector = app.extensions['sqlalchemy'].connectors[key]
            self.assertEqual(engine, connector.get_engine())
            self.assertEqual(str(engine.url),
                             app.config['SQLALCHEMY_BINDS'][key])

        # do the models have the correct engines?
        self.assertEqual(db.metadata.tables['foo'].info['bind_key'], 'foo')
        self.assertEqual(db.metadata.tables['bar'].info['bind_key'], 'bar')
        self.assertEqual(db.metadata.tables['baz'].info.get('bind_key'), None)

        # see the tables created in an engine
        metadata = db.MetaData()
        metadata.reflect(bind=db.get_engine(app, 'foo'))
        self.assertEqual(len(metadata.tables), 1)
        self.assertTrue('foo' in metadata.tables)

        metadata = db.MetaData()
        metadata.reflect(bind=db.get_engine(app, 'bar'))
        self.assertEqual(len(metadata.tables), 1)
        self.assertTrue('bar' in metadata.tables)

        metadata = db.MetaData()
        metadata.reflect(bind=db.get_engine(app))
        self.assertEqual(len(metadata.tables), 1)
        self.assertTrue('baz' in metadata.tables)

        # do the session have the right binds set?
        self.assertEqual(db.get_binds(app), {
            Foo.__table__: db.get_engine(app, 'foo'),
            Bar.__table__: db.get_engine(app, 'bar'),
            Baz.__table__: db.get_engine(app, None)
        })

        # do the models in the same session?
        foo = Foo()
        bar = Bar()
        baz = Baz()
        db.session.add(foo)
        db.session.add(bar)
        db.session.add(baz)
        assert foo in db.session
        assert bar in db.session
        assert baz in db.session

        db.drop_all()
示例#47
0
    def test_basic_binds(self):
        import tempfile
        _, db1 = tempfile.mkstemp()
        _, db2 = tempfile.mkstemp()

        def _remove_files():
            import os
            try:
                os.remove(db1)
                os.remove(db2)
            except IOError:
                pass

        atexit.register(_remove_files)

        app = Zask(__name__)
        app.config['SQLALCHEMY_ENGINE'] = 'sqlite://'
        app.config['SQLALCHEMY_BINDS'] = {
            'foo': 'sqlite:///' + db1,
            'bar': 'sqlite:///' + db2
        }
        db = sqlalchemy.SQLAlchemy(app)

        class Foo(db.Model):
            __bind_key__ = 'foo'
            __table_args__ = {"info": {"bind_key": "foo"}}
            id = db.Column(db.Integer, primary_key=True)

        class Bar(db.Model):
            __bind_key__ = 'bar'
            id = db.Column(db.Integer, primary_key=True)

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

        db.create_all()

        # simple way to check if the engines are looked up properly
        self.assertEqual(db.get_engine(app, None), db.engine)
        for key in 'foo', 'bar':
            engine = db.get_engine(app, key)
            connector = app.extensions['sqlalchemy'].connectors[key]
            self.assertEqual(engine, connector.get_engine())
            self.assertEqual(str(engine.url),
                             app.config['SQLALCHEMY_BINDS'][key])

        # do the models have the correct engines?
        self.assertEqual(db.metadata.tables['foo'].info['bind_key'], 'foo')
        self.assertEqual(db.metadata.tables['bar'].info['bind_key'], 'bar')
        self.assertEqual(db.metadata.tables['baz'].info.get('bind_key'), None)

        # see the tables created in an engine
        metadata = db.MetaData()
        metadata.reflect(bind=db.get_engine(app, 'foo'))
        self.assertEqual(len(metadata.tables), 1)
        self.assertTrue('foo' in metadata.tables)

        metadata = db.MetaData()
        metadata.reflect(bind=db.get_engine(app, 'bar'))
        self.assertEqual(len(metadata.tables), 1)
        self.assertTrue('bar' in metadata.tables)

        metadata = db.MetaData()
        metadata.reflect(bind=db.get_engine(app))
        self.assertEqual(len(metadata.tables), 1)
        self.assertTrue('baz' in metadata.tables)

        # do the session have the right binds set?
        self.assertEqual(
            db.get_binds(app), {
                Foo.__table__: db.get_engine(app, 'foo'),
                Bar.__table__: db.get_engine(app, 'bar'),
                Baz.__table__: db.get_engine(app, None)
            })

        # do the models in the same session?
        foo = Foo()
        bar = Bar()
        baz = Baz()
        db.session.add(foo)
        db.session.add(bar)
        db.session.add(baz)
        assert foo in db.session
        assert bar in db.session
        assert baz in db.session

        db.drop_all()
示例#48
0
def test_config_from_file():
    app = Zask(__name__)
    app.config.from_pyfile(__file__.rsplit('.', 1)[0] + '.py')
    common_object_test(app)
示例#49
0
def test_default_config():
    app = Zask(__name__)
    config = app.config
    assert app.config['DEBUG'] == True