Пример #1
0
def test_request_response():
    #-----------------------------------
    # preparations
    #-----------------------------------

    # cleanup a bit
    inject.clear()

    def my_config(binder):
        binder.bind('settings', None)
    inject.configure(my_config)


    # log.startLogging(sys.stdout)

    server = Server(port=9998, no_ssl=True)
    server.bind()

    client = Client(port=9998, no_ssl=True)
    yield client.connect()

    response = yield client.call_sync('ping')

    assert response == 'pong'

    client.shutdown()
    server.shutdown()
Пример #2
0
async def logging_support(hax_state: HaxGlobalState):
    def configure(binder: inject.Binder):
        binder.bind(HaxGlobalState, hax_state)

    inject.clear_and_configure(configure)
    yield ''
    inject.clear()
Пример #3
0
def test_request_response_no_such_command():
    #-----------------------------------
    # preparations
    #-----------------------------------

    # cleanup a bit
    inject.clear()

    def my_config(binder):
        binder.bind('settings', None)

    inject.configure(my_config)

    log.startLogging(sys.stdout)

    server = Server(port=9996, no_ssl=True)
    server.bind()

    client = Client(port=9996, no_ssl=True)
    yield client.connect()

    with pytest.raises(ApiError):
        yield client.call_sync('hoho')

    client.shutdown()
    server.shutdown()
Пример #4
0
def test_request_response_no_such_command():
    #-----------------------------------
    # preparations
    #-----------------------------------

    # cleanup a bit
    inject.clear()

    def my_config(binder):
        binder.bind('settings', None)
    inject.configure(my_config)


    log.startLogging(sys.stdout)

    server = Server(port=9996, no_ssl=True)
    server.bind()

    client = Client(port=9996, no_ssl=True)
    yield client.connect()

    with pytest.raises(ApiError):
        yield client.call_sync('hoho')

    client.shutdown()
    server.shutdown()
Пример #5
0
def test_request_response():
    #-----------------------------------
    # preparations
    #-----------------------------------

    # cleanup a bit
    inject.clear()

    def my_config(binder):
        binder.bind('settings', None)

    inject.configure(my_config)

    # log.startLogging(sys.stdout)

    server = Server(port=9998, no_ssl=True)
    server.bind()

    client = Client(port=9998, no_ssl=True)
    yield client.connect()

    response = yield client.call_sync('ping')

    assert response == 'pong'

    client.shutdown()
    server.shutdown()
Пример #6
0
def backend_and_solver(_backend, _solver):
    def conf(binder):
        binder.install(_backend)
        binder.install(_solver)

    inject.clear_and_configure(conf)
    yield
    inject.clear()
Пример #7
0
 def test_is_configured__should_return_true_when_injector_present(self):
     assert inject.is_configured() is False
     
     inject.configure()
     assert inject.is_configured() is True
     
     inject.clear()
     assert inject.is_configured() is False
Пример #8
0
    def test_is_configured__should_return_true_when_injector_present(self):
        assert inject.is_configured() is False

        inject.configure()
        assert inject.is_configured() is True

        inject.clear()
        assert inject.is_configured() is False
Пример #9
0
def client(db) -> FlaskClient:
    inject.clear()

    os.environ['FLASK_ENV'] = 'testing'

    application = create_app()
    application.testing = True
    return application.test_client()
Пример #10
0
def injector(bind_config):

    def configurator(binder):
        for key, val in bind_config.items():
            binder.bind(key, val)

    inject.clear_and_configure(configurator)
    yield
    inject.clear()
Пример #11
0
def set_inject():
    inject.clear_and_configure(lambda x: x.bind(ChangelogRepo, Mock()).bind(
        ContactsRepo, Mock()).bind(DiscountsRepo, Mock(
        )).bind(GeoRepo, Mock()).bind(HousesRepo, Mock()).bind(
            MembersRepo, Mock()).bind(OccupancyRepo, Mock()).bind(
                PricesRepo, Mock()).bind(ReservationsCacheRepo, Mock()).bind(
                    ReservationsRepo, Mock()).bind(RoomsRepo, Mock()).bind(
                        RoomTypesRepo, Mock()).bind(PoliciesRepo, Mock()))
    yield
    inject.clear()
Пример #12
0
def run_jupyter(dir, fname, path=None, copy_dir=False):
    dir = dir.replace('/', os.path.sep)
    fname = os.path.join(dir, fname)
    import nbformat
    from nbconvert.preprocessors import ExecutePreprocessor
    with open(fname) as f:
        nb = nbformat.read(f, as_version=4)
    if copy_dir:
        copytree(dir, path)
    ep = ExecutePreprocessor(timeout=600)
    ep.preprocess(nb, {'metadata': {'path': path}} if path is not None else {})
    inject.clear()
Пример #13
0
def test_large_grid(solver_, backend_):
    try:
        configure_application(solver_, backend_)
        c = Config(TimeGridConf(1, 1, 1), SpatialMeshConf(100, 1),
                   inner_regions=[InnerRegionConf('tube',
                                                  Tube((50, 50, 10), (50, 50, 12), 10, 90),
                                                  10)])
        r = Runner(c.make())
        r.eval_and_write_fields_without_particles()
        assert r.simulation.potential.data.mean() >= 0
        assert r.simulation.potential.data.mean() <= 10
        assert abs(r.simulation.potential.data.max() - 10) < 0.01
        assert abs(r.simulation.potential.data.min()) < 0.01
    finally:
        inject.clear()
Пример #14
0
def test_events():
    inject.clear()
    rc = yield redis.Connection(dbid=2)
    yield rc.flushdb()

    eb = EventBus(rc)
    yield eb.connect()

    test_events.test = None

    def boo(pattern, message):
        assert message == 'hoho'
        assert pattern == 'foo'
        test_events.test = message

    eb.on('foo', boo)

    yield eb.fire_event('foo', 'hoho')

    def check_results():
        assert test_events.test == 'hoho'

    reactor.callLater(50, check_results)
Пример #15
0
def test_events():
    inject.clear()
    rc = yield redis.Connection(dbid=2)
    yield rc.flushdb()

    eb = EventBus(rc)
    yield eb.connect()

    test_events.test = None

    def boo(pattern, message):
        assert message == 'hoho'
        assert pattern == 'foo'
        test_events.test = message

    eb.on('foo', boo)

    yield eb.fire_event('foo', 'hoho')

    def check_results():
        assert test_events.test == 'hoho'

    reactor.callLater(50, check_results)
Пример #16
0
def test_main(mocker, capsys, tmpdir, monkeypatch, solver_, backend_):
    inject.clear()
    monkeypatch.chdir(tmpdir)
    config = tmpdir.join("test_main.conf")
    Config(time_grid=TimeGridConf(10, 5, 1)).export_to_fname("test_main.conf")
    argv = ["main.py", str(config)]
    if solver_ != ' ':
        argv += ["--solver", solver_]
    if backend_ != ' ':
        argv += ["--backend", backend_]
    mocker.patch("sys.argv", argv)
    main()
    inject.clear()
    out, err = capsys.readouterr()
    assert err == ""
    assert out == f"""Trying to guess input file type: {config}
### Config:
time_grid = TimeGridConf(total=10.0, save_step=5.0, step=1.0)
spatial_mesh = SpatialMeshConf(size=array([10., 10., 10.]), step=array([1., 1., 1.]))
sources = []
inner_regions = []
output_file = OutputFileConf(prefix='out_', suffix='.h5', format_='cpp')
boundary_conditions = BoundaryConditionsConf(right=0.0, left=0.0, bottom=0.0, top=0.0, near=0.0, far=0.0)
particle_interaction_model = ParticleInteractionModelConf(model='PIC')
external_fields = []
Writing initial fields to file
Writing to file out_fieldsWithoutParticles.h5
Writing step 0 to file
Writing to file out_0000000.h5
\rTime step from 0 to 1 of 10\rTime step from 1 to 2 of 10\rTime step from 2 to 3 of 10\rTime step from 3 to 4 of 10\rTime step from 4 to 5 of 10
Writing step 5 to file
Writing to file out_0000005.h5
\rTime step from 5 to 6 of 10\rTime step from 6 to 7 of 10\rTime step from 7 to 8 of 10\rTime step from 8 to 9 of 10\rTime step from 9 to 10 of 10
Writing step 10 to file
Writing to file out_0000010.h5
"""

    argv = ["main.py", "out_0000005.h5"]
    if solver_ != ' ':
        argv += ["--solver", solver_]
    if backend_ != ' ':
        argv += ["--backend", backend_]
    mocker.patch("sys.argv", argv)
    main()
    inject.clear()
    out, err = capsys.readouterr()
    assert err == ""
    assert out == f"""Trying to guess input file type: out_0000005.h5
Пример #17
0
 def client(self, aiohttp_client):
     loop = asyncio.get_event_loop()
     inject.clear()
     app = build_app()
     inject.clear_and_configure(configure)
     return loop.run_until_complete(aiohttp_client(app))
Пример #18
0
 def tearDown(self):
     inject.clear()
 def setUp(self):
     inject.clear()
def client() -> FlaskClient:
    inject.clear()
    application = create_application()
    application.testing = True
    return application.test_client()
Пример #21
0
 def tearDown(self) -> None:
     inject.clear()
Пример #22
0
def test_tasks():

    #-----------------------------------
    # preparations
    #-----------------------------------

    # cleanup a bit
    inject.clear()

    rc = yield redis.Connection(dbid=2)
    eb = EventBus(rc)
    yield eb.connect()

    def my_config(binder):
        binder.bind(redis.Connection, rc)
        binder.bind(EventBus, eb)
        binder.bind('settings', None)

    inject.configure(my_config)

    yield rc.flushdb()

    api = inject.instance(ApiRpcServer)


    #-----------------------------------
    # Test itself
    #-----------------------------------

    # this will emulate some long-running process
    task_defered = defer.Deferred()


    # this is mock that will execute our long-running process
    task = flexmock()
    task.should_receive('foo').with_args(int, 123, 'test').once().and_return(task_defered)

    # register our task
    api.tasks['baz'] = task.foo

    # start server -> real server on tcp port
    server = Server(port=9997, no_ssl=True)
    server.bind()

    # real client connecton here
    client = Client(port=9997, no_ssl=True)
    yield client.connect()


    # client calls a task
    task = Task('baz')
    yield client.call(task, 123, 'test')

    yield sleep(0.1)

    assert task.id > 0
    assert task.name == 'baz'

    assert task.is_running is True

    assert len(server.rpc_server.tasks_running) == 1
    assert server.rpc_server.tasks_running[task.id]['name'] == 'baz'
    assert len(server.rpc_server.task_list()) == 1

    # no data should be on client
    yield sleep(0.1)
    assert task.data == []
    assert task.response is None

    # now server sends some progress
    yield server.clients[0].send_event('task.progress.%s' % task.id, 'nami-nami')


    # and client should receive this data
    yield sleep(0.1)

    assert task.data == ['nami-nami']
    assert task.is_running is True
    assert task.response is None

    # now our long-running process stopped and returned some result
    yield task_defered.callback('this is respnse')


    # and client should recieve this resul
    yield sleep(0.1)

    assert task.data == ['nami-nami']
    assert task.is_running == False
    assert task.response == 'this is respnse'

    assert len(server.rpc_server.tasks_running) == 0
    assert len(server.rpc_server.task_list()) == 0


    #-----------------------------------
    # Cleanup
    #-----------------------------------

    client.shutdown()
    server.shutdown()

    yield sleep(0.1)
Пример #23
0
def test_task_terminate():

    #-----------------------------------
    # preparations
    #-----------------------------------

    # cleanup a bit
    inject.clear()

    rc = yield redis.Connection(dbid=2)
    eb = EventBus(rc)
    yield eb.connect()

    def my_config(binder):
        binder.bind(redis.Connection, rc)
        binder.bind(EventBus, eb)
        binder.bind('settings', None)

    inject.configure(my_config)

    yield rc.flushdb()

    api = inject.instance(ApiRpcServer)

    #-----------------------------------
    # Test itself
    #-----------------------------------

    # this will emulate some long-running process
    task_defered = defer.Deferred()

    # this is mock that will execute our long-running process
    task = flexmock()
    task.should_receive('foo').with_args(
        int, 123, 'test').once().and_return(task_defered)

    # register our task
    api.tasks['baz'] = task.foo

    # start server -> real server on tcp port
    server = Server(port=9987, no_ssl=True)
    server.bind()

    # real client connecton here
    client = Client(port=9987, no_ssl=True)
    yield client.connect()

    # client calls a task
    task = Task('baz')
    yield client.call(task, 123, 'test')

    yield sleep(0.1)

    assert task.id > 0
    assert task.name == 'baz'

    assert task.is_running is True

    # now client terminates the task
    yield sleep(0.1)

    client.terminate_task(task.id)

    yield sleep(0.1)

    assert task.is_running is False

    #-----------------------------------
    # Cleanup
    #-----------------------------------

    client.shutdown()
    server.shutdown()

    yield sleep(0.1)
Пример #24
0
def backend(_backend):
    inject.clear_and_configure(_backend)
    yield
    inject.clear()
Пример #25
0
def solver(_solver):
    inject.clear_and_configure(_solver)
    yield
    inject.clear()
Пример #26
0
def configure_dependencies():
    inject.clear_and_configure(
        lambda binder: binder.bind(StrictRedis, fakeredis.FakeStrictRedis()),
        bind_in_runtime=False)
    yield
    inject.clear()
Пример #27
0
import inject
from math import sqrt
from datetime import datetime, timedelta

import letsfuk
from tornado.testing import AsyncHTTPTestCase

from letsfuk import Config
from letsfuk.models.user import User as UserModel
from letsfuk.db import Base, commit
from letsfuk.db.models import (Station, Subscriber, PrivateChat, StationChat,
                               PushNotification, User, Session, Unread)
from letsfuk.ioc import testing_configuration

# Set up database for all tests
inject.clear()
inject.clear_and_configure(testing_configuration)
engine = inject.instance('db_engine')
Base.metadata.drop_all(bind=engine)
Base.metadata.create_all(engine)


class Generator(object):
    letters = [chr(ord('a') + i) for i in range(26)]
    domains = [
        "hotmail.com", "gmail.com", "aol.com", "mail.com", "mail.koz",
        "yahoo.com"
    ]

    def __init__(self):
        self.generated = set()
Пример #28
0
def inject_services(configurator):
    inject.clear_and_configure(configurator)
    yield
    inject.clear()
Пример #29
0
def inject_services(configurator):
    inject.clear_and_configure(configurator)
    yield
    inject.clear()
Пример #30
0
def teardown():
    inject.clear()
Пример #31
0
def test_tasks():

    #-----------------------------------
    # preparations
    #-----------------------------------

    # cleanup a bit
    inject.clear()

    rc = yield redis.Connection(dbid=2)
    eb = EventBus(rc)
    yield eb.connect()

    def my_config(binder):
        binder.bind(redis.Connection, rc)
        binder.bind(EventBus, eb)
        binder.bind('settings', None)

    inject.configure(my_config)

    yield rc.flushdb()

    api = inject.instance(ApiRpcServer)

    #-----------------------------------
    # Test itself
    #-----------------------------------

    # this will emulate some long-running process
    task_defered = defer.Deferred()

    # this is mock that will execute our long-running process
    task = flexmock()
    task.should_receive('foo').with_args(
        int, 123, 'test').once().and_return(task_defered)

    # register our task
    api.tasks['baz'] = task.foo

    # start server -> real server on tcp port
    server = Server(port=9997, no_ssl=True)
    server.bind()

    # real client connecton here
    client = Client(port=9997, no_ssl=True)
    yield client.connect()

    # client calls a task
    task = Task('baz')
    yield client.call(task, 123, 'test')

    yield sleep(0.1)

    assert task.id > 0
    assert task.name == 'baz'

    assert task.is_running is True

    assert len(server.rpc_server.tasks_running) == 1
    assert server.rpc_server.tasks_running[task.id]['name'] == 'baz'
    assert len(server.rpc_server.task_list()) == 1

    # no data should be on client
    yield sleep(0.1)
    assert task.data == []
    assert task.response is None

    # now server sends some progress
    yield server.clients[0].send_event('task.progress.%s' % task.id,
                                       'nami-nami')

    # and client should receive this data
    yield sleep(0.1)

    assert task.data == ['nami-nami']
    assert task.is_running is True
    assert task.response is None

    # now our long-running process stopped and returned some result
    yield task_defered.callback('this is respnse')

    # and client should recieve this resul
    yield sleep(0.1)

    assert task.data == ['nami-nami']
    assert task.is_running == False
    assert task.response == 'this is respnse'

    assert len(server.rpc_server.tasks_running) == 0
    assert len(server.rpc_server.task_list()) == 0

    #-----------------------------------
    # Cleanup
    #-----------------------------------

    client.shutdown()
    server.shutdown()

    yield sleep(0.1)
Пример #32
0
 def tearDown(self):
     inject.clear()
Пример #33
0
def test_task_terminate():

    #-----------------------------------
    # preparations
    #-----------------------------------

    # cleanup a bit
    inject.clear()

    rc = yield redis.Connection(dbid=2)
    eb = EventBus(rc)
    yield eb.connect()

    def my_config(binder):
        binder.bind(redis.Connection, rc)
        binder.bind(EventBus, eb)
        binder.bind('settings', None)

    inject.configure(my_config)

    yield rc.flushdb()

    api = inject.instance(ApiRpcServer)


    #-----------------------------------
    # Test itself
    #-----------------------------------

    # this will emulate some long-running process
    task_defered = defer.Deferred()


    # this is mock that will execute our long-running process
    task = flexmock()
    task.should_receive('foo').with_args(int, 123, 'test').once().and_return(task_defered)

    # register our task
    api.tasks['baz'] = task.foo

    # start server -> real server on tcp port
    server = Server(port=9987, no_ssl=True)
    server.bind()

    # real client connecton here
    client = Client(port=9987, no_ssl=True)
    yield client.connect()


    # client calls a task
    task = Task('baz')
    yield client.call(task, 123, 'test')

    yield sleep(0.1)

    assert task.id > 0
    assert task.name == 'baz'

    assert task.is_running is True


    # now client terminates the task
    yield sleep(0.1)

    client.terminate_task(task.id)

    yield sleep(0.1)

    assert task.is_running is False

    #-----------------------------------
    # Cleanup
    #-----------------------------------

    client.shutdown()
    server.shutdown()

    yield sleep(0.1)
def client() -> TestClient:
    inject.clear()
    app = create_application()
    return TestClient(app)