示例#1
0
async def test_signals():
    x, y = X(), Y()

    on_stopped_mock = Mock()
    on_started_mock = Mock()

    @y.on_stopped.connect
    async def my_on_stopped(self, value, **kwargs):
        on_stopped_mock(self, value)

    @y.on_started.connect
    async def my_on_started(self, value, **kwargs):
        on_started_mock(self, value)

    await y.on_started.send(value=1)
    on_started_mock.assert_called_once_with(y, 1)

    await y.on_stopped.send(value=2)
    on_stopped_mock.assert_called_once_with(y, 2)
    assert on_started_mock.call_count == 1
    await x.on_started.send(value=3)
    await x.on_stopped(value=4)

    assert x.on_started.ident
    assert label(x.on_started)
    assert repr(x.on_started)

    assert on_started_mock.call_count == 1
    assert on_stopped_mock.call_count == 1
示例#2
0
def test_Proxy_from_source__py37_class_argument():
    class AbstractSource(abc.ABC):
        @abc.abstractmethod
        def add(self, arg):
            ...

        @abc.abstractmethod
        def mul(self, arg):
            ...

    class ConcreteSource(AbstractSource):
        def __init__(self, value):
            self.value = value

        def add(self, arg):
            return self.value + arg

        def mul(self, arg):
            return self.value * arg

    class ProxySource(Proxy[AbstractSource], source=AbstractSource):
        ...

    on_final_mock = Mock()
    on_final = Proxy(on_final_mock)

    p = ProxySource(lambda: ConcreteSource(2))
    p._add_proxy_finalizer(on_final)
    assert p.add(4) == 6
    assert p.mul(4) == 8

    on_final_mock.assert_called_once_with()
示例#3
0
 async def test_publish_message__wait_enabled(self, *, topic, app):
     producer = Mock(send_and_wait=AsyncMock())
     topic._get_producer = AsyncMock(return_value=producer)
     callback = Mock(name='callback')
     headers = {'k': 'v'}
     fm = topic.as_future_message(
         key='foo',
         value='bar',
         partition=130,
         timestamp=312.5134,
         headers=headers,
         key_serializer='json',
         value_serializer='json',
         callback=callback,
     )
     await topic.publish_message(fm, wait=True)
     key, headers = topic.prepare_key('foo', 'json', None, headers)
     value, headers = topic.prepare_value('bar', 'json', None, headers)
     producer.send_and_wait.coro.assert_called_once_with(
         topic.get_topic_name(),
         key,
         value,
         headers=headers,
         partition=130,
         timestamp=312.5134,
     )
     callback.assert_called_once_with(fm)
示例#4
0
def test_find_app():
    imp = Mock(name="imp")
    symbol_by_name = Mock(name="symbol_by_name")
    with patch("faust.cli.base.prepare_app") as prepare_app:
        res = find_app("foo", imp=imp, symbol_by_name=symbol_by_name)
        assert res is prepare_app.return_value
        symbol_by_name.assert_called_once_with("foo", imp=imp)
        prepare_app.assert_called_once_with(symbol_by_name.return_value, "foo")
示例#5
0
def test_find_app():
    imp = Mock(name='imp')
    symbol_by_name = Mock(name='symbol_by_name')
    with patch('faust.cli.base.prepare_app') as prepare_app:
        res = find_app('foo', imp=imp, symbol_by_name=symbol_by_name)
        assert res is prepare_app.return_value
        symbol_by_name.assert_called_once_with('foo', imp=imp)
        prepare_app.assert_called_once_with(symbol_by_name.return_value, 'foo')
示例#6
0
    async def test_transition_with(self, *, service):
        called = Mock()

        async def outer():
            assert 'FLAG' in service.diag.flags
            called()

        await service.transition_with('FLAG', outer())
        called.assert_called_once_with()
示例#7
0
    async def test_timer(self, *, app):
        did_execute = Mock(name='did_execute')

        @app.timer(0.1)
        async def foo():
            did_execute()
            await app.stop()

        await foo()
        did_execute.assert_called_once_with()
