Пример #1
0
    def __enter__(self):
        """
        Defines the behaviour for __enter__
        :return: no return
        """

        HTTPretty.enable()
Пример #2
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
Пример #3
0
    def setUp(self):
        self.region = RegionInfo(
            name='cc-zone-1',
            endpoint='mockservice.cc-zone-1.amazonaws.com',
            connection_cls=MockAWSService)

        HTTPretty.enable()
Пример #4
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()
Пример #5
0
    def setup_class(cls):
        cls.token_api_client = TokenAPI_Client(url=IDENTITY_ENDPOINT_URL,
                                               auth_token="AUTH_TOKEN",
                                               serialize_format="json",
                                               deserialize_format="json")

        HTTPretty.enable()
Пример #6
0
 def setUp(self):
     HTTPretty.enable()
     self.strategy = TestStrategy(self.backend, TestStorage)
     User.reset_cache()
     TestUserSocialAuth.reset_cache()
     TestNonce.reset_cache()
     TestAssociation.reset_cache()
Пример #7
0
def test_fake_socket_passes_through_gettimeout():
    import socket
    HTTPretty.enable()
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.truesock = MagicMock()
    expect(s.gettimeout).called_with().should_not.throw(AttributeError)
    s.truesock.gettimeout.assert_called_with()
Пример #8
0
    def setUp(self):
        # monkey patch Django's send_mail() function for fun & profit!
        # We must patch the name of the function relative to the module that
        # is using it (kittens.views), NOT at the source (django.core.mail).
        # autospec will enforce a signature check on all function calls.
        self.send_mail_patcher = patch(
            'testtrick.apps.kittens.views.send_mail',
            autospec=True)
        self.mock_send_mail = self.send_mail_patcher.start()
        # create a fake object to use as a return value from our patched
        # function. it is silly to mock an integer, but this is intended
        # to demonstrate the use of Mock objects in concert with monkey
        # patching. This would make more sense if send_mail() returned an
        # object or anything more complex than an integer primitive
        send_mail_return_mock = MagicMock(return_value=1)
        # set the return value on the mock send_mail function to be our integer
        self.mock_send_mail.return_value = int(send_mail_return_mock)

        # Mock out our reddit API endpoint
        HTTPretty.enable()
        HTTPretty.allow_net_connect = False
        HTTPretty.register_uri(
            HTTPretty.GET,
            "http://www.reddit.com/r/Awww/search/.json",
            body=MOCK_RESPONSE,
            content_type='application/json')
Пример #9
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
Пример #10
0
    def setUp(self):
        self.region = RegionInfo(
            name='cc-zone-1',
            endpoint='mockservice.cc-zone-1.amazonaws.com',
            connection_cls=MockAWSService)

        HTTPretty.enable()
Пример #11
0
def test_global_boolean_enabled():
    HTTPretty.disable()
    expect(HTTPretty.is_enabled()).to.be.falsy
    HTTPretty.enable()
    expect(HTTPretty.is_enabled()).to.be.truthy
    HTTPretty.disable()
    expect(HTTPretty.is_enabled()).to.be.falsy
Пример #12
0
    def setup_class(cls):
        cls.raw_image_str = open(
            os.path.join(os.path.dirname(__file__), 'data/image.json')).read()
        cls.raw_images_str = open(
            os.path.join(os.path.dirname(__file__),
                         'data/images.json')).read()

        cls.raw_images_schema_str = open(
            os.path.join(os.path.dirname(__file__),
                         'data/images_schema.json')).read()
        cls.raw_image_schema_str = open(
            os.path.join(os.path.dirname(__file__),
                         'data/image_schema.json')).read()

        if IS_MOCK:
            HTTPretty.enable()
            cls.mock_api()

        cls.image_obj = Image._json_to_obj(cls.raw_image_str)
        cls.images_obj = Image._json_to_obj(cls.raw_images_str)

        cls.images_client = ImagesClient(
            base_url='http://localhost/v2',
            auth_token='36a04b4e71484ab9aacb1d0ac95733fc',
            serialize_format='json',
            deserialize_format='json')
Пример #13
0
def test_socktype_good_python_version():
    import socket

    with patch("socket.SocketType", socket.socket):
        HTTPretty.enable()
        expect(socket.SocketType).to.equal(socket.socket)
        HTTPretty.disable()
