Beispiel #1
0
def mocked_urls(url_files, methods=None):
    """mocks the underlying python sockets library to return a given file's
    content
    """
    # if environment variable is set, then don't mock the tests just grab files
    # over the network. Example:
    #    env ULMO_DONT_MOCK_TESTS=1 py.test
    if os.environ.get('ULMO_DONT_MOCK_TESTS', False):
        yield

    else:
        if isinstance(url_files, basestring):
            url_files = {'.*': url_files}

        HTTPretty.enable()
        for url_match, url_file in url_files.iteritems():
            if not isinstance(url_match, basestring) and len(url_match) == 2:
                url_match, methods = url_match

            if not os.path.isabs(url_file):
                url_file = get_test_file_path(url_file)

            callback = _build_request_callback(url_file)
            url_re = re.compile(url_match)

            if methods is None:
                methods = ['GET', 'POST', 'HEAD']

            for method in methods:
                request_class = getattr(HTTPretty, method)
                HTTPretty.register_uri(request_class, url_re, body=callback)
        yield
        HTTPretty.disable()
        HTTPretty.reset()
    def start(cls, fixtures):
        """Start running this class' fixtures"""
        # If we can't iterate over our fixtures, complain and leave
        if not hasattr(fixtures, '__iter__'):
            raise TypeError('Expected `fixtures` to be an iterable sequence but it was not. '
                            'Please make it a list or a tuple.')

        # Keep track if HTTPretty was started outside of FixtureManager
        #   This means that we should not auto-disable HTTPretty when nested_count returns to 0
        if FixtureManager.nested_count == 0:
            FixtureManager.httpretty_enabled_at_start = HTTPretty.is_enabled()

        # Increase our internal counter
        # DEV: Keep count on our base class so the `nested_count` is "global" for all subclasses
        FixtureManager.nested_count += 1

        # If HTTPretty hasn't been started yet, then reset its info and start it
        if not HTTPretty.is_enabled():
            HTTPretty.reset()
            HTTPretty.enable()

        # Initialize our class
        instance = cls()

        # Start each of our fixtures
        # DEV: We must use a separate function to closure `fixture` to prevent reuse in loops
        for fixture_key in fixtures:
            instance.start_fixture(fixture_key)

        # Return our generated server
        return instance
Beispiel #3
0
 def tearDown(self):
     HTTPretty.disable()
     HTTPretty.reset()
     self.backend = None
     self.strategy = None
     self.name = None
     self.complete_url = None
Beispiel #4
0
def test_httpretty_reset_by_switching_protocols_for_same_port():
    "HTTPretty should reset protocol/port associations"

    HTTPretty.register_uri(
        HTTPretty.GET,
        "http://api.yipit.com:1234/v1/deal",
        body=lambda method, uri, headers: [200, headers, uri])

    response = requests.get('http://api.yipit.com:1234/v1/deal')

    expect(response.text).to.equal('http://api.yipit.com:1234/v1/deal')
    expect(HTTPretty.last_request.method).to.equal('GET')
    expect(HTTPretty.last_request.path).to.equal('/v1/deal')

    HTTPretty.reset()

    HTTPretty.register_uri(
        HTTPretty.GET,
        "https://api.yipit.com:1234/v1/deal",
        body=lambda method, uri, headers: [200, headers, uri])

    response = requests.get('https://api.yipit.com:1234/v1/deal')

    expect(response.text).to.equal('https://api.yipit.com:1234/v1/deal')
    expect(HTTPretty.last_request.method).to.equal('GET')
    expect(HTTPretty.last_request.path).to.equal('/v1/deal')
 def tearDown(self):
     HTTPretty.disable()
     HTTPretty.reset()
     self.backend = None
     self.strategy = None
     self.name = None
     self.complete_url = None
Beispiel #6
0
    def start(cls, fixtures):
        """Start running this class' fixtures"""
        # If we can't iterate over our fixtures, complain and leave
        if not hasattr(fixtures, '__iter__'):
            raise TypeError(
                'Expected `fixtures` to be an iterable sequence but it was not. '
                'Please make it a list or a tuple.')

        # Keep track if HTTPretty was started outside of FixtureManager
        #   This means that we should not auto-disable HTTPretty when nested_count returns to 0
        if FixtureManager.nested_count == 0:
            FixtureManager.httpretty_enabled_at_start = HTTPretty.is_enabled()

        # Increase our internal counter
        # DEV: Keep count on our base class so the `nested_count` is "global" for all subclasses
        FixtureManager.nested_count += 1

        # If HTTPretty hasn't been started yet, then reset its info and start it
        if not HTTPretty.is_enabled():
            HTTPretty.reset()
            HTTPretty.enable()

        # Initialize our class
        instance = cls()

        # Start each of our fixtures
        # DEV: We must use a separate function to closure `fixture` to prevent reuse in loops
        for fixture_key in fixtures:
            instance.start_fixture(fixture_key)

        # Return our generated server
        return instance
