def test_upload_app_poll_status(self):
        mock_response = self.mock_post.return_value
        mock_response.ok = True
        mock_response.return_value = {
            'success': True,
            'status_url': 'http://example.com/status/'
        }

        response_not_completed = Response()
        response_not_completed.status_code = 200
        response_not_completed.encoding = 'utf-8'
        response_not_completed._content = json.dumps(
            {'completed': False, 'application_url': ''}).encode('utf-8')
        response_completed = Response()
        response_completed.status_code = 200
        response_completed.encoding = 'utf-8'
        response_completed._content = json.dumps(
            {'completed': True, 'revision': 14,
             'application_url': 'http://example.org'}).encode('utf-8')
        self.mock_get.side_effect = [
            response_not_completed,
            response_not_completed,
            response_completed,
        ]
        response = upload_app(self.package_name, self.data)
        self.assertEqual(response, {
            'success': True,
            'errors': [],
            'application_url': 'http://example.org',
            'revision': 14,
        })
        self.assertEqual(self.mock_get.call_count, 3)
Beispiel #2
0
    def test_avi_json(self):
        rsp = Response()
        rsp.status_code = 404
        rsp._content = 'Not found'
        try:
            avi_rsp = ApiResponse(rsp)
            avi_rsp.json()
            assert False
        except ObjectNotFound:
            pass
        except Exception:
            assert False

        rsp.status_code = 501
        try:
            avi_rsp = ApiResponse(rsp)
            avi_rsp.json()
            assert False
        except APIError:
            pass
        except Exception:
            assert False

        rsp.status_code = 200
        rsp._content = json.dumps({'count': 3, 'results': ['a', 'b', 'c']})
        try:
            avi_rsp = ApiResponse(rsp)
            obj = avi_rsp.json()
            assert obj['count']
            assert avi_rsp.count() == 3
            assert len(obj['results']) == 3
        except Exception as e:
            log.debug('exception %s', str(e))
            log.debug('%s', traceback.format_exc())
            assert False
    def test_should_contain1(self, requests):
        response = Response()
        response.status_code = 200
        response._content = """
        <CFRDOC>
            <AMDDATE>Jan 1, 2001</AMDDATE>
            <PARTS>Part 111 to 222</PARTS>
        </CFRDOC>"""
        response._content_consumed = True
        requests.get.return_value = response

        volume = annual.Volume(2001, 12, 2)
        self.assertFalse(volume.should_contain(1))
        self.assertFalse(volume.should_contain(100))
        self.assertFalse(volume.should_contain(300))
        self.assertFalse(volume.should_contain(250))
        self.assertTrue(volume.should_contain(111))
        self.assertTrue(volume.should_contain(211))
        self.assertTrue(volume.should_contain(222))

        response._content = """
        <CFRDOC>
            <AMDDATE>Jan 1, 2001</AMDDATE>
            <PARTS>Parts 587 to End</PARTS>
        </CFRDOC>"""
        response._content_consumed = True

        volume = annual.Volume(2001, 12, 2)
        self.assertFalse(volume.should_contain(111))
        self.assertFalse(volume.should_contain(586))
        self.assertTrue(volume.should_contain(587))
        self.assertTrue(volume.should_contain(600))
        self.assertTrue(volume.should_contain(999999))
def test_delete_operation():
    response = Response()
    response._content = '{"access_token":"CLIENT_ACCESS_TOKEN","token_type":"Bearer","expires_in":3887999}'
    requests.post = MagicMock(return_value=response)

    auth = APIManager('CLIENT_ID', 'CLIENT_SECRET', 'HOSTNAME')

    response = Response()
    response._content = '{"message": "SUCCESS"}'
    requests.delete = MagicMock(return_value=response)
    delete = auth.delete('ROUTE')
    assert delete.content == '{"message": "SUCCESS"}'
def test_authenticate_decorator():
    response = Response()
    response._content = '{"access_token":"ACCESS_TOKEN","token_type":"Bearer","expires_in":-5}'
    requests.post = MagicMock(return_value=response)

    auth = APIManager('CLIENT_ID', 'CLIENT_SECRET', 'HOSTNAME')

    assert auth.access_token['access_token'] == 'ACCESS_TOKEN'

    response._content = '{"access_token":"REFRESHED_ACCESS_TOKEN","token_type":"Bearer","expires_in":3887999}'
    auth.post('/')

    assert auth.access_token['access_token'] == 'REFRESHED_ACCESS_TOKEN'
