Example #1
0
def get_mock():
    ysc = youtube_status_code
    yu = youtube_url
    yc = youtube_cookies
    yt = youtube_text
    yh = youtube_headers
    yosc = youtube_oembed_status_code
    you = youtube_oembed_url
    yoh = youtube_oembed_headers
    yot = youtube_oembed_text

    mock_obj_1 = Mock()
    mock_obj_1.status_code = ysc
    mock_obj_1.url = yu
    mock_obj_1.headers = yh
    mock_obj_1.cookies = yc
    mock_obj_1.text = yt
    mock_obj_1.json = lambda: json.loads(mock_obj_1.text)

    mock_obj_2 = Mock()
    mock_obj_2.status_code = 200
    mock_obj_2.url = you
    mock_obj_2.headers = yoh
    mock_obj_2.text = yot
    mock_obj_2.json = lambda: json.loads(mock_obj_2.text)

    return [mock_obj_1, mock_obj_1, mock_obj_2]
Example #2
0
 def test_import_geospatial_data_task_error(self, post_mock, execute_tasks_mock, delete_mock, get_mock):
     """Import data source test with task failing."""
     get_mock.__name__ = "get"
     delete_mock.__name__ = "delete"
     post_mock.__name__ = "post"
     res = {"uuid": "test_blob_uuid"}
     mock_1 = Mock()
     mock_1.status_code = 200
     mock_1.json.return_value = res
     post_mock.return_value = mock_1
     mock_2 = Mock()
     mock_2.status_code = 200
     mock_2.json.side_effect = snowfloat.errors.RequestError(status=500, code=None, message=None, more=None)
     delete_mock.return_value = mock_2
     mock_3 = Mock()
     mock_3.status_code = 200
     mock_3.json.side_effect = [
         {"uuid": "test_blob_uuid", "state": "started"},
         {"uuid": "test_blob_uuid", "state": "success"},
     ]
     get_mock.return_value = mock_3
     execute_tasks_mock.return_value = [{"error": "test_error"}]
     tfile = tempfile.NamedTemporaryFile(delete=False)
     tfile.close()
     self.assertRaises(
         snowfloat.errors.RequestError,
         self.client.import_geospatial_data,
         tfile.name,
         srid=4326,
         state_check_interval=0.1,
     )
     self.import_geospatial_data_helper(post_mock, get_mock, execute_tasks_mock)
     os.remove(tfile.name)
    def test_registration(self):
        """
        Test handle registration and subsequent checks.
        """
        client = self.portal.handle_client

        response = Mock()
        response.status_code = 201
        response.headers = {"location": self.handle_url}
        client.session.post = Mock(return_value=response)

        view = self.portal.page.restrictedTraverse("hasHandle")

        self.assertEqual(view.create(), self.handle_url)
        self.assertTrue(view.hasHandle())
        self.assertEqual(view.handle(), self.handle)

        response.status_code = 204
        response.text = ""
        client.session.get = Mock(return_value=response)
        client.session.put = Mock(return_value=response)
        client.session.delete = Mock(return_value=response)

        self.assertEqual(view.read(), self.handle_url)
        self.assertEqual(view.update(), self.handle_url)

        self.assertTrue(view.hasDeletePermission())
        self.assertEqual(view.delete(), None)
Example #4
0
    def test_parse_fedora_access(self):
        TEMPLATE_TEXT = """
            {% load fedora %}
            {% fedora_access %}
                {{ test_obj.value }}
            {% permission_denied %}
                permission fallback
            {% fedora_failed %}
                connection fallback
            {% end_fedora_access %}
        """
        t = Template(TEMPLATE_TEXT)
        test_obj = MockFedoraObject()
        ctx = Context({"test_obj": test_obj})

        val = t.render(ctx)
        self.assertEqual(val.strip(), "sample text")

        response = Mock()
        response.status_code = 401
        response.headers = {"content-type": "text/plain"}
        response.content = ""
        test_obj._value = PermissionDenied(response)  # force test_obj.value to fail
        val = t.render(ctx)
        self.assertEqual(val.strip(), "permission fallback")

        response.status_code = 500
        test_obj._value = RequestFailed(response)  # force test_obj.value to fail
        val = t.render(ctx)
        self.assertEqual(val.strip(), "connection fallback")