Пример #14
0
def test_httpretty_bypasses_when_disabled():
    u"HTTPretty should bypass all requests by disabling it"

    HTTPretty.register_uri(HTTPretty.GET,
                           "http://localhost:9999/go-for-bubbles/",
                           body="glub glub")

    HTTPretty.disable()

    fd = urllib2.urlopen('http://localhost:9999/go-for-bubbles/')
    got1 = fd.read()
    fd.close()

    assert that(got1).equals(
        '. o O 0 O o . o O 0 O o . o O 0 O o . o O 0 O o . o O 0 O o .')

    fd = urllib2.urlopen('http://localhost:9999/come-again/')
    got2 = fd.read()
    fd.close()

    assert that(got2).equals('<- HELLO WORLD ->')

    HTTPretty.enable()

    fd = urllib2.urlopen('http://localhost:9999/go-for-bubbles/')
    got3 = fd.read()
    fd.close()

    assert that(got3).equals('glub glub')
Пример #15
0
 def setUp(self):
     """ Set stuff up
     """
     self.item_doc = self.get_doc('item_doc.json')
     self.items_doc = self.get_doc('items_doc.json')
     self.item_versions = self.get_doc('item_versions.json')
     self.collection_versions = self.get_doc('collection_versions.json')
     self.collections_doc = self.get_doc('collections_doc.json')
     self.collection_doc = self.get_doc('collection_doc.json')
     self.citation_doc = self.get_doc('citation_doc.xml')
     # self.biblio_doc = self.get_doc('bib_doc.xml')
     self.attachments_doc = self.get_doc('attachments_doc.json')
     self.tags_doc = self.get_doc('tags_doc.json')
     self.groups_doc = self.get_doc('groups_doc.json')
     self.item_templt = self.get_doc('item_template.json')
     self.item_types = self.get_doc('item_types.json')
     self.item_fields = self.get_doc('item_fields.json')
     self.keys_response = self.get_doc('keys_doc.txt')
     self.creation_doc = self.get_doc('creation_doc.json')
     self.item_file = self.get_doc('item_file.pdf')
     # Add the item file to the mock response by default
     HTTPretty.enable()
     HTTPretty.register_uri(
         HTTPretty.GET,
         'https://api.zotero.org/users/myuserID/items',
         content_type='application/json',
         body=self.items_doc)
Пример #16
0
    def __enter__(self):
        """
        Defines the behaviour for __enter__
        :return: no return
        """

        HTTPretty.enable()
Пример #17
0
def test_fake_socket_passes_through_setblocking():
    import socket
    HTTPretty.enable()
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.truesock = MagicMock()
    expect(s.setblocking).called_with(0).should_not.throw(AttributeError)
    s.truesock.setblocking.assert_called_with(0)
Пример #18
0
    def setUp(self):
        self.url = IDENTITY_ENDPOINT_URL
        self.serialize_format = "json"
        self.deserialize_format = "json"
        self.auth_token = "AUTH_TOKEN"
        self.admin_extensions = "OS-KSADM"

        self.tenant_api_client = TenantsAPI_Client(
            url=self.url,
            auth_token=self.auth_token,
            serialize_format=self.serialize_format,
            deserialize_format=self.deserialize_format)

        self.tenant_id = "TENANT_ID"
        self.tenants_url = "{0}/v2.0/tenants".format(self.url)
        self.tenant_url = "{0}/v2.0/tenants/{1}".format(self.url,
                                                        self.tenant_id)
        self.user_id = "USER_ID"
        self.users_url = "{0}/v2.0/users".format(self.url)
        self.user_url = "{0}/{1}".format(self.users_url, self.user_id)
        self.tenant_users_url = "{0}/users".format(self.tenant_url)
        self.user_role_url = "{0}/{1}/roles".format(self.tenant_users_url,
                                                    self.user_id)
        self.role_id = "ROLE_ID"
        self.tenant_user_role_url = "{0}/{1}/{2}".format(self.user_role_url,
                                                         self.admin_extensions,
                                                         self.role_id)

        HTTPretty.enable()
Пример #19
0
def test_fake_socket_passes_through_shutdown():
    import socket
    HTTPretty.enable()
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.truesock = MagicMock()
    expect(s.shutdown).called_with(socket.SHUT_RD).should_not.throw(AttributeError)
    s.truesock.shutdown.assert_called_with(socket.SHUT_RD)
