Python requests_mock.ANY Examples

The following are 30 code examples of requests_mock.ANY(). 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 requests_mock , or try the search function .
Example #1
Source File: testcase.py    From ringcentral-python with MIT License 6 votes vote down vote up
def get_sdk(self, mock):

        sdk = SDK('whatever', 'whatever', 'mock://whatever', redirect_uri='mock://whatever-redirect')

        self.authentication_mock(mock)
        sdk.platform().login('18881112233', None, 'password')

        matcher = re.compile('pubsub\.pubnub\.com')

        mock.register_uri(
            method=requests_mock.ANY,
            url=matcher,
            text=''
        )

        matcher = re.compile('ps\.pndsn\.com')

        mock.register_uri(
            method=requests_mock.ANY,
            url=matcher,
            text=''
        )

        return sdk 
Example #2
Source File: test_packet.py    From packet-python with GNU Lesser General Public License v3.0 6 votes vote down vote up
def call_api(self, method, type="GET", params=None):
        with requests_mock.Mocker() as m:
            mock = {
                "DELETE": m.delete,
                "GET": m.get,
                "PUT": m.put,
                "POST": m.post,
                "PATCH": m.patch,
            }[type]

            if type == "DELETE":
                mock(requests_mock.ANY)
                return super(PacketMockManager, self).call_api(method, type, params)

            fixture = "%s_%s" % (type.lower(), method.lower())
            fixture = fixture.replace("/", "_").split("?")[0]
            fixture = "test/fixtures/%s.json" % fixture

            headers = {"content-type": "application/json"}

            with open(fixture) as data_file:
                j = json.load(data_file)

            mock(requests_mock.ANY, headers=headers, json=j)
            return super(PacketMockManager, self).call_api(method, type, params) 
Example #3
Source File: test_client.py    From python-ouraring with MIT License 6 votes vote down vote up
def test_token_refresh():
    update_called = []

    # hacky way to test side effect
    def token_updater(token):
        update_called.append(1)

    client = OuraClient('test_id', access_token='token', refresh_callback=token_updater)
    adapter.register_uri(requests_mock.POST, requests_mock.ANY, status_code=401, text=json.dumps({
            'access_token': 'fake_return_access_token',
            'refresh_token': 'fake_return_refresh_token'
        }))
    adapter.register_uri(requests_mock.GET, requests_mock.ANY, status_code=401, text=json.dumps({ 'a': 'b'}))

    client._session.mount(client.API_ENDPOINT, adapter)
    try:
        resp = client.user_info()
    except:
        pass
    assert len(update_called) == 1 
Example #4
Source File: test_mock_solver_loading.py    From dwave-cloud-client with Apache License 2.0 6 votes vote down vote up
def setup_server(m):
    """Add endpoints to the server."""
    # Content strings
    first_solver_response = structured_solver_data(solver_name)
    second_solver_response = structured_solver_data(second_solver_name)
    two_solver_response = '[' + first_solver_response + ',' + second_solver_response + ']'

    # Setup the server
    headers = {'X-Auth-Token': token}
    m.get(requests_mock.ANY, status_code=404)
    m.get(all_solver_url, status_code=403, request_headers={})
    m.get(solver1_url, status_code=403, request_headers={})
    m.get(solver2_url, status_code=403, request_headers={})
    m.get(all_solver_url, text=two_solver_response, request_headers=headers)
    m.get(solver1_url, text=first_solver_response, request_headers=headers)
    m.get(solver2_url, text=second_solver_response, request_headers=headers) 
Example #5
Source File: test_download.py    From audiomate with MIT License 6 votes vote down vote up
def test_download_file(sample_zip_data, tmpdir):
    dl_path = 'http://some.url/thezipfile.zip'
    target_path = os.path.join(tmpdir.strpath, 'target.zip')

    with requests_mock.Mocker() as mock:
        # Return any size (doesn't matter, only for prints)
        mock.head(requests_mock.ANY, headers={'Content-Length': '100'})

        mock.get(dl_path, content=sample_zip_data)

        download.download_file(dl_path, target_path)

    assert os.path.isfile(target_path)

    with open(target_path, 'rb') as f:
        assert f.read() == sample_zip_data 
Example #6
Source File: test_app.py    From habitica-github with MIT License 6 votes vote down vote up
def test_score_task(self, m):
        # arrange
        expected_headers = {
            'x-api-user': self.api_user,
            'x-api-key': self.api_key,
        }

        expected_url = 'https://habitica.com/api/v3/tasks/task1/score/up'

        m.post(requests_mock.ANY, text='{}')

        # act
        app.score_task('task1', 'up')

        # assert
        history = m.request_history
        self.assertEqual(len(history), 1)

        request = history[0]
        self.assertEqual(request.url, expected_url)
        self.assertEqual(request.method, 'POST')
        for item in expected_headers.items():
            self.assertIn(item, request.headers.items()) 