Example #5
0
    def test_auth_header_preserved_from_s3_redirects(self):
        request = AWSRequest()
        request.url = "https://bucket.s3.amazonaws.com/"
        request.method = "GET"
        request.headers["Authorization"] = "original auth header"
        prepared_request = request.prepare()

        fake_response = Mock()
        fake_response.headers = {"location": "https://bucket.s3-us-west-2.amazonaws.com"}
        fake_response.url = request.url
        fake_response.status_code = 307
        fake_response.is_permanent_redirect = False
        # This line is needed to disable the cookie handling
        # code in requests.
        fake_response.raw._original_response = None

        success_response = Mock()
        success_response.raw._original_response = None
        success_response.is_redirect = False
        success_response.status_code = 200
        session = BotocoreHTTPSession()
        session.send = Mock(return_value=success_response)

        list(session.resolve_redirects(fake_response, prepared_request, stream=False))

        redirected_request = session.send.call_args[0][0]
        # The Authorization header for the newly sent request should
        # still have our original Authorization header.
        self.assertEqual(redirected_request.headers["Authorization"], "original auth header")
Example #6
0
 def test_import_geospatial_data_blob_state_failure(self, post_mock, execute_tasks_mock, delete_mock, get_mock):
     """Import data source test with upload blob failing."""
     get_mock.__name__ = "get"
     delete_mock.__name__ = "delete"
     post_mock.__name__ = "post"
     res = {"uuid": "test_blob_uuid"}
     mock_1 = Mock()
     mock_1.status_code = 200
     mock_1.json.return_value = res
     post_mock.return_value = mock_1
     mock_2 = Mock()
     mock_2.status_code = 200
     mock_2.json.return_value = {}
     delete_mock.return_value = mock_2
     mock_3 = Mock()
     mock_3.status_code = 200
     mock_3.json.side_effect = [
         {"uuid": "test_blob_uuid", "state": "started"},
         {"uuid": "test_blob_uuid", "state": "failure"},
     ]
     get_mock.return_value = mock_3
     tfile = tempfile.NamedTemporaryFile(delete=False)
     tfile.close()
     self.assertRaises(
         snowfloat.errors.RequestError, self.client.import_geospatial_data, tfile.name, state_check_interval=0.1
     )
     self.import_geospatial_data_helper(post_mock, get_mock, execute_tasks_mock, validate_execute_tasks=False)
     os.remove(tfile.name)
Example #7
0
 def __init__(self):
     ticket_mock = Mock()
     ticket_mock.content = json.dumps(_get_ticket("Test"))
     ticket_mock.status_code = 200
     child_mock = Mock()
     child_mock.content = json.dumps([_get_ticket("Child"), _get_ticket("Child2")])
     child_mock.status_code = 200
     self.mocks = [ticket_mock, child_mock]
 def test_delete(self):
     resp = Mock()
     resp.status_code = 200
     body = None
     self.instances.api.client.delete = Mock(return_value=(resp, body))
     self.instances.delete("instance1")
     resp.status_code = 500
     self.assertRaises(Exception, self.instances.delete, "instance1")
Example #9
0
        def side_effect(*args, **kwargs):
            response = Mock()
            data = json.loads(kwargs.get("data", "{}"))
            if "source_language_code" in data and "name" in data and "slug" in data:
                response.status_code = 201
            else:
                response.status_code = 400

            return response
 def test__action(self):
     resp = Mock()
     self.management.api.client.post = Mock(return_value=(resp, "body"))
     resp.status_code = 200
     self.management._action(1, "body")
     self.assertEqual(1, self.management.api.client.post.call_count)
     resp.status_code = 400
     self.assertRaises(Exception, self.management._action, 1, "body")
     self.assertEqual(2, self.management.api.client.post.call_count)
 def test_index(self):
     resp = Mock()
     resp.status_code = 400
     body = {"Accounts": {}}
     self.accounts.api.client.get = Mock(return_value=(resp, body))
     self.assertRaises(Exception, self.accounts.index)
     resp.status_code = 200
     self.assertTrue(isinstance(self.accounts.index(), base.Resource))
     self.accounts.api.client.get = Mock(return_value=(resp, None))
     self.assertRaises(Exception, self.accounts.index)
