WireMock-Net / WireMock.Net

WireMock.Net is a flexible product for stubbing and mocking web HTTP responses using advanced request matching and response templating. Based on the functionality from http://WireMock.org, but extended with more functionality.
Apache License 2.0
1.35k stars 197 forks source link

How to get a Random Long? #1033

Closed felipetofoli closed 6 months ago

felipetofoli commented 6 months ago

How to get a Random Long?

I tried this implementation: "{{Random Type=\"Long\" Min=1000000000 Max=9999999999}}", but I am getting an error, even though 1000000000 and 9999999999 are valid Int64 numbers.

Is this handlebar expression correct? Or do we have a bug when generating Random long numbers?

Following are more details.

Implementation

 var settings = new WireMockServerSettings
{
    AllowPartialMapping = true,
    StartAdminInterface = true,
    Urls = new[] { "http://localhost:3000/", },
    Logger = new WireMockConsoleLogger(),
};

var server = StandAloneApp.Start(settings);

server
    .Given(Request.Create()
        .WithPath(new ExactMatcher("/"))
        .UsingGet())
    .RespondWith(Response.Create()
        .WithStatusCode(200)
        .WithHeader("Content-Type", "application/json")
        .WithBodyAsJson(new
        {
            id = "{{Random Type=\"Long\" Min=1000000000 Max=9999999999}}",
        })
        .WithTransformer());

Console.WriteLine("Press any key to stop the server");
Console.ReadKey();

Response (error)

HTTP/1.1 500 Internal Server Error
Content-Type: application/json
Date: Fri, 08 Dec 2023 16:36:45 GMT
Server: Kestrel
Transfer-Encoding: chunked

{"Status":"Object of type 'System.String' cannot be converted to type 'System.Int64'."}

Logs