def test_httpretty_reset_by_switching_protocols_for_same_port():
    "HTTPretty should reset protocol/port associations"

    HTTPretty.register_uri(
        HTTPretty.GET,
        "http://api.yipit.com:1234/v1/deal",
        body=lambda method, uri, headers: [200, headers, uri]
    )

    response = requests.get('http://api.yipit.com:1234/v1/deal')

    expect(response.text).to.equal('http://api.yipit.com:1234/v1/deal')
    expect(HTTPretty.last_request.method).to.equal('GET')
    expect(HTTPretty.last_request.path).to.equal('/v1/deal')

    HTTPretty.reset()

    HTTPretty.register_uri(
        HTTPretty.GET,
        "https://api.yipit.com:1234/v1/deal",
        body=lambda method, uri, headers: [200, headers, uri]
    )

    response = requests.get('https://api.yipit.com:1234/v1/deal')

    expect(response.text).to.equal('https://api.yipit.com:1234/v1/deal')
    expect(HTTPretty.last_request.method).to.equal('GET')
    expect(HTTPretty.last_request.path).to.equal('/v1/deal')
Beispiel #8
0
    def __init__(self, func=None):
        self.started = False
        HTTPretty.reset()

        self.timeout_filter = None
        self.timeout_connection = False
        self.timeout_connection_successful_post = False
        self.func = func
Beispiel #9
0
 def tearDown(self):
     self.strategy = None
     User.reset_cache()
     TestUserSocialAuth.reset_cache()
     TestNonce.reset_cache()
     TestAssociation.reset_cache()
     HTTPretty.disable()
     HTTPretty.reset()
Beispiel #10
0
 def __exit__(self, etype, value, traceback):
     """
     :param etype: exit type
     :param value: exit value
     :param traceback: the traceback for the exit
     """
     HTTPretty.reset()
     HTTPretty.disable()
Beispiel #11
0
    def __init__(self, func=None):
        self.started = False
        HTTPretty.reset()

        self.timeout_filter = None
        self.timeout_connection = False
        self.timeout_connection_successful_post = False
        self.func = func
Beispiel #12
0
 def __exit__(self, etype, value, traceback):
     """
     :param etype: exit type
     :param value: exit value
     :param traceback: the traceback for the exit
     """
     HTTPretty.reset()
     HTTPretty.disable()
Beispiel #13
0
    def stop(self):
        self.__class__.nested_count -= 1

        if self.__class__.nested_count < 0:
            raise RuntimeError('Called stop() before start().')

        if self.__class__.nested_count == 0:
            HTTPretty.disable()
            HTTPretty.reset()
Beispiel #14
0
 def __exit__(self, etype, value, traceback):
     """
     Defines the behaviour for __exit__
     :param etype: exit type
     :param value: exit value
     :param traceback: the traceback for the exit
     """
     HTTPretty.reset()
     HTTPretty.disable()
Beispiel #15
0
    def stop(self):
        self.__class__.nested_count -= 1

        if self.__class__.nested_count < 0:
            raise RuntimeError('Called stop() before start().')

        if self.__class__.nested_count == 0:
            HTTPretty.disable()
            HTTPretty.reset()
 def __exit__(self, etype, value, traceback):
     """
     Defines the behaviour for __exit__
     :param etype: exit type
     :param value: exit value
     :param traceback: the traceback for the exit
     """
     HTTPretty.reset()
     HTTPretty.disable()
        def wrapper(*args, **kwargs):
            HTTPretty.reset()
            HTTPretty.enable()

            _do_httpretty_registration(path)

            try:
                return func(*args, **kwargs)
            finally:
                HTTPretty.disable()
Beispiel #18
0
 def tearDown(self):
     HTTPretty.disable()
     HTTPretty.reset()
     self.backend = None
     self.strategy = None
     self.name = None
     self.complete_url = None
     User.reset_cache()
     TestUserSocialAuth.reset_cache()
     TestNonce.reset_cache()
     TestAssociation.reset_cache()
     TestCode.reset_cache()