Example #7
Source File: test_btcde_func.py    From btcde with MIT License 6 votes vote down vote up
def test_signature_post(self, mock_logger, m):
        '''Test signature on a post request.'''
        params = {'max_amount': 10,
                  'price': 1337,
                  'trading_pair': 'btceur',
                  'type': 'buy' }
        response = self.sampleData('createOrder')
        m.post(requests_mock.ANY, json=response, status_code=201)
        self.conn.createOrder(params['type'],
                              params['trading_pair'],
                              params['max_amount'],
                              params['price'])
        history = m.request_history
        request_signature = history[0].headers.get('X-API-SIGNATURE')
        verified_signature = self.verifySignature(self.conn.orderuri,
                                                  'POST', self.conn.nonce,
                                                  params)
        self.assertEqual(request_signature, verified_signature)
        self.assertTrue(mock_logger.debug.called) 
Example #8
Source File: test_voxforge.py    From audiomate with MIT License 6 votes vote down vote up
def test_available_files(self, sample_response):
        with requests_mock.Mocker() as mock:
            # Return any size (doesn't matter, only for prints)
            mock.head(requests_mock.ANY, headers={'Content-Length': '100'})

            url = 'http://someurl.com/some/download/dir'
            mock.get(url, text=sample_response)
            files = voxforge.VoxforgeDownloader.available_files(url)

            assert set(files) == {
                'http://someurl.com/some/download/dir/1337ad-20170321-amr.tgz',
                'http://someurl.com/some/download/dir/1337ad-20170321-bej.tgz',
                'http://someurl.com/some/download/dir/1337ad-20170321-blf.tgz',
                'http://someurl.com/some/download/dir/1337ad-20170321-czb.tgz',
                'http://someurl.com/some/download/dir/1337ad-20170321-hii.tgz'
            } 
Example #9
Source File: test_btcde_func.py    From btcde with MIT License 6 votes vote down vote up
def test_show_orderbook(self, mock_logger, m):
        '''Test function showOrderbook.'''
        params = {'price': 1337,
                  'trading_pair': 'btceur',
                  'type': 'buy'}
        base_url = 'https://api.bitcoin.de/v2/orders'
        url_args = '?' + urlencode(params)
        response = self.sampleData('showOrderbook_buy')
        m.get(requests_mock.ANY, json=response, status_code=200)
        self.conn.showOrderbook(params.get('type'),
                                params.get('trading_pair'),
                                price=params.get('price'))
        history = m.request_history
        self.assertEqual(history[0].method, "GET")
        self.assertEqual(history[0].url, base_url + url_args)
        self.assertTrue(mock_logger.debug.called) 
Example #10
Source File: test_btcde_func.py    From btcde with MIT License 6 votes vote down vote up
def test_createOrder(self, mock_logger, m):
        '''Test function createOrder.'''
        params = {'max_amount': '10',
                  'price': '10',
                  'trading_pair': 'btceur',
                  'type': 'buy'
                  }
        base_url = 'https://api.bitcoin.de/v2/orders'
        url_args = '?' + urlencode(params)
        response = self.sampleData('createOrder')
        m.post(requests_mock.ANY, json=response, status_code=201)
        self.conn.createOrder(params.get('type'),
                              params.get('trading_pair'),
                              params.get('max_amount'),
                              params.get('price'))
        history = m.request_history
        self.assertEqual(history[0].method, "POST")
        self.assertEqual(history[0].url, base_url + url_args)
        self.assertTrue(mock_logger.debug.called) 
Example #11
Source File: test_btcde_func.py    From btcde with MIT License 6 votes vote down vote up
def test_executeTrade(self, mock_logger, m):
        '''Test function executeTrade.'''
        params = {'amount': '10',
                  'order_id': '1337',
                  'trading_pair': 'btceur',
                  'type': 'buy'}
        base_url = 'https://api.bitcoin.de/v2/trades/{}'\
                   .format(params.get('order_id'))
        url_args = '?' + urlencode(params)
        response = self.sampleData('executeTrade')
        m.get(requests_mock.ANY, json=response, status_code=200)
        m.post(requests_mock.ANY, json=response, status_code=201)
        self.conn.executeTrade(params.get('order_id'),
                               params.get('type'),
                               params.get('trading_pair'),
                               params.get('amount'))
        history = m.request_history
        self.assertEqual(history[0].method, "POST")
        self.assertEqual(history[0].url, base_url + url_args)
        self.assertTrue(mock_logger.debug.called) 
