Test the API using its own request/response examples.
503644
function (baseUrl, callback) {
    callback = callback || function (error, results) {
      if (error) {
        console.error.apply(console,
          error.stack ? [ error.stack ] : [ 'Error:', error ]);
      }
      var total = results.passed.length + results.failed.length;
      console.log('Results: ' + results.passed.length + '/' + total + ' test' +
        (total === 1 ? '' : 's') + ' passed.');
      if (results.failed.length > 0) {
        console.error('Failed:', jsonStringifyWithFunctions(results.failed));
      }
    };

    var results = {
      failed: [],
      passed: []
    };

    this.exportAllTests(baseUrl, function runNextTest (tests) {
      if (tests.length === 0) {
        callback(null, results);
        return;
      }

      var i = Math.floor(Math.random() * tests.length);
      var test = tests.splice(i, 1)[0];
      test(function (error, testResults) {
        if (testResults) {
          results.failed = results.failed.concat(testResults.failed);
          results.passed = results.passed.concat(testResults.passed);
        }
        if (error) {
          callback(error, results);
          return;
        }
        runNextTest(tests);
      });
    });
  }
178754
def _request(self, method, endpoint, id=None, **kwargs):
        ""
        request = getattr(requests, method, None)
        if not callable(request):
            raise RequestError('Invalid method %s' % method)
        # Find files, separate them out to correct kwarg for requests.
        data = kwargs.get('data')
        if data:
            files = {}
            for name, value in list(data.items()):
                # Value might be a file-like object (with a read method), or it
                # might be a (filename, file-like) tuple.
                if hasattr(value, 'read') or isinstance(value, tuple):
                    files[name] = data.pop(name)
            if files:
                kwargs.setdefault('files', {}).update(files)
        path = ['api', self.version, endpoint]
        # If we received an ID, append it to the path.
        if id:
            path.append(str(id))
        # Join fragments into a URL
        path = '/'.join(path)
        if not path.endswith('/'):
            path += '/'
        while '//' in path:
            path = path.replace('//', '/')
        url = self.url + path
        # Add our user agent.
        kwargs.setdefault('headers', {}).setdefault('User-Agent',
                                                    HTTP_USER_AGENT)
        # Now try the request, if we get throttled, sleep and try again.
        trys, retrys = 0, 3
        while True:
            if trys == retrys:
                raise RequestError('Could not complete request after %s trys.'
                                   % trys)
            trys += 1
            try:
                return self._do_request(request, url, **kwargs)
            except ResponseError as e:
                if self.throttle_wait and e.status_code == 503:
                    m = THROTTLE_PATTERN.match(
                        e.response.headers.get('x-throttle', ''))
                    if m:
                        time.sleep(float(m.group(1)))
                        continue
                # Failed for a reason other than throttling.
                raise
481471
def _make_request(self, request):
        
        # TODO: I'm sure all kinds of error checking needs to go here
        try:
            response_raw = urllib2.urlopen(request)
        except urllib2.HTTPError, e:
            print e.read()
            raise

        response_str = response_raw.read()
        response = json.loads(response_str)

        self._last_request = request
        self._last_response = response_raw
        self._last_response_str = response_str
        return response
1124770
function reqres(res, req) {
    if (req && req._headers) {
        throw new Error('Received response object where request object was expected');
    }
    this.res = res;
    this.req = req;
    if (res) {
        if (res.$ && res.$.data) {
            this.data = res.$.data;
        }
        else {
            this.data = { error: null };
            if (!res.$) {
                res.$ = this;
            }
        }
    }
}
335172
def execute(self, requests, resp_generator, *args, **kwargs):
        '''
            
        '''
        return [resp_generator(request) for request in requests]
757151
def do_request(method, url, options = {})
      begin
        response = self.class.send(method, api_url(url), options)
        check_response_codes(response)
        response.parsed_response
      rescue Timeout::Error
        raise Unavailable.new('Service Unavailable')
      end
    end
1373621
def request_examples(self, attack_config, criteria, run_counts, batch_size):
    
    raise NotImplementedError(str(type(self)) +
                              "needs to implement request_examples")
1104833
def _make_request(
            self, api_resource, method='GET', params=None, **kwargs):
        
        if kwargs.get('json'):
            headers = {
                'Authorization': 'Bearer {}'.format(self._token),
                'Content-Type': 'application/json'
            }
        else:
            headers = {
                'Authorization': 'Bearer {}'.format(self._token)
            }

        response = requests.request(
            method=method,
            url='{0}{1}'.format(self.BASE_API_URL, api_resource),
            headers=headers,
            params=params,
            **kwargs
        )

        if response.status_code >= 400:
            error_response = response.json()

            raise(ToshlException(
                status_code=response.status_code,
                error_id=error_response['error_id'],
                error_description=error_response['description'],
                extra_info=error_response.get('fields')))

        return response