Example #12
0
        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 201
            data = json.loads(kwargs.get("data", "{}"))
            for param in required_post_params:
                if param not in data:
                    response.status_code = 400
                    response.content = "%r is required"
                    break

            return response
Example #13
0
    def test_fetch_access_token(self, mock_client_log_request, mock_oauth1):
        # mock the OAuth1 and session post response
        mock_oauth1.return_value = "oauth"
        r = Mock()
        r.content = "oauth_token=key"
        self.mock_requests_session.return_value.post.return_value = r
        self.client._token = {"key": "key", "secret": "secret", "verifier": "verifier"}

        # UnAuthorized Case
        r.status_code = 401
        with self.assertRaises(ox3apiclient.OAuthException):
            self.client.fetch_access_token()
        # Authorized Case
        r.status_code = 200
        self.assertEqual(self.client.fetch_access_token(), "key")
Example #14
0
    def test_call(self):
        body = "body"
        headers = {"header": "value"}
        path = "/authorize"
        status_code = 200
        http_code = "200 OK"

        environment = {"PATH_INFO": path, "myvar": "value"}

        request_mock = Mock(spec=Request)
        request_class_mock = Mock(return_value=request_mock)

        responseMock = Mock(spec=Response)
        responseMock.body = body
        responseMock.headers = headers
        responseMock.status_code = status_code

        server_mock = Mock(spec=Provider)
        server_mock.dispatch.return_value = responseMock

        start_response_mock = Mock()

        wsgi = Wsgi(server=server_mock, authorize_uri=path, request_class=request_class_mock, env_vars=["myvar"])
        result = wsgi(environment, start_response_mock)

        request_class_mock.assert_called_with(environment)
        server_mock.dispatch.assert_called_with(request_mock, {"myvar": "value"})
        start_response_mock.assert_called_with(http_code, headers.items())
        self.assertEqual(result, [body])
    def test_epic_create(self):
        """Test EPIC's creation of a handle - they require a 'put'"""
        client = self.portal.handle_client
        page = self.portal.page

        response1 = Mock()
        response1.status_code = 405
        response2 = Mock()
        response2.status_code = 201
        response2.headers = {"location": self.handle_url}

        client.session.post = Mock(return_value=response1)
        client.session.put = Mock(return_value=response2)
        hdl = client.create(page)

        self.assertEqual(hdl, self.handle_url)
    def it_can_construct_a_special_uri_for_delete_operations(self):
        class Doc(Document):
            id = fields.NumberField()

            class Meta:
                backend_type = "http"

            def uri(self):
                return "get"

            def delete_uri(self):
                return "delete"

        manager = BackendManager("http")
        doc = Doc({"id": 1})

        expected = {"id": 1}

        response = Mock(name="mock_http_response")
        response.status_code = 200

        # set the return value of the GET request and the DELETE request
        self.mock_request.delete.return_value = response
        response.content = json.dumps(expected)
        self.mock_request.get.return_value = response

        # now make the fetch operation
        manager.delete(doc)

        # we should have made one GET and one PUT request
        eq_([("delete", {"url": "delete"})], self.mock_request.method_calls)
    def it_can_update_the_document_on_the_remote_backend(self):
        class Doc(Document):
            id = fields.NumberField()
            name = fields.StringField()

            class Meta:
                backend_type = "http"

            def uri(self):
                return "http://location"

        doc = Doc({"id": 1})

        expected = {"id": 1, "name": "other"}

        response = Mock(name="mock_http_response")
        response.content = json.dumps(expected)
        response.status_code = 200

        # set the return value of the GET request
        self.mock_request.get.return_value = response
        self.mock_request.put.return_value = response

        doc.update({"name": "other"})

        # we should have made one GET and one PUT request
        eq_(
            [("get", {"url": "http://location"}), ("put", {"url": "http://location", "data": json.dumps(expected)})],
            self.mock_request.method_calls,
        )
        eq_("other", doc.name)
Example #18
0
    def test_unexpected_response_without_error_message(self):

        response = Mock()
        response.status_code = 422
        response.content = "no processable response"
        exception = UnexpectedResponse(response)
        self.assertEqual("%s" % exception, "Unexpected response from server (422 error code)")
Example #19
0
def create_mock_json(path, status_code=200):
    with open(path) as f:
        resp = Mock()
        resp.content = f.read()
        resp.json.return_value = json.loads(resp.content)
        resp.status_code = status_code
        return resp
