Ejemplo n.º 1
0
def text_request(reg):
    req = MockRequest(
        MockTextMessage('foo'),
        reg,
    )
    run(req.transform())
    return req
Ejemplo n.º 2
0
def test_flush():
    args = []
    kwargs = {}

    async def do_flush(*a, **k):
        args.extend(a)
        kwargs.update(k)

    mm = MiddlewareManager.instance()
    mm.middlewares = [AutoSleep]

    flush = mm.get('flush', do_flush)
    run(flush(None, [lyr.Stack([lyr.Text('hello'), lyr.Text('wassup')])]))

    assert args == [
        None,
        [
            lyr.Stack([
                lyr.RawText('hello'),
            ]),
            lyr.Stack([
                lyr.Sleep(0.7),
            ]),
            lyr.Stack([
                lyr.RawText('wassup'),
            ]),
        ]
    ]

    assert kwargs == {}
Ejemplo n.º 3
0
def test_facebook_button():
    fb = Facebook()
    s = stack(ButtonTemplate('foo', [UrlButton('foo', 'https://example.com')]))

    with patch.object(fb, '_send', return_value=instant_run()) as mock_send:
        run(fb.send(None, s))
        mock_send.assert_called_once_with(
            None, {
                'attachment': {
                    'type': 'template',
                    'payload': {
                        'template_type':
                        'button',
                        'text':
                        'foo',
                        'buttons': [
                            {
                                'type': 'web_url',
                                'title': 'foo',
                                'url': 'https://example.com'
                            },
                        ],
                    },
                },
            }, s)
Ejemplo n.º 4
0
def main():
    init_logger()
    init_uvloop()

    from bernard.conf import settings
    from os import getenv

    if settings.CODE_LIVE_RELOAD and getenv('_IN_CHILD') != 'yes':
        from ._live_reload import start_parent
        return start_parent()

    # noinspection PyBroadException
    try:
        from aiohttp import web
        from bernard.server import app
        from bernard.utils import run
        from bernard.platforms import start_all

        run(start_all())

        if settings.CODE_LIVE_RELOAD:
            init_live_reload(False)
    except Exception:
        logger.exception('Something bad happened while bootstraping')

        if settings.CODE_LIVE_RELOAD:
            init_live_reload(True)
    else:
        # noinspection PyArgumentList
        web.run_app(app, **settings.SERVER_BIND)
Ejemplo n.º 5
0
def test_text_trigger(text_request):
    with patch_conf(LOADER_CONFIG):
        tt_factory = trig.Text.builder(intents.BAZ)
        tt = tt_factory(text_request)
        assert run(tt.rank()) == 1.0

        tt_factory = trig.Text.builder(intents.FOO)
        tt = tt_factory(text_request)
        assert run(tt.rank()) == 0.0
Ejemplo n.º 6
0
def test_caller_extra():
    m = MiddlewareManager()

    rn = m.get('return_n', return_n)

    assert run(rn(0)) == 0

    with pytest.raises(ValueError):
        run(rn(0))
Ejemplo n.º 7
0
    def _init_loaders(self) -> None:
        """
        Gets loaders from conf, make instances and subscribe to them.
        """

        for loader in settings.I18N_INTENTS_LOADERS:
            loader_class = import_class(loader['loader'])
            instance = loader_class()
            instance.on_update(self.update)
            run(instance.load(**loader['params']))
Ejemplo n.º 8
0
def redis_store():
    store = RedisRegisterStore()
    run(store.async_init())
    yield store

    async def shutdown():
        store.pool.close()
        await store.pool.wait_closed()

    run(shutdown())
Ejemplo n.º 9
0
def test_platform_event():
    platform = Platform()
    mock_cb = Mock()
    data = MockEmptyMessage()
    responder = Responder(platform)

    platform.on_message(mock_cb)
    run(platform._notify(data, responder))

    mock_cb.assert_called_once_with(data, responder, True)
Ejemplo n.º 10
0
    def _init_loaders(self) -> None:
        """
        This creates the loaders instances and subscribes to their updates.
        """

        for loader in settings.I18N_TRANSLATION_LOADERS:
            loader_class = import_class(loader['loader'])
            instance = loader_class()
            instance.on_update(self.update)
            run(instance.load(**loader['params']))
