Example #1
0
 def test_forbidden_flash(self):
     # Bug 1005674
     flash_file = StaticFile("/path/to/playerWithControls.swf")
     environ = {"QUERY_STRING": "flv=http://example.com/logjammin.flv"}
     start_response = Mock()
     self.wn.serve(flash_file, environ, start_response)
     start_response.assert_called_with("403 Forbidden", [])
Example #2
0
    def test_enter__exit(self):
        hub = Hub()
        P = hub.poller = Mock()
        hub.init = Mock()

        on_close = Mock()
        hub.on_close.append(on_close)

        with hub:
            hub.init.assert_called_with()

            read_A = Mock()
            read_B = Mock()
            hub.update_readers({10: read_A, File(11): read_B})
            write_A = Mock()
            write_B = Mock()
            hub.update_writers({20: write_A, File(21): write_B})
            self.assertTrue(hub.readers)
            self.assertTrue(hub.writers)
        self.assertFalse(hub.readers)
        self.assertFalse(hub.writers)

        P.unregister.assert_has_calls([call(10), call(11), call(20), call(21)], any_order=True)

        on_close.assert_called_with(hub)
Example #3
0
    def test_recv_edu(self):
        recv_observer = Mock()
        recv_observer.return_value = defer.succeed(())

        self.federation.register_edu_handler("m.test", recv_observer)

        yield self.mock_resource.trigger(
            "PUT",
            "/_matrix/federation/v1/send/1001000/",
            """{
                "origin": "remote",
                "origin_server_ts": 1001000,
                "pdus": [],
                "edus": [
                    {
                        "origin": "remote",
                        "destination": "test",
                        "edu_type": "m.test",
                        "content": {"testing": "reply here"}
                    }
                ]
            }""",
        )

        recv_observer.assert_called_with("remote", {"testing": "reply here"})
Example #4
0
class TestWebQueue(unittest.TestCase):
    def setUp(self):
        self.rb = Mock(spec=rb.RBHandler)
        controller.rb_handler["rb"] = self.rb
        self.response = Mock()
        self.app = Server()

        self.queue_patch = patch("rhythmweb.controller.rb.Queue", spec=rb.Queue)
        self.queue_class = self.queue_patch.start()
        self.queue = Mock(spec=rb.Queue)
        self.queue_class.return_value = self.queue

    def tearDown(self):
        self.queue_patch.stop()

    def test_basic_do_get(self):
        self.queue.get_play_queue.return_value = [Stub(id=1), Stub(id=2), Stub(id=3)]
        result = handle_request(self.app, environ("/rest/queue"), self.response)
        self.response.assert_called_with(
            "200 OK",
            [("Content-type", "application/json; charset=UTF-8"), ("Cache-Control: ", "no-cache; must-revalidate")],
        )
        returned = json.loads(result)
        self.queue.get_play_queue.assert_called_with()
        for index, entry in enumerate(returned["entries"], 1):
            self.assertEquals(index, entry["id"])

    def test_basic_do_post(self):
        result = handle_request(self.app, environ("/rest/queue", post_data="bla=1"), self.response)
        self.response.assert_called_with("405 method POST not allowed", [("Content-type", "text/html; charset=UTF-8")])
Example #5
0
    def test_initialization(self, NeuralNet):
        input = Mock(__name__="InputLayer", __bases__=(InputLayer,))
        hidden1, hidden2, output = [Mock(__name__="MockLayer", __bases__=(Layer,)) for i in range(3)]
        nn = NeuralNet(
            layers=[
                (input, {"shape": (10, 10), "name": "input"}),
                (hidden1, {"some": "param", "another": "param"}),
                (hidden2, {}),
                (output, {"name": "output"}),
            ],
            input_shape=(10, 10),
            mock1_some="iwin",
        )
        out = nn.initialize_layers(nn.layers)

        input.assert_called_with(name="input", shape=(10, 10))
        nn.layers_["input"] is input.return_value

        hidden1.assert_called_with(incoming=input.return_value, name="mock1", some="iwin", another="param")
        nn.layers_["mock1"] is hidden1.return_value

        hidden2.assert_called_with(incoming=hidden1.return_value, name="mock2")
        nn.layers_["mock2"] is hidden2.return_value

        output.assert_called_with(incoming=hidden2.return_value, name="output")

        assert out is nn.layers_["output"]
