예제 #1
0
def activate_tineye_mock(*fixtures, eternal=False):
    debug("INIT urllib3 mock for TINEYE")
    responses = Responses("urllib3")
    fixture_generator = get_fixture_generator(fixtures, eternal)

    def tineye_response(request):
        debug("served urllib3 mock for TINEYE")
        fixture = next(fixture_generator)
        return (fixture[METADATA]["status"], {}, fixture[CONTENT])

    responses.add_callback("POST", re.compile(r".*api\.tineye\.com/rest/search/.*"), callback=tineye_response)

    def pass_through(req):
        """
        workaround for elasticsearch which uses urllib3 as well
        """
        """
        logger.debug("urllib3-PASS-THROUGH: " + str(
            (req.method, req.host, req.port, req.url, )
        ))
        """
        new_params = {}
        for key in ["method", "headers", "body", "url"]:
            new_params[key] = getattr(req, key)
        http = HTTPConnectionPool(host=req.host, port=req.port)
        res = orig_urlopen(http, **new_params)
        return (res.status, res.getheaders(), res.data)

    responses.add_callback(mock.ANY, re.compile(r"/.*"), callback=pass_through)

    def wrap(f):
        @responses.activate
        def test_new(*args):
            return f(*args)

        return test_new

    return wrap
예제 #2
0
class TestAuthentication(object):

    responses = Responses('requests.packages.urllib3')

    def testRefreshAuthentication(self):

        auth = AuthenticationProvider.currentAuth()

        assert auth.accessToken
        assert auth.expires
        assert auth.tokenType == 'Bearer'
        assert auth.expiresIn == 3600
        assert auth.refreshToken == os.environ.get('REFRESH_TOKEN')
        assert not auth.isExpired
        assert auth is AuthenticationProvider.currentAuth()
예제 #3
0
def responses():
    responses_mock = Responses("requests.packages.urllib3")

    def _find_request(call):
        mock_url = responses_mock._find_match(call.request)
        if not mock_url:
            raise Exception(f"Call not mocked: {call.request}")
        return mock_url

    def _to_tuple(url_mock):
        return (url_mock["url"], url_mock["method"],
                url_mock["match_querystring"])

    with responses_mock:
        yield responses_mock

        mocked_urls = map(_to_tuple, responses_mock._urls)
        used_urls = map(_to_tuple, map(_find_request, responses_mock.calls))
        not_used = set(mocked_urls) - set(used_urls)
        if not_used:
            pytest.fail(f"Found unused responses mocks: {not_used}",
                        pytrace=False)
예제 #4
0
import unittest
from apidaze.http import Http
from apidaze.sip_users import Sip_users
from urllib3_mock import Responses
import json

responses = Responses('urllib3')