Example #12
Source File: test_mock_solver_loading.py    From dwave-cloud-client with Apache License 2.0 5 votes vote down vote up
def test_load_missing_solver(self):
        """Try to load a solver that does not exist."""
        with requests_mock.mock() as m:
            m.get(requests_mock.ANY, status_code=404)
            with Client(url, token) as client:
                with self.assertRaises(SolverNotFoundError):
                    client.get_solver(solver_name) 
Example #13
Source File: test_btcde_func.py    From btcde with MIT License 5 votes vote down vote up
def test_showOrderbookCompact(self, mock_logger, m):
        '''Test function showOrderbookCompact.'''
        params = {'trading_pair': 'btceur'}
        base_url = 'https://api.bitcoin.de/v2/orders/compact'
        url_args = '?trading_pair={}'.format(params.get('trading_pair'))
        response = self.sampleData('showOrderbookCompact')
        m.get(requests_mock.ANY, json=response, status_code=200)
        self.conn.showOrderbookCompact(params.get('trading_pair'))
        history = m.request_history
        self.assertEqual(history[0].method, "GET")
        self.assertEqual(history[0].url, base_url + url_args)
        self.assertTrue(mock_logger.debug.called) 
Example #14
Source File: test_acls.py    From python-barbicanclient with Apache License 2.0 5 votes vote down vote up
def test_should_get_container_acl_with_trailing_slashes(self):
        self.responses.get(requests_mock.ANY,
                           json=self.get_acl_response_data())
        # check if trailing slashes are corrected in get call.
        self.manager.get(entity_ref=self.container_ref + '///')
        self.assertEqual(self.container_acl_ref,
                         self.responses.last_request.url) 
Example #15
Source File: test_acls.py    From python-barbicanclient with Apache License 2.0 5 votes vote down vote up
def test_should_get_secret_acl_with_extra_trailing_slashes(self):
        self.responses.get(requests_mock.ANY,
                           json=self.get_acl_response_data())
        # check if trailing slashes are corrected in get call.
        self.manager.get(entity_ref=self.secret_ref + '///')
        self.assertEqual(self.secret_acl_ref,
                         self.responses.last_request.url) 
Example #16
Source File: test_btcde_func.py    From btcde with MIT License 5 votes vote down vote up
def test_dont_fail_on_non_utf8(self, m):
        '''Test if no exception raises with a non-utf8 response.
        https://github.com/peshay/btcde/issues/12'''
        filepath = 'tests/resources/NonUTF8'
        with open(filepath, 'r') as f:
            m.post(requests_mock.ANY, content=f.read().encode('utf-16', 'replace'), status_code=403)
        try:
            self.conn.executeTrade('foobar', 'buy', 'btceur', '0')
            self.assertTrue(True)
        except UnicodeDecodeError:
            self.assertTrue(False) 
Example #17
Source File: test_btcde_func.py    From btcde with MIT License 5 votes vote down vote up
def test_decimal_parsing(self, mock_logger, m):
        '''Test if the decimal parsing calculates correctly.'''
        params = {'type': 'buy',
                  'trading_pair': 'btceur',
                  'max_amount': 10,
                  'price': 1337}
        response = self.sampleData('showOrderbook_buy')
        m.get(requests_mock.ANY, json=response, status_code=200)
        data = self.conn.showOrderbook(params.get('type'),
                                       params.get('trading_pair'),
                                       price=params.get('price'))
        price = data.get('orders')[0].get('price')
        self.assertIsInstance(price, Decimal)
        self.assertEqual(price + Decimal('22.3'), Decimal('2232.2'))
        self.assertNotEqual(float(price) + float('22.3'), float('2232.2')) 
Example #18
Source File: test_pagination.py    From Mastodon.py with MIT License 5 votes vote down vote up
def test_link_headers(api):
    rmock = requests_mock.Adapter()
    api.session.mount(api.api_base_url, rmock)

    _id='abc1234'

    rmock.register_uri('GET', requests_mock.ANY, json=[{"foo": "bar"}], headers={"link":"""
            <{base}/api/v1/timelines/tag/{tag}?max_id={_id}>; rel="next", <{base}/api/v1/timelines/tag/{tag}?since_id={_id}>; rel="prev"
        """.format(base=api.api_base_url, tag=UNLIKELY_HASHTAG, _id=_id).strip()
    })

    resp = api.timeline_hashtag(UNLIKELY_HASHTAG)
    assert resp[0]._pagination_next['max_id'] == _id
    assert resp[0]._pagination_prev['since_id'] == _id 