Beispiel #6
0
    def request(self, url, method, **kwargs):

        resp = Response()

        if url == '/role_assignments?scope.domain.id=default':
            json_data = open(UNIT_TEST_RESOURCES_FOLDER + LIST_ROLE_ASSIGNMENTS_RESPONSE_FILE_EXTENDED1).read()
            resp.status_code = OK
            resp._content = json_data
        elif url == '/role_assignments?user.id=fake3&scope.domain.id=default':
            json_data = open(UNIT_TEST_RESOURCES_FOLDER + LIST_USERS_RESPONSE_FILE2).read()
            resp.status_code = OK
            resp._content = json_data
        return resp
        def mock_response():
            global HIT_COUNT
            HIT_COUNT += 1
            r = Response()
            r.status_code = 200
            if HIT_COUNT == 1:
                with open("app/ciscoeox/tests/data/cisco_eox_response_page_1_of_2.json") as f:
                    r._content = f.read().encode("utf-8")

            else:
                with open("app/ciscoeox/tests/data/cisco_eox_response_page_2_of_2.json") as f:
                    r._content = f.read().encode("utf-8")
            return r
        def _request(method, url, *args, **kwargs):
            assert method == 'GET'
            assert url == 'http://localhost:123/collection.txt'
            r = Response()
            r.status_code = 200
            try:
                with open(self.tmpfile, 'rb') as f:
                    r._content = f.read()
            except IOError:
                r._content = b''

            r.headers['Content-Type'] = 'text/icalendar'
            r.encoding = 'ISO-8859-1'
            return r
Beispiel #9
0
        def _request(method, url, *args, **kwargs):
            assert method == 'GET'
            assert url == 'http://localhost:123/collection.txt'
            assert 'vdirsyncer' in kwargs['headers']['User-Agent']
            r = Response()
            r.status_code = 200
            try:
                with open(self.tmpfile, 'rb') as f:
                    r._content = f.read()
            except IOError:
                r._content = b''

            r.headers['Content-Type'] = 'text/calendar'
            r.encoding = 'utf-8'
            return r
    def test_run_tests(self):
        rainforest = Rainforest('CLIENT_TOKEN')

        # Validate that the potential for an invalid client token raises an exception
        mocked_response = Response()
        mocked_response.status_code = 404
        mocked_response._content = '{"error":"Account not found"}'

        requests.post = Mock(return_value=mocked_response)

        with self.assertRaises(RainforestError):
            rainforest.run_tests([1,2,3])

        # Validate that the potential for an invalid client token raises an exception
        mocked_response = Response()
        mocked_response.status_code = 400
        mocked_response._content = '{"error":"You must specify the tags or tests parameter"}'

        requests.post = Mock(return_value=mocked_response)

        with self.assertRaises(RainforestError):
            rainforest.run_tests(["a","b","c"])

        # Validate that tests get returned properly on a successful case
        mocked_response = Response()
        mocked_response.status_code = 201
        mocked_response._content = '{"id":1,"object":"Run","created_at":"2014-04-19T06:06:47Z","environment_id":1770,"state_log":[],"state":"queued","result":"no_result","expected_wait_time":8100.0,"browsers":[{"name":"chrome","state":"disabled"},{"name":"firefox","state":"disabled"},{"name":"ie8","state":"disabled"},{"name":"ie9","state":"disabled"},{"name":"safari","state":"disabled"}],"requested_tests":[1,2,3]}'

        requests.post = Mock(return_value=mocked_response)

        test_run = rainforest.run_tests([1,2,3])

        requests.post.assert_called_with('https://app.rainforestqa.com/api/1/runs', data='{"tests": [1, 2, 3]}', headers={
            'Content-Type'  : 'application/json',
            'Accept'        : 'application/json',
            'CLIENT_TOKEN'  : 'CLIENT_TOKEN',
        })

        self.assertIsInstance(test_run, TestRun)
        self.assertEqual(test_run.id, 1)
        self.assertEqual(test_run.object, 'Run')
        self.assertEqual(test_run.created_at, '2014-04-19T06:06:47Z')
        self.assertEqual(test_run.environment_id, 1770)
        self.assertEqual(test_run.state, 'queued')
        self.assertEqual(test_run.result, 'no_result')
        self.assertEqual(test_run.expected_wait_time, 8100.0)
        self.assertEqual(test_run.browsers, [{"name":"chrome","state":"disabled"},{"name":"firefox","state":"disabled"},{"name":"ie8","state":"disabled"},{"name":"ie9","state":"disabled"},{"name":"safari","state":"disabled"}])
        self.assertEqual(test_run.requested_tests, [1,2,3])
def test_yahoo_get_by_date(yahoo, logger):
    sample = Response()
    sample.status_code = 200
    sample._content = YAHOO_RESPONSE
    yahoo._get = lambda *a, **kw: sample

    assert yahoo.get_by_date(date.today(), "CZK", logger) == Decimal("25.959")