Example #20
0
def generic_successful_response():
    mock_network_response = Mock(DefaultNetworkResponse)
    mock_network_response.content = b'{"message": "success"}'
    mock_network_response.status_code = 200
    mock_network_response.ok = True
    mock_network_response.raw = Mock()
    return mock_network_response
Example #21
0
File: base.py Project: jinnko/rauth
 def setUp(self):
     response = Mock()
     response.content = json.dumps({"status": "ok"})
     response.headers = {"Content-Type": "application/json"}
     response.ok = True
     response.status_code = requests.codes.ok
     self.response = response
Example #22
0
    def test_duck_type_for_file_check(self):
        # As part of determining whether or not we can rewind a stream
        # we first need to determine if the thing is a file like object.
        # We should not be using an isinstance check.  Instead, we should
        # be using duck type checks.
        class LooksLikeFile(object):
            def __init__(self):
                self.seek_called = False

            def read(self, amount=None):
                pass

            def seek(self, where):
                self.seek_called = True

        looks_like_file = LooksLikeFile()
        self.prepared_request.body = looks_like_file

        fake_response = Mock()
        fake_response.status_code = 307

        # Then requests calls our reset_stream hook.
        self.prepared_request.reset_stream_on_redirect(fake_response)

        # The stream should now be reset.
        self.assertTrue(looks_like_file.seek_called)
Example #23
0
 def test_get_current_balance(self, mock_request):
     mock_response = Mock()
     mock_response.status_code = 200
     mock_response.text = "Some text data"
     mock_request.get.return_value = mock_response
     account = Account(Mock())
     self.assertEqual({"status": 200, "data": "Some text data"}, account.get_current_balance(1))
Example #24
0
def set_method_mock(method_mock, name, status_code, return_value):
    """Set method mock return value with mock."""
    method_mock.__name__ = name
    mock = Mock()
    mock.status_code = status_code
    mock.json.return_value = return_value
    method_mock.return_value = mock
Example #25
0
    def mock_response(self, status_code, headers, data):
        mock_response = Mock()
        mock_response.status_code = status_code
        mock_response.headers = headers
        mock_response.text = json.dumps(data)

        self.request_mock.return_value = mock_response
Example #26
0
 def setUp(self):
     response = Mock()
     response.content = self.response_body
     response.status_code = 200
     with patch("requests.post") as post:
         post.return_value = response
         self.perform_action()
Example #27
0
    def setUp(self):
        # mock request object
        request = Request()
        request.method = "GET"
        request.url = "http://example.com/"
        request.params = {}
        request.data = {}
        request.params_and_data = {}
        self.request = request

        # mock response object
        response = Mock()
        response.content = "access_token=321"
        response.headers = {"content-type": "text/html; charset=UTF-8"}
        response.ok = True
        response.status_code = 200
        self.response = response

        # mock raise_for_status with an error
        def raise_for_status():
            raise Exception("Response not OK!")

        self.raise_for_status = raise_for_status

        # mock hook object
        hook = Mock()
        hook.consumer_key = "123"
        hook.consumer_secret = "456"
        hook.access_token = "321"
        hook.access_token_secret = "654"
        self.hook = hook
Example #28
0
def non_json_response():
    mock_network_response = Mock(DefaultNetworkResponse)
    mock_network_response.content = b""
    mock_network_response.ok = True
    mock_network_response.status_code = 200
    mock_network_response.json.side_effect = ValueError("No JSON object could be decoded")
    return mock_network_response
Example #29
0
def _check_for_new_project_kwargs(*args, **kwargs):
    response = Mock()
    data = json.loads(kwargs.get("data", "{}"))
    required_kwargs = ["source_language_code", "name", "slug", "repository_url", "private"]
    missing_keys = set(required_kwargs) - set(data.keys())
    print(data)
    if missing_keys:
        response.status_code = 400
        response.content = missing_keys
    elif not data["private"] and data["repository_url"] is None:
        response.status_code = 400
        response.content = "repository_url is required for public " "repositories"
    else:
        response.status_code = 201

    return response
 def request(*args, **kwargs):
     response = Mock()
     response.status_code = status
     if fixture:
         fixture_path = os.path.join(FIXTURES, fixture)
         response.content = open(fixture_path).read()
     return response