Пример #20
0
def test_httpretty_bypasses_when_disabled(context):
    u"HTTPretty should bypass all requests by disabling it"

    HTTPretty.register_uri(
        HTTPretty.GET, "http://localhost:9999/go-for-bubbles/",
        body="glub glub")

    HTTPretty.disable()

    fd = urllib2.urlopen('http://localhost:9999/go-for-bubbles/')
    got1 = fd.read()
    fd.close()

    expect(got1).to.equal(
        '. o O 0 O o . o O 0 O o . o O 0 O o . o O 0 O o . o O 0 O o .')

    fd = urllib2.urlopen('http://localhost:9999/come-again/')
    got2 = fd.read()
    fd.close()

    expect(got2).to.equal('<- HELLO WORLD ->')

    HTTPretty.enable()

    fd = urllib2.urlopen('http://localhost:9999/go-for-bubbles/')
    got3 = fd.read()
    fd.close()

    expect(got3).to.equal('glub glub')
Пример #21
0
def test_fake_socket_passes_through_getpeername():
    import socket
    HTTPretty.enable()
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.truesock = MagicMock()
    expect(s.getpeername).called_with().should_not.throw(AttributeError)
    s.truesock.getpeername.assert_called_with()
Пример #22
0
def test_global_boolean_enabled():
    HTTPretty.disable()
    expect(HTTPretty.is_enabled()).to.be.falsy
    HTTPretty.enable()
    expect(HTTPretty.is_enabled()).to.be.truthy
    HTTPretty.disable()
    expect(HTTPretty.is_enabled()).to.be.falsy
Пример #23
0
    def setup_class(cls):
        cls.token_api_client = TokenAPI_Client(
            url=IDENTITY_ENDPOINT_URL,
            auth_token="AUTH_TOKEN",
            serialize_format="json",
            deserialize_format="json")

        HTTPretty.enable()
Пример #24
0
 def setUp(self):
     HTTPretty.enable()
     HTTPretty.register_uri(
         HTTPretty.POST,
         ("http://doc-demo-userdomain.us-east-1.cloudsearch.amazonaws.com/"
          "2011-02-01/documents/batch"),
         body=json.dumps(self.response).encode('utf-8'),
         content_type="application/json")
Пример #25
0
def test_fake_socket_passes_through_bind():
    import socket
    HTTPretty.enable()
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.truesock = MagicMock()
    expect(s.bind).called_with(
        ('127.0.0.1', 1000)).should_not.throw(AttributeError)
    s.truesock.bind.assert_called_with(('127.0.0.1', 1000))
Пример #26
0
 def setUp(self):
     HTTPretty.enable()
     HTTPretty.register_uri(
         HTTPretty.POST,
         ("http://doc-demo-userdomain.us-east-1.cloudsearch.amazonaws.com/"
          "2011-02-01/documents/batch"),
         body=json.dumps(self.response),
         content_type="application/json")
Пример #27
0
 def setUp(self):
     HTTPretty.enable()
     User.reset_cache()
     TestUserSocialAuth.reset_cache()
     TestNonce.reset_cache()
     TestAssociation.reset_cache()
     self.backend = module_member('social.backends.github.GithubOAuth2')
     self.strategy = TestStrategy(self.backend, TestStorage)
     self.user = None
Пример #28
0
 def setUp(self):
     HTTPretty.enable()
     User.reset_cache()
     TestUserSocialAuth.reset_cache()
     TestNonce.reset_cache()
     TestAssociation.reset_cache()
     self.backend = module_member('social.backends.github.GithubOAuth2')
     self.strategy = TestStrategy(self.backend, TestStorage)
     self.user = None
Пример #29
0
 def setUp(self):
     HTTPretty.enable()
     self.backend = module_member(self.backend_path)
     self.complete_url = "/complete/{0}/".format(self.backend.name)
     self.strategy = TestStrategy(self.backend, TestStorage, redirect_uri=self.complete_url)
     self.strategy.set_settings(
         {"SOCIAL_AUTH_AUTHENTICATION_BACKENDS": (self.backend_path, "tests.backends.broken_test.BrokenBackendAuth")}
     )
     # Force backends loading to trash PSA cache
     load_backends(self.strategy.get_setting("SOCIAL_AUTH_AUTHENTICATION_BACKENDS"), force_load=True)