def create_response(**kw):
    r = Response()
    r._content = b''
    r.status = 200
    for k, v in kw.items():
        setattr(r, k, v)
    return r
Beispiel #13
0
def responses(code, path=None, redirection=None, data=None,
              url=None,
              headers=None):
    if headers is None:
        headers = {'Content-Type': 'text/xml'}
    response = Response()
    response.status_code = code
    if path is not None and redirection is None:
        with open(data_file(path), 'rb') as f:
            response.raw = BytesIO(f.read())
    elif data is not None:
        response._content = data.encode('utf-8')
    if redirection is not None:
        temp = Response()
        temp.status_code = 301 if 'permanent' in redirection else 302
        temp.url = path
        response.history.append(temp)
        response.url = redirection
        headers['location'] = path
    if url is None:
        if redirection is not None:
            url = redirection
        else:
            url = 'https://example.com/{}'.format(str(uuid4()))
    response.url = url
    response.headers = headers
    return response
Beispiel #14
0
    def test_keystone_client_exception(self, logger):
        """
        ``keystoneclient.openstack.common.apiclient.exceptions.BadRequest`` is
        treated similarly to ``novaclient.exceptions.ClientException``.

        See ``test_novaclient_exception``.
        """
        response = Response()
        response._content = "hello world"
        result = KeystoneHttpError(
            message="Some things went wrong with some other things.",
            details={"key": "value"},
            response=response,
            request_id="abcdefghijklmnopqrstuvwxyz",
            url="/foo/bar",
            method="POST",
            http_status=INTERNAL_SERVER_ERROR,
        )
        logging_dummy = LoggingDummy(Dummy(result))
        self.assertRaises(KeystoneHttpError, logging_dummy.raise_method)

        logged = LoggedMessage.of_type(
            logger.messages, KEYSTONE_HTTP_ERROR,
        )[0]
        assertContainsFields(
            self, logged.message, {
                u"code": result.http_status,
                u"message": result.message,
                u"details": result.details,
                u"request_id": result.request_id,
                u"url": result.url,
                u"method": result.method,
                u"response": "hello world",
            },
        )
Beispiel #15
0
    def test_cutout_get_success(self, mock_session):
        resolution = 0
        x_range = '20:40'
        y_range = '50:70'
        z_range = '30:50'
        time_range = '10:25'
        url_prefix = 'https://api.theboss.io'
        auth = 'mytoken'

        fake_prepped_req = PreparedRequest()
        fake_prepped_req.headers = {}
        mock_session.prepare_request.return_value = fake_prepped_req 

        data = numpy.random.randint(0, 3000, (15, 20, 20, 20), numpy.uint16)
        compressed_data = blosc.pack_array(data)
        fake_response = Response()
        fake_response.status_code = 200
        fake_response._content = compressed_data
        mock_session.send.return_value = fake_response
        send_opts = {}

        actual = self.vol.cutout_get(
            self.chan, resolution, x_range, y_range, z_range, time_range,
            url_prefix, auth, mock_session, send_opts)

        numpy.testing.assert_array_equal(data, actual)
Beispiel #16
0
    def logged_in(self, login='******', travis_user=True):
        """ A context manager to do stuff, while logged in as fred. """

        response = Response()
        response._content = json.dumps(
            dict(id=12345, login=login, name='Fred')
        )
        data = Mock()
        data.get = Mock(return_value=response)
        data.access_token = GH_TOKEN

        true = Mock(return_value=True)

        if travis_user:
            travis_patch = patch('travis_utils.is_travis_user', true)
            travis_patch.start()

        with patch('statiki.github', Mock(spec=OAuth2Service)) as gh:
            gh.get_auth_session = Mock(return_value=data)

            try:
                yield self.app.get('/authorized?code="bazooka"')

            finally:
                if travis_user:
                    travis_patch.stop()

                self.app.get('/logout')
Beispiel #17
0
 def stub(url):
     response = Response()
     response._content = json
     response.url = url
     response.status_code = status_code
     response.json = json_loads_stub(json)
     return response
