Test a request handler against one of its own request/response examples.
773599
function (baseUrl, method, handler, example, callback) {
    baseUrl = baseUrl || 'http://localhost';

    var client = null;
    var results = {
      failed: [],
      passed: []
    };
    var self = this;
    var testUrl = url.parse(String(baseUrl));
    testUrl.pathname = normalizePath(self.path, testUrl.pathname);
    testUrl = url.parse(url.format(testUrl));
    switch (testUrl.protocol) {
      case 'https:':
        client = https;
        break;
      case 'http:':
        client = http;
        break;
      default:
        var error = new Error('Invalid base site: ' + baseUrl +
          ' (should start with "http://" or "https://")');
        callback(error, results);
        return;
    }

    var beforeEachTest = self.beforeEachTest || function (next) { next(); };
    if (typeof beforeEachTest !== 'function') {
      callback(new Error('"beforeEachTest" should be a function'), results);
      return;
    }

    var afterEachTest = self.afterEachTest || function (next) { next(); };
    if (typeof afterEachTest !== 'function') {
      callback(new Error('"afterEachTest" should be a function'), results);
      return;
    }

    var requestOptions = {
      hostname: testUrl.hostname,
      port: testUrl.port,
      path: testUrl.pathname,
      method: method
    };

    var exampleRequest = example.request || {};
    var exampleResponse = example.response || {};

    if (exampleRequest.urlParameters) {
      requestOptions.path = replaceUrlParameters(requestOptions.path,
        exampleRequest.urlParameters);
    }

    if (exampleRequest.queryParameters) {
      var queryPairs = [];
      for (var queryParameter in exampleRequest.queryParameters) {
        var queryValue = exampleRequest.queryParameters[queryParameter];
        queryPairs.push(encodeURIComponent(queryParameter) +
          (queryValue ? '=' + encodeURIComponent(queryValue) : ''));
      }
      requestOptions.path += '?' + queryPairs.join('&');
    }

    if (exampleRequest.headers) {
      requestOptions.headers = exampleRequest.headers;
    }

    var summary = {
      handler: handler.title || '(no title)',
      method: requestOptions.method,
      uri: requestOptions.path,
      request: exampleRequest
    };

    beforeEachTest(function (error) {
      if (error) {
        callback(error, results);
        return;
      }

      var request = client.request(requestOptions, function (response) {
        var success = true;

        var expectedStatusCode = (typeof exampleResponse.status === 'function'
          ? exampleResponse.status
          : function (statusCode) {
            return statusCode === (exampleResponse.status || 200);
          });
        if (!expectedStatusCode(response.statusCode)) {
          success = false;
        }

        var expectedHeaders = null;
        if (exampleResponse.headers) {
          expectedHeaders = exampleResponse.headers;
          for (var header in expectedHeaders) {
            var headerValue = expectedHeaders[header];
            var expectedHeaderValue = (typeof headerValue === 'function'
              ? headerValue
              : function (value) {
                return value === headerValue;
              });
            if (!expectedHeaderValue(response.headers[header.toLowerCase()])) {
              success = false;
              break;
            }
          }
        }

        var expectedBody = null;
        if ('body' in exampleResponse) {
          var exampleBody = exampleResponse.body;
          expectedBody = (typeof exampleBody === 'function'
            ? exampleBody
            : function (body) {
              return body === jsonStringifyIfObject(exampleBody).trim();
            });
        }

        var body = '';
        response.on('data', function (chunk) {
          body += String(chunk);
        });

        response.on('end', function () {
          clearTimeout(timeout);
          body = body.trim();
          if (expectedBody !== null && !expectedBody(body)) {
            success = false;
          }
          if (success) {
            summary.response = exampleResponse;
            results.passed.push(summary);
            afterEachTest(function (error) {
              callback(error, results);
            });
            return;
          }
          summary.expectedResponse = exampleResponse;
          summary.actualResponse = {
            status: response.statusCode
          };
          if (expectedHeaders !== null) {
            summary.actualResponse.headers = response.headers;
          }
          if (expectedBody !== null) {
            summary.actualResponse.body = body;
          }
          results.failed.push(summary);
          afterEachTest(function (error) {
            callback(error, results);
          });
        });
      });

      request.on('error', function (error) {
        clearTimeout(timeout);
        summary.expectedResponse = exampleResponse;
        summary.actualResponse = {
          error: error.message || String(error)
        };
        results.failed.push(summary);
        afterEachTest(function (error) {
          callback(error, results);
        });
      });

      // Abort requests that take longer than 10 seconds.
      var timeout = setTimeout(function () {
        request.emit('error', new Error('timed out'));
      }, 10000);

      if ('body' in exampleRequest) {
        request.write(jsonStringifyIfObject(exampleRequest.body));
      }
      request.end();
    });
  }
1016432
def handle_single_request(self, request_object):
        
        if not isinstance(request_object, (MethodCall, Notification)):
            raise TypeError("Invalid type for request_object")

        method_name = request_object.method_name
        params = request_object.params
        req_id = request_object.id

        request_body = self.build_request_body(method_name, params, id=req_id)
        http_request = self.build_http_request_obj(request_body)

        try:
            response = urllib.request.urlopen(http_request)
        except urllib.request.HTTPError as e:
            raise CalledServiceError(e)

        if not req_id:
            return

        response_body = json.loads(response.read().decode())
        return response_body