Пример #30
0
 def setUp(self):
     HTTPretty.enable()
     User.reset_cache()
     TestUserSocialAuth.reset_cache()
     TestNonce.reset_cache()
     TestAssociation.reset_cache()
     Backend = module_member("social.backends.github.GithubOAuth2")
     self.strategy = self.strategy or TestStrategy(TestStorage)
     self.backend = Backend(self.strategy, redirect_uri="/complete/github")
     self.user = None
Пример #31
0
        def wrapper(*args, **kwargs):
            HTTPretty.reset()
            HTTPretty.enable()

            _do_httpretty_registration(path)

            try:
                return func(*args, **kwargs)
            finally:
                HTTPretty.disable()
Пример #32
0
 def setUp(self):
     HTTPretty.enable()
     User.reset_cache()
     TestUserSocialAuth.reset_cache()
     TestNonce.reset_cache()
     TestAssociation.reset_cache()
     Backend = module_member('social_core.backends.github.GithubOAuth2')
     self.strategy = self.strategy or TestStrategy(TestStorage)
     self.backend = Backend(self.strategy, redirect_uri='/complete/github')
     self.user = None
Пример #33
0
    def setUp(self):
        HTTPretty.enable()
        body = self.response

        if not isinstance(body, basestring):
            body = json.dumps(body)

        HTTPretty.register_uri(HTTPretty.GET, FULL_URL,
                               body=body,
                               content_type=self.content_type,
                               status=self.response_status)
Пример #34
0
    def setUp(self):
        HTTPretty.enable()
        body = self.response

        if not isinstance(body, bytes):
            body = json.dumps(body).encode('utf-8')

        HTTPretty.register_uri(HTTPretty.GET, FULL_URL,
                               body=body,
                               content_type=self.content_type,
                               status=self.response_status)
Пример #35
0
 def test_latest_subject_positions(self):
     message = self._skeleton_message()
     RoomPosition().process_message(message)
     path = 'latest_subject_positions/%s' % message['sensor_id']
     full_path = "http://127.0.0.1:8000/%s" % path
     HTTPretty.enable()
     HTTPretty.register_uri(HTTPretty.GET, full_path)
     response = requests.get(full_path)
     HTTPretty.disable()
     eq_(response.status_code, STATUS_OK,
         'Response has status_code: %s' % response.status_code)
Пример #36
0
 def setUp(self):
     '''
     Mock-out our Reddit API endpoint.
     '''
     self.kitten_email_subject = "You've received a kitten!"
     HTTPretty.enable()
     HTTPretty.allow_net_connect = False
     HTTPretty.register_uri(
         HTTPretty.GET,
         "http://www.reddit.com/r/Awww/search/.json",
         body=MOCK_RESPONSE,
         content_type='application/json')
Пример #37
0
def test_socktype_bad_python_version_regression():
    """ Some versions of python accidentally internally shadowed the SockType
    variable, so it was no longer the socket object but and int Enum representing
    the socket type e.g. AF_INET. Make sure we don't patch SockType in these cases
    https://bugs.python.org/issue20386
    """
    import socket
    someObject = object()
    with patch('socket.SocketType', someObject):
        HTTPretty.enable()
        expect(socket.SocketType).to.equal(someObject)
        HTTPretty.disable()
Пример #38
0
def test_socktype_bad_python_version_regression():
    """ Some versions of python accidentally internally shadowed the SockType
    variable, so it was no longer the socket object but and int Enum representing
    the socket type e.g. AF_INET. Make sure we don't patch SockType in these cases
    https://bugs.python.org/issue20386
    """
    import socket
    someObject = object()
    with patch('socket.SocketType', someObject):
        HTTPretty.enable()
        expect(socket.SocketType).to.equal(someObject)
        HTTPretty.disable()
Пример #39
0
    def setup_class(cls):
        HTTPretty.enable()

        cls.images_client = ImagesClient(
            url=GLANCE_API_SERVER_ENDPOINT,
            auth_token="36a04b4e71484ab9aacb1d0ac95733fc",
            serialize_format="json",
            deserialize_format="json")

        cls.image_id = '1c675abd94f49cda114e12490b328d9'
        cls.images_uri = '{0}/images'.format(GLANCE_API_SERVER_ENDPOINT)
        cls.image_uri = '{0}/{1}'.format(cls.images_uri, cls.image_id)