class TestSip_users(unittest.TestCase):
    @property
    def httpInstance(self):
        return Http(
            api_key='API_KEY',
            api_secret='API_SECRET',
            api_url='http://api.url')

    @property
    def sip_users(self):
        return Sip_users(self.httpInstance)

    @responses.activate
    def prepare_list(self, status_code):
        body = {
            'body': [{
                'id': 2517,
                'name': 'test',
                'callerid': {
                    'outboundCallerIdName': 'test',
                    'outboundCallerIdNumber': '14125423968',
                    'internalCallerIdName': 'test',
예제 #5
0
def urllib3_mocker() -> Responses:
    responses = Responses()
    with responses:
        yield responses
예제 #6
0
파일: test_api.py 프로젝트: JiriKr/pycsob
import pytest
from collections import OrderedDict
from freezegun import freeze_time
from requests.exceptions import HTTPError
from unittest import TestCase
from unittest.mock import call, patch
from urllib3_mock import Responses

from pycsob import conf, utils
from pycsob.client import CsobClient

KEY_PATH = os.path.abspath(
    os.path.join(os.path.dirname(__file__), "fixtures", "test.key"))
PAY_ID = "34ae55eb69e2cBF"

responses = Responses(package="requests.packages.urllib3")


@freeze_time("2019-05-02 16:14:26")
class CsobClientTests(TestCase):

    dttm = "20190502161426"
    dttime = datetime.datetime(2019, 5, 2, 16, 14, 26)

    def setUp(self):
        self.c = CsobClient(
            merchant_id="MERCHANT",
            base_url="https://gw.cz",
            private_key_file=KEY_PATH,
            csob_pub_key_file=KEY_PATH,
        )
예제 #7
0
import json
import types
import pytest
from merlin.model import ModelType
from urllib3_mock import Responses
from unittest.mock import patch

import client as cl
from merlin.batch.config import PredictionJobConfig, ResultType
from merlin.batch.job import JobStatus
from merlin.batch.sink import BigQuerySink, SaveMode
from merlin.batch.source import BigQuerySource
from merlin.endpoint import VersionEndpoint

responses = Responses('requests.packages.urllib3')

default_resource_request = cl.ResourceRequest(1, 1, "100m", "128Mi")
env_1 = cl.Environment(1,
                       "dev",
                       "cluster-1",
                       True,
                       default_resource_request=default_resource_request)
env_2 = cl.Environment(2,
                       "dev-2",
                       "cluster-2",
                       False,
                       default_resource_request=default_resource_request)
ep1 = cl.VersionEndpoint("1234", 1, "running", "localhost/1", "svc-1",
                         env_1.name, env_1, "grafana.com")
ep2 = cl.VersionEndpoint("4567", 1, "running", "localhost/1", "svc-2",
예제 #8
0
import pytest
import urllib3.poolmanager
from urllib3.exceptions import MaxRetryError, TimeoutError
from urllib3_mock import Responses

from elasticapm.conf import constants
from elasticapm.transport.base import TransportException
from elasticapm.transport.http import Transport
from elasticapm.utils import compat

try:
    import urlparse
except ImportError:
    from urllib import parse as urlparse

responses = Responses("urllib3")


def test_send(waiting_httpserver):
    waiting_httpserver.serve_content(
        code=202, content="", headers={"Location": "http://example.com/foo"})
    transport = Transport(waiting_httpserver.url)
    try:
        url = transport.send(compat.b("x"))
        assert url == "http://example.com/foo"
    finally:
        transport.close()


@responses.activate
def test_timeout():
예제 #9
0
import json

from urllib3_mock import Responses

from tests.core.resource_test_base import ResourcesTestBase

responses = Responses()


class TestAnnotations(ResourcesTestBase):
    """Test annotations.

    """
    @responses.activate
    def test_search(self):
        responses.add('POST',
                      '/map-service/annotations/search-annotations',
                      body=json.dumps({'results': [{
                          '_id': 'annotation-id'
                      }]}),
                      status=200,
                      content_type='application/json')

        self.sdk.annotations.search(project='project-id')

        calls = responses.calls
        self.assertEqual(len(calls), 1)

        self.assertEqual(calls[0].request.url,
                         '/map-service/annotations/search-annotations')
        self.assertEqual(calls[0].request.method, 'POST')
예제 #10
0
import unittest
import re
import logging
import urllib
import six
from six import PY3

from urllib3_mock import Responses
from datetime import datetime

from phaxio import PhaxioApi

# need to set up mocks for both urllib3-based requests (used for most everything) and requests-based ones (used for some posts)
responses_requests = Responses('requests.packages.urllib3')
responses_urllib = Responses()

test_phone_number = '2065551234'
test_phone_number2 = '2065551235'
test_fax_id = 12345


class PhaxioApiUnitTests(unittest.TestCase):

    logger = logging.getLogger(__name__)
    logger.level = logging.DEBUG

    handler = logging.FileHandler('test.log')
    handler.setFormatter(
        logging.Formatter(
            '%(asctime)s - %(name)s - %(funcName)s - %(levelname)s - %(message)s'
        ))
예제 #11
0
import pytest
import requests
from requests.exceptions import InvalidURL, MissingSchema
from urllib3_mock import Responses

from elasticapm.traces import capture_span

try:
    from requests.packages import urllib3  # noqa
    responses = Responses('requests.packages.urllib3')
except ImportError:
    responses = Responses('urllib3')
responses.add('GET', '/', status=200, adding_headers={'Location': 'http://example.com/foo'})


def test_requests_instrumentation(instrument, elasticapm_client):
    elasticapm_client.begin_transaction("transaction.test")
    with capture_span("test_request", "test"):
        # NOTE: The `allow_redirects` argument has to be set to `False`,
        # because mocking is done a level deeper, and the mocked response
        # from the `HTTPAdapter` is about to be used to make further
        # requests to resolve redirects, which doesn't make sense for this
        # test case.
        requests.get('http://example.com', allow_redirects=False)
    elasticapm_client.end_transaction("MyView")

    transactions = elasticapm_client.instrumentation_store.get_all()
    spans = transactions[0]['spans']
    assert 'GET example.com' == spans[0]['name']
    assert 'http://example.com/' == spans[0]['context']['url']