Python mock.Mock() Examples

The following are 30 code examples of mock.Mock(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module mock , or try the search function .
Example #1
Source File: tests.py    From WazeRouteCalculator with GNU General Public License v3.0 7 votes vote down vote up
def test_calc_route_info_stopatbounds_missing_bounds(self):
        with requests_mock.mock() as m:
            lat = [47.49, 47.612, 47.645]
            lon = [19.04, 18.99, 18.82]
            bounds = [None, None, {"bottom": 47.6, "top": 47.7, "left": 18.8, "right": 18.9}]
            length = [400, 5000, 500]
            time = [45, 300, 60]
            address_to_coords_response = [
                '[{"city":"Test1","location":{"lat":%s,"lon":%s},"bounds":null}]' % (lat[0], lon[0]),
                '[{"city":"Test2","location":{"lat":%s,"lon":%s},"bounds":%s}]' % (lat[2], lon[2], str(bounds[2]).replace("'", '"'))
            ]
            m.get(self.address_req, [{'text': address_to_coords_response[0]}, {'text': address_to_coords_response[1]}])
            route = wrc.WazeRouteCalculator("", "")
        route_mock = mock.Mock(return_value={"results": [
            {"length": length[0], "crossTime": time[0], "path": {"x": lon[0], "y": lat[0]}},
            {"length": length[1], "crossTime": time[1], "path": {"x": lon[1], "y": lat[1]}},
            {"length": length[2], "crossTime": time[2], "path": {"x": lon[2], "y": lat[2]}}
        ]})
        route.get_route = route_mock
        time, dist = route.calc_route_info(stop_at_bounds=True)
        assert route_mock.called
        assert time == 5.75
        assert dist == 5.40 
Example #2
Source File: test_voice_webhook.py    From python-rest-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_voice_create_webhook(self):
        http_client = Mock()
        http_client.request.return_value = '''{
          "data": [
            {
              "id": "534e1848-235f-482d-983d-e3e11a04f58a",
              "url": "https://example.com/",
              "token": "foobar",
              "createdAt": "2017-03-15T14:10:07Z",
              "updatedAt": "2017-03-15T14:10:07Z"
            }
          ],
          "_links": {
            "self": "/webhooks/534e1848-235f-482d-983d-e3e11a04f58a"
          }
        }'''

        create_webhook_request = VoiceCreateWebhookRequest(url="https://example.com/", title="FooBar", token="foobar")
        created_webhook = Client('', http_client).voice_create_webhook(create_webhook_request)

        http_client.request.assert_called_once_with(VOICE_API_ROOT + '/' + VOICE_WEB_HOOKS_PATH, 'POST',
                                                    create_webhook_request.__dict__())
        self.assertEqual(create_webhook_request.url, created_webhook.url)
        self.assertEqual(create_webhook_request.token, created_webhook.token) 
Example #3
Source File: box_predictor_builder_test.py    From DOTA_models with Apache License 2.0 6 votes vote down vote up
def test_build_default_mask_rcnn_box_predictor(self):
    box_predictor_proto = box_predictor_pb2.BoxPredictor()
    box_predictor_proto.mask_rcnn_box_predictor.fc_hyperparams.op = (
        hyperparams_pb2.Hyperparams.FC)
    box_predictor = box_predictor_builder.build(
        argscope_fn=mock.Mock(return_value='arg_scope'),
        box_predictor_config=box_predictor_proto,
        is_training=True,
        num_classes=90)
    self.assertFalse(box_predictor._use_dropout)
    self.assertAlmostEqual(box_predictor._dropout_keep_prob, 0.5)
    self.assertEqual(box_predictor.num_classes, 90)
    self.assertTrue(box_predictor._is_training)
    self.assertEqual(box_predictor._box_code_size, 4)
    self.assertFalse(box_predictor._predict_instance_masks)
    self.assertFalse(box_predictor._predict_keypoints) 
Example #4
Source File: test_interactor.py    From python-clean-architecture with MIT License 6 votes vote down vote up
def test_multiple_error_class(
            self, container, error_handler, request_data, validators):
        error_instance = ValueError()
        interactor_mock = mock.Mock(side_effect=error_instance)
        interactor_function = interactor_factory(
            error_class=(LogicError, ValueError),
            error_handler=error_handler
        )
        interactor = interactor_function(*validators)(interactor_mock)(container)

        interactor(request_data)

        validators[0].assert_called_once_with(request_data)
        validators[1].assert_called_once_with(request_data)
        interactor_mock.assert_called_once_with(request_data)
        error_handler.assert_called_once_with(
            error=error_instance,
            function_name='mock.mock.validated_by.<locals>.decorator.<locals>.decorated',
            args=(request_data,),
            kwargs={}
        ) 
Example #5
Source File: test_interactor.py    From python-clean-architecture with MIT License 6 votes vote down vote up
def test_interactor_error_caught(
            self, container, interactor_function, error_handler, request_data, validators):
        error_instance = LogicError('foo')
        interactor_mock = mock.Mock(side_effect=error_instance)
        interactor = interactor_function(*validators)(interactor_mock)(container)

        interactor(request_data)

        validators[0].assert_called_once_with(request_data)
        validators[1].assert_called_once_with(request_data)
        interactor_mock.assert_called_once_with(request_data)
        error_handler.assert_called_once_with(
            error=error_instance,
            function_name='mock.mock.validated_by.<locals>.decorator.<locals>.decorated',
            args=(request_data,),
            kwargs={}
        ) 
Example #6
Source File: test_voicemessage.py    From python-rest-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_voicemessages_list(self):
        http_client = Mock()
        http_client.request.return_value = '{ "offset": 0, "limit": 10, "count": 2, "totalCount": 2, "links": { "first": "https://rest.messagebird.com/voicemessages/?offset=0&limit=30", "previous": null, "next": null, "last": "https://rest.messagebird.com/voicemessages/?offset=0&limit=30" }, "items": [ { "id": "12345678-9012-3456-7890-123456789012", "href": "https://rest.messagebird.com/voicemessages/12345678-9012-3456-7890-123456789012", "originator": null, "body": "This is a test message.", "reference": null, "language": "en-gb", "voice": "male", "repeat": 1, "ifMachine": "continue", "machineTimeout": 7000, "scheduledDatetime": null, "createdDatetime": "2020-02-04T15:15:30+00:00", "recipients": { "totalCount": 1, "totalSentCount": 1, "totalDeliveredCount": 1, "totalDeliveryFailedCount": 0, "items": [ { "recipient": 31612345678, "originator": null, "status": "answered", "statusDatetime": "2020-02-04T15:15:57+00:00" } ] } }, { "id": "12345678-9012-3456-7890-123456789013", "href": "https://rest.messagebird.com/voicemessages/12345678-9012-3456-7890-123456789013", "originator": null, "body": "The voice message to be sent", "reference": null, "language": "en-gb", "voice": "female", "repeat": 1, "ifMachine": "delay", "machineTimeout": 7000, "scheduledDatetime": null, "createdDatetime": "2020-02-04T12:26:44+00:00", "recipients": { "totalCount": 1, "totalSentCount": 1, "totalDeliveredCount": 1, "totalDeliveryFailedCount": 0, "items": [ { "recipient": 31612345678, "originator": null, "status": "answered", "statusDatetime": "2020-02-04T12:27:32+00:00" } ] } } ] }'

        voice_messages = Client('', http_client).voice_message_list()

        http_client.request.assert_called_once_with(
            'voicemessages?limit=10&offset=0', 'GET', None)

        voice_messages_check = {
            '12345678-9012-3456-7890-123456789012': {
                "id": '12345678-9012-3456-7890-123456789012',
                "href": "https://rest.messagebird.com/voicemessages/12345678-9012-3456-7890-123456789012"
            },
            '12345678-9012-3456-7890-123456789013': {
                "id": '12345678-9012-3456-7890-123456789013',
                "href": "https://rest.messagebird.com/voicemessages/12345678-9012-3456-7890-123456789013"
            }
        }

        for item in voice_messages.items:
            message_specific = voice_messages_check.get(item.id)
            self.assertEqual(message_specific['id'], item.id)
            self.assertEqual(message_specific['href'], item.href)
        self.assertIsInstance(str(voice_messages), str) 
Example #7
Source File: test_voice_transcription.py    From python-rest-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_download_voice_transcription(self):
        http_client = Mock()
        http_client.request.return_value = ''

        url = 'https://voice.messagebird.com/calls/'
        call_id = '74bd9fac-742e-4f7c-aef2-bf068c80fd00'
        leg_id = 'd931d0e8-3385-43b3-964b-c9dda2581213'
        recording_id = '4c444e1e-3cea-4b52-90f7-55dec7b2e05e'
        transcription_id = 'fb455b79-c4de-419f-8f72-8c199975c12a'

        Client('', http_client).voice_transcription_download(
            call_id,
            leg_id,
            recording_id,
            transcription_id
        )

        http_client.request.assert_called_once_with(
            url + call_id + '/legs/' + leg_id + '/recordings/' + recording_id + '/transcriptions/' + transcription_id,
            'GET',
            None
        ) 
Example #8
Source File: test_decorators.py    From python-clean-architecture with MIT License 6 votes vote down vote up
def test_injectable_function(self, container, context):
        mock_dependency = mock.Mock()
        container.register_by_name("dependency", lambda *args: mock_dependency)

        @container_supplier
        @inject
        def f(dependency=Inject(name="dependency"), **kwargs):
            # noinspection PyCallingNonCallable
            dependency(**kwargs)
            return 42

        f_closure = f(container, context)
        result = f_closure(foo='bar')

        mock_dependency.assert_called_once_with(foo='bar')
        assert result == 42 
Example #9
Source File: tst_client.py    From marketo-rest-python with MIT License 6 votes vote down vote up
def test_api_call(m_http_lib, client):
    get_request_mock = Mock(return_value={
        'access_token': '1234', 'expires_in': 1000, 'scope': '1'
    })
    request_mock = Mock(get=get_request_mock)
    m_http_lib.return_value = request_mock
    args = (1, 2, 3)
    kwargs = {'a': 1, 'b': 2}
    client._api_call('get', '/test', *args, **kwargs)
    get_request_mock.assert_called_with(*(('/test',) + args), **kwargs)
    assert client.API_CALLS_MADE == 1

    limit = 4
    client = MarketoClient('123-FDY-456', 'randomclientid', 'supersecret', limit)
    with pytest.raises(Exception) as excinfo:
        for i in xrange(limit):
            client._api_call('get', '/test', *args, **kwargs)
        assert excinfo.value == {
            'message': 'API Calls exceeded the limit : %s' % limit,
            'code': '416'
        } 
Example #10
Source File: test_voice_recording.py    From python-rest-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_voice_recording_view(self):
        http_client = Mock()
        http_client.request.return_value = '{"data":[{"id":"12345678-9012-3456-7890-123456789012","format":"wav","legId":"87654321-0987-6543-2109-876543210987","status":"done","duration":32,"type":"transfer","createdAt":"2018-01-01T00:00:01Z","updatedAt":"2018-01-01T00:00:05Z","deletedAt":null}],"_links":{"file":"/calls/12348765-4321-0987-6543-210987654321/legs/87654321-0987-6543-2109-876543210987/recordings/12345678-9012-3456-7890-123456789012.wav","self":"/calls/12345678-9012-3456-7890-123456789012/legs/12348765-4321-0987-6543-210987654321/recordings/12345678-9012-3456-7890-123456789012"},"pagination":{"totalCount":0,"pageCount":0,"currentPage":0,"perPage":0}}'

        voice_recording = Client('', http_client).voice_recording_view(
            '12348765-4321-0987-6543-210987654321',
            '87654321-0987-6543-2109-876543210987',
            '12345678-9012-3456-7890-123456789012'
        )

        http_client.request.assert_called_once_with(
            'https://voice.messagebird.com/calls/12348765-4321-0987-6543-210987654321/legs/87654321-0987-6543-2109-876543210987/recordings/12345678-9012-3456-7890-123456789012',
            'GET', None)

        self.assertEqual('12345678-9012-3456-7890-123456789012', voice_recording.id)
        self.assertEqual('done', voice_recording.status)
        self.assertEqual('wav', voice_recording.format)
        self.assertEqual(datetime(2018, 1, 1, 0, 0, 1, tzinfo=tzutc()), voice_recording.createdAt)
        self.assertEqual(datetime(2018, 1, 1, 0, 0, 5, tzinfo=tzutc()), voice_recording.updatedAt)
        self.assertEqual(2, len(voice_recording._links))
        self.assertIsInstance(str(voice_recording), str) 
Example #11
Source File: test_gquery.py    From grlc with MIT License 6 votes vote down vote up
def test_get_enumeration(self, mock_get):
        mock_get.return_value = Mock(ok=True)
        mock_get.return_value.json.return_value = {
            'results': {
                'bindings': [
                    {'o1': {'value': 'v1'}},
                    {'o1': {'value': 'v2'}}
                ]
            }
        }

        rq, _ = self.loader.getTextForName('test-rq')
        metadata = {'enumerate': 'o1'}
        enumeration = gquery.get_enumeration(rq, 'o1', 'http://mock-endpoint/sparql', metadata)
        self.assertIsInstance(enumeration, list, 'Should return a list of values')
        self.assertEqual(len(enumeration), 2, 'Should have two elements') 
Example #12
Source File: mock_data.py    From grlc with MIT License 6 votes vote down vote up
def mock_requestsGithub(uri, headers={}, params={}):
    if uri.endswith('contents'):
        return_value = Mock(ok=True)
        return_value.json.return_value = mock_files
        return return_value
    else:
        targetFile = uri.replace('https://raw.githubusercontent.com/fakeuser/fakerepo/master/', path.join(base_url, ''))
        if path.exists(targetFile):
            f = open(targetFile, 'r')
            lines = f.readlines()
            text = ''.join(lines)
            return_value = Mock(status_code=200)
            return_value.text = text
            return return_value
        else:
            return_value = Mock(status_code=404)
            return return_value 
Example #13
Source File: tests.py    From WazeRouteCalculator with GNU General Public License v3.0 6 votes vote down vote up
def test_calc_route_info_with_ignored_and_nort(self):
        with requests_mock.mock() as m:
            lat = [47.49, 47.612, 47.645]
            lon = [19.04, 18.99, 18.82]
            bounds = [{"bottom": 47.4, "top": 47.5, "left": 19, "right": 19.1}, None, {"bottom": 47.6, "top": 47.7, "left": 18.8, "right": 18.9}]
            length = [400, 5000, 500]
            time = [40, 360, 60]
            nort_time = [40, 300, 50]
            address_to_coords_response = [
                '[{"city":"Test1","location":{"lat":%s,"lon":%s},"bounds":%s}]' % (lat[0], lon[0], str(bounds[0]).replace("'", '"')),
                '[{"city":"Test2","location":{"lat":%s,"lon":%s},"bounds":%s}]' % (lat[2], lon[2], str(bounds[2]).replace("'", '"'))
            ]
            m.get(self.address_req, [{'text': address_to_coords_response[0]}, {'text': address_to_coords_response[1]}])
            route = wrc.WazeRouteCalculator("", "")
        route_mock = mock.Mock(return_value={"results": [
            {"length": length[0], "crossTime": time[0], "crossTimeWithoutRealTime": nort_time[0], "path": {"x": lon[0], "y": lat[0]}},
            {"length": length[1], "crossTime": time[1], "crossTimeWithoutRealTime": nort_time[1], "path": {"x": lon[1], "y": lat[1]}},
            {"length": length[2], "crossTime": time[2], "crossTimeWithoutRealTime": nort_time[2], "path": {"x": lon[2], "y": lat[2]}}
        ]})
        route.get_route = route_mock
        time, dist = route.calc_route_info(stop_at_bounds=True, real_time=False)
        assert route_mock.called
        assert time == 5.00
        assert dist == 5.00 
Example #14
Source File: tests.py    From WazeRouteCalculator with GNU General Public License v3.0 6 votes vote down vote up
def test_calc_route_info_with_ignored(self):
        with requests_mock.mock() as m:
            lat = [47.49, 47.612, 47.645]
            lon = [19.04, 18.99, 18.82]
            bounds = [{"bottom": 47.4, "top": 47.5, "left": 19, "right": 19.1}, None, {"bottom": 47.6, "top": 47.7, "left": 18.8, "right": 18.9}]
            length = [400, 5000, 500]
            time = [40, 300, 50]
            address_to_coords_response = [
                '[{"city":"Test1","location":{"lat":%s,"lon":%s},"bounds":%s}]' % (lat[0], lon[0], str(bounds[0]).replace("'", '"')),
                '[{"city":"Test2","location":{"lat":%s,"lon":%s},"bounds":%s}]' % (lat[2], lon[2], str(bounds[2]).replace("'", '"'))
            ]
            m.get(self.address_req, [{'text': address_to_coords_response[0]}, {'text': address_to_coords_response[1]}])
            route = wrc.WazeRouteCalculator("", "")
        route_mock = mock.Mock(return_value={"results": [
            {"length": length[0], "crossTime": time[0], "path": {"x": lon[0], "y": lat[0]}},
            {"length": length[1], "crossTime": time[1], "path": {"x": lon[1], "y": lat[1]}},
            {"length": length[2], "crossTime": time[2], "path": {"x": lon[2], "y": lat[2]}}
        ]})
        route.get_route = route_mock
        time, dist = route.calc_route_info(stop_at_bounds=True)
        assert route_mock.called
        assert time == 5.00
        assert dist == 5.00 
Example #15
Source File: test_conversation_message.py    From python-rest-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_create_message(self):
        http_client = Mock()
        http_client.request.return_value = '{"id":"id","conversationId":"conversation-id","channelId":"channel-id","type":"text","content":{"text":"Example Text Message"},"direction":"sent","status":"pending","createdDatetime":"2019-04-02T11:57:52.142641447Z","updatedDatetime":"2019-04-02T11:57:53.142641447Z"}'

        data = {
            'channelId': 1234,
            'type': 'text',
            'content': {
                'text': 'this is a message'
            },
        }

        msg = Client('', http_client).conversation_create_message('conversation-id', data)

        self.assertEqual(datetime(2019, 4, 2, 11, 57, 53, tzinfo=tzutc()), msg.updatedDatetime)
        self.assertEqual(datetime(2019, 4, 2, 11, 57, 52, tzinfo=tzutc()), msg.createdDatetime)

        http_client.request.assert_called_once_with('conversations/conversation-id/messages', 'POST', data) 
Example #16
Source File: test_voice_webhook.py    From python-rest-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_voice_update_webhook(self):
        http_client = Mock()
        http_client.request.return_value = '''{
          "data": [
            {
              "id": "534e1848-235f-482d-983d-e3e11a04f58a",
              "url": "https://example.com/baz",
              "token": "foobar",
              "createdAt": "2017-03-15T13:27:02Z",
              "updatedAt": "2017-03-15T13:28:01Z"
            }
          ],
          "_links": {
            "self": "/webhooks/534e1848-235f-482d-983d-e3e11a04f58a"
          }
        }'''
        webhook_id = '534e1848-235f-482d-983d-e3e11a04f58a'
        update_webhook_request = VoiceUpdateWebhookRequest(title="FooBar", token="foobar")
        updated_webhook = Client('', http_client).voice_update_webhook(webhook_id, update_webhook_request)

        http_client.request.assert_called_once_with(
            VOICE_API_ROOT + '/' + VOICE_WEB_HOOKS_PATH + '/' + webhook_id, 'PUT', update_webhook_request.__dict__())

        self.assertEqual(update_webhook_request.token, updated_webhook.token) 
Example #17
Source File: test_conversation.py    From python-rest-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_conversation_start(self):
        http_client = Mock()
        http_client.request.return_value = '{"id":"1234","contactId":"1234","contact":{"id":"1234","href":"https://contacts.messagebird.com/v2/contacts/1234","msisdn":99999999999,"displayName":"99999999999","firstName":"","lastName":"","customDetails":{},"attributes":{},"createdDatetime":"2019-04-02T08:19:37Z","updatedDatetime":"2019-04-02T08:19:38Z"},"channels":[{"id":"1234","name":"channel-name","platformId":"sms","status":"active","createdDatetime":"2019-04-01T15:25:12Z","updatedDatetime":"0001-01-01T00:00:00Z"}],"status":"active","createdDatetime":"2019-04-02T08:19:37Z","updatedDatetime":"2019-04-02T08:54:42.497114599Z","lastReceivedDatetime":"2019-04-02T08:54:42.464955904Z","lastUsedChannelId":"1234","messages":{"totalCount":1,"href":"https://conversations.messagebird.com/v1/conversations/1234/messages"}}'

        data = {
            'channelId': '1234',
            'to': '+99999999999',
            'type': "text",
            'content': {
                'text': 'Message Example'
            },
        }

        msg = Client('', http_client).conversation_start(data)

        http_client.request.assert_called_once_with('conversations/start', 'POST', data)

        self.assertEqual('1234', msg.id)
        self.assertEqual(99999999999, msg.contact.msisdn)
        self.assertEqual(datetime(2019, 4, 2, 8, 19, 37, tzinfo=tzutc()), msg.contact.createdDatetime)
        self.assertEqual(datetime(2019, 4, 2, 8, 19, 38, tzinfo=tzutc()), msg.contact.updatedDatetime)
        self.assertEqual('channel-name', msg.channels[0].name) 
Example #18
Source File: test_call_flow.py    From python-rest-api with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_numbers_add(self):
        http_client = Mock()
        http_client.request.return_value = '{}'

        Client('', http_client).call_flow_numbers_add(
            'de3ed163-d5fc-45f4-b8c4-7eea7458c635',
            ['31611111111', '31611111112']
        )

        params = {'numbers': ['31611111111', '31611111112']}

        http_client.request.assert_called_once_with(
            'call-flows/de3ed163-d5fc-45f4-b8c4-7eea7458c635/numbers', 'POST', params) 
Example #19
Source File: test_group.py    From python-rest-api with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_group(self):
        http_client = Mock()
        http_client.request.return_value = '{"id": "group-id","href": "https://rest.messagebird.com/groups/group-id","name": "Friends","contacts": {"totalCount": 3,"href": "https://rest.messagebird.com/groups/group-id"},"createdDatetime": "2018-07-25T12:16:10+00:00","updatedDatetime": "2018-07-25T12:16:23+00:00"}'

        group = Client('', http_client).group('group-id')

        http_client.request.assert_called_once_with('groups/group-id', 'GET', None)

        self.assertEqual('Friends', group.name)
        self.assertEqual(3, group.contacts.totalCount) 
Example #20
Source File: test_group.py    From python-rest-api with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_group_remove_contact(self):
        http_client = Mock()
        http_client.request.return_value = ''

        Client('', http_client).group_remove_contact('group-id', 'contact-id')

        http_client.request.assert_called_once_with('groups/group-id/contacts/contact-id', 'DELETE', None) 
Example #21
Source File: test_number.py    From python-rest-api with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_delete_number(self):
        http_client = Mock()
        http_client.request.return_value = '{}'

        Client('', http_client).delete_number('31971234567')

        http_client.request.assert_called_once_with('phone-numbers/31971234567', 'DELETE', None) 
Example #22
Source File: test_voicemessage.py    From python-rest-api with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_voicemessage(self):
        http_client = Mock()
        http_client.request.return_value = '{"body": "Hello World","createdDatetime": "2015-01-05T16:11:24+00:00","href": "https://rest.messagebird.com/voicemessages/voicemessage-id","id": "voicemessage-id","ifMachine": "continue","language": "en-gb","originator": "MessageBird","recipients": {"items": [{"recipient": 31612345678,"status": "calling","statusDatetime": "2015-01-05T16:11:24+00:00"}],"totalCount": 1,"totalDeliveredCount": 0,"totalDeliveryFailedCount": 0,"totalSentCount": 1},"reference": null,"repeat": 1,"scheduledDatetime": null,"voice": "female"}'

        voice_message = Client(
            '', http_client).voice_message('voicemessage-id')

        http_client.request.assert_called_once_with(
            'voicemessages/voicemessage-id', 'GET', None)

        self.assertEqual('voicemessage-id', voice_message.id) 
Example #23
Source File: test_contact.py    From python-rest-api with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_contact_list(self):
        http_client = Mock()
        http_client.request.return_value = '{"offset": 0,"limit": 20,"count": 2,"totalCount": 2,"links": {"first": "https://rest.messagebird.com/contacts?offset=0","previous": null,"next": null,"last": "https://rest.messagebird.com/contacts?offset=0"},"items": [{"id": "first-id","href": "https://rest.messagebird.com/contacts/first-id","msisdn": 31612345678,"firstName": "Foo","lastName": "Bar","customDetails": {"custom1": null,"custom2": null,"custom3": null,"custom4": null},"groups": {"totalCount": 0,"href": "https://rest.messagebird.com/contacts/first-id/groups"},"messages": {"totalCount": 0,"href": "https://rest.messagebird.com/contacts/first-id/messages"},"createdDatetime": "2018-07-13T10:34:08+00:00","updatedDatetime": "2018-07-13T10:34:08+00:00"},{"id": "second-id","href": "https://rest.messagebird.com/contacts/second-id","msisdn": 49612345678,"firstName": "Hello","lastName": "World","customDetails": {"custom1": null,"custom2": null,"custom3": null,"custom4": null},"groups": {"totalCount": 0,"href": "https://rest.messagebird.com/contacts/second-id/groups"},"messages": {"totalCount": 0,"href": "https://rest.messagebird.com/contacts/second-id/messages"},"createdDatetime": "2018-07-13T10:33:52+00:00","updatedDatetime": null}]}'

        contact_list = Client('', http_client).contact_list(10, 20)

        http_client.request.assert_called_once_with('contacts?limit=10&offset=20', 'GET', None)

        self.assertEqual(2, contact_list.totalCount)
        self.assertEqual('https://rest.messagebird.com/contacts?offset=0', contact_list.links.first)
        self.assertEqual('https://rest.messagebird.com/contacts/first-id/groups', contact_list.items[0].groups.href) 
Example #24
Source File: test_contact.py    From python-rest-api with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_contact_update(self):
        http_client = Mock()
        http_client.request.return_value = ''

        Client('', http_client).contact_update('contact-id', {'msisdn': 31687654321, 'custom4': 'fourth'})

        http_client.request.assert_called_once_with(
            'contacts/contact-id', 'PATCH', {'msisdn': 31687654321, 'custom4': 'fourth'}
        ) 
Example #25
Source File: test_contact.py    From python-rest-api with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_contact_delete_invalid(self):
        http_client = Mock()
        http_client.request.return_value = '{"errors": [{"code": 20,"description": "contact not found","parameter": null}]}'

        with self.assertRaises(ErrorException):
            Client('', http_client).contact_delete('non-existent-contact-id')

        http_client.request.assert_called_once_with('contacts/non-existent-contact-id', 'DELETE', None) 
Example #26
Source File: test_contact.py    From python-rest-api with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_contact_create(self):
        http_client = Mock()
        http_client.request.return_value = '{}'

        Client('', http_client).contact_create(31612345678, {'firstName': 'Foo', 'custom3': 'Third'})

        http_client.request.assert_called_once_with(
            'contacts', 'POST', {'msisdn': 31612345678, 'firstName': 'Foo', 'custom3': 'Third'}) 
Example #27
Source File: test_contact.py    From python-rest-api with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_contact(self):
        http_client = Mock()
        http_client.request.return_value = '{"id": "contact-id","href": "https://rest.messagebird.com/contacts/contact-id","msisdn": 31612345678,"firstName": "Foo","lastName": "Bar","customDetails": {"custom1": "First","custom2": "Second","custom3": "Third","custom4": "Fourth"},"groups": {"totalCount": 3,"href": "https://rest.messagebird.com/contacts/contact-id/groups"},"messages": {"totalCount": 5,"href": "https://rest.messagebird.com/contacts/contact-id/messages"},"createdDatetime": "2018-07-13T10:34:08+00:00","updatedDatetime": "2018-07-13T10:44:08+00:00"}'

        contact = Client('', http_client).contact('contact-id')

        http_client.request.assert_called_once_with('contacts/contact-id', 'GET', None)

        self.assertEqual(31612345678, contact.msisdn)
        self.assertEqual('First', contact.customDetails.custom1)
        self.assertEqual(3, contact.groups.totalCount)
        self.assertEqual('https://rest.messagebird.com/contacts/contact-id/messages', contact.messages.href) 
Example #28
Source File: test_lookup.py    From python-rest-api with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_lookup_hlr_create(self):
        http_client = Mock()
        http_client.request.return_value = '{}'

        Client('', http_client).lookup_hlr_create(31612345678, {'reference': 'MyReference'})

        http_client.request.assert_called_once_with('lookup/31612345678/hlr', 'POST', {'reference': 'MyReference'}) 
Example #29
Source File: test_lookup.py    From python-rest-api with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_lookup_hlr(self):
        http_client = Mock()
        http_client.request.return_value = '{"id": "hlr-id","network": 20416,"reference": "reference2000","status": "active","createdDatetime": "2015-12-15T08:19:24+00:00","statusDatetime": "2015-12-15T08:19:25+00:00"}'

        lookup_hlr = Client('', http_client).lookup_hlr(31612345678, {'reference': 'reference2000'})

        http_client.request.assert_called_once_with('lookup/31612345678/hlr', 'GET', {'reference': 'reference2000'})

        self.assertEqual(lookup_hlr.status, 'active') 
Example #30
Source File: test_lookup.py    From python-rest-api with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_lookup(self):
        http_client = Mock()
        http_client.request.return_value = '{"href": "https://rest.messagebird.com/lookup/31612345678","countryCode": "NL","countryPrefix": 31,"phoneNumber": 31612345678,"type": "mobile","formats": {"e164": "+31612345678","international": "+31 6 12345678","national": "06 12345678","rfc3966": "tel:+31-6-12345678"},"hlr": {"id": "hlr-id","network": 20416,"reference": "reference2000","status": "active","createdDatetime": "2015-12-15T08:19:24+00:00","statusDatetime": "2015-12-15T08:19:25+00:00"}}'

        lookup = Client('', http_client).lookup('0612345678', {'countryCode': 'NL'})

        http_client.request.assert_called_once_with('lookup/0612345678', 'GET', {'countryCode': 'NL'})

        self.assertEqual('mobile', lookup.type)