Beispiel #18
0
 def _method(self, url, *args, **kwargs):
     success = url in self.urls
     content = self.urls.get(url, '')
     resp = Response()
     resp._content = content.encode('utf-8')
     resp.status_code = codes.ok if success else codes.not_found
     return resp
    def test_download_fails_due_to_hash_mismatch(self):
        snap_content = b'1234567890'
        mock_details = self.mock_get.return_value
        mock_details.ok = True
        mock_details.content = json.dumps({
            '_embedded': {
                    'clickindex:package': [{
                        'download_url': 'http://localhost',
                        'anon_download_url': 'http://localhost',
                        'download_sha512': '12345',
                    }],
            }
        }).encode('utf-8')
        mock_snap = Response()
        mock_snap.status_code = 200
        mock_snap._content = snap_content

        self.mock_get.side_effect = [mock_details, mock_snap]

        with self.assertRaises(RuntimeError) as raised:
            download('os', 'edge', 'os.snap', None, 'amd64')

        self.assertEqual("Failed to download 'os'", str(raised.exception))
        self.mock_logger.info.assert_has_calls([
            call("Getting details for 'os'"),
            call("Downloading 'os'")])
        self.assertTrue(os.path.exists('os.snap'))
Beispiel #20
0
def fake_response_handler(url=None, **kwargs):
    r = Response()
    r.status_code = 200
    r.encoding = "utf-8"
    assert url in fake_responses, "unknown URL: " + url
    r._content = fake_responses[url]
    return r
    def test_download_redownload_as_hash_mismatches(self):
        with open('os.snap', 'wb') as f:
            f.write(b'0000000')

        snap_content = b'1234567890'
        snap_sha512 = ('12b03226a6d8be9c6e8cd5e55dc6c7920caaa39df14aab92d5e'
                       '3ea9340d1c8a4d3d0b8e4314f1f6ef131ba4bf1ceb9186ab87c'
                       '801af0d5c95b1befb8cedae2b9')
        mock_details = self.mock_get.return_value
        mock_details.ok = True
        mock_details.content = json.dumps({
            '_embedded': {
                    'clickindex:package': [{
                        'download_url': 'http://localhost',
                        'anon_download_url': 'http://localhost',
                        'download_sha512': snap_sha512,
                    }],
            }
        }).encode('utf-8')
        mock_snap = Response()
        mock_snap.status_code = 200
        mock_snap._content = snap_content

        self.mock_get.side_effect = [mock_details, mock_snap]

        download('os', 'edge', 'os.snap', None, 'amd64')

        self.mock_logger.info.assert_has_calls([
            call("Getting details for 'os'"),
            call("Downloading 'os'"),
            call("Successfully downloaded 'os'")])
        self.assertTrue(os.path.exists('os.snap'))
Beispiel #22
0
    def test_upload_app_ok(self):
        # fake upload response
        mock_response = self.mock_post.return_value
        mock_response.ok = True
        mock_response.return_value = {
            'success': True,
            'status_url': 'http://example.com/status/',
        }
        # fake poll status response
        application_url = 'http://example.com/app/1'
        revision = '1'
        ok_response = Response()
        ok_response.status_code = 200
        ok_response.encoding = 'utf-8'
        ok_response._content = json.dumps(
            {'completed': True, 'revision': revision,
             'application_url': application_url}).encode('utf-8')
        self.mock_get.return_value = ok_response

        success = upload(self.binary_file.name, 'foo')

        self.assertTrue(success)
        self.assertIn(
            call('Application uploaded successfully (as revision {})'.format(
                revision)),
            self.mock_logger.info.call_args_list)
        self.assertIn(call('Please check out the application at: %s\n',
                           application_url),
                      self.mock_logger.info.call_args_list)
Beispiel #23
0
    def test_get_json_data(self, gobase_get_full_response):
        response = Response()
        response._content = "not a json object"
        gobase_get_full_response.return_value = response

        with self.assertRaises(GoCdApiException):
            self.gobase.get_json_data(self.gobase.url)
Beispiel #24
0
 def make_response(self, status_code=200, reason='OK', data=None):
     data = data or {}
     response = Response()
     response.status_code = status_code
     response.reason = reason
     response._content = json.dumps(data).encode('utf-8')
     return response
    def test_snap_already_downloaded(self):
        snap_content = b'1234567890'
        snap_sha512 = ('12b03226a6d8be9c6e8cd5e55dc6c7920caaa39df14aab92d5e'
                       '3ea9340d1c8a4d3d0b8e4314f1f6ef131ba4bf1ceb9186ab87c'
                       '801af0d5c95b1befb8cedae2b9')

        with open('os.snap', 'wb') as f:
            f.write(snap_content)

        mock_details = self.mock_get.return_value
        mock_details.ok = True
        mock_details.content = json.dumps({
            'download_url': 'http://localhost',
            'download_sha512': snap_sha512,
        }).encode('utf-8')
        mock_snap = Response()
        mock_snap.status_code = 200
        mock_snap._content = snap_content

        self.mock_get.side_effect = [mock_details, mock_snap]

        download('os', 'os.snap', None, 'amd64')

        self.mock_logger.info.assert_has_calls([
            call("Getting details for 'os'"),
            call("Already downloaded 'os'")])
        self.assertTrue(os.path.exists('os.snap'))