08/12/2023 16:41:03 [Info] : By Stef Heyenrath (https://github.com/WireMock-Net/WireMock.Net)
08/12/2023 16:41:03 [Debug] : Server settings {
  "Port": null,
  "UseSSL": null,
  "HostingScheme": null,
  "StartAdminInterface": true,
  "ReadStaticMappings": null,
  "WatchStaticMappings": null,
  "WatchStaticMappingsInSubdirectories": null,
  "ProxyAndRecordSettings": null,
  "Urls": [
    "http://localhost:3000/"
  ],
  "StartTimeout": 10000,
  "AllowPartialMapping": true,
  "AdminUsername": null,
  "AdminPassword": null,
  "AdminAzureADTenant": null,
  "AdminAzureADAudience": null,
  "RequestLogExpirationDuration": null,
  "MaxRequestLogCount": null,
  "CorsPolicyOptions": null,
  "AllowCSharpCodeMatcher": null,
  "AllowBodyForAllHttpMethods": null,
  "AllowOnlyDefinedHttpStatusCodeInResponse": null,
  "DisableJsonBodyParsing": null,
  "DisableRequestBodyDecompressing": null,
  "DisableDeserializeFormUrlEncoded": null,
  "HandleRequestsSynchronously": null,
  "CertificateSettings": null,
  "CustomCertificateDefined": false,
  "ClientCertificateMode": 0,
  "AcceptAnyClientCertificate": false,
  "WebhookSettings": null,
  "UseRegexExtended": true,
  "SaveUnmatchedRequests": null,
  "DoNotSaveDynamicResponseInLogEntry": null,
  "QueryParameterMultipleValueSupport": null
}
08/12/2023 16:41:04 [Info] : Server using .NET 6.0
08/12/2023 16:41:04 [Info] : AllowPartialMapping is set to True
08/12/2023 16:41:04 [Info] : Version [1.5.41.0]
08/12/2023 16:41:04 [Info] : Server listening at http://localhost:3000
Press any key to stop the server
08/12/2023 16:41:08 [Error] : Providing a Response for Mapping '5376449f-29f8-4686-8fb8-e13e328082ba' failed. HttpStatusCode set to 500. Exception: System.ArgumentException: Object of type 'System.String' cannot be converted to type 'System.Int64'.
   at HandlebarsDotNet.Helpers.HandlebarsHelpers.InvokeMethod(Nullable`1 model, Boolean methodIsOnlyUsedInContextOfABlockHelper, IHandlebars context, String helperName, MethodInfo methodInfo, Arguments arguments, Object instance, IHelperOptions options)
   at HandlebarsDotNet.Helpers.HandlebarsHelpers.<>c__DisplayClass8_0.<RegisterValueHelper>b__0(HelperOptions& options, Context& context, Arguments& arguments)
   at HandlebarsDotNet.Helpers.DelegateReturnHelperWithOptionsDescriptor.HandlebarsDotNet.Helpers.IHelperDescriptor<HandlebarsDotNet.HelperOptions>.Invoke(EncodedTextWriter& output, HelperOptions& options, Context& context, Arguments& arguments)
   at lambda_method37(Closure , EncodedTextWriter& , BindingContext )
   at HandlebarsDotNet.HandlebarsEnvironment.<>c__DisplayClass19_0.<Compile>b__0(TextWriter writer, Object context, Object data)
   at HandlebarsDotNet.HandlebarsEnvironment.<>c__DisplayClass20_0.<Compile>b__0(Object context, Object data)
   at WireMock.Transformers.Handlebars.HandlebarsContext.ParseAndEvaluate(String text, Object model)
   at WireMock.Transformers.Transformer.WalkNode(ITransformerContext transformerContext, ReplaceNodeOptions options, JToken node, Object model)
   at WireMock.Transformers.Transformer.WalkNode(ITransformerContext transformerContext, ReplaceNodeOptions options, JToken node, Object model)
   at WireMock.Transformers.Transformer.TransformBodyAsJson(ITransformerContext transformerContext, ReplaceNodeOptions options, Object model, IBodyData original)
   at WireMock.Transformers.Transformer.TransformBodyData(ITransformerContext transformerContext, ReplaceNodeOptions options, TransformModel model, IBodyData original, Boolean useTransformerForBodyAsFile)
   at WireMock.Transformers.Transformer.Transform(IMapping mapping, IRequestMessage requestMessage, IResponseMessage original, Boolean useTransformerForBodyAsFile, ReplaceNodeOptions options)
   at WireMock.ResponseBuilders.Response.ProvideResponseAsync(IMapping mapping, IRequestMessage requestMessage, WireMockServerSettings settings)
   at WireMock.Owin.WireMockMiddleware.InvokeInternalAsync(HttpContext ctx)
08/12/2023 16:41:08 [DebugRequestResponse] : Admin[False] {
  "Guid": "e9362a3c-d993-4d0c-bd39-452998c629e7",
  "Request": {
    "ClientIP": "::1",
    "DateTime": "2023-12-08T16:41:07.6321922Z",
    "Path": "/",
    "AbsolutePath": "/",
    "Url": "http://localhost:3000/",
    "AbsoluteUrl": "http://localhost:3000/",
    "ProxyUrl": null,
    "Query": {},
    "Method": "GET",
    "Headers": {
      "Accept": [
        "*/*"
      ],
      "Connection": [
        "keep-alive"
      ],
      "Host": [
        "localhost:3000"
      ],
      "User-Agent": [
        "PostmanRuntime/7.35.0"
      ],
      "Accept-Encoding": [
        "gzip, deflate, br"
      ],
      "Cache-Control": [
        "no-cache"
      ],
      "Postman-Token": [
        "26af13e8-28d3-4842-8e02-1b0cbeec3fd8"
      ]
    },
    "Cookies": {},
    "Body": null,
    "BodyAsJson": null,
    "BodyAsBytes": null,
    "BodyEncoding": null,
    "DetectedBodyType": null,
    "DetectedBodyTypeFromContentType": null
  },
  "Response": {
    "StatusCode": 500,
    "Headers": {
      "Content-Type": [
        "application/json"
      ]
    },
    "BodyDestination": null,
    "Body": null,
    "BodyAsJson": {
      "Guid": null,
      "Status": "Object of type 'System.String' cannot be converted to type 'System.Int64'.",
      "Error": null
    },
    "BodyAsBytes": null,
    "BodyAsFile": null,
    "BodyAsFileIsCached": null,
    "BodyOriginal": null,
    "BodyEncoding": null,
    "DetectedBodyType": 2,
    "DetectedBodyTypeFromContentType": null,
    "FaultType": null,
    "FaultPercentage": null
  },
  "MappingGuid": "5376449f-29f8-4686-8fb8-e13e328082ba",
  "MappingTitle": null,
  "RequestMatchResult": {
    "TotalScore": 2.0,
    "TotalNumber": 2,
    "IsPerfectMatch": true,
    "AverageTotalScore": 1.0,
    "MatchDetails": [
      {
        "Name": "PathMatcher",
        "Score": 1.0
      },
      {
        "Name": "MethodMatcher",
        "Score": 1.0
      }
    ]
  },
  "PartialMappingGuid": "5376449f-29f8-4686-8fb8-e13e328082ba",
  "PartialMappingTitle": null,
  "PartialRequestMatchResult": {
    "TotalScore": 2.0,
    "TotalNumber": 2,
    "IsPerfectMatch": true,
    "AverageTotalScore": 1.0,
    "MatchDetails": [
      {
        "Name": "PathMatcher",
        "Score": 1.0
      },
      {
        "Name": "MethodMatcher",
        "Score": 1.0
      }
    ]
  }
}

Please, let me know if you need any other information. Thanks.

StefH commented 6 months ago

it's a bug in Handlebars : https://github.com/Handlebars-Net/Handlebars.Net/pull/562

I'll check if I can build a workaround in wiremock

StefH commented 6 months ago

https://github.com/WireMock-Net/WireMock.Net/pull/1034

StefH commented 6 months ago

Solved in new version

felipetofoli commented 6 months ago

Thanks!