Example #19
Source File: test_btcde_func.py    From btcde with MIT License 5 votes vote down vote up
def test_showPublicTradeHistory_since(self, mock_logger, m):
        '''Test function showPublicTradeHistory with since_tid.'''
        params = {'since_tid': '123', 'trading_pair': 'btceur'}
        base_url = 'https://api.bitcoin.de/v2/trades/history'
        url_args = '?' + urlencode(params)
        response = self.sampleData('showPublicTradeHistory')
        m.get(requests_mock.ANY, json=response, status_code=200)
        self.conn.showPublicTradeHistory(params.get('trading_pair'),
                                         since_tid=params.get('since_tid'))
        history = m.request_history
        self.assertEqual(history[0].method, "GET")
        self.assertEqual(history[0].url, base_url + url_args)
        self.assertTrue(mock_logger.debug.called) 
Example #20
Source File: test_btcde_func.py    From btcde with MIT License 5 votes vote down vote up
def test_showRates(self, mock_logger, m):
        '''Test function showRates.'''
        params = {'trading_pair': 'btceur'}
        base_url = 'https://api.bitcoin.de/v2/rates'
        url_args = '?trading_pair={}'.format(params.get('trading_pair'))
        response = self.sampleData('showRates')
        m.get(requests_mock.ANY, json=response, status_code=200)
        self.conn.showRates(params.get('trading_pair'))
        history = m.request_history
        self.assertEqual(history[0].method, "GET")
        self.assertEqual(history[0].url, base_url + url_args)
        self.assertTrue(mock_logger.debug.called) 
Example #21
Source File: test_btcde_func.py    From btcde with MIT License 5 votes vote down vote up
def test_showPublicTradeHistory(self, mock_logger, m):
        '''Test function showPublicTradeHistory.'''
        params = {'trading_pair': 'btceur'}
        base_url = 'https://api.bitcoin.de/v2/trades/history'
        url_args = '?trading_pair={}'.format(params.get('trading_pair'))
        response = self.sampleData('showPublicTradeHistory')
        m.get(requests_mock.ANY, json=response, status_code=200)
        self.conn.showPublicTradeHistory(params.get('trading_pair'))
        history = m.request_history
        self.assertEqual(history[0].method, "GET")
        self.assertEqual(history[0].url, base_url + url_args)
        self.assertTrue(mock_logger.debug.called) 
Example #22
Source File: 03_requests_mock.py    From Python-Microservices-Development with MIT License 5 votes vote down vote up
def test_get_new_bugs(self, mocker):
        # mocking the requests call and send back two bugs
        bugs = [{'id': 1184528}, {'id': 1184524}]
        mocker.get(requests_mock.ANY, json={'bugs': bugs})

        zilla = MyBugzilla('tarek@mozilla.com', server = 'http://yeah')
        bugs = list(zilla.get_new_bugs())
        self.assertEqual(bugs[0]['link'], 'http://yeah/show_bug.cgi?id=1184528') 
Example #23
Source File: test_btcde_func.py    From btcde with MIT License 5 votes vote down vote up
def test_allowed_currency(self, mock_logger, m):
        '''Test the allowed currencies.'''
        i = 0
        for curr in ['btc', 'bch', 'eth', 'btg', 'bsv']:
            params = {'currency': curr}
            base_url = 'https://api.bitcoin.de/v2/account/ledger'
            url_args = '?currency={}'.format(params.get('currency'))
            response = self.sampleData('showAccountLedger')
            m.get(requests_mock.ANY, json=response, status_code=200)
            self.conn.showAccountLedger(params.get('currency'))
            history = m.request_history
            self.assertEqual(history[i].method, "GET")
            self.assertEqual(history[i].url, base_url + url_args)
            self.assertTrue(mock_logger.debug.called)
            i += 1 
Example #24
Source File: test_btcde_func.py    From btcde with MIT License 5 votes vote down vote up
def test_showMyTrades_with_params(self, mock_logger, m):
        '''Test function showMyTrades with parameters.'''
        params = {'trading_pair': 'btceur',
                  'type': 'buy' }
        base_url = 'https://api.bitcoin.de/v2/trades'
        url_args = '?' + urlencode(params)
        response = self.sampleData('showMyTrades')
        m.get(requests_mock.ANY, json=response, status_code=200)
        self.conn.showMyTrades(type=params.get('type'),
                               trading_pair=params.get('trading_pair'))
        history = m.request_history
        self.assertEqual(history[0].method, "GET")
        self.assertEqual(history[0].url, base_url + url_args)
        self.assertTrue(mock_logger.debug.called) 