Пример #40
0
    def start(self):
        self.backend.reset()
        HTTPretty.enable()

        for method in HTTPretty.METHODS:
            for key, value in self.backend.urls.iteritems():
                HTTPretty.register_uri(method=method, uri=re.compile(key), body=value)

            # Mock out localhost instance metadata
            HTTPretty.register_uri(
                method=method, uri=re.compile("http://169.254.169.254/latest/meta-data/.*"), body=metadata_response
            )
Пример #41
0
 def setUp(self):
     self.dir_name = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data')
     HTTPretty.enable()
     HTTPretty.register_uri(HTTPretty.GET, "http://fooimages.org/image1.png",
                            body="foo")
     HTTPretty.register_uri(HTTPretty.GET, "http://foofiles.org/text1.txt",
                            body="foo")
     HTTPretty.register_uri(HTTPretty.GET, "http://foofiles.org/text2.txt",
                            body="foo")
     f = open(os.path.join(self.dir_name, 'page.html'))
     self.html = f.read()
     f.close()
Пример #42
0
def test_unix_socket():
    import socket
    HTTPretty.enable()

    # Create a UDS socket
    sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    server_address = './not-exist-socket'
    try:
        sock.connect(server_address)
    except socket.error:
        # We expect this, since the server_address does not exist
        pass
Пример #43
0
def test_unix_socket():
    import socket
    HTTPretty.enable()

    # Create a UDS socket
    sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    server_address = './not-exist-socket'
    try:
        sock.connect(server_address)
    except socket.error:
        # We expect this, since the server_address does not exist
        pass
Пример #44
0
    def setup_class(cls):
        HTTPretty.enable()

        cls.images_client = ImagesClient(
            url=GLANCE_API_SERVER_ENDPOINT,
            auth_token="36a04b4e71484ab9aacb1d0ac95733fc",
            serialize_format="json",
            deserialize_format="json"
        )

        cls.image_id = '1c675abd94f49cda114e12490b328d9'
        cls.images_uri = '{0}/images'.format(GLANCE_API_SERVER_ENDPOINT)
        cls.image_uri = '{0}/{1}'.format(cls.images_uri, cls.image_id)
Пример #45
0
    def start(self):
        """Starts the mocked context by enabling HTTPretty to route requests to
        the defined endpoints.
        """
        from .endpoints import clear_endpoints
        self.started = True
        clear_endpoints()
        clear_backends()

        if not HTTPretty.is_enabled():
            HTTPretty.enable()

        self._register()
Пример #46
0
    def start(self):
        """Starts the mocked context by enabling HTTPretty to route requests to
        the defined endpoints.
        """
        from .endpoints import clear_endpoints
        self.started = True
        clear_endpoints()
        clear_backends()

        if not HTTPretty.is_enabled():
            HTTPretty.enable()

        self._register()
Пример #47
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()
Пример #48
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()
Пример #49
0
    def test_latest_subject_positions(self):
        # Keep this import here in order to avoid OpenCV imports
        from pipeline.room_position import RoomPosition

        message = self._skeleton_message()
        RoomPosition().process_message(message)
        path = 'latest_subject_positions/%s' % message['sensor_id']
        full_path = "http://127.0.0.1:8000/%s" % path
        HTTPretty.enable()
        HTTPretty.register_uri(HTTPretty.GET, full_path)
        response = requests.get(full_path)
        HTTPretty.disable()
        eq_(response.status_code, STATUS_OK,
            'Response has status_code: %s' % response.status_code)
Пример #50
0
    def start_mocking(self):
        self.__class__._count += 1
        self.backend.reset()

        if not HTTPretty.is_enabled():
            HTTPretty.enable()

        for method in HTTPretty.METHODS:
            # mock all url to dropbox for any module....
            for key, value in self.backend.urls.iteritems():
                HTTPretty.register_uri(
                    method=method,
                    uri=re.compile(key),
                    body=value,
                )
