当前位置: 首页>>代码示例>>Python>>正文


Python MockHttpServer.start方法代码示例

本文整理汇总了Python中vumi.tests.utils.MockHttpServer.start方法的典型用法代码示例。如果您正苦于以下问题:Python MockHttpServer.start方法的具体用法?Python MockHttpServer.start怎么用?Python MockHttpServer.start使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在vumi.tests.utils.MockHttpServer的用法示例。


在下文中一共展示了MockHttpServer.start方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: WeChatTestCase

# 需要导入模块: from vumi.tests.utils import MockHttpServer [as 别名]
# 或者: from vumi.tests.utils.MockHttpServer import start [as 别名]
class WeChatTestCase(VumiTestCase):

    def setUp(self):
        self.tx_helper = self.add_helper(TransportHelper(WeChatTransport))
        self.request_queue = DeferredQueue()
        self.mock_server = MockHttpServer(self.handle_api_request)
        self.add_cleanup(self.mock_server.stop)
        return self.mock_server.start()

    def handle_api_request(self, request):
        self.request_queue.put(request)
        return NOT_DONE_YET

    def get_transport(self, **config):
        defaults = {
            'api_url': self.mock_server.url,
            'auth_token': 'token',
            'twisted_endpoint': 'tcp:0',
            'wechat_appid': 'appid',
            'wechat_secret': 'secret',
            'embed_user_profile': False,
        }
        defaults.update(config)
        return self.tx_helper.get_transport(defaults)

    @inlineCallbacks
    def get_transport_with_access_token(self, access_token, **config):
        transport = yield self.get_transport(**config)
        yield transport.redis.set(WeChatTransport.ACCESS_TOKEN_KEY,
                                  access_token)
        returnValue(transport)
开发者ID:Nagato23,项目名称:vumi,代码行数:33,代码来源:test_wechat.py

示例2: TestYoPaymentHandler

# 需要导入模块: from vumi.tests.utils import MockHttpServer [as 别名]
# 或者: from vumi.tests.utils.MockHttpServer import start [as 别名]
class TestYoPaymentHandler(VumiTestCase):

    @inlineCallbacks
    def setUp(self):
        self.eh_helper = self.add_helper(EventHandlerHelper())
        yield self.eh_helper.setup_event_dispatcher(
            'afropinions', YoPaymentHandler, {
                'poll_manager_prefix': 'vumigo.',
                'username': 'username',
                'password': 'password',
                'url': None,
                'method': 'POST',
                'amount': 1000,
                'reason': 'foo',
            })
        self.eh_helper.track_event('survey_completed', 'afropinions')

    @inlineCallbacks
    def test_hitting_url(self):
        msisdn = u'+2345'
        message_id = u'message-id'
        event = self.eh_helper.make_event('survey_completed', {
            'from_addr': msisdn,
            'message_id': message_id,
            'transport_type': 'ussd',
            'participant': {'interactions': 2},
        })

        self.mock_server = MockHttpServer()
        yield self.mock_server.start()

        self.eh_helper.get_handler('afropinions').url = self.mock_server.url

        yield self.eh_helper.dispatch_event(event)
        received_request = yield self.mock_server.queue.get()
        self.assertEqual(received_request.args['msisdn'][0], msisdn)
        self.assertEqual(received_request.args['amount'][0], '2000')
        self.assertEqual(received_request.args['reason'][0], 'foo')

        headers = received_request.requestHeaders
        self.assertEqual(headers.getRawHeaders('Content-Type'),
            ['application/x-www-form-urlencoded'])
        self.assertEqual(headers.getRawHeaders('Authorization'),
            ['Basic %s' % (base64.b64encode('username:password'),)])
        yield self.mock_server.stop()

    def test_auth_headers(self):
        handler = self.eh_helper.get_handler('afropinions')
        auth = handler.get_auth_headers('username', 'password')
        credentials = base64.b64encode('username:password')
        self.assertEqual(auth, {
            'Authorization': 'Basic %s' % (credentials.strip(),)
            })
开发者ID:ChrisNolan1992,项目名称:vumi-go,代码行数:55,代码来源:test_handlers.py

示例3: TestTransport

# 需要导入模块: from vumi.tests.utils import MockHttpServer [as 别名]
# 或者: from vumi.tests.utils.MockHttpServer import start [as 别名]
class TestTransport(TestCase):

    @inlineCallbacks
    def setUp(self):
        DelayedCall.debug = True
        self.ok_transport_calls = DeferredQueue()
        self.mock_service = MockHttpServer(self.handle_request)
        yield self.mock_service.start()
        config = {
            'transport_name': 'test_ok_transport',
            'transport_type': 'ok',
            'ussd_string_prefix': '',
            'web_path': "foo",
            'web_port': 0,
            'url': self.mock_service.url,
            'username': 'testuser',
            'password': 'testpass',
            }
        self.worker = get_stubbed_worker(OkTransport, config)
        self.broker = self.worker._amqp_client.broker
        yield self.worker.startWorker()
        self.worker_url = self.worker.get_transport_url()

    @inlineCallbacks
    def tearDown(self):
        yield self.worker.stopWorker()
        yield self.mock_service.stop()

    def handle_request(self, request):
        self.ok_transport_calls.put(request)
        return ''

    @inlineCallbacks
    def test_health(self):
        result = yield http_request(self.worker_url + "health", "",
                                    method='GET')
        self.assertEqual(json.loads(result), {
            'pending_requests': 0
        })

    @inlineCallbacks
    def test_inbound(self):
        d = http_request(self.worker_url + "foo", '', method='GET')
        msg, = yield self.broker.wait_messages("vumi",
            "test_ok_transport.inbound", 1)
        payload = msg.payload
        tum = TransportUserMessage(**payload)
        rep = tum.reply("OK")
        self.broker.publish_message("vumi", "test_ok_transport.outbound",
                rep)
        response = yield d
        self.assertEqual(response, 'OK')