示例#8
0
def test_find_app__attribute_error():
    imp = Mock(name='imp')
    symbol_by_name = Mock(name='symbol_by_name')
    symbol_by_name.side_effect = AttributeError()
    with patch('faust.cli.base.prepare_app') as prepare_app:
        res = find_app('foo', imp=imp, symbol_by_name=symbol_by_name)
        assert res is prepare_app.return_value
        symbol_by_name.assert_called_once_with('foo', imp=imp)
        imp.assert_called_once_with('foo')
        prepare_app.assert_called_once_with(imp.return_value, 'foo')
示例#9
0
def test_find_app__attribute_error():
    imp = Mock(name="imp")
    symbol_by_name = Mock(name="symbol_by_name")
    symbol_by_name.side_effect = AttributeError()
    with patch("faust.cli.base.prepare_app") as prepare_app:
        res = find_app("foo", imp=imp, symbol_by_name=symbol_by_name)
        assert res is prepare_app.return_value
        symbol_by_name.assert_called_once_with("foo", imp=imp)
        imp.assert_called_once_with("foo")
        prepare_app.assert_called_once_with(imp.return_value, "foo")
示例#10
0
    async def test_from_awaitable(self, *, service):
        foo = Mock()

        async def mywait():
            foo()

        s = service.from_awaitable(mywait())
        async with s:
            pass
        foo.assert_called_once_with()
        await s.on_stop()
示例#11
0
    async def test_timer(self, *, app):
        did_execute = Mock(name='did_execute')
        app._producer = Mock(name='producer', flush=AsyncMock())

        @app.timer(0.1)
        async def foo():
            did_execute()
            await app.stop()

        await foo()
        did_execute.assert_called_once_with()
示例#12
0
    async def test_send_and_wait(self, *, manager):
        on_send = Mock()

        async def send(*args, **kwargs):
            on_send(*args, **kwargs)
            return done_future()
        manager.send = send

        await manager.send_and_wait('t', 'k', 'v', 3, 43.2, {})
        on_send.assert_called_once_with(
            't', 'k', 'v', 3, 43.2, {},
        )
示例#13
0
    async def test_from_awaitable__raises_cancel(self, *, service):
        foo = Mock()

        async def mywait():
            foo()
            raise asyncio.CancelledError()

        s = service.from_awaitable(mywait())
        with pytest.raises(asyncio.CancelledError):
            async with s:
                pass
        foo.assert_called_once_with()
示例#14
0
    async def test_crontab(self, *, app):
        did_execute = Mock(name='did_execute')
        app._producer = Mock(name='producer', flush=AsyncMock())

        with patch('faust.app.base.cron') as cron:
            cron.secs_for_next.return_value = 0.1

            @app.crontab('* * * * *')
            async def foo():
                did_execute()
                await app.stop()

            await foo()
            did_execute.assert_called_once_with()
示例#15
0
    async def test_from_awaitable__sleeping_is_cancelled(self, *, service):
        foo = Mock()

        async def mywait():
            foo()
            asyncio.ensure_future(s.stop())
            await asyncio.sleep(10.0)

        s = service.from_awaitable(mywait())
        async with s:
            await s.stop()
            await asyncio.sleep(0)
            await asyncio.sleep(0)
        foo.assert_called_once_with()
示例#16
0
    async def test_concurrent(self):
        t = Mock()

        async def wrapped():
            await asyncio.sleep(0.5)
            return t()

        x = StampedeWrapper(wrapped)

        async def caller():
            return await x()

        assert all(
            ret is t.return_value
            for ret in await asyncio.gather(*[caller() for i in range(10)]))

        t.assert_called_once_with()
示例#17
0
    async def test_crontab(self):
        m = Mock()

        with patch("mode.services.secs_for_next") as secs_for_next:
            secs_for_next.secs_for_next.return_value = 0.1

            class Foo(Service):
                @Service.crontab("* * * * *")
                async def foo(self):
                    m()
                    self._stopped.set()

            foo = Foo()
            foo.sleep = AsyncMock()
            async with foo:
                await asyncio.sleep(0)

            m.assert_called_once_with()
示例#18
0
    async def test_delegate_to_sinks(self, *, agent, agent2, foo_topic):
        agent2.send = AsyncMock(name='agent2.send')
        foo_topic.send = AsyncMock(name='foo_topic.send')
        sink_callback = Mock(name='sink_callback')
        sink_callback2_mock = Mock(name='sink_callback2_mock')

        async def sink_callback2(value):
            return sink_callback2_mock(value)

        agent._sinks = [
            agent2,
            foo_topic,
            sink_callback,
            sink_callback2,
        ]

        value = Mock(name='value')
        await agent._delegate_to_sinks(value)

        agent2.send.assert_called_once_with(value=value)
        foo_topic.send.assert_called_once_with(value=value)
        sink_callback.assert_called_once_with(value)
        sink_callback2_mock.assert_called_once_with(value)
示例#19
0
def test_import_from_cwd__custom_imp():
    imp = Mock(name="imp")
    with patch("importlib.import_module"):
        res = import_from_cwd(".foo", package="baz", imp=imp)
        assert res is imp.return_value
        imp.assert_called_once_with(".foo", package="baz")
示例#20
0
def test_sync_signals():
    x = SyncX()
    x2 = SyncX()

    on_stopped_mock = Mock()
    on_started_mock = Mock()

    @x.on_stopped.connect
    def my_on_stopped(self, code: int, reason: str, **kwargs: Any) -> None:
        assert kwargs["signal"] == x.on_stopped
        on_stopped_mock(self, code, reason)

    @x.on_started.connect
    def my_on_started(self, **kwargs: Any) -> None:
        assert kwargs["signal"] == x.on_started
        on_started_mock(self)

    x.on_started.send()
    on_started_mock.assert_called_once_with(x)

    x.on_stopped.send(303, "sorry not sorry")
    on_stopped_mock.assert_called_once_with(x, 303, "sorry not sorry")
    assert on_started_mock.call_count == 1

    assert x.on_started.ident
    assert label(x.on_started)
    assert label(X.on_started)
    assert repr(x.on_started)
    assert repr(X.on_started)

    prev, x.on_started.owner = x.on_started.owner, None
    assert label(x.on_started)
    x.on_started.owner = prev

    x.on_started()
    assert on_started_mock.call_count == 2

    x2.on_started.send()
    x2.on_started.send()

    assert on_started_mock.call_count == 2

    new_sender = Mock()
    sig2 = x2.on_started.clone(default_sender=new_sender)
    assert sig2.default_sender == new_sender

    sig3 = sig2.with_default_sender(None)
    assert sig3.default_sender == sig2.default_sender

    new_sender2 = Mock()
    sig4 = sig3.with_default_sender(new_sender2)
    assert sig4.default_sender == new_sender2

    sig4.name = ""
    sig4.__set_name__(sig3, "foo")
    assert sig4.name == "foo"
    assert sig4.owner == sig3
    sig4.__set_name__(sig2, "bar")
    assert sig4.name == "foo"
    assert sig4.owner == sig2

    sig4.default_sender = None
    with pytest.raises(TypeError):
        sig4.unpack_sender_from_args()
    assert sig4.unpack_sender_from_args(1) == (1, ())
    assert sig4.unpack_sender_from_args(1, 2) == (1, [2])

    partial_yes = sig4.connect(None)
    mockfun = Mock()
    partial_yes(mockfun)
    sig4.disconnect(mockfun)

    sig2.connect(mockfun, weak=True)
    sig2.disconnect(mockfun, weak=True)
示例#21
0
def test_sync_signals():
    x = SyncX()
    x2 = SyncX()

    on_stopped_mock = Mock()
    on_started_mock = Mock()

    @x.on_stopped.connect
    def my_on_stopped(self, code: int, reason: str, **kwargs: Any) -> None:
        assert kwargs['signal'] == x.on_stopped
        on_stopped_mock(self, code, reason)

    @x.on_started.connect
    def my_on_started(self, **kwargs: Any) -> None:
        assert kwargs['signal'] == x.on_started
        on_started_mock(self)

    x.on_started.send()
    on_started_mock.assert_called_once_with(x)

    x.on_stopped.send(303, 'sorry not sorry')
    on_stopped_mock.assert_called_once_with(x, 303, 'sorry not sorry')
    assert on_started_mock.call_count == 1

    x.on_started.send()
    assert on_started_mock.call_count == 2

    x2.on_started.send()
    x2.on_started.send()

    assert on_started_mock.call_count == 2

    new_sender = Mock()
    sig2 = x2.on_started.clone(default_sender=new_sender)
    assert sig2.default_sender == new_sender

    sig3 = sig2.with_default_sender(None)
    assert sig3.default_sender == sig2.default_sender

    new_sender2 = Mock()
    sig4 = sig3.with_default_sender(new_sender2)
    assert sig4.default_sender == new_sender2

    sig4.name = ''
    sig4.__set_name__(sig3, 'foo')
    assert sig4.name == 'foo'
    assert sig4.owner == sig3
    sig4.__set_name__(sig2, 'bar')
    assert sig4.name == 'foo'
    assert sig4.owner == sig2

    sig4.default_sender = None
    with pytest.raises(TypeError):
        sig4.unpack_sender_from_args()
    assert sig4.unpack_sender_from_args(1) == (1, ())
    assert sig4.unpack_sender_from_args(1, 2) == (1, [2])

    partial_yes = sig4.connect(None)
    mockfun = Mock()
    partial_yes(mockfun)
    sig4.disconnect(mockfun)

    sig2.connect(mockfun, weak=True)
    sig2.disconnect(mockfun, weak=True)
示例#22
0
def test_import_from_cwd__custom_imp():
    imp = Mock(name='imp')
    with patch('importlib.import_module'):
        res = import_from_cwd('.foo', package='baz', imp=imp)
        assert res is imp.return_value
        imp.assert_called_once_with('.foo', package='baz')
示例#23
0
def test__restore_from_keywords():
    m = Mock()
    _restore_from_keywords(m, {'foo': 1, 'bar': 20})
    m.assert_called_once_with(foo=1, bar=20)
示例#24
0
    async def assert_url_called(self, case, fut, method, url, **kwargs):
        case.url_request = AsyncMock("url_request")
        response = await fut
        assert response is case.url_request.coro.return_value
        case.url_request.coro.assert_called_once_with(
            method,
            url,
            **kwargs,
        )

    @pytest.mark.asyncio
    async def test_url_request(self, *, case, mock_http_client):
        case.app._http_client = mock_http_client
        case._maybe_recover_from_failed_state = Mock()
        await case.url_request("get", "http://foo/") == "foo"
        case._maybe_recover_from_failed_state.assert_called_once_with()

    @pytest.mark.asyncio
    @pytest.mark.http_session(status_code=500, max_failures=None)
    async def test_url_request_fails(self, *, case, mock_http_client):
        case.on_suite_fail = AsyncMock()
        case.sleep = AsyncMock()
        case.app._http_client = mock_http_client
        await case.url_request("get", "http://foo/") is None
        case.on_suite_fail.assert_called_once_with(ANY)

    @pytest.mark.asyncio
    @pytest.mark.http_session(status_code=500, max_failures=3)
    async def test_url_request_fails_recover(self, *, case, mock_http_client):
        case.sleep = AsyncMock()
        case.app._http_client = mock_http_client
示例#25
0
def test__restore_from_keywords():
    m = Mock()
    _restore_from_keywords(m, {"foo": 1, "bar": 20})
    m.assert_called_once_with(foo=1, bar=20)