Example #1
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]
Example #2
0
def mock_response(fixture=None, status=200):
    response = Mock()
    if fixture is None:
        response.content = ""
    elif isinstance(fixture, dict):
        response.content = str(fixture)
    else:
        response.content = load_fixture(fixture)
    response.status_code = status
    return response
Example #3
0
        def side_effect(*args, **kwargs):
            response = Mock()
            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"
                    return response

            response.status_code = 200
            response.content = json.dumps({"s": 1})
            return response
Example #4
0
 def inner(status_code=200, response_ok=True, response=None, content=None):
     mock_box_response = Mock(BoxResponse)
     mock_network_response = Mock(DefaultNetworkResponse)
     mock_box_response.network_response = mock_network_response
     mock_box_response.status_code = status_code
     mock_box_response.ok = response_ok
     if response is not None:
         mock_box_response.json.return_value = response
         mock_box_response.content = json.dumps(response).encode()
     else:
         mock_box_response.content = content
     return mock_box_response, mock_network_response
 def get_mock(url):
     """
     We must use a different mock for this one, to return different XML
     contents, given the same XML file (for different servers).
     """
     mock = Mock()
     if "domain3.com/example2.xml" in url:
         mock.content = open("xmls/example2.xml", "r").read()
     elif "domain4.com/example2.xml" in url:
         mock.content = open("xmls/example5.xml", "r").read()
     else:
         mock.content = open("xmls/{url}".format(url=url[len("http://domainN.com/") :]), "r").read()
     return mock
 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
Example #7
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
Example #8
0
 def create_response(self):
     response = Mock()
     response.items = Mock(return_value=[("Content-Type", "text/html; charset=utf-8")])
     response.status_code = 200
     response.reason_phrase = "OK"
     response.content = "Hello, world. You're at the polls index."
     return response
 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 #10
0
    def test_success(self):
        rpc = Mock()
        result = Mock()
        result.status_code = 200
        result.content = '{"ticket":"123456"}'
        rpc.get_result = Mock(return_value=result)
        pswdless.urlfetch.create_rpc = Mock(return_value=rpc)
        fetch = Mock()
        pswdless.urlfetch.make_fetch_call = fetch
        post_params = {
            "app_id": 1,
            "token": "2",
            "hook": "http://yourhooke.com",
            "email": "foo@bar.com",
            "lang": "pt_BR",
        }
        url = "https://pswdless.appspot.com/rest/login"
        send_login_params = {"url_login": url}
        send_login_params.update(post_params)

        send_login = facade.send_login_email(**send_login_params)
        send_login.execute()
        self.assertDictEqual({"ticket": "123456"}, send_login.result)
        les_model = LoginEmailSentCertified.find_by_ticket("123456").get()
        self.assertEqual("123456", les_model.ticket)
        fetch.assert_called_once_with(
            rpc, url, urllib.urlencode(post_params), method=urlfetch.POST, validate_certificate=True
        )
Example #11
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 #12
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)")
    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 #14
0
 def test_all_jobs(self, requests, Template):
     response = Mock()
     response.content = "{'jobs':[{'name': 'job1', 'color': 'blue'}]}"
     requests.get.return_value = response
     jobs = self.jenkins.all_jobs()
     requests.get.assert_called_once_with("http://jenkins/api/python", auth=None)
     self.assertEqual(jobs, [("job1", "blue")])
Example #15
0
    def test_fail_max_retry(self):
        # this tests the read function when HTTP requests keep returning 503s
        # read call fails when it reaches the maximum number of retries, in
        # this case set to 2

        # mock the 503 responses
        mock_resp = Mock(name="503 resp")
        mock_resp.status_code = 503
        mock_resp.content = "Testing"

        headers = {"Content-Length": 10, "X-CADC-Content-Length": 5, "Retry-After": 4}

        def getheader(name, default):
            return headers[name]

        mock_resp.headers = MagicMock()
        mock_resp.headers.get.side_effect = getheader

        conn = Connection()
        conn.session.send = Mock(return_value=mock_resp)
        vofile = vos.VOFile(["Some URL"], conn, "GET")
        req = requests.Request("GET", "http://some/url")
        vofile.request = req.prepare()

        # set number of retries to 1 and check the OSError was thrown
        vofile.maxRetries = 1
        with self.assertRaises(OSError) as cm:
            vofile.read()
        mock_resp.headers.get.assert_called_with("Retry-After", 5)