开发者ID:BantouTelecom,项目名称:vumi,代码行数:54,代码来源:test_httprpc.py

示例4: TestStreamingClient

# 需要导入模块: from vumi.tests.utils import MockHttpServer [as 别名]
# 或者: from vumi.tests.utils.MockHttpServer import start [as 别名]
class TestStreamingClient(VumiTestCase):

    @inlineCallbacks
    def setUp(self):
        self.mock_server = MockHttpServer(self.handle_request)
        self.add_cleanup(self.mock_server.stop)
        yield self.mock_server.start()
        self.url = self.mock_server.url
        self.client = StreamingClient()
        self.messages_received = DeferredQueue()
        self.errors_received = DeferredQueue()
        self.disconnects_received = DeferredQueue()

        def reason_trapper(reason):
            if reason.trap(ResponseDone):
                self.disconnects_received.put(reason.getErrorMessage())

        self.receiver = self.client.stream(
            Message,
            self.messages_received.put, self.errors_received.put,
            self.url, on_disconnect=reason_trapper)

    def handle_request(self, request):
        self.mock_server.queue.put(request)
        return NOT_DONE_YET

    @inlineCallbacks
    def test_callback_on_disconnect(self):
        req = yield self.mock_server.queue.get()
        req.write(
            '%s\n' % (Message(foo='bar').to_json().encode('utf-8'),))
        req.finish()
        message = yield self.messages_received.get()
        self.assertEqual(message['foo'], 'bar')
        reason = yield self.disconnects_received.get()
        # this is the error message we get when a ResponseDone is raised
        # which happens when the remote server closes the connection.
        self.assertEqual(reason, 'Response body fully received')

    @inlineCallbacks
    def test_invalid_json(self):
        req = yield self.mock_server.queue.get()
        req.write("Hello\n")
        req.finish()
        try:
            yield self.errors_received.get()
        except VumiBridgeInvalidJsonError, e:
            self.assertEqual(e.args, ("Hello",))
        else:
开发者ID:Nagato23,项目名称:vumi,代码行数:51,代码来源:test_client.py

示例5: TestGoConversationTransportBase

# 需要导入模块: from vumi.tests.utils import MockHttpServer [as 别名]
# 或者: from vumi.tests.utils.MockHttpServer import start [as 别名]
class TestGoConversationTransportBase(VumiTestCase):

    transport_class = None

    @inlineCallbacks
    def setUp(self):
        self.tx_helper = self.add_helper(TransportHelper(self.transport_class))
        self.mock_server = MockHttpServer(self.handle_inbound_request)
        self.add_cleanup(self.mock_server.stop)
        self.clock = Clock()

        yield self.mock_server.start()

        self._pending_reqs = []
        self.add_cleanup(self.finish_requests)

    @inlineCallbacks
    def get_transport(self, **config):
        defaults = {
            'base_url': self.mock_server.url,
            'account_key': 'account-key',
            'conversation_key': 'conversation-key',
            'access_token': 'access-token',
        }
        defaults.update(config)
        transport = yield self.tx_helper.get_transport(defaults)
        yield self.setup_transport(transport)
        returnValue(transport)

    def setup_transport(self, transport):
        pass

    @inlineCallbacks
    def finish_requests(self):
        for req in self._pending_reqs:
            if not req.finished:
                yield req.finish()

    def handle_inbound_request(self, request):
        self.mock_server.queue.put(request)
        return NOT_DONE_YET

    @inlineCallbacks
    def get_next_request(self):
        req = yield self.mock_server.queue.get()
        self._pending_reqs.append(req)
        returnValue(req)
开发者ID:Nagato23,项目名称:vumi,代码行数:49,代码来源:test_vumi_bridge.py

示例6: TestQuietGetPage

# 需要导入模块: from vumi.tests.utils import MockHttpServer [as 别名]
# 或者: from vumi.tests.utils.MockHttpServer import start [as 别名]
class TestQuietGetPage(VumiTestCase):

    @inlineCallbacks
    def setUp(self):
        self.mock_http = MockHttpServer(self._handle_request)
        self.add_cleanup(self.mock_http.stop)
        yield self.mock_http.start()

    def _handle_request(self, request):
        request.setResponseCode(http.OK)
        request.do_not_log = True
        return "Hello"

    @inlineCallbacks
    def test_request(self):
        with LogCatcher() as lc:
            result = yield quiet_get_page(self.mock_http.url)
            self.assertEqual(lc.logs, [])
        self.assertEqual(result, "Hello")
开发者ID:AndrewCvekl,项目名称:vumi,代码行数:21,代码来源:test_sentry.py

示例7: TestVas2NetsSmsTransport