Beispiel #26
0
    def test_outside_app(self):
        resp = Response()
        resp.status_code = 200
        resp._content = '{"ok": true}'

        flexmock(urlfetch.S).should_receive('request').with_args(
        method='POST',
        url='http://services.dev.guokr.com/taskqueue.json',
        files=None,
        data={
            'appname': 'test',
            'method_': 'GET',
            'url_': 'http://www.g.cn',
            'countdown_': 0
            }).and_return(resp).once()
        taskqueue.add_url('http://www.g.cn') # success

        flexmock(urlfetch.S).should_receive('request').and_return(resp)
        self.assertRaises(RuntimeError, taskqueue.add_url, '/test') # fail
        self.assertRaises(RuntimeError, taskqueue.add, '.test_view') # fail

        with self.app.test_request_context('http://localhost/testxx'):
            flexmock(urlfetch.S).should_receive('request').with_args(
                method='POST',
                url='http://services.dev.guokr.com/taskqueue.json',
                files=None,
                data={
                    'appname': 'test',
                    'method_': 'POST',
                    'url_': 'http://backends.dev.guokr.com/test.json',
                    'countdown_': 0
                }).and_return(resp).twice()
            taskqueue.add_url('/test.json', method_='POST') # success
            taskqueue.add('.test_view', method='POST') # success
Beispiel #27
0
 def send(self, request, stream=False, timeout=None, verify=True, cert=None,
          proxies=None):
     resp = Response()
     resp.status_code = 200
     ticket = re.findall(r"abematv-license://(.*)", request.url)[0]
     resp._content = self._get_videokey_from_ticket(ticket)
     return resp
Beispiel #28
0
 def new_response(self, response):
     """Convert an tornado.HTTPResponse object to a requests.Response object"""
     new = Response()
     new._content = response.body
     new.status_code = response.code
     new.headers = dict(response.headers.get_all())
     return new
Beispiel #29
0
def build_response(request,
                   status_code=200,
                   headers={},
                   content='(none)'):
    """
    Build a :class:`requests.Response` object on the basis of the passed
    parameters.
    """

    response = Response()

    response.status_code = status_code
    response.reason = responses[status_code]
    response.headers = CaseInsensitiveDict(headers)
    # Pretend that we've already read from the socket
    response._content = content

    response.encoding = get_encoding_from_headers(response.headers)
    response.url = request.url
    response.raw = MockRawResponse()

    # Give the Response some context.
    response.request = request
    response.connection = MockConnection()

    return response
Beispiel #30
0
    def test_upload_app_ignore_non_ok_responses(self):
        mock_response = self.mock_post.return_value
        mock_response.ok = True
        mock_response.return_value = {
            'success': True,
            'status_url': 'http://example.com/status/',
        }

        ok_response = Response()
        ok_response.status_code = 200
        ok_response.encoding = 'utf-8'
        ok_response._content = json.dumps(
            {'completed': True, 'revision': 14}).encode('utf-8')
        nok_response = Response()
        nok_response.status_code = 503

        self.mock_get.side_effect = [nok_response, nok_response, ok_response]
        response = upload_app(self.package_name, self.data)
        self.assertEqual(response, {
            'success': True,
            'errors': [],
            'application_url': '',
            'revision': 14,
        })
        self.assertEqual(self.mock_get.call_count, 3)
    def test_request_failure_with_error_payload(self):
        response = Response()
        response.status_code = 400
        response._content = bytes('{"errors":[{"message":"Bad request"}]}', "UTF-8")

        with self.assertRaises(HTTPError) as cm:
            _validate_cloudflare_response(response, _on_update_success)

        self.assertEqual(str(cm.exception), "400 Client Error: None for url: None: Bad request")
Beispiel #32
0
 async def new_response(self, response):
     """Convert an aiohttp.Response object to a requests.Response object"""
     new = Response()
     new._content = await response.read()
     new.status_code = response.status
     new.headers = response.headers
     new.cookies = response.cookies
     new.encoding = response.charset
     return new