Example #25
Source File: test_btcde_func.py    From btcde with MIT License 5 votes vote down vote up
def test_showMyTrades(self, mock_logger, m):
        '''Test function showMyTrades.'''
        base_url = 'https://api.bitcoin.de/v2/trades'
        url_args = ''
        response = self.sampleData('showMyTrades')
        m.get(requests_mock.ANY, json=response, status_code=200)
        self.conn.showMyTrades()
        history = m.request_history
        self.assertEqual(history[0].method, "GET")
        self.assertEqual(history[0].url, base_url + url_args)
        self.assertTrue(mock_logger.debug.called) 
Example #26
Source File: test_btcde_func.py    From btcde with MIT License 5 votes vote down vote up
def test_showMyOrderDetails(self, mock_logger, m):
        '''Test function showMyOrderDetails.'''
        params = {'order_id': '1337'}
        base_url = 'https://api.bitcoin.de/v2/orders/{}'\
                   .format(params.get('order_id'))
        url_args = ''
        response = self.sampleData('showMyOrderDetails')
        m.get(requests_mock.ANY, json=response, status_code=200)
        self.conn.showMyOrderDetails(params.get('order_id'))
        history = m.request_history
        self.assertEqual(history[0].method, "GET")
        self.assertEqual(history[0].url, base_url + url_args)
        self.assertTrue(mock_logger.debug.called) 
Example #27
Source File: test_btcde_func.py    From btcde with MIT License 5 votes vote down vote up
def test_showMyOrders(self, mock_logger, m):
        '''Test function showMyOrders.'''
        params = {'trading_pair': 'btceur',
                  'type': 'buy' }
        base_url = 'https://api.bitcoin.de/v2/orders/my_own'
        url_args = '?' + urlencode(params)
        response = self.sampleData('showMyOrders')
        m.get(requests_mock.ANY, json=response, status_code=200)
        self.conn.showMyOrders(type=params.get('type'),
                               trading_pair=params.get('trading_pair'))
        history = m.request_history
        self.assertEqual(history[0].method, "GET")
        self.assertEqual(history[0].url, base_url + url_args)
        self.assertTrue(mock_logger.debug.called) 
Example #28
Source File: test_btcde_func.py    From btcde with MIT License 5 votes vote down vote up
def test_signature_delete(self, mock_logger, m):
        '''Test signature on a delete request.'''
        order_id = 'A1234BC'
        trading_pair = 'btceur'
        m.delete(requests_mock.ANY, json={}, status_code=200)
        self.conn.deleteOrder(order_id, trading_pair)
        history = m.request_history
        request_signature = history[0].headers.get('X-API-SIGNATURE')
        url = self.conn.orderuri + "/" + order_id + "/" + trading_pair
        verified_signature = self.verifySignature(url, 'DELETE', self.conn.nonce, {})
        self.assertEqual(request_signature, verified_signature)
        self.assertTrue(mock_logger.debug.called) 
Example #29
Source File: test_btcde_func.py    From btcde with MIT License 5 votes vote down vote up
def test_signature_get(self, mock_logger, m):
        '''Test signature on a get request.'''
        params = {'trading_pair': 'btceur',
                   'type': 'buy' }
        response = self.sampleData('showOrderbook_buy')
        m.get(requests_mock.ANY, json=response, status_code=200)
        self.conn.showOrderbook(params.get('type'),
                                params.get('trading_pair'))
        history = m.request_history
        request_signature = history[0].headers.get('X-API-SIGNATURE')
        verified_signature = self.verifySignature(self.conn.orderuri,
                                                  'GET', self.conn.nonce,
                                                  params)
        self.assertEqual(request_signature, verified_signature)
        self.assertTrue(mock_logger.debug.called) 
Example #30
Source File: test_keycloak.py    From vitrage with Apache License 2.0 5 votes vote down vote up
def test_in_keycloak_mode_wrong_token(self, _, req_mock):

        # Imitate failure response from KeyCloak.
        req_mock.get(
            requests_mock.ANY,
            status_code=401,
            reason='Access token is invalid'
        )

        resp = self.post_json('/topology/',
                              params=None,
                              headers=HEADERS,
                              expect_errors=True)

        self.assertEqual('401 Unauthorized', resp.status)