Beispiel #19
0
def mocked_urls(url_files, methods=None, force=False):
    """mocks the underlying python sockets library to return a given file's
    content. Note: that this function checks for an environment variable named
    ULMO_DONT_MOCK_TESTS; if that environment variable is set then urls will
    not be mocked and the HTTP requests will go over the network. For example,
    this could be used to to run the whole test suite without mocking files:
    #    env ULMO_DONT_MOCK_TESTS=1 py.test

    Parameters
    ----------
    url_files : str or dict
        Files to be mocked. It can either be a string representation of a
        filepath to a file whose contents will be used as a response to all
        HTTP requests. Or it can be a dict where the keys are regular
        expression strings and the values are filepaths - the regex keys will
        be used to match urls if they match, the file path will be used.

    methods : iterable of str or None
        HTTP methods that will be mocked. If set to None (default) then the
        default methods are GET, POST and HEAD.
    """
    # if environment variable is set, then mock the tests otherwise just grab files
    # over the network. Example:
    #    env ULMO_MOCK_TESTS=1 py.test
    if not os.environ.get('ULMO_MOCK_TESTS', False) and not force:
        yield

    else:
        if isinstance(url_files, basestring):
            url_files = {'.*': url_files}

        HTTPretty.enable()
        for url_match, url_file in url_files.items():
            if not isinstance(url_match, basestring) and len(url_match) == 2:
                url_match, methods = url_match

            if not os.path.isabs(url_file):
                url_file = get_test_file_path(url_file)

            callback = _build_request_callback(url_file)
            url_re = re.compile(url_match)

            if methods is None:
                methods = ['GET', 'POST', 'HEAD']

            for method in methods:
                request_class = getattr(HTTPretty, method)
                HTTPretty.register_uri(request_class, url_re, match_querystring=True, body=callback)
        yield
        HTTPretty.disable()
        HTTPretty.reset()
Beispiel #20
0
def mocked_urls(url_files, methods=None):
    """mocks the underlying python sockets library to return a given file's
    content. Note: that this function checks for an environment variable named
    ULMO_DONT_MOCK_TESTS; if that environment variable is set then urls will
    not be mocked and the HTTP requests will go over the network. For example,
    this could be used to to run the whole test suite without mocking files:
    #    env ULMO_DONT_MOCK_TESTS=1 py.test

    Parameters
    ----------
    url_files : str or dict
        Files to be mocked. It can either be a string representation of a
        filepath to a file whose contents will be used as a response to all
        HTTP requests. Or it can be a dict where the keys are regular
        expression strings and the values are filepaths - the regex keys will
        be used to match urls if they match, the file path will be used.

    methods : iterable of str or None
        HTTP methods that will be mocked. If set to None (default) then the
        default methods are GET, POST and HEAD.
    """
    if os.environ.get('ULMO_DONT_MOCK_TESTS', False):
        yield

    else:
        if isinstance(url_files, basestring):
            url_files = {'.*': url_files}

        HTTPretty.enable()
        for url_match, url_file in url_files.iteritems():
            if not isinstance(url_match, basestring) and len(url_match) == 2:
                url_match, methods = url_match

            if not os.path.isabs(url_file):
                url_file = get_test_file_path(url_file)

            callback = _build_request_callback(url_file)
            url_re = re.compile(url_match)

            if methods is None:
                methods = ['GET', 'POST', 'HEAD']

            for method in methods:
                request_class = getattr(HTTPretty, method)
                HTTPretty.register_uri(request_class,
                                       url_re,
                                       match_querystring=True,
                                       body=callback)
        yield
        HTTPretty.disable()
        HTTPretty.reset()
Beispiel #21
0
def test_httpretty_should_not_raise_on_socket_send_when_uri_not_registered():
    ("HTTPretty should not raise a RuntimeError when the fakesocket "
     "is used in an invalid usage.")

    import socket
    HTTPretty.enable()

    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
    sock.setblocking(0)
    expect(sock.sendto).when.called_with(
        b'whatever', ('127.0.0.1', 53)).should_not.throw(RuntimeError)

    sock.close()
    HTTPretty.reset()
    HTTPretty.disable()