Example #6
0
    def test_diff(self, mock_time):
        ptool = self.get_obj()
        content1 = "line1\nline2"
        content2 = "line3"

        self.now = 1345640723

        def time_rv():
            self.now += 1
            return self.now

        mock_time.side_effect = time_rv

        rv = ["line1", "line2", "line3"]
        func = Mock()
        func.return_value = rv
        self.assertItemsEqual(ptool._diff(content1, content2, func), rv)
        func.assert_called_with(["line1", "line2"], ["line3"])

        func.reset_mock()
        mock_time.reset_mock()

        def time_rv():
            self.now += 5
            return self.now

        mock_time.side_effect = time_rv

        def slow_diff(content1, content2):
            for i in range(1, 10):
                yield "line%s" % i

        func.side_effect = slow_diff
        self.assertFalse(ptool._diff(content1, content2, func), rv)
        func.assert_called_with(["line1", "line2"], ["line3"])
    def test_rmtree_ignore_unlink_rmdir_exception(self):
        dir1_list = ["dir2", "file"]
        empty_list = []
        mock_listdir = Mock()
        mock_listdir.side_effect = [dir1_list, empty_list]

        mock_isdir = Mock()
        mock_isdir.side_effect = [True, False]

        mock_unlink = Mock()
        mock_unlink.side_effect = [OSError]

        mock_rmdir = Mock()
        mock_rmdir.side_effect = [0, OSError]

        mock_islink = Mock()
        mock_islink.return_value = False

        with nested(
            patch("gluster.gfapi.Volume.listdir", mock_listdir),
            patch("gluster.gfapi.Volume.isdir", mock_isdir),
            patch("gluster.gfapi.Volume.islink", mock_islink),
            patch("gluster.gfapi.Volume.unlink", mock_unlink),
            patch("gluster.gfapi.Volume.rmdir", mock_rmdir),
        ):
            self.vol.rmtree("dir1", True)
            mock_rmdir.assert_any_call("dir1/dir2")
            mock_unlink.assert_called_once_with("dir1/file")
            mock_rmdir.assert_called_with("dir1")
Example #8
0
    def test_inactive_login_fails(self):
        """ Make sure we can't login with an inactive user """
        from pyramid_signup.models import User

        user = User(username="sontek", password="temp")

        self.session.add(user)
        self.session.flush()

        from pyramid_signup.views import AuthController

        self.config.add_route("index", "/")
        self.config.include("pyramid_signup")

        request = self.get_csrf_request(
            post={"submit": True, "Username": "sontek", "Password": "temp"}, request_method="POST"
        )

        flash = Mock()

        request.session.flash = flash

        view = AuthController(request)
        view.login()

        flash.assert_called_with(u"Your account is not active, please check your e-mail.", "error")
Example #9
0
    def test_register_existing_user(self):
        from pyramid_signup.views import RegisterController
        from pyramid_mailer.mailer import DummyMailer
        from pyramid_mailer.interfaces import IMailer
        from pyramid_signup.models import User

        self.config.include("pyramid_signup")
        self.config.registry.registerUtility(DummyMailer(), IMailer)

        self.config.add_route("index", "/")

        admin = User(username="sontek", password="temp")
        self.session.add(admin)
        self.session.flush()

        request = self.get_csrf_request(
            post={
                "Username": "sontek",
                "Password": {"value": "test123", "confirm": "test123"},
                "Email": "sontek@gmail.com",
            },
            request_method="POST",
        )

        flash = Mock()
        request.session.flash = flash

        controller = RegisterController(request)
        controller.register()

        flash.assert_called_with(u"That username is already used.", "error")