Пример #51
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 setUp(self):
     HTTPretty.enable()
     Backend = module_member(self.backend_path)
     self.strategy = TestStrategy(TestStorage)
     self.complete_url = self.raw_complete_url.format(Backend.name)
     self.backend = Backend(self.strategy, redirect_uri=self.complete_url)
     self.strategy.set_settings({
         'SOCIAL_AUTH_AUTHENTICATION_BACKENDS':
         (self.backend_path,
          'social_core.tests.backends.test_broken.BrokenBackendAuth')
     })
     # Force backends loading to trash PSA cache
     load_backends(
         self.strategy.get_setting('SOCIAL_AUTH_AUTHENTICATION_BACKENDS'),
         force_load=True)
Пример #53
0
    def setUp(self):
        self.url = IDENTITY_ENDPOINT_URL
        self.serialized_format = "json"
        self.deserialized_format = "json"
        self.auth_token = "AUTH_TOKEN"
        self.admin_extensions = "OS-KSADM"

        self.extensions_api_client = ExtensionsAPI_Client(
            url=self.url,
            auth_token=self.auth_token,
            serialized_format=self.serialized_format,
            deserialized_format=self.deserialized_format)

        self.role_id = "1"

        HTTPretty.enable()
Пример #54
0
 def setUp(self):
     HTTPretty.enable()
     self.backend = module_member(self.backend_path)
     self.complete_url = '/complete/{0}/'.format(self.backend.name)
     self.strategy = TestStrategy(self.backend, TestStorage,
                                  redirect_uri=self.complete_url)
     self.strategy.set_settings({
         'SOCIAL_AUTH_AUTHENTICATION_BACKENDS': (
             self.backend_path,
             'tests.backends.broken_test.BrokenBackendAuth'
         )
     })
     # Force backends loading to trash PSA cache
     load_backends(
         self.strategy.get_setting('SOCIAL_AUTH_AUTHENTICATION_BACKENDS'),
         force_load=True
     )
Пример #55
0
    def setUp(self):
        HTTPretty.enable()
        Backend = module_member(self.backend_path)
        self.strategy = views.load_strategy()
        self.backend = Backend(self.strategy, redirect_uri=self.complete_url)
        self.name = self.backend.name.upper().replace('-', '_')
        self.complete_url = self.strategy.build_absolute_uri(
            self.raw_complete_url.format(self.backend.name))
        backends = (self.backend_path, )
        load_backends(backends, force_load=True)

        user_data_body = json.loads(self.user_data_body)
        self.email = '*****@*****.**'
        user_data_body['email'] = self.email
        self.user_data_body = json.dumps(user_data_body)

        self.do_rest_login()
Пример #56
0
    def start(self):
        self.backend.reset()
        HTTPretty.enable()

        for method in HTTPretty.METHODS:
            for key, value in self.backend.urls.iteritems():
                HTTPretty.register_uri(
                    method=method,
                    uri=re.compile(key),
                    body=value,
                )

            # Mock out localhost instance metadata
            HTTPretty.register_uri(
                method=method,
                uri=re.compile('http://169.254.169.254/latest/meta-data/.*'),
                body=metadata_response)
Пример #57
0
 def setUp(self):
     HTTPretty.enable()
     self.backend = module_member(self.backend_path)
     name = self.backend.name
     self.complete_url = self.raw_complete_url.format(name)
     self.strategy = TestStrategy(self.backend, TestStorage)
     name = name.upper().replace('-', '_')
     self.strategy.set_settings({
         'SOCIAL_AUTH_' + name + '_KEY':
         'a-key',
         'SOCIAL_AUTH_' + name + '_SECRET':
         'a-secret-key',
         'SOCIAL_AUTH_AUTHENTICATION_BACKENDS':
         (self.backend_path, 'tests.backends.broken_test.BrokenBackendAuth')
     })
     # Force backends loading to trash PSA cache
     load_backends(
         self.strategy.get_setting('SOCIAL_AUTH_AUTHENTICATION_BACKENDS'),
         force_load=True)
Пример #58
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()
Пример #59
0
def test_http_passthrough():
    url = 'http://ip4.me/'
    response1 = requests.get(url)

    HTTPretty.enable()
    HTTPretty.register_uri(HTTPretty.GET,
                           'http://google.com/',
                           body="Not Google")

    response2 = requests.get('http://google.com/')
    expect(response2.content).to.equal(b'Not Google')

    response3 = requests.get(url)
    expect(response3.content).to.equal(response1.content)

    HTTPretty.disable()

    response4 = requests.get(url)
    expect(response4.content).to.equal(response1.content)