689055
def error_handling(cls, fn):
        """"""
        def wrapper(*args, **kwargs):
            try:
                result = fn(*args, **kwargs)
                return result
            except InvalidRequestError as e:
                write_exception(e)

                if hasattr(e, 'request'):
                    write_error_message('request {0}'.format(repr(e.request)))
                if hasattr(e, 'response'):
                    write_error_message('response {0}'.format(repr(e.response)))

                raise e
        return wrapper
946540
private <T> HttpResponseHandler<T> getNonNullResponseHandler(
            HttpResponseHandler<T> responseHandler) {
        if (responseHandler != null) {
            return responseHandler;
        } else {
            // Return a Dummy, No-Op handler
            return new HttpResponseHandler<T>() {

                @Override
                public T handle(HttpResponse response) throws Exception {
                    return null;
                }

                @Override
                public boolean needsConnectionLeftOpen() {
                    return false;
                }
            };
        }
    }
644138
function(url) {
            if (url == null) return this;
            if (url.length > 0 && url[0] == "/") {
                url = url.replace("/", "");
            }
            var matched = _.any(this.handlers, function(handler) {
                if (handler.route.test(url)) {
                    handler.callback(url);
                    return true;
                }
                return false;
            });
            logging.log("handle state ", url, matched != null);
            return matched;
        }
600901
def process_request(self):
        """"""
        self.response = self.request_handler.process_request(
            self.method, self.request_data)
1061044
def CallApiHandler(handler, args, token=None):
    """"""

    result = handler.Handle(args, token=token)

    expected_type = handler.result_type
    if expected_type is None:
      expected_type = None.__class__

    if result.__class__ != expected_type:
      raise UnexpectedResultTypeError(
          "Expected %s, but got %s." %
          (expected_type.__name__, result.__class__.__name__))

    return result
715900
def get_handler(self, request):
        
        try:
            f = self._json_rpc_methods[request.method]

        except (AttributeError, KeyError):  # pragma no coverage
            raise RPCMethodError("Received invalid method '{}'".format(request.method))

        return f
352167
def use(klass, *args, &block)
      request_handler   = "#{klass.name}::RequestHandler".safe_constantize
      response_handler  = "#{klass.name}::ResponseHandler".safe_constantize
      exception_handler = "#{klass.name}::ExceptionHandler".safe_constantize

      request_handlers   << request_handler.new(*args, &block) if request_handler
      response_handlers  << response_handler.new(*args, &block) if response_handler
      exception_handlers << exception_handler.new(*args, &block) if exception_handler
    end
562228
def handler(self, environ, start_response):
        """"""

        if environ['REQUEST_METHOD'] == 'POST':
            return self.handle_POST(environ, start_response)
        else:
            start_response("400 Bad request", [('Content-Type', 'text/plain')])
            return ['']
1202475
def _request(self, url, **kwargs):
        '''
        '''
        if self.method is None:
            raise NotImplementedError('method must be defined on a subclass')
        response = requests.request(self.method, url, **kwargs)
        return self.response_class(response, sender=self)
1188545
function( handler ) {
		var hooks = [];

		// Hooks are ignored on skipped tests
		if ( this.skip ) {
			return hooks;
		}

		if ( this.module.testEnvironment &&
				QUnit.objectType( this.module.testEnvironment[ handler ] ) === "function" ) {
			hooks.push( this.queueHook( this.module.testEnvironment[ handler ], handler ) );
		}

		return hooks;
	}
1281776
function handleRequest(middleware, handlers, mode, checkArity, req, res, errorHandler) {
  const done = err => err && setImmediate(errorHandler, err, req, res);
  // run global middleware first, then start handling request
  // this is important to allow loggers for example to kick-in regardless
  runMiddlewareStack(middleware, req, res, (err) => {
    if (err) {
      done(err);
      return;
    }
    // try to apply supplied handlers to the requested operation
    handleOperation(handlers, mode, checkArity, req, res, done);
  });
}
1374735
def _process_response(self, response, object_mapping=None):
        
        try:
            pretty_response = response.json()
        except ValueError:
            pretty_response = response
        for handler in self._response_handlers:
            if handler.applies_to(self, response):
                log.debug("{} matched: {}".format(handler.__name__, pretty_response))
                r = handler(self, object_mapping).build(response)
                self._clean_dirty_objects()
                return r
        raise ZenpyException("Could not handle response: {}".format(pretty_response))
822615
def _handle_api(self, handler, handler_args, handler_kwargs):
        
        try:
            status_code, return_value = handler(*handler_args, **handler_kwargs)
        except APIError as error:
            return error.send()

        web.ctx.status = _convert_http_status(status_code)
        return _api_convert_output(return_value)
480342
def add_request_handler(self, request_handler):
        # type: (AbstractRequestHandler) -> None
        
        if request_handler is None:
            raise RuntimeConfigException(
                "Valid Request Handler instance to be provided")

        if not isinstance(request_handler, AbstractRequestHandler):
            raise RuntimeConfigException(
                "Input should be a RequestHandler instance")

        self.request_handler_chains.append(GenericRequestHandlerChain(
            request_handler=request_handler))
576483
function requestHandler (method) {
  return function (req, res, next) {
    method.call(this, req, responseHandler(res, next));
  }.bind(this);
}