Beispiel #33
0
def _get_dummy_response(body, status_code=200) -> Response:
    body_encoding = "utf-8"
    body_string = body if isinstance(body, str) else json.dumps(body)
    body_bytes = bytes(body_string, body_encoding)
    response = Response()
    response.status_code = status_code
    response.encoding = body_encoding
    response._content = body_bytes
    return response
    def test_request_failure_without_error_payload(self):
        response = Response()
        response.status_code = 400
        response._content = bytes('{}', "UTF-8")

        with self.assertRaises(ValueError) as cm:
            _validate_cloudflare_response(response, _on_update_success)

        self.assertEqual(str(cm.exception), "Cloudflare API response was malformed: b'{}'")
    def test_execute(self):
        client = ApiClient()
        with patch('yandex_checkout.client.ApiClient.execute') as request_mock:
            res = Response()
            res.status_code = 200
            res._content = b"{}"
            request_mock.return_value = res

            client.request(HttpVerb.POST, '/path', RequestObject({"param": "param"}), {'header': 'header'})
Beispiel #36
0
 def response2(self):
     resp = Response()
     resp.status_code = 200
     resp.url = 'https://www.youtube.com/watch?v=scbrjaqM3Oc'
     resp.encoding = 'utf8'
     resp.headers['content-type'] = 'text/html'
     with open('tests/fixtures/article-2.html') as fd:
         resp._content = fd.read()
     return resp
Beispiel #37
0
 def get_response(self, scheme='http:'):
     resp = Response()
     resp.url = scheme + self.response_url
     resp.status_code = 200
     resp.encoding = 'utf8'
     resp.headers['content-type'] = 'text/html'
     with open('tests/fixtures/article.html') as fd:
         resp._content = fd.read()
     return resp
Beispiel #38
0
        def mocked_post(*args, **kwargs):
            mocked_response = Response()
            requested_url = args[1]
            if "/server/request-token/" == urlparse(requested_url).path:
                # token generated for private key settings.SSO_PRIVATE_KEY = 'priv1'
                mocked_response._content = (
                    b'{"request_token": "XcHtuemqcjnIT6J2WHTFswLQP0W07nI96XfxqGkm6b1zFToF0YGEoIYu3'
                    b'7QOajkc"}.XTd9sA.quRsXFxqMk-ufwSc79q-_YLDNzg'
                )
            elif "/server/verify/" == urlparse(requested_url).path:
                mocked_response._content = (
                    b'{"username": "******", "email": "*****@*****.**", "first_name": '
                    b'"Jan", "last_name": "Kowalski", "is_staff": false, "is_superuser": false, '
                    b'"is_active": true}.XTg4IQ._cANZR5jHvtwhNzcnNYDfE1nLHE'
                )

            mocked_response.status_code = 200
            return mocked_response
    def test_operation_failure_with_valid_payload(self):
        response = Response()
        response.status_code = 200
        response._content = bytes('{"success":false,"errors":[{"message":"Bad request"}]}', "UTF-8")

        with self.assertRaises(ValueError) as cm:
            _validate_cloudflare_response(response, _on_update_success)

        self.assertEqual(str(cm.exception), "Operation failed: Bad request")
    def test_invalid_payload(self):
        response = Response()
        response.status_code = 200
        response._content = bytes("abc", "UTF-8")

        with self.assertRaises(ValueError) as cm:
            _validate_cloudflare_response(response, _on_update_success)

        self.assertEqual(str(cm.exception), "Cloudflare API response did not contain valid JSON: b'abc'")
Beispiel #41
0
def fake_request(*args, **kwargs):
    # FIXME: Replace with responses
    r = Response()
    r.status_code = 200

    try:
        _token = kwargs['headers']['Authorization']
    except KeyError:
        r._content = b'{"shoe_size": 10}'  # type: ignore
    else:
        _token = _token[7:]
        if _token == 'abcdef':
            r._content = b'{"shoe_size": 11}'  # type: ignore
        else:
            r._content = b'{"shoe_size": 12}'  # type: ignore

    r.headers = {'content-type': 'application/json'}
    return r
Beispiel #42
0
def __return_response(actual_endpoint, expected_endpoint, http_code,
                      json_result):
    if actual_endpoint == expected_endpoint:
        response = Response()
        response.status_code = http_code
        response._content = json_result.encode()
        return response
    raise Exception('Fail ! BAD endpoint.\nActual  : %s\nExpected: %s' %
                    (actual_endpoint, expected_endpoint))
Beispiel #43
0
    def test_update_funding_fails_on_rate_limit(self, get_markets_mock: AsyncMock):
        resp = Response()
        resp.status_code = 429
        resp._content = b'{"errors": [{"msg": "Too many requests"}]}'
        get_markets_mock.return_value = DydxApiError(resp)

        self.async_run_with_timeout(self.exchange._update_funding_rates())

        self.check_is_logged(log_level="NETWORK", message="Rate-limit error.")