Example #16
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 #17
0
 def test_list_objects_with_invalid_content_length(self):
     http_response = Mock()
     http_response.encoding = "utf-8"
     http_response.headers = CaseInsensitiveDict(
         {
             "Date": "Thu, 22 Aug 2013 02:11:57 GMT",
             # We say we have 265 bytes but we're returning 0,
             # this should raise an exception because this is not
             # a HEAD request.
             "Content-Length": "265",
             "x-amz-request-id": "2B74ECB010FF029E",
             "ETag": '"40d06eb6194712ac1c915783004ef730"',
             "Server": "AmazonS3",
             "content-type": "binary/octet-stream",
             "Content-Type": "binary/octet-stream",
             "accept-ranges": "bytes",
             "Last-Modified": "Tue, 20 Aug 2013 18:33:25 GMT",
             "x-amz-server-side-encryption": "AES256",
         }
     )
     http_response.content = ""
     http_response.request.method = "GET"
     list_objects = self.s3.get_operation("ListObjects")
     expected = {
         "AcceptRanges": "bytes",
         "ContentType": "binary/octet-stream",
         "LastModified": "Tue, 20 Aug 2013 18:33:25 GMT",
         "ContentLength": "265",
         "ETag": '"40d06eb6194712ac1c915783004ef730"',
         "ServerSideEncryption": "AES256",
     }
     with self.assertRaises(IncompleteReadError):
         response_data = get_response(self.session, list_objects, http_response)[1]
Example #18
0
    def test_success(self):
        # Setting up valid ticket
        valid_ticket = "valid_ticket"
        LoginEmailSentCertified(ticket=valid_ticket).put()

        # setting user data return
        rpc = Mock()
        result = Mock()
        result.status_code = 200
        result.content = '{"id":"123456","email":"foo@bar.com"}'
        rpc.get_result = Mock(return_value=result)
        pswdless.urlfetch.create_rpc = Mock(return_value=rpc)
        fetch = Mock()
        pswdless.urlfetch.make_fetch_call = fetch
        post_params = {"app_id": "1", "token": "2", "ticket": valid_ticket}
        url_detail = "https://pswdless.appspot.com/rest/detail"
        params = {"url_detail": url_detail}
        params.update(post_params)
        response = Mock()
        response.set_cookie = Mock()
        cmd = LogUserIn(cookie_name="user", response=response, **params)
        cmd.execute()
        self.assertDictEqual({"id": "123456", "email": "foo@bar.com"}, cmd.result)
        fetch.assert_called_once_with(
            rpc, url_detail, urllib.urlencode(post_params), method=urlfetch.POST, validate_certificate=True
        )
        self.assertIsNone(LoginEmailSentCertified.find_by_ticket(valid_ticket).get())
        response.set_cookie.assert_called_once_with("user", cmd._signed, httponly=True)
Example #19
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
    def it_can_delete_resources_from_a_remote_endpoint(self):
        mock_resp = Mock(name="mock_response")
        expected = {"id": 1}
        mock_resp.content = json.dumps(expected)

        self.mock_request.delete.return_value = mock_resp

        manager = BackendManager("http")

        class Doc(Document):
            id = fields.NumberField()

            class Meta:
                backend_type = "http"

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

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

        manager.delete(doc)

        # make sure we are working with correct expectations
        eq_(HttpBackendManager, type(manager))
        eq_([("delete", {"url": doc.uri()})], self.mock_request.method_calls)
Example #21
0
 def test_arbitrary_member(self, mock_request):
     mock_response = Mock()
     mock_response.ok = True
     mock_response.content = json.dumps({"short_codes": []})
     mock_request.return_value = mock_response
     self.assertEqual([], self.client.sms.short_codes.list())
     mock_request.assert_called_once_with("GET", ANY, params=ANY, auth=AUTH, timeout=sentinel.timeout)
