MockOgHrefClient.advance constructor

MockOgHrefClient.advance(
  1. Map<Uri, MockOgHrefClientContent> contentLinker, {
  2. String errorContentType = _PLAIN_TEXT_MIME,
})

Define new replicated Client for executing under test environment.

All expected content in specific links should be stored into contentLinker which is a Map with Uri key and MockOgHrefClientContent as a value which denotes expected content and content type when "surfing" URL. If the incoming Request.url can be found in contentLinker, the returned Response will provided content of the Uri in status code 200 and 404 when no Uri mapped. However, it returns HTTP status 400 if the incoming Request.method is neither GET nor HEAD.

Moreover, every Uri mapped in contentLinker MUST BE used HTTP(S) protocol. If at least one Uri.scheme return other than HTTP(S), it throws ArgumentError.

See also

  • MockOgHrefClient.quick : Quick builder version of MockOgHrefClient that Uris are mapping with String content with unified content type.

Implementation

MockOgHrefClient.advance(Map<Uri, MockOgHrefClientContent> contentLinker,
    {String errorContentType = _PLAIN_TEXT_MIME}) {
  if (contentLinker.keys.any((element) => !_isHttpScheme(element))) {
    throw ArgumentError(
        "Content linker's URL must be assigned with HTTP(S) scheme.");
  }

  _c = MockClient((request) {
    final Map<Uri, MockOgHrefClientContent> ctxLinker =
        Map.unmodifiable(contentLinker);

    Uri incomingUrl = request.url;

    if (!_isHttpScheme(incomingUrl)) {
      throw ClientException(
          "The request should be HTTP(S), eventhough is mock client.");
    }

    return Future.delayed(_generateResponseDelay(), () {
      final Map<String, String> errorHeader = {
        "content-type": errorContentType
      };

      if (!{"GET", "HEAD"}
          .any((element) => element == request.method.toUpperCase())) {
        return Response("", 400, request: request, headers: errorHeader);
      }

      MockOgHrefClientContent? bodyCtx = ctxLinker[incomingUrl];

      if (bodyCtx == null) {
        return Response("", 404, headers: errorHeader, request: request);
      }

      return Response(request.method == "GET" ? bodyCtx.content : "", 200,
          headers: {"content-type": bodyCtx.contentType}, request: request);
    });
  });
}