Beispiel #44
0
def fake_request(*args, **kwargs):
    # FIXME: Replace with responses
    r = Response()
    r.status_code = 200

    try:
        _token = kwargs["headers"]["Authorization"]
    except KeyError:
        r._content = b'{"shoe_size": 10}'  # type: ignore
    else:
        _token = _token[7:]
        if _token == "abcdef":
            r._content = b'{"shoe_size": 11}'  # type: ignore
        else:
            r._content = b'{"shoe_size": 12}'  # type: ignore

    r.headers = {"content-type": "application/json"}
    return r
Beispiel #45
0
    def test_update_funding_fails_on_other_dydx_api_error(self, get_markets_mock: AsyncMock):
        resp = Response()
        resp.status_code = 430
        resp._content = b'{"errors": [{"msg": "Some other dydx API error."}]}'
        get_markets_mock.return_value = DydxApiError(resp)

        self.async_run_with_timeout(self.exchange._update_funding_rates())

        self.check_is_logged(log_level="NETWORK", message="dYdX API error.")
Beispiel #46
0
 def test_view(self, mock):
     resp = Response()
     resp.status_code = 200
     resp._content = json.dumps([{
         'reference': 1,
     }])
     mock.return_value = resp
     self.should_redirect_to_login_when_anonymous()
     self.is_callable(self.user)
Beispiel #47
0
    def test_get_recursive(self, mock_requests_request):
        result_one = Response()
        result_one.status_code = 200
        result_one._content = str.encode(
            '{"data": '
            '[{"type": "test", "id": "abc"}], '
            '"meta": {"total": 2}, '
            '"links": {"next": "https://api.exonet.nl/next_page"}'
            "}")

        result_two = Response()
        result_two.status_code = 200
        result_two._content = str.encode('{"data": '
                                         '[{"type": "test", "id": "def"}], '
                                         '"meta": {"total": 2}, '
                                         '"links": {"next": null}'
                                         "}")

        request_result = [result_one, result_two]
        mock_requests_request.side_effect = request_result

        self.request_builder.get_recursive()
        mock_requests_request.assert_any_call(
            "GET",
            "https://api.exonet.nl/things",
            headers={
                "Accept": "application/vnd.Exonet.v1+json",
                "Content-Type": "application/json",
                "Authorization": "Bearer None",
            },
            json=None,
            params={},
        )
        mock_requests_request.assert_any_call(
            "GET",
            "https://api.exonet.nl/next_page",
            headers={
                "Accept": "application/vnd.Exonet.v1+json",
                "Content-Type": "application/json",
                "Authorization": "Bearer None",
            },
            json=None,
            params=None,
        )
def test_aggregated_list_rest(
        transport: str = "rest",
        request_type=compute.AggregatedListAcceleratorTypesRequest):
    client = AcceleratorTypesClient(
        credentials=ga_credentials.AnonymousCredentials(),
        transport=transport,
    )

    # Everything is optional in proto3 as far as the runtime is concerned,
    # and we are mocking out the actual API, so just send an empty request.
    request = request_type()

    # Mock the http request call within the method and fake a response.
    with mock.patch.object(Session, "request") as req:
        # Designate an appropriate value for the returned response.
        return_value = compute.AcceleratorTypeAggregatedList(
            id="id_value",
            items={
                "key_value":
                compute.AcceleratorTypesScopedList(accelerator_types=[
                    compute.AcceleratorType(
                        creation_timestamp="creation_timestamp_value")
                ])
            },
            kind="kind_value",
            next_page_token="next_page_token_value",
            self_link="self_link_value",
            unreachables=["unreachables_value"],
            warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED),
        )

        # Wrap the value into a proper Response obj
        json_return_value = compute.AcceleratorTypeAggregatedList.to_json(
            return_value)
        response_value = Response()
        response_value.status_code = 200
        response_value._content = json_return_value.encode("UTF-8")
        req.return_value = response_value
        response = client.aggregated_list(request)

    # Establish that the response is the type that we expect.
    assert isinstance(response, pagers.AggregatedListPager)
    assert response.id == "id_value"
    assert response.items == {
        "key_value":
        compute.AcceleratorTypesScopedList(accelerator_types=[
            compute.AcceleratorType(
                creation_timestamp="creation_timestamp_value")
        ])
    }
    assert response.kind == "kind_value"
    assert response.next_page_token == "next_page_token_value"
    assert response.self_link == "self_link_value"
    assert response.unreachables == ["unreachables_value"]
    assert response.warning == compute.Warning(
        code=compute.Warning.Code.CLEANUP_FAILED)
 def side_effect(url, stream=False):
     response = Response()
     response.status_code = 200
     response._content_consumed = True
     if 'bulkdata' in url:
         response._content = """
         <CFRDOC>
             <AMDDATE>Jan 1, 2001</AMDDATE>
             <PARTS>Part 111 to 222</PARTS>
             %s
             %s
         </CFRDOC>""" % (pt111, pt112)
     elif url.endswith('part111.xml'):
         response._content = pt111
     elif url.endswith('part112.xml'):
         response._content = pt112
     else:
         response.status_code = 404
     return response