315665
def _call(self, method, url, params):
        """"""
        request_params = {}
        if method == 'GET':
            request_params['params'] = params
        elif method == 'POST':
            request_params['data'] = params
        response = requests.request(method, url, **request_params)
        return response
998452
def check_response(response):
    
    if response.status_code < 200 or response.status_code > 300:
        raise ServerError('API requests returned with error: %s'
                          % response.status_code)

    try:
        response_text = loads(response.text)
    except ValueError:
        raise ServerError('The API did not returned a JSON string.')

    if not response_text:
        raise EmptyResponse()

    if 'failure' in response_text:
        if response_text['failure'] == 'Falscher Dateityp':
            raise UnsupportedFormat('Please look at picflash.org '
                                    'witch formats are supported')
        else:
            raise UnkownError(response_text['failure'])
934654
def validate():
    ''''''
    with current_app.test_request_context():
        schema = json.loads(json.dumps(api.__schema__))
    try:
        schemas.validate(schema)
        success('API specifications are valid')
    except schemas.SchemaValidationError as e:
        exit_with_error('API specifications are not valid', e)
858624
def _get_request(url_root,api_key,path,response_type,params, ssl_verify):
    
    url = _url_builder(url_root,api_key,path,params)
    content = _fetch(url, ssl_verify)
    response = _dispatch(response_type)(content)
    return response
1182353
def __make_request_method(self, teststep_dict, entry_json):
        
        method = entry_json["request"].get("method")
        if not method:
            logging.exception("method missed in request.")
            sys.exit(1)

        teststep_dict["request"]["method"] = method
218467
function main (url, configs, responseType = 'json') {
  let retryOptions = {
    retries: configs.retries
  }

  let fetchOptions = {
    headers,
    timeout: configs.timeout,
    agent: proxy(configs.proxy)
  }

  return pRetry(function () {
    return fetch(url, fetchOptions).then(response => {
      return responseType === 'json' ? response.json() : response.text()
    })
  }, retryOptions)
}
846247
def run
      if response.is_a? @expected_response
        self.class.on_response.call(self, response)
        response.tap do
          parse_response!
        end
      else
        raise HTTPError.new(error_message, response: response)
      end
    end
862137
def request(self, method, uri, **kw):
        
        expect = kw.pop("expect", [])
        mime_body = kw.pop("mime_body", None)

        headers = kw.pop("headers", {})
        data = kw.pop("data", None)

        if mime_body:
            mimevalues = self.mimeobjects.get(mime_body.__class__)

            if not mimevalues:
                raise ClientException(
                    ("Cannot handle object of type "
                     "{0!r}").format(mime_body.__class__))

            mapping = mimevalues[0]

            document_type, mimetype, validator = mapping

            data = document_type.render(validator, mime_body)
            headers["Content-Type"] = mimetype

        if uri[0] != '/':
            uri = '/' + uri

        url = "{self.scheme}://{self.host}{uri}".format(self=self, uri=uri)

        response = self.session.request(
            method, url,
            headers=headers,
            data=data,
            **kw)

        content_type = response.headers.get("Content-Type")

        if content_type is None or not response.content:
            return response, None

        mimetype, opts = werkzeug.http.parse_options_header(content_type)

        if mimetype not in self.mimetypes:
            raise ClientException(
                "Cannot handle response type: {0}".format(mimetype))

        document_type, document_class, validator = self.mimetypes.get(mimetype)

        if expect and document_class not in expect:
            raise ClientException(
                "Unexpected response type: {0}".format(mimetype))

        try:
            obj = document_type.parse(validator,
                                      document_class,
                                      response.content)
        except MimeValidationError as e:
            raise ClientException(
                "Response format invalid: {0}".format(str(e)))
        except:
            log.error(
                "Failed to parse content of type: {0}".format(mimetype),
                exc_info=sys.exc_info())
            raise ClientException(
                "Failed to parse content of type: {0}".format(mimetype))

        return response, obj
635450
def api_call(self, opts, args=None, body=None, **kwargs):
        """"""
        if args:
            path = opts['name'] % args
        else:
            path = opts['name']
        path = '/api/v1%s' % path
        return self._request(
            opts['method'], path=path, payload=body, **kwargs)