Beispiel #22
0
def test_httpretty_should_not_raise_on_socket_send_when_uri_not_registered():
    """HTTPretty should not raise a RuntimeError when the fakesocket is used in
    an invalid usage.
    """
    import socket

    HTTPretty.enable()

    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
    sock.setblocking(0)
    expect(sock.sendto).when.called_with(b"whatever", ("127.0.0.1", 53)).should_not.throw(RuntimeError)

    sock.close()
    HTTPretty.reset()
    HTTPretty.disable()
def test_httpretty_should_raise_on_socket_send_when_uri_registered():
    """HTTPretty should raise a RuntimeError when the fakesocket is used in
    an invalid usage.
    """
    import socket
    HTTPretty.enable()

    HTTPretty.register_uri(HTTPretty.GET, 'http://127.0.0.1:5000')
    expect(core.POTENTIAL_HTTP_PORTS).to.be.equal(set([80, 443, 5000]))

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect(('127.0.0.1', 5000))
    expect(sock.send).when.called_with(b'whatever').to.throw(RuntimeError)
    sock.close()

    # restore the previous value
    core.POTENTIAL_HTTP_PORTS.remove(5000)
    HTTPretty.reset()
    HTTPretty.disable()
Beispiel #24
0
def test_httpretty_should_raise_on_socket_send_when_uri_registered():
    """HTTPretty should raise a RuntimeError when the fakesocket is used in
    an invalid usage.
    """
    import socket
    HTTPretty.enable()

    HTTPretty.register_uri(HTTPretty.GET,
                           'http://127.0.0.1:5000')
    expect(core.POTENTIAL_HTTP_PORTS).to.be.equal(set([80, 443, 5000]))

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect(('127.0.0.1', 5000))
    expect(sock.send).when.called_with(b'whatever').to.throw(RuntimeError)
    sock.close()

    # restore the previous value
    core.POTENTIAL_HTTP_PORTS.remove(5000)
    HTTPretty.reset()
    HTTPretty.disable()
 def tearDown(self):
     HTTPretty.disable()
     HTTPretty.reset()
Beispiel #26
0
def test_does_not_have_last_request_by_default():
    'HTTPretty.last_request is a dummy object by default'
    HTTPretty.reset()

    expect(HTTPretty.last_request.headers).to.be.empty
    expect(HTTPretty.last_request.body).to.be.empty
Beispiel #27
0
    def __init__(self, backends):
        self.backends = backends

        if self.__class__.nested_count == 0:
            HTTPretty.reset()
Beispiel #28
0
 def tearDown(self):
     super(BasicClientCase, self).tearDown()
     HTTPretty.disable()
     HTTPretty.reset()
Beispiel #29
0
    def setUp(self):
        super(BasicClientCase, self).setUp()

        os.environ[ENV_KEY_WERCKER_URL] = self.wercker_url
        HTTPretty.reset()
        HTTPretty.enable()
Beispiel #30
0
 def tearDown(self):
     super(BasicClientCase, self).tearDown()
     HTTPretty.disable()
     HTTPretty.reset()
Beispiel #31
0
 def setUp(self):
     HTTPretty.reset()
     HTTPretty.enable()
Beispiel #32
0
 def setUp(self):
     HTTPretty.reset()
     HTTPretty.enable()
Beispiel #33
0
def test_does_not_have_last_request_by_default():
    'HTTPretty.last_request is a dummy object by default'
    HTTPretty.reset()

    expect(HTTPretty.last_request.headers).to.be.empty
    expect(HTTPretty.last_request.body).to.be.empty
Beispiel #34
0
    def setUp(self):
        super(BasicClientCase, self).setUp()

        os.environ[ENV_KEY_WERCKER_URL] = self.wercker_url
        HTTPretty.reset()
        HTTPretty.enable()
Beispiel #35
0
    def __init__(self, backend):
        self.backend = backend

        if self.__class__.nested_count == 0:
            HTTPretty.reset()
Beispiel #36
0
 def setUp(cls):
     HTTPretty.reset()
     HTTPretty.enable()
 def tearDown(self):
     mail.outbox = []
     # stop patching send_mail
     self.send_mail_patcher.stop()
     HTTPretty.disable()
     HTTPretty.reset()
Beispiel #38
0
 def __init__(self, backend):
     self.backend = backend
     HTTPretty.reset()
Beispiel #39
0
def http(request):
    from httpretty import HTTPretty
    HTTPretty.reset()
    HTTPretty.enable()
    request.addfinalizer(HTTPretty.disable)
Beispiel #40
0
 def __exit__(self, *args):
     """
     Defines the behaviour for __exit__
     """
     HTTPretty.reset()
     HTTPretty.disable()