Beispiel #50
0
def test_send_message_json_OK(mock_send):
    svc = OnapService()
    mocked_response = Response()
    mocked_response._content = b'{"yolo": "yala"}'
    mocked_response.encoding = "UTF-8"
    mocked_response.status_code = 200
    mock_send.return_value = mocked_response
    response = svc.send_message_json("GET", 'test get', 'http://my.url/')
    mock_send.assert_called_once_with("GET", 'test get', 'http://my.url/')
    assert response['yolo'] == 'yala'
Beispiel #51
0
def make_response(content: dict = None,
                  dumped_data: str = None,
                  status_code: int = 200,
                  reason: str = "OK") -> Response:
    response_obj = Response()
    response_obj.status_code = status_code
    response_obj._content = dumped_data if dumped_data else dump_any_dict(
        content).encode()
    response_obj.reason = reason
    return response_obj
Beispiel #52
0
 def get(self, method, url, *a, **kw):
     assert method == "GET"
     assert url == collection_url
     r = Response()
     r.status_code = 200
     assert responses
     r._content = responses.pop().encode("utf-8")
     r.headers["Content-Type"] = "text/calendar"
     r.encoding = "ISO-8859-1"
     return r
Beispiel #53
0
def test_send_message_json_bad_json_no_exception(mock_send):
    svc = OnapService()
    mocked_response = Response()
    mocked_response._content = b'yolo'
    mocked_response.encoding = "UTF-8"
    mocked_response.status_code = 200
    mock_send.return_value = mocked_response
    response = svc.send_message_json("GET", 'test get', 'http://my.url/')
    mock_send.assert_called_once_with("GET", 'test get', 'http://my.url/')
    assert response == {}
Beispiel #54
0
 def test_page_handler_is_called_for_json(self, *_):
     """Assert page handler is called when json without a task."""
     response = Response()
     response.status_code = 201
     response._content = b'{"foo": "1234"}'
     response.headers["Content-Type"] = "application/json"
     with mock.patch.object(api, "page_handler",
                            lambda *_: "page_handler_called"):
         self.assertEqual(api.smart_handler(self.client, response),
                          "page_handler_called")
Beispiel #55
0
 def test_task_handler_is_called_for_tasks(self, *_):
     """Assert task handler is called when 202 with task is response."""
     response = Response()
     response.status_code = 202
     response._content = b'{"task": "1234"}'
     response.headers["Content-Type"] = "application/json"
     with mock.patch.object(api, "task_handler",
                            lambda *_: "task_handler_called"):
         self.assertEqual(api.smart_handler(self.client, response),
                          "task_handler_called")
Beispiel #56
0
 def list(self, ctx):
     response = Response()
     response.status_code = 200
     res = []
     for __theme in available_themes:
         t1 = {"theme": __theme}
         res.append(t1)
     t = {"list": res}
     response._content = json.dumps(t).encode('utf-8')
     return response
Beispiel #57
0
 def ctms_error(self, status_code, detail, reason):
     """Return a CTMS error response"""
     response = Response()
     response.status_code = status_code
     response._content = json.dumps({"detail": detail})
     if reason:
         response.reason = reason
     error = HTTPError()
     error.response = response
     return error
Beispiel #58
0
 def get(self, method, url, *a, **kw):
     assert method == 'GET'
     assert url == collection_url
     r = Response()
     r.status_code = 200
     assert responses
     r._content = responses.pop().encode('utf-8')
     r.headers['Content-Type'] = 'text/icalendar'
     r.encoding = 'ISO-8859-1'
     return r
Beispiel #59
0
    def mock_session_get(self, url: str) -> Response:
        # pylint: disable=W0212(protected-access)
        # pylint: disable=W0613(unused-argument)
        print(f"Mocking get for URL: {url}")
        response = Response()
        response.status_code = 200
        response.url = expected_url
        response._content = expected_content

        return response
Beispiel #60
0
    def _mock_get(self, endpoint: str, *args, **kwargs) -> Response:
        from tests.test_srvs import django_srv

        response = Response()

        data: Dict[str, Dict[str, str]] = handle_requests.get_data(django_srv.root)
        response._content = json.dumps(data)

        response.status_code = 200
        return response