# 需要导入模块: from vumi.tests.utils import MockHttpServer [as 别名]
# 或者: from vumi.tests.utils.MockHttpServer import start [as 别名]
class TestVas2NetsSmsTransport(VumiTestCase):
    @inlineCallbacks
    def setUp(self):
        self.clock = Clock()
        self.patch(Vas2NetsSmsTransport, 'get_clock', lambda _: self.clock)

        self.remote_request_handler = lambda _: 'OK.1234'
        self.remote_server = MockHttpServer(self.remote_handle_request)
        yield self.remote_server.start()
        self.addCleanup(self.remote_server.stop)

        self.tx_helper = self.add_helper(
            HttpRpcTransportHelper(Vas2NetsSmsTransport))

        connection_pool = HTTPConnectionPool(reactor, persistent=False)
        treq._utils.set_global_pool(connection_pool)

    @inlineCallbacks
    def mk_transport(self, **kw):
        config = {
            'web_port': 0,
            'web_path': '/api/v1/vas2nets/sms/',
            'publish_status': True,
            'outbound_url': urljoin(self.remote_server.url, 'nonreply'),
            'username': 'root',
            'password': 't00r',
        }
        config.update(kw)

        transport = yield self.tx_helper.get_transport(config)
        self.patch(transport, 'get_clock', lambda _: self.clock)
        returnValue(transport)

    @inlineCallbacks
    def patch_reactor_call_later(self):
        yield self.wait_for_test_setup()
        self.patch(reactor, 'callLater', self.clock.callLater)

    def wait_for_test_setup(self):
        """
        Wait for test setup to complete.

        Twisted's twisted.trial._asynctest runner calls `reactor.callLater`
        to set the test timeout *after* running the start of the test. We
        thus need to wait for this to happen *before* we patch
        `reactor.callLater`.
        """
        d = Deferred()
        reactor.callLater(0, d.callback, None)
        return d

    def capture_remote_requests(self, response='OK.1234'):
        def handler(req):
            reqs.append(req)
            return response

        reqs = []
        self.remote_request_handler = handler
        return reqs

    def remote_handle_request(self, req):
        return self.remote_request_handler(req)

    def get_host(self, transport):
        addr = transport.web_resource.getHost()
        return '%s:%s' % (addr.host, addr.port)

    def assert_contains_items(self, obj, items):
        for name, value in items.iteritems():
            self.assertEqual(obj[name], value)

    def assert_uri(self, actual_uri, path, params):
        actual_path, actual_params = actual_uri.split('?')
        self.assertEqual(actual_path, path)

        self.assertEqual(
            sorted(actual_params.split('&')),
            sorted(urlencode(params).split('&')))

    def assert_request_params(self, transport, req, params):
        self.assert_contains_items(req, {
            'method': 'GET',
            'path': transport.config['web_path'],
            'content': '',
            'headers': {
                'Connection': ['close'],
                'Host': [self.get_host(transport)]
            }
        })

        self.assert_uri(req['uri'], transport.config['web_path'], params)

    @inlineCallbacks
    def test_inbound(self):
        yield self.mk_transport()

        res = yield self.tx_helper.mk_request(
            sender='+123',
            receiver='456',
            msgdata='hi',
#.........这里部分代码省略.........
开发者ID:praekelt,项目名称:vumi-vas2nets,代码行数:103,代码来源:test_vas2nets_sms.py

示例8: TestStreamingHTTPWorker

# 需要导入模块: from vumi.tests.utils import MockHttpServer [as 别名]
# 或者: from vumi.tests.utils.MockHttpServer import start [as 别名]
class TestStreamingHTTPWorker(VumiTestCase):

    @inlineCallbacks
    def setUp(self):
        self.app_helper = self.add_helper(AppWorkerHelper(StreamingHTTPWorker))

        self.config = {
            'health_path': '/health/',
            'web_path': '/foo',
            'web_port': 0,
            'metrics_prefix': 'metrics_prefix.',
        }
        self.app = yield self.app_helper.get_app_worker(self.config)
        self.addr = self.app.webserver.getHost()
        self.url = 'http://%s:%s%s' % (
            self.addr.host, self.addr.port, self.config['web_path'])

        conv_config = {
            'http_api': {
                'api_tokens': [
                    'token-1',
                    'token-2',
                    'token-3',
                ],
                'metric_store': 'metric_store',
            }
        }
        conversation = yield self.app_helper.create_conversation(
            config=conv_config)
        yield self.app_helper.start_conversation(conversation)
        self.conversation = yield self.app_helper.get_conversation(
            conversation.key)

        self.auth_headers = {
            'Authorization': ['Basic ' + base64.b64encode('%s:%s' % (
                conversation.user_account.key, 'token-1'))],
        }

        self.client = StreamingClient()

        # Mock server to test HTTP posting of inbound messages & events
        self.mock_push_server = MockHttpServer(self.handle_request)
        yield self.mock_push_server.start()
        self.add_cleanup(self.mock_push_server.stop)
        self.push_calls = DeferredQueue()
        self._setup_wait_for_request()
        self.add_cleanup(self._wait_for_requests)

    def _setup_wait_for_request(self):
        # Hackery to wait for the request to finish
        self._req_state = {
            'queue': DeferredQueue(),
            'expected': 0,
        }
        orig_track = StreamingConversationResource.track_request
        orig_release = StreamingConversationResource.release_request

        def track_wrapper(*args, **kw):
            self._req_state['expected'] += 1
            return orig_track(*args, **kw)

        def release_wrapper(*args, **kw):
            return orig_release(*args, **kw).addCallback(
                self._req_state['queue'].put)

        self.patch(
            StreamingConversationResource, 'track_request', track_wrapper)
        self.patch(
            StreamingConversationResource, 'release_request', release_wrapper)

    @inlineCallbacks
    def _wait_for_requests(self):
        while self._req_state['expected'] > 0:
            yield self._req_state['queue'].get()
            self._req_state['expected'] -= 1

    def handle_request(self, request):
        self.push_calls.put(request)
        return NOT_DONE_YET

    @inlineCallbacks
    def pull_message(self, count=1):
        url = '%s/%s/messages.json' % (self.url, self.conversation.key)

        messages = DeferredQueue()
        errors = DeferredQueue()
        receiver = self.client.stream(
            TransportUserMessage, messages.put, errors.put, url,
            Headers(self.auth_headers))

        received_messages = []
        for msg_id in range(count):
            yield self.app_helper.make_dispatch_inbound(
                'in %s' % (msg_id,), message_id=str(msg_id),
                conv=self.conversation)
            recv_msg = yield messages.get()
            received_messages.append(recv_msg)

        receiver.disconnect()
        returnValue((receiver, received_messages))
#.........这里部分代码省略.........
开发者ID:ChrisNolan1992,项目名称:vumi-go,代码行数:103,代码来源:test_vumi_app.py

示例9: TestAcksCellulantSmsTransport

# 需要导入模块: from vumi.tests.utils import MockHttpServer [as 别名]
# 或者: from vumi.tests.utils.MockHttpServer import start [as 别名]
class TestAcksCellulantSmsTransport(VumiTestCase):

    @inlineCallbacks
    def setUp(self):
        self.cellulant_sms_calls = DeferredQueue()
        self.mock_cellulant_sms = MockHttpServer(self.handle_request)
        self._mock_response = ''
        yield self.mock_cellulant_sms.start()
        self.add_cleanup(self.mock_cellulant_sms.stop)

        self.config = {
            'web_path': "foo",
            'web_port': 0,
            'credentials': {
                '2371234567': {
                    'username': 'user',
                    'password': 'pass',
                },
                '9292': {
                    'username': 'other-user',
                    'password': 'other-pass',
                }
            },
            'outbound_url': self.mock_cellulant_sms.url,
            'validation_mode': 'permissive',
        }
        self.tx_helper = self.add_helper(
            TransportHelper(CellulantSmsTransport))
        self.transport = yield self.tx_helper.get_transport(self.config)
        self.transport_url = self.transport.get_transport_url()

    def mock_response(self, response):
        self._mock_response = response

    def handle_request(self, request):
        self.cellulant_sms_calls.put(request)
        return self._mock_response

    @inlineCallbacks
    def mock_event(self, msg, nr_events):
        self.mock_response(msg)
        yield self.tx_helper.make_dispatch_outbound(
            "foo", to_addr='2371234567', message_id='id_%s' % (msg,))
        yield self.cellulant_sms_calls.get()
        events = yield self.tx_helper.wait_for_dispatched_events(nr_events)
        returnValue(events)

    @inlineCallbacks
    def test_nack_param_error_E0(self):
        [nack] = yield self.mock_event('E0', 1)
        self.assertEqual(nack['event_type'], 'nack')
        self.assertEqual(nack['user_message_id'], 'id_E0')
        self.assertEqual(nack['nack_reason'],
            self.transport.KNOWN_ERROR_RESPONSE_CODES['E0'])

    @inlineCallbacks
    def test_nack_login_error_E1(self):
        [nack] = yield self.mock_event('E1', 1)
        self.assertEqual(nack['event_type'], 'nack')
        self.assertEqual(nack['user_message_id'], 'id_E1')
        self.assertEqual(nack['nack_reason'],
            self.transport.KNOWN_ERROR_RESPONSE_CODES['E1'])

    @inlineCallbacks
    def test_nack_credits_error_E2(self):
        [nack] = yield self.mock_event('E2', 1)
        self.assertEqual(nack['event_type'], 'nack')
        self.assertEqual(nack['user_message_id'], 'id_E2')
        self.assertEqual(nack['nack_reason'],
            self.transport.KNOWN_ERROR_RESPONSE_CODES['E2'])

    @inlineCallbacks
    def test_nack_delivery_failed_1005(self):
        [nack] = yield self.mock_event('1005', 1)
        self.assertEqual(nack['event_type'], 'nack')
        self.assertEqual(nack['user_message_id'], 'id_1005')
        self.assertEqual(nack['nack_reason'],
            self.transport.KNOWN_ERROR_RESPONSE_CODES['1005'])

    @inlineCallbacks
    def test_unknown_response(self):
        [nack] = yield self.mock_event('something_unexpected', 1)
        self.assertEqual(nack['event_type'], 'nack')
        self.assertEqual(nack['user_message_id'], 'id_something_unexpected')
        self.assertEqual(nack['nack_reason'],
            'Unknown response code: something_unexpected')

    @inlineCallbacks
    def test_ack_success(self):
        [event] = yield self.mock_event('1', 1)
        self.assertEqual(event['event_type'], 'ack')
        self.assertEqual(event['user_message_id'], 'id_1')
开发者ID:Nagato23,项目名称:vumi,代码行数:94,代码来源:test_cellulant_sms.py

示例10: TestRapidSMSRelay

# 需要导入模块: from vumi.tests.utils import MockHttpServer [as 别名]
# 或者: from vumi.tests.utils.MockHttpServer import start [as 别名]
class TestRapidSMSRelay(VumiTestCase):

    def setUp(self):
        self.app_helper = self.add_helper(ApplicationHelper(RapidSMSRelay))

    @inlineCallbacks
    def setup_resource(self, callback=None, auth=None, config=None):
        if callback is None:
            callback = lambda r: self.fail("No RapidSMS requests expected.")
        self.mock_server = MockHttpServer(callback)
        self.add_cleanup(self.mock_server.stop)
        yield self.mock_server.start()
        url = '%s%s' % (self.mock_server.url, '/test/resource/path')
        self.app = yield self.setup_app(url, auth=auth, config=config)

    def setup_app(self, url, auth=None, config=None):
        vumi_username, vumi_password = auth if auth else (None, None)
        app_config = {
            'rapidsms_url': url,
            'web_path': '/send/',
            'web_port': '0',
            'rapidsms_username': 'username',
            'rapidsms_password': 'password',
            'vumi_username': vumi_username,
            'vumi_password': vumi_password,
            'allowed_endpoints': ['default', '10010', '10020'],
        }
        if config:
            app_config.update(config)
        return self.app_helper.get_application(app_config)

    def get_response_msgs(self, response):
        payloads = from_json(response.delivered_body)
        return [TransportUserMessage(
                _process_fields=False, **to_kwargs(payload))
                for payload in payloads]

    @inlineCallbacks
    def test_rapidsms_relay_success(self):
        def cb(request):
            msg = TransportUserMessage.from_json(request.content.read())
            self.assertEqual(msg['content'], 'hello world')
            self.assertEqual(msg['from_addr'], '+41791234567')
            return 'OK'

        yield self.setup_resource(cb)
        yield self.app_helper.make_dispatch_inbound("hello world")
        self.assertEqual([], self.app_helper.get_dispatched_outbound())

    @inlineCallbacks
    def test_rapidsms_relay_unicode(self):
        def cb(request):
            msg = TransportUserMessage.from_json(request.content.read())
            self.assertEqual(msg['content'], u'h\xc6llo')
            return 'OK'

        yield self.setup_resource(cb)
        yield self.app_helper.make_dispatch_inbound(u'h\xc6llo')
        self.assertEqual([], self.app_helper.get_dispatched_outbound())

    @inlineCallbacks
    def test_rapidsms_relay_with_basic_auth(self):
        def cb(request):
            self.assertEqual(request.getUser(), 'username')
            self.assertEqual(request.getPassword(), 'password')
            msg = TransportUserMessage.from_json(request.content.read())
            self.assertEqual(msg['message_id'], 'abc')
            self.assertEqual(msg['content'], 'hello world')
            self.assertEqual(msg['from_addr'], '+41791234567')
            return 'OK'

        yield self.setup_resource(cb)
        yield self.app_helper.make_dispatch_inbound(
            "hello world", message_id="abc")
        self.assertEqual([], self.app_helper.get_dispatched_outbound())

    @inlineCallbacks
    def test_rapidsms_relay_with_bad_basic_auth(self):
        def cb(request):
            request.setResponseCode(http.UNAUTHORIZED)
            return 'Not Authorized'

        yield self.setup_resource(cb)
        yield self.app_helper.make_dispatch_inbound("hi")
        self.assertEqual([], self.app_helper.get_dispatched_outbound())

    @inlineCallbacks
    def test_rapidsms_relay_logs_events(self):
        yield self.setup_resource()
        with LogCatcher() as lc:
            yield self.app_helper.make_dispatch_delivery_report(
                self.app_helper.make_outbound("foo", message_id="abc"))
            yield self.app_helper.make_dispatch_ack(
                self.app_helper.make_outbound("foo", message_id="1"))
            self.assertEqual(lc.messages(), [
                "Delivery report received for message u'abc',"
                " status u'delivered'",
                "Acknowledgement received for message u'1'",
            ])
        self.assertEqual([], self.app_helper.get_dispatched_outbound())
#.........这里部分代码省略.........
开发者ID:Nagato23,项目名称:vumi,代码行数:103,代码来源:test_rapidsms_relay.py

示例11: TestAppositTransport

# 需要导入模块: from vumi.tests.utils import MockHttpServer [as 别名]
# 或者: from vumi.tests.utils.MockHttpServer import start [as 别名]
class TestAppositTransport(VumiTestCase):

    @inlineCallbacks
    def setUp(self):
        self.mock_server = MockHttpServer(self.handle_inbound_request)
        self.outbound_requests = DeferredQueue()
        self.mock_server_response = ''
        self.mock_server_response_code = http.OK
        yield self.mock_server.start()
        self.add_cleanup(self.mock_server.stop)

        config = {
            'web_path': 'api/v1/apposit/sms',
            'web_port': 0,
            'credentials': {
                '8123': {
                    'username': 'root',
                    'password': 'toor',
                    'service_id': 'service-id-1',
                },
                '8124': {
                    'username': 'admin',
                    'password': 'nimda',
                    'service_id': 'service-id-2',
                }
            },
            'outbound_url': self.mock_server.url,
        }
        self.tx_helper = self.add_helper(
            TransportHelper(
                AppositTransport, transport_addr='8123',
                mobile_addr='251911223344'))
        self.transport = yield self.tx_helper.get_transport(config)
        self.transport_url = self.transport.get_transport_url()
        self.web_path = config['web_path']

    def send_full_inbound_request(self, **params):
        return http_request_full(
            '%s%s' % (self.transport_url, self.web_path),
            data=urlencode(params),
            method='POST',
            headers={'Content-Type': self.transport.CONTENT_TYPE})

    def send_inbound_request(self, **kwargs):
        params = {
            'from': '251911223344',
            'to': '8123',
            'channel': 'SMS',
            'content': 'never odd or even',
            'isTest': 'true',
        }
        params.update(kwargs)
        return self.send_full_inbound_request(**params)

    def handle_inbound_request(self, request):
        self.outbound_requests.put(request)
        request.setResponseCode(self.mock_server_response_code)
        return self.mock_server_response

    def set_mock_server_response(self, code=http.OK, body=''):
        self.mock_server_response_code = code
        self.mock_server_response = body

    def assert_outbound_request(self, request, **kwargs):
        expected_args = {
            'username': 'root',
            'password': 'toor',
            'serviceId': 'service-id-1',
            'fromAddress': '8123',
            'toAddress': '251911223344',
            'content': 'so many dynamos',
            'channel': 'SMS',
        }
        expected_args.update(kwargs)

        self.assertEqual(request.path, '/')
        self.assertEqual(request.method, 'POST')
        self.assertEqual(dict((k, [v]) for k, v in expected_args.iteritems()),
                         request.args)
        self.assertEqual(request.getHeader('Content-Type'),
                         self.transport.CONTENT_TYPE)

    def assert_message_fields(self, msg, **kwargs):
        fields = {
            'transport_name': self.tx_helper.transport_name,
            'transport_type': 'sms',
            'from_addr': '251911223344',
            'to_addr': '8123',
            'content': 'so many dynamos',
            'provider': 'apposit',
            'transport_metadata': {'apposit': {'isTest': 'true'}},
        }
        fields.update(kwargs)

        for field_name, expected_value in fields.iteritems():
            self.assertEqual(msg[field_name], expected_value)

    def assert_ack(self, ack, msg):
        self.assertEqual(ack.payload['event_type'], 'ack')
        self.assertEqual(ack.payload['user_message_id'], msg['message_id'])
#.........这里部分代码省略.........
开发者ID:Nagato23,项目名称:vumi,代码行数:103,代码来源:test_apposit.py

示例12: TestMxitTransport

# 需要导入模块: from vumi.tests.utils import MockHttpServer [as 别名]
# 或者: from vumi.tests.utils.MockHttpServer import start [as 别名]
class TestMxitTransport(VumiTestCase):
    @inlineCallbacks
    def setUp(self):
        self.mock_http = MockHttpServer(self.handle_request)
        self.mock_request_queue = DeferredQueue()
        yield self.mock_http.start()
        self.addCleanup(self.mock_http.stop)

        config = {
            "web_port": 0,
            "web_path": "/api/v1/mxit/mobiportal/",
            "client_id": "client_id",
            "client_secret": "client_secret",
            "api_send_url": self.mock_http.url,
            "api_auth_url": self.mock_http.url,
        }
        self.sample_loc_str = "cc,cn,sc,sn,cc,c,noi,cfb,ci"
        self.sample_profile_str = "lc,cc,dob,gender,tariff"
        self.sample_html_str = "<&>"
        self.sample_req_headers = {
            "X-Device-User-Agent": "ua",
            "X-Mxit-Contact": "contact",
            "X-Mxit-USERID-R": "user-id",
            "X-Mxit-Nick": "nick",
            "X-Mxit-Location": self.sample_loc_str,
            "X-Mxit-Profile": self.sample_profile_str,
            "X-Mxit-User-Input": self.sample_html_str,
        }
        self.sample_menu_resp = "\n".join(["Hello!", "1. option 1", "2. option 2", "3. option 3"])
        # same as above but the o's are replaced with
        # http://www.fileformat.info/info/unicode/char/f8/index.htm
        slashed_o = "\xc3\xb8"
        self.sample_unicode_menu_resp = unicode(self.sample_menu_resp.replace("o", slashed_o), "utf-8")

        self.tx_helper = self.add_helper(TransportHelper(MxitTransport))
        self.transport = yield self.tx_helper.get_transport(config)
        # NOTE: priming redis with an access token
        self.transport.redis.set(self.transport.access_token_key, "foo")
        self.url = self.transport.get_transport_url(config["web_path"])

    def handle_request(self, request):
        self.mock_request_queue.put(request)
        return NOT_DONE_YET

    def test_is_mxit_request(self):
        req = Request(None, True)
        self.assertFalse(self.transport.is_mxit_request(req))
        req.requestHeaders.addRawHeader("X-Mxit-Contact", "foo")
        self.assertTrue(self.transport.is_mxit_request(req))

    def test_noop(self):
        self.assertEqual(self.transport.noop("foo"), "foo")

    def test_parse_location(self):
        self.assertEqual(
            self.transport.parse_location(self.sample_loc_str),
            {
                "country_code": "cc",
                "country_name": "cn",
                "subdivision_code": "sc",
                "subdivision_name": "sn",
                "city_code": "cc",
                "city": "c",
                "network_operator_id": "noi",
                "client_features_bitset": "cfb",
                "cell_id": "ci",
            },
        )

    def test_parse_profile(self):
        self.assertEqual(
            self.transport.parse_profile(self.sample_profile_str),
            {
                "country_code": "cc",
                "date_of_birth": "dob",
                "gender": "gender",
                "language_code": "lc",
                "tariff_plan": "tariff",
            },
        )

    def test_html_decode(self):
        self.assertEqual(self.transport.html_decode(self.sample_html_str), "<&>")

    def test_get_request_data(self):
        req = Request(None, True)
        headers = req.requestHeaders
        for key, value in self.sample_req_headers.items():
            headers.addRawHeader(key, value)

        data = self.transport.get_request_data(req)

        self.assertEqual(
            data,
            {
                "X-Device-User-Agent": "ua",
                "X-Mxit-Contact": "contact",
                "X-Mxit-Location": {
                    "cell_id": "ci",
                    "city": "c",
#.........这里部分代码省略.........
开发者ID:Nagato23,项目名称:vumi,代码行数:103,代码来源:test_mxit.py

示例13: AirtelBfTransportTestCase

# 需要导入模块: from vumi.tests.utils import MockHttpServer [as 别名]
# 或者: from vumi.tests.utils.MockHttpServer import start [as 别名]
class AirtelBfTransportTestCase(TransportTestCase):
    
    transport_name = 'airtel'
    transport_type = 'sms'
    transport_class = AirtelBfHttpTransport

    
    send_path = '/sendsms/index'
    send_port = 9999
    
    @inlineCallbacks
    def setUp(self):
        yield super(AirtelBfTransportTestCase, self).setUp()

        self.airtel_sms_calls = DeferredQueue()
        self.mock_airtel_sms = MockHttpServer(self.handle_request)
        yield self.mock_airtel_sms.start()        
        
        self.config = {
            'transport_name': self.transport_name,
            'receive_path': 'sendsms',
            'receive_port': 9998,
            'outbound_url': self.mock_airtel_sms.url,
            'default_shortcode': '3411',
            'login': 'texttochange',
            'password': 'password'
            }
        self.transport = yield self.get_transport(self.config)
        self.transport_url = self.transport.get_transport_url()

    @inlineCallbacks
    def tearDown(self):
        yield self.mock_airtel_sms.stop()
        yield super(AirtelBfTransportTestCase, self).tearDown()

    def handle_request(self, request):
        self.airtel_sms_calls.put(request)
        return ''

    @inlineCallbacks
    def test_sending_sms(self):
        yield self.dispatch(self.mkmsg_out())
        req = yield self.airtel_sms_calls.get()
        self.assertEqual(req.path, '/')
        self.assertEqual(req.method, 'GET')
        self.assertEqual({
            'DA': ['9292'],
            'SOA': ['+41791234567'],
            'content': ['hello world'],
            'u': ['texttochange'],
            'p': ['password']
            }, req.args)        
        [smsg] = self.get_dispatched_events()
        self.assertEqual(
            self.mkmsg_ack(user_message_id='1',
                           sent_message_id='1'),
            smsg)


    @inlineCallbacks
    def test_sending_sms_complex(self):
        yield self.dispatch(self.mkmsg_out(
            from_addr="+2261", content=u'setoffre #A#BELG=10/tete+300000/pu# envoy\xe9 depuis SIMAgriMobile'))
        req = yield self.airtel_sms_calls.get()
        self.assertEqual(req.path, '/')
        self.assertEqual(req.method, 'GET')
        self.assertEqual(
            'setoffre #A#BELG=10/tete+300000/pu# envoyé depuis SIMAgriMobile',
            req.args['content'][0])
        [smsg] = self.get_dispatched_events()
        self.assertEqual(
            self.mkmsg_ack(user_message_id='1',
                           sent_message_id='1'),
            smsg)    

    def mkurl_raw(self, **params):
        return '%s%s?%s' % (
            self.transport_url,
            self.config['receive_path'],
            urlencode(params))    

    def mkurl(self, content, from_addr, **kw):
        params = {
            'message': content,
            'msisdn': from_addr}
        params.update(kw)
        return self.mkurl_raw(**params)

    @inlineCallbacks
    def test_receiving_sms(self):
        url = self.mkurl('Hello envoy\xc3\xa9', '+2261')
        response = yield http_request_full(url, method='GET')
        [smsg] = self.get_dispatched_messages()

        self.assertEqual(response.code, http.OK)
        self.assertEqual(u'Hello envoy\xe9', smsg['content'])
        self.assertEqual('3411', smsg['to_addr'])
        self.assertEqual('+2261', smsg['from_addr'])

    @inlineCallbacks
#.........这里部分代码省略.........
开发者ID:hacklabcbba,项目名称:vumi-simagri,代码行数:103,代码来源:test_airtel_bf_http.py

示例14: TestNoStreamingHTTPWorkerBase

# 需要导入模块: from vumi.tests.utils import MockHttpServer [as 别名]
# 或者: from vumi.tests.utils.MockHttpServer import start [as 别名]
class TestNoStreamingHTTPWorkerBase(VumiTestCase):

    @inlineCallbacks
    def setUp(self):
        self.app_helper = self.add_helper(
            AppWorkerHelper(NoStreamingHTTPWorker))

        self.config = {
            'health_path': '/health/',
            'web_path': '/foo',
            'web_port': 0,
            'metrics_prefix': 'metrics_prefix.',
        }
        self.app = yield self.app_helper.get_app_worker(self.config)
        self.addr = self.app.webserver.getHost()
        self.url = 'http://%s:%s%s' % (
            self.addr.host, self.addr.port, self.config['web_path'])

        # Mock server to test HTTP posting of inbound messages & events
        self.mock_push_server = MockHttpServer(self.handle_request)
        yield self.mock_push_server.start()
        self.add_cleanup(self.mock_push_server.stop)
        self.push_calls = DeferredQueue()

        self.conversation = yield self.create_conversation(
            self.get_message_url(), self.get_event_url(),
            ['token-1', 'token-2', 'token-3'])

        self.auth_headers = {
            'Authorization': ['Basic ' + base64.b64encode('%s:%s' % (
                self.conversation.user_account.key, 'token-1'))],
        }

        self._setup_wait_for_request()
        self.add_cleanup(self._wait_for_requests)

    def get_message_url(self):
        return self.mock_push_server.url

    def get_event_url(self):
        return self.mock_push_server.url

    @inlineCallbacks
    def create_conversation(self, message_url, event_url, tokens):
        config = {
            'http_api_nostream': {
                'api_tokens': tokens,
                'push_message_url': message_url,
                'push_event_url': event_url,
                'metric_store': 'metric_store',
            }
        }
        conv = yield self.app_helper.create_conversation(config=config)
        yield self.app_helper.start_conversation(conv)
        conversation = yield self.app_helper.get_conversation(conv.key)
        returnValue(conversation)

    def _setup_wait_for_request(self):
        # Hackery to wait for the request to finish
        self._req_state = {
            'queue': DeferredQueue(),
            'expected': 0,
        }
        orig_track = ConversationResource.track_request
        orig_release = ConversationResource.release_request

        def track_wrapper(*args, **kw):
            self._req_state['expected'] += 1
            return orig_track(*args, **kw)

        def release_wrapper(*args, **kw):
            return orig_release(*args, **kw).addCallback(
                self._req_state['queue'].put)

        self.patch(ConversationResource, 'track_request', track_wrapper)
        self.patch(ConversationResource, 'release_request', release_wrapper)

    @inlineCallbacks
    def _wait_for_requests(self):
        while self._req_state['expected'] > 0:
            yield self._req_state['queue'].get()
            self._req_state['expected'] -= 1

    def handle_request(self, request):
        self.push_calls.put(request)
        return NOT_DONE_YET

    def assert_bad_request(self, response, reason):
        self.assertEqual(response.code, http.BAD_REQUEST)
        data = json.loads(response.delivered_body)
        self.assertEqual(data, {
            "success": False,
            "reason": reason,
        })
开发者ID:ChrisNolan1992,项目名称:vumi-go,代码行数:96,代码来源:test_vumi_app.py

示例15: CmYoTransportTestCase

# 需要导入模块: from vumi.tests.utils import MockHttpServer [as 别名]
# 或者: from vumi.tests.utils.MockHttpServer import start [as 别名]
class CmYoTransportTestCase(TransportTestCase):

    transport_name = 'cm'
    transport_type = 'sms'
    transport_class = CmYoTransport
    
    send_path = '/sendsms'
    send_port = 9999

    yo_incomming_template = ('%s%s?sender=0041791234567&'
                             'code=%s&message=%s')

    @inlineCallbacks
    def setUp(self):
        DelayedCall.debug = True
        yield super(CmYoTransportTestCase, self).setUp()
        
        self.cmyo_sms_calls = DeferredQueue()
        self.mock_cmyo_sms = MockHttpServer(self.handle_request)
        yield self.mock_cmyo_sms.start()           
        
        self.config = {
            'transport_name': self.transport_name,
            'login': 'login',
            'password': 'password',
            'default_origin': "+313455",
            'customer_id': '3454',
            'receive_path': 'yo',
            'receive_port': 9998,
            'outbound_url': self.mock_cmyo_sms.url,            
        }
        self.transport = yield self.get_transport(self.config)
        self.transport_url = self.transport.get_transport_url()
        self.today = datetime.utcnow().date()

    @inlineCallbacks
    def tearDown(self):
        yield self.mock_cmyo_sms.stop()
        yield super(CmYoTransportTestCase, self).tearDown()

    def mkmsg_fail(self, user_message_id='1',
                   failure_level='', failure_code=0,
                   failure_reason='', transport_metadata={}):
        if transport_metadata is None:
            transport_metadata = {}
        return TransportEvent(
            event_id=RegexMatcher(r'^[0-9a-fA-F]{32}$'),
            event_type='delivery_report',
            delivery_status='failed',
            failure_level=failure_level,
            failure_code=failure_code,
            failure_reason=failure_reason,
            user_message_id=user_message_id,
            timestamp=UTCNearNow(),
            transport_name=self.transport_name,
            transport_metadata=transport_metadata)

    def mkmsg_in(self, content='Hello World',
                 from_addr='41791234567',
                 session_event=TransportUserMessage.SESSION_NONE,
                 message_id='abc', transport_type=None,
                 transport_metadata=None):
        if transport_type is None:
            transport_type = self.transport_type
        if transport_metadata is None:
            transport_metadata = {}
        return TransportUserMessage(
            from_addr='+41791234567',
            to_addr='9292',
            group=None,
            message_id=message_id,
            transport_name=self.transport_name,
            transport_type=transport_type,
            transport_metadata=transport_metadata,
            content=content,
            session_event=session_event,
            timestamp=UTCNearNow())

    #def make_resource_worker(self, msg, code=http.OK, send_id=None):
        #w = get_stubbed_worker(TestResourceWorker, {})
        #w.set_resources([
            #(self.send_path, TestResource, (msg, code, send_id))])
        #self._workers.append(w)
        #return w.startWorker()

    def handle_request(self, request):
        self.cmyo_sms_calls.put(request)
        return ''

    @inlineCallbacks
    def test_sending_sms(self):
        msg = self.mkmsg_out(to_addr='+41791234567', content=u'Message envoy\xe9')
        yield self.dispatch(msg)
        req = yield self.cmyo_sms_calls.get()
        self.assertEqual(req.path, '/')
        self.assertEqual(req.method, 'POST')
        [smsg] = self.get_dispatched_events()
        
        self.assertEqual('1', smsg['user_message_id'])
        self.assertEqual('1', smsg['sent_message_id'])
#.........这里部分代码省略.........
开发者ID:hacklabcbba,项目名称:vumi-simagri,代码行数:103,代码来源:test_cm_nl_yo_ug_http.py


注:本文中的vumi.tests.utils.MockHttpServer.start方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。