Example #10
0
    def test_canInstall(self, mock_canInstall):
        posix = self.get_obj()
        entry = lxml.etree.Element("Path", name="test", type="file")

        # first, test superclass canInstall failure
        mock_canInstall.return_value = False
        self.assertFalse(posix.canInstall(entry))
        mock_canInstall.assert_called_with(posix, entry)

        # next, test fully_specified failure
        posix.logger.error.reset_mock()
        mock_canInstall.reset_mock()
        mock_canInstall.return_value = True
        mock_fully_spec = Mock()
        mock_fully_spec.return_value = False
        posix._handlers[entry.get("type")].fully_specified = mock_fully_spec
        self.assertFalse(posix.canInstall(entry))
        mock_canInstall.assert_called_with(posix, entry)
        mock_fully_spec.assert_called_with(entry)
        self.assertTrue(posix.logger.error.called)

        # finally, test success
        posix.logger.error.reset_mock()
        mock_canInstall.reset_mock()
        mock_fully_spec.reset_mock()
        mock_fully_spec.return_value = True
        self.assertTrue(posix.canInstall(entry))
        mock_canInstall.assert_called_with(posix, entry)
        mock_fully_spec.assert_called_with(entry)
        self.assertFalse(posix.logger.error.called)
Example #11
0
    def test_viewmapper(self):
        from nefertari.view import ViewMapper

        bc1 = Mock()
        bc3 = Mock()
        bc2 = Mock()

        class MyView(object):
            Model = Mock

            def __init__(self, ctx, req):
                self._before_calls = {"index": [bc1], "show": [bc3]}
                self._after_calls = {"show": [bc2]}
                self._json_params = {}
                self.context = "foo"
                self.request = Mock(action="index")

            @wrap_me(before=bc2)
            def index(self):
                return ["thing"]

        request = MagicMock()
        resource = MagicMock(actions=["index"])

        wrapper = ViewMapper(**{"attr": "index"})(MyView)
        result = wrapper(resource, request)

        assert request.filters == {"show": [bc2]}
        assert request.action == "index"
        assert result == ["thing"]

        bc1.assert_called_with(request=request)
        assert not bc2.called
        assert not bc3.called
def test_api_call_context(pingpong_thrift_client, pingpong_service_key, pingpong_thrift_service, fake_time):
    from thrift_connector.hooks import before_call, after_call

    mock_before_hook = Mock()
    mock_after_hook = Mock()
    before_call.register(mock_before_hook)
    after_call.register(mock_after_hook)

    pool = ClientPool(
        pingpong_thrift_service,
        pingpong_thrift_client.host,
        pingpong_thrift_client.port,
        name=pingpong_service_key,
        raise_empty=False,
        max_conn=3,
        connction_class=pingpong_thrift_client.pool.connction_class,
    )
    pool.ping()

    # get one client manually, there should be one client in pool,
    # since there's only one call
    client = pool.get_client()
    assert client.test_connection()
    pool.put_back_connection(client)

    mock_before_hook.assert_called_with(pool, client, "ping", fake_time.time())
    mock_after_hook.assert_called_with(pool, client, "ping", fake_time.time(), 0, "pong")
Example #13
0
class TestMakeScript:
    def setUp(self):
        self.make_file_executable = Mock()
        self.write_file = Mock()

        def capture(name, contents):
            self.name = name
            self.contents = contents

        self.write_file.side_effect = capture

        bindir = Scripts(make_file_executable=self.make_file_executable, write_file=self.write_file)
        bindir.add_script("trash-put", "trashcli.cmds", "put")

    def test_should_set_executable_permission(self):
        self.make_file_executable.assert_called_with("trash-put")

    def test_should_write_the_script(self):
        self.write_file.assert_called_with("trash-put", mock.ANY)

    def test_the_script_should_call_the_right_function_from_the_right_module(self):
        args, kwargs = self.write_file.call_args
        (_, contents) = args
        expected = dedent(
            """\
            #!/usr/bin/env python
            from __future__ import absolute_import
            import sys
            from trashcli.cmds import put as main
            sys.exit(main())
            """
        )
        assert_equals(expected, contents, "Expected:\n---\n%s---\n" "Actual  :\n---\n%s---\n" % (expected, contents))
Example #14
0
 def test_forbidden_flash_no_qs(self):
     # Bug 1005674
     flash_file = StaticFile("/path/to/playerWithControls.swf")
     environ = {"QUERY_STRING": ""}
     start_response = Mock()
     self.wn.serve(flash_file, environ, start_response)
     start_response.assert_called_with("403 Forbidden", [])
Example #15
0
    def test_logout(self):
        from horus.views import AuthController
        from horus.tests.models import User
        from horus.interfaces import IUserClass
        from horus.interfaces import IActivationClass
        from horus.tests.models import Activation

        self.config.registry.registerUtility(Activation, IActivationClass)
        self.config.registry.registerUtility(User, IUserClass)
        self.config.add_route("index", "/")
        self.config.include("horus")
        request = testing.DummyRequest()

        flash = Mock()
        invalidate = Mock()

        request.user = Mock()
        request.session = Mock()
        request.session.invalidate = invalidate
        request.session.flash = flash

        view = AuthController(request)
        with patch("horus.views.forget") as forget:
            with patch("horus.views.HTTPFound") as HTTPFound:
                view.logout()
                flash.assert_called_with("Logged out successfully.", "success")
                forget.assert_called_with(request)
                assert invalidate.called
                assert HTTPFound.called
Example #16
0
    def test_registration_craps_out(self):
        from pyramid_signup.views import RegisterController
        from pyramid_mailer.interfaces import IMailer

        def send(message):
            raise Exception("I broke!")

        mailer = Mock()
        mailer.send = send

        self.config.include("pyramid_signup")
        self.config.registry.registerUtility(mailer, IMailer)

        self.config.add_route("index", "/")

        request = self.get_csrf_request(
            post={
                "Username": "admin",
                "Password": {"value": "test123", "confirm": "test123"},
                "Email": "sontek@gmail.com",
            },
            request_method="POST",
        )

        flash = Mock()
        request.session.flash = flash

        request.user = Mock()
        controller = RegisterController(request)
        controller.register()

        flash.assert_called_with("I broke!", "error")
Example #17
0
    def test_forgot_password_valid_user(self):
        from horus.views import ForgotPasswordController
        from pyramid_mailer.interfaces import IMailer
        from pyramid_mailer.mailer import DummyMailer
        from horus.interfaces import IUserClass
        from horus.tests.models import User

        self.config.registry.registerUtility(User, IUserClass)

        self.config.add_route("index", "/")
        self.config.include("horus")
        self.config.registry.registerUtility(DummyMailer(), IMailer)

        user = User(username="sontek", password="temp", email="sontek@gmail.com")
        user.password = "foo"

        self.session.add(user)
        self.session.flush()

        request = self.get_csrf_request(post={"email": "sontek@gmail.com"}, request_method="POST")

        request.user = None

        flash = Mock()
        request.session.flash = flash

        view = ForgotPasswordController(request)
        response = view.forgot_password()

        flash.assert_called_with("Please check your e-mail to reset your password.", "success")
        assert response.status_int == 302
Example #18
0
    def test_prepare_execute_chef_iaas_fail(self):
        self.dtrs.result = {
            "document": _get_one_node_cluster_doc("node1", "image1"),
            "node": {"ctx_method": "chef", "chef_attributes": {}, "chef_runlist": [], "chef_credential": "chef1"},
        }
        chef_creds = self._get_chef_creds()
        self.dtrs.credentials["chef"][("asterix", "chef1")] = chef_creds
        launch_id = _new_id()
        instance_id = _new_id()
        caller = "asterix"
        launch, nodes = self.core.prepare_provision(
            launch_id=launch_id, deployable_type="foo", instance_ids=[instance_id], site="site1", caller=caller
        )

        mock_chefapi = Mock()
        mock_chefnode = Mock()
        mock_node = Mock()
        mock_chefnode.return_value = mock_node
        mock_chefnode.list.return_value = {}
        with patch("epu.provisioner.test.util.FakeNodeDriver.create_node") as mock_method:
            mock_method.side_effect = InvalidCredsError()
            with patch.multiple("chef", ChefAPI=mock_chefapi, Node=mock_chefnode):
                self.core.execute_provision(launch, nodes, caller)
                mock_chefapi.assert_called_with(chef_creds["url"], chef_creds["client_key"], chef_creds["client_name"])
                self.assertEqual(mock_chefapi.call_count, 2)
                self.assertTrue(mock_chefnode.list.called)
                self.assertTrue(mock_node.delete.called)
        self.assertTrue(self.notifier.assure_state(states.FAILED))

        node = self.store.get_node(instance_id)
        self.assertEqual(node["chef_credential"], "chef1")
Example #19
0
    def test_proc_state_change_callback(self):
        self._start_container()

        m = Mock()
        pm = self.container.proc_manager
        pm.add_proc_state_changed_callback(m)

        pid = self._spawnproc(pm, "service")

        m.assert_called_with(ANY, ProcessStateEnum.RUNNING, self.container)
        self.assertIsInstance(m.call_args[0][0], SampleProcess)

        self.container.terminate_process(pid)

        m.assert_called_with(ANY, ProcessStateEnum.TERMINATED, self.container)
        self.assertIsInstance(m.call_args[0][0], SampleProcess)

        pm.remove_proc_state_changed_callback(m)

        cur_call_count = m.call_count
        pid = self._spawnproc(pm, "service")

        self.assertEquals(m.call_count, cur_call_count)  # should not have been touched

        self.container.terminate_process(pid)

        self.assertEquals(m.call_count, cur_call_count)  # should not have been touched
    def test_telnetrmq_statusagent_run_readstatus(self):
        agentconf = {
            "channel": {"exchange": "home.events", "type": "direct"},
            "messages": {"routing_key": "home.events.multimedia.music.telnet"},
        }
        telnetconf = {"host": "telnet.lan", "port": 20000}
        rmqconf = {"host": "rmq.lan"}
        agent = TelnetProbeStatus(agentconf, telnetconf, rmqconf)

        # Mocks creation
        telnetstatus = "data data"
        mockedreaduntil = Mock(return_value=telnetstatus)

        # Mocks binding
        agent.telnetclient = Mock()
        agent.telnetclient.client.read_some = mockedreaduntil

        # Setup generic mock for others methods wich are not tested here
        ignoredmocks = Mock()
        agent.telnetclient.connect = ignoredmocks
        agent.telnetclient.disconnect = ignoredmocks
        agent.basic_publish_json = Mock()

        # Call
        agent.run()

        # Tests
        mockedreaduntil.assert_called_with()
        agent.basic_publish_json.assert_called_with(telnetstatus)
Example #21
0
    def test_call(self):
        body = "body"
        headers = {"header": "value"}
        path = "/authorize"
        status_code = 200
        http_code = "200 OK"

        environment = {"PATH_INFO": path, "myvar": "value"}

        request_mock = Mock(spec=Request)
        request_class_mock = Mock(return_value=request_mock)

        responseMock = Mock(spec=Response)
        responseMock.body = body
        responseMock.headers = headers
        responseMock.status_code = status_code

        server_mock = Mock(spec=Provider)
        server_mock.dispatch.return_value = responseMock

        start_response_mock = Mock()

        wsgi = Wsgi(server=server_mock, authorize_uri=path, request_class=request_class_mock, env_vars=["myvar"])
        result = wsgi(environment, start_response_mock)

        request_class_mock.assert_called_with(environment)
        server_mock.dispatch.assert_called_with(request_mock, {"myvar": "value"})
        start_response_mock.assert_called_with(http_code, headers.items())
        self.assertEqual(result, [body])
Example #22
0
    def test_iterable_factory_outgoing(self):
        values = [Mock(name="value1", bar=1), Mock(name="value2", bar=2), Mock(name="value3", bar=3)]
        iterable = MagicMock(name="iterable")
        iterable.__iter__.return_value = iter(values)

        class MockResource(ModelResource):
            model_class = Mock()
            fields = [AttributeField(attribute="bar", type=int)]

        iterable_factory = Mock(name="iterable_factory", return_value=iterable)

        source_object = Mock(name="source_object")
        target_dict = {}

        field = IterableField(attribute="foo", resource_class=MockResource, iterable_factory=iterable_factory)

        field.handle_outgoing(mock_context(), source_object, target_dict)

        self.assertEqual(
            target_dict["foo"],
            [
                {"bar": 1, "_id": str(values[0].pk)},
                {"bar": 2, "_id": str(values[1].pk)},
                {"bar": 3, "_id": str(values[2].pk)},
            ],
        )

        iterable_factory.assert_called_with(source_object.foo)
Example #23
0
 def test_with_defaults(self, objective, get_output):
     loss_function, target = Mock(), Mock()
     loss_function.return_value = np.array([1, 2, 3])
     result = objective([1, 2, 3], loss_function=loss_function, target=target)
     assert result == 2.0
     get_output.assert_called_with(3, deterministic=False)
     loss_function.assert_called_with(get_output.return_value, target)
Example #24
0
 def test_execute_event(self):
     cmd_handler = CommandLineHandler()
     listener = Mock()
     cmd_handler.execute += listener
     cmd_handler.line_changed("a command")
     cmd_handler.finish()
     listener.assert_called_with("a command")
Example #25
0
    def test_enter__exit(self):
        hub = Hub()
        P = hub.poller = Mock()
        on_close = Mock()
        hub.on_close.add(on_close)

        try:
            read_A = Mock()
            read_B = Mock()
            hub.add_reader(10, read_A)
            hub.add_reader(File(11), read_B)
            write_A = Mock()
            write_B = Mock()
            hub.add_writer(20, write_A)
            hub.add_writer(File(21), write_B)
            self.assertTrue(hub.readers)
            self.assertTrue(hub.writers)
        finally:
            hub.close()
        self.assertFalse(hub.readers)
        self.assertFalse(hub.writers)

        P.unregister.assert_has_calls([call(10), call(11), call(20), call(21)], any_order=True)

        on_close.assert_called_with(hub)
Example #26
0
    def test_login_fails_bad_credentials(self):
        """ Make sure we can't login with bad credentials"""
        from horus.views import AuthController
        from horus.interfaces import IUserClass
        from horus.tests.models import User
        from horus.interfaces import IActivationClass
        from horus.tests.models import Activation

        self.config.registry.registerUtility(Activation, IActivationClass)

        self.config.registry.registerUtility(User, IUserClass)
        self.config.add_route("index", "/")
        self.config.include("horus")

        request = self.get_csrf_request(
            post={"submit": True, "username": "admin", "password": "test123"}, request_method="POST"
        )

        flash = Mock()
        request.session.flash = flash

        view = AuthController(request)
        view.login()

        flash.assert_called_with("Invalid username or password.", "error")
Example #27
0
    def test_entry_init(self, mock_entry_init):
        eset = self.get_obj()
        eset.entries = dict()
        evt = Mock()
        evt.filename = "test.txt"
        handler = Mock()
        handler.__basenames__ = []
        handler.__extensions__ = []
        handler.deprecated = False
        handler.experimental = False
        handler.__specific__ = True

        # test handling an event with the parent entry_init
        eset.entry_init(evt, handler)
        mock_entry_init.assert_called_with(eset, evt, entry_type=handler, specific=handler.get_regex.return_value)
        self.assertItemsEqual(eset.entries, dict())

        # test handling the event with a Cfg handler
        handler.__specific__ = False
        eset.entry_init(evt, handler)
        handler.assert_called_with(os.path.join(eset.path, evt.filename))
        self.assertItemsEqual(eset.entries, {evt.filename: handler.return_value})
        handler.return_value.handle_event.assert_called_with(evt)

        # test handling an event for an entry that already exists with
        # a Cfg handler
        handler.reset_mock()
        eset.entry_init(evt, handler)
        self.assertFalse(handler.called)
        self.assertItemsEqual(eset.entries, {evt.filename: handler.return_value})
        eset.entries[evt.filename].handle_event.assert_called_with(evt)
Example #28
0
    def test_inactive_login_fails(self):
        """Make sure we can't log in with an inactive user."""
        from horus.tests.models import User
        from horus.interfaces import IUserClass
        from horus.interfaces import IActivationClass
        from horus.tests.models import Activation

        self.config.registry.registerUtility(Activation, IActivationClass)

        self.config.registry.registerUtility(User, IUserClass)
        user = User(username="sontek", email="sontek@gmail.com")
        user.password = "foo"
        user.activation = Activation()
        self.session.add(user)
        self.session.flush()

        from horus.views import AuthController

        self.config.add_route("index", "/")
        self.config.include("horus")

        request = self.get_csrf_request(
            post={"submit": True, "username": "sontek", "password": "foo"}, request_method="POST"
        )

        flash = Mock()

        request.session.flash = flash

        view = AuthController(request)
        view.login()

        flash.assert_called_with("Your account is not active, please check your e-mail.", "error")
Example #29
0
    def test_annotate_decorator(self):
        from celery.app.task import Task

        class adX(Task):
            abstract = True

            def run(self, y, z, x):
                return y, z, x

        check = Mock()

        def deco(fun):
            def _inner(*args, **kwargs):
                check(*args, **kwargs)
                return fun(*args, **kwargs)

            return _inner

        app = Celery(set_as_current=False)
        app.conf.CELERY_ANNOTATIONS = {adX.name: {"@__call__": deco}}
        adX.bind(app)
        self.assertIs(adX.app, app)

        i = adX()
        i(2, 4, x=3)
        check.assert_called_with(i, 2, 4, x=3)

        i.annotate()
        i.annotate()
Example #30
0
class test_Message_DECODER_ENCODER:
    def setup(self):
        self.tgt = Mock()
        self._push = MESSAGE_DECODER(self.tgt)

    def test_simple(self):
        x = MESSAGE_ENCODER(self._push)("hello", hello_world)
        assert_equal(x, 1)
        self.tgt.assert_called_with(hello_world)

    def test_multi_push(self):
        x = MESSAGE_ENCODER(self._push)("hello", [hello_world, hello_other])
        assert_equal(x, 2)
        self.tgt.assert_has_calls([call(hello_world), call(hello_other)])

    def test_empty_push(self):
        MESSAGE_DECODER(self.tgt)(b"")
        self.tgt.assert_has_calls([])

    def test_buffering(self):
        buf = StringIO()
        MESSAGE_ENCODER(buf.write)("hello", hello_world)

        msg = buf.getvalue()
        split = len(msg) / 2
        buf1 = msg[:split]
        buf2 = msg[split:]

        decoder = MESSAGE_DECODER(self.tgt)

        decoder(buf1)
        self.tgt.assert_has_calls([])

        decoder(buf2)
        self.tgt.assert_called_with(hello_world)