Example #22
0
def test_api_decorator():
    """
    Test APIDecorator
    """
    content = {"name": "Test", "stuff": "stuff"}

    request = Mock()
    request.content = Mock()
    request.content.read = Mock(return_value=json.dumps(content))

    apiPkg = pdrest.APIPackage(request)
    user = APIDecoratorUser()

    # Test the NOT_DONE_YET branch of code in APIDecorator.
    user.runNotDoneYet(request)

    # TODO: These fail because of missing variables (failureKey, failureDict,
    # etc.) Where are those supposed to come from?
    #    user.runSuccess(request)
    #    assert user.rest.postprocess.call_count == 1
    #
    #    apiPkg.countFailure = True
    #    user.runFailure(reques)
    #    assert user.rest.failprocess.call_count == 1
    #
    #    apiPkg.countFailure = False
    #    user.runFailure(request)
    #    assert user.rest.failprocess.call_count == 2

    # Try test with missing required field
    del content["name"]
    request.content.read = Mock(return_value=json.dumps(content))
    user.runNotDoneYet(request)
    def it_can_fetch_resources_from_a_remote_endpoint(self):
        mock_resp = Mock(name="mock_response")
        expected = {"id": 1}
        mock_resp.content = json.dumps(expected)

        self.mock_request.get.return_value = mock_resp

        manager = BackendManager("http")

        class Doc(Document):
            id = fields.NumberField()

            class Meta:
                backend_type = "http"

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

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

        # the http manager returns the response as python dict
        content = manager.fetch(doc)

        # make sure we are working with correct expectations
        eq_(HttpBackendManager, type(manager))
        eq_(mock_resp, manager.response)
        ok_(isinstance(content, dict))
        eq_([("get", {"url": doc.uri()})], self.mock_request.method_calls)
Example #24
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
    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)
Example #26
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 #27
0
 def test_get_response_size_from_content(self):
     parser = HTMLParser("", False)
     mock_response = Mock()
     mock_response.headers = {}
     mock_response.content = "1234567890"
     parser.response = mock_response
     assert parser.get_response_size() == 10
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
 def test_head_object(self):
     http_response = Mock()
     http_response.encoding = "utf-8"
     http_response.headers = {
         "Date": "Thu, 22 Aug 2013 02:11:57 GMT",
         "Content-Length": "265",
         "x-amz-request-id": "2B74ECB010FF029E",
         "ETag": '"40d06eb6194712ac1c915783004ef730"',
         "Server": "AmazonS3",
         "content-type": "binary/octet-stream",
         "Content-Type": "binary/octet-stream",
         "accept-ranges": "bytes",
         "Last-Modified": "Tue, 20 Aug 2013 18:33:25 GMT",
         "x-amz-server-side-encryption": "AES256",
     }
     http_response.content = ""
     put_object = self.s3.get_operation("HeadObject")
     expected = {
         "AcceptRanges": "bytes",
         "ContentType": "binary/octet-stream",
         "LastModified": "Tue, 20 Aug 2013 18:33:25 GMT",
         "ContentLength": "265",
         "ETag": '"40d06eb6194712ac1c915783004ef730"',
         "ServerSideEncryption": "AES256",
     }
     response_data = get_response(self.session, put_object, http_response)[1]
     self.assertEqual(response_data, expected)
Example #30
0
    def setUp(self):
        WebauthTestCase.setUp(self)

        # mock service for testing
        service = OAuth2Service(
            "example",
            consumer_key="123",
            consumer_secret="456",
            access_token_url="http://example.com/access_token",
            authorize_url="http://example.com/authorize",
        )
        self.service = service

        def raise_for_status():
            raise Exception("Response not OK!")

        self.raise_for_status = raise_for_status

        # mock response for testing
        response = Mock()
        response.content = "access_token=321"
        response.ok = True
        response.status_code = 200
        response.raise_for_status = lambda: None
        self.response = response