Ejemplo n.º 11
0
def test_text_trigger(reg):
    intents.db.dict[None] = {
        'THANKS': [('thanks', 'no thanks')],
    }

    req = MockRequest(MockTextMessage('no thanks', True), reg)
    run(req.transform())
    ct_factory = Text.builder(intents.THANKS)
    ct: Text = ct_factory(req)

    assert run(ct.rank()) == 0.0
Ejemplo n.º 12
0
def test_facebook_sleep():
    duration = 0.001
    fb = Facebook()
    s = stack(Sleep(duration))

    start = time()
    # noinspection PyTypeChecker
    run(fb.send(None, s))
    stop = time()

    assert (stop - start) >= duration
Ejemplo n.º 13
0
def test_telegram_sleep():
    duration = 0.001
    tg = Telegram()
    s = stack(Sleep(duration))

    start = time()
    # noinspection PyTypeChecker
    run(tg.send(None, s))
    stop = time()

    assert (stop - start) >= duration
Ejemplo n.º 14
0
def test_load_translations_csv():
    mock_cb = Mock()
    data = {
        'FOO': 'éléphant',
        'BAR': 'baz',
    }

    loader = CsvTranslationLoader()
    loader.on_update(mock_cb)
    run(loader.load(file_path=TRANS_FILE_PATH))

    mock_cb.assert_called_once_with(data)
Ejemplo n.º 15
0
    def handle(self, *layers: BaseLayer):
        """
        Call this method to send a test message. Call it OUTSIDE the async
        loop. It will return when the message is fully handled.
        """

        self.sent = []
        stack = Stack(list(layers))
        message = TestMessage(stack)
        responder = TestResponder(self)

        run(self._notify(message, responder))
Ejemplo n.º 16
0
def test_transform_layers(reg):
    with patch_conf(LOADER_CONFIG):
        req = Request(
            MockTextMessage(),
            reg,
        )
        run(req.transform())
        stack = req.stack

        assert layers.RawText in stack._transformed
        assert stack.get_layer(layers.RawText).text == 'foo'
        assert len(stack.get_layers(layers.Text)) == 1
        assert len(stack.get_layers(layers.RawText)) == 1
Ejemplo n.º 17
0
def test_fsm_confused_state():
    with patch_conf(settings_file=ENGINE_SETTINGS_FILE):
        fsm = FSM()

        reg = Register({})
        req = Request(MockEmptyMessage(), reg)
        run(req.transform())
        assert fsm._confused_state(req) == BaseTestState

        reg = Register({Register.STATE: 'tests.issue_0001.states.Hello'})
        req = Request(MockEmptyMessage(), reg)
        run(req.transform())
        assert fsm._confused_state(req) == Hello
Ejemplo n.º 18
0
def test_next_not_called():
    m = MiddlewareManager()
    m.middlewares = [BadPlayer]

    rn = m.get('return_n', return_n)

    error_msg = '"BadPlayer.return_n" did not call `self.next()`, or forgot ' \
                'to await it'

    with pytest.raises(TypeError) as exec_info:
        run(rn(0))

    assert str(exec_info.value) == error_msg
Ejemplo n.º 19
0
def test_render():
    with patch_conf(LOADER_CONFIG):
        wd = WordDictionary()
        t = Translator(wd)
        req = MockRequest()

        req.flags = {'gender': 'unknown'}
        assert run(t.HELLO.render_list(req)) == ['hello', 'wassup?']

        req.flags = {'gender': 'male'}
        assert run(t.HELLO.render_list(req)) == ['hello boy', 'wassup?']

        req.flags = {'gender': 'female'}
        assert run(t.HELLO.render_list(req)) == ['hello girl', 'wassup?']
Ejemplo n.º 20
0
def test_translate():
    with patch_conf(LOADER_CONFIG_1):
        wd = WordDictionary()
        t = Translator(wd)
        req = MockRequest()

        req.locale = 'fr'
        assert run(t.HELLO.render(req)) == 'Bonjour'

        req.locale = 'en'
        assert run(t.HELLO.render(req)) == 'Hello'

        req.locale = 'de'
        assert run(t.HELLO.render(req)) == 'Bonjour'
Ejemplo n.º 21
0
def test_register_context_manager():
    store = MockRegisterStore()

    async def test():
        async with store.work_on_register('my-key') as reg:
            assert store.called['start']
            assert store.called['get']
            assert isinstance(reg, Register)
            assert reg == {'fake_context': True}
            reg.replacement = {'new_data': True}

        assert store.called['replace']
        assert store.called['finish']

    run(test())
Ejemplo n.º 22
0
def make_test_fsm() -> Tuple[FSM, TestPlatform]:
    """
    Generate both a FSM and a test platform for unit testing purposes.

    The will use the current configuration to load stories and transitions.
    """

    fsm = FSM()
    run(fsm.async_init())

    platform = TestPlatform()
    # noinspection PyTypeChecker
    platform.on_message(fsm.handle_message)

    return fsm, platform
Ejemplo n.º 23
0
def test_get_strings():
    with patch_conf(LOADER_CONFIG):
        db = IntentsDb()
        maker = IntentsMaker(db)
        req = MockRequest()

        assert run(maker.HELLO.strings()) == [('Bonjour',)]

        req.locale = 'fr'
        assert run(maker.HELLO.strings(req)) == [('Bonjour',)]

        req.locale = 'en'
        assert run(maker.HELLO.strings(req)) == [('Hello',)]

        req.locale = 'de'
        assert run(maker.HELLO.strings(req)) == [('Bonjour',)]
Ejemplo n.º 24
0
def test_intents_maker_singleton():
    with patch_conf(LOADER_CONFIG_3):
        from sys import modules
        if 'bernard.i18n' in modules:
            del modules['bernard.i18n']

        from bernard.i18n import intents as i
        assert run(i.FOO.strings()) == [('bar', ), ('baz', )]
Ejemplo n.º 25
0
def test_wrong_import():
    conf = dict(BASE_CONF)
    conf['DEFAULT_STATE'] = 'does.not.Exist'

    with patch_conf(conf):
        problems = run(get_fsm_problems())

    assert any(x.code == '00005' for x in problems)
Ejemplo n.º 26
0
def test_expand():
    a = AutoSleep(None)

    t = lyr.RawText('hello')
    assert run(alist(a.expand(None, t))) \
        == [lyr.RawText('hello'), lyr.Sleep(0.7)]

    t = lyr.Text('hello')
    assert run(alist(a.expand(None, t))) \
        == [lyr.RawText('hello'), lyr.Sleep(0.7)]

    t = lyr.MultiText('hello')
    assert run(alist(a.expand(None, t))) \
        == [lyr.RawText('hello'), lyr.Sleep(0.7)]

    t = lyr.Sleep(1.0)
    assert run(alist(a.expand(None, t))) == [lyr.Sleep(1.0)]
Ejemplo n.º 27
0
def test_patch_register():
    register = {}

    k = ReplyKeyboard([[KeyboardButton(
        text='Foo',
        choice='foo',
    )]])

    run(k.patch_register(register, None))

    assert register == {
        'choices': {
            'foo': {
                'intent': None,
                'text': 'Foo',
            }
        }
    }
Ejemplo n.º 28
0
def test_load_intents_csv():
    mock_cb = Mock()
    data = {
        'FOO': ['bar', 'baz'],
        'BAR': ['ᕕ( ՞ ᗜ ՞ )ᕗ', '∩༼˵☯‿☯˵༽つ¤=[]:::::>', 'c( ⁰ 〰 ⁰ )੭'],
        'BAZ': ['foo'],
    }
    file_path = os.path.join(
        os.path.dirname(__file__),
        'assets',
        'intents.csv',
    )

    loader = CsvIntentsLoader()
    loader.on_update(mock_cb)
    run(loader.load(file_path=file_path))

    mock_cb.assert_called_once_with(data)
Ejemplo n.º 29
0
def test_caller_stack():
    m = MiddlewareManager()
    m.middlewares = [
        AddOne,
        AddOne,
    ]

    rn = m.get('return_n', return_n)

    assert run(rn(40)) == 42
Ejemplo n.º 30
0
def test_redis_register_store(redis_store):
    key = 'my-key'
    register_key = 'register::content:my-key'
    lock_key = 'register::lock:my-key'

    assert redis_store.lock_key(key) == lock_key
    assert redis_store.register_key(key) == register_key

    async def test():
        with await redis_store.pool as r:
            await r.delete(register_key, lock_key)

        async with redis_store.work_on_register(key) as reg:
            assert reg == {}
            reg.replacement = {'key_was_set': True}

        async with redis_store.work_on_register(key) as reg:
            assert reg == {'key_was_set': True}

    run(test())