Giter Site home page Giter Site logo

wiremock-net / wiremock.net Goto Github PK

View Code? Open in Web Editor NEW
1.3K 25.0 194.0 9.74 MB

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.

License: Apache License 2.0

C# 99.96% Batchfile 0.04%
wiremock mock-server http-listener tdd testing mocking mockwebserver csharp dotnet http

wiremock.net's People

Contributors

akamud avatar alastairtree avatar andi0b avatar azure-pipelines[bot] avatar billybraga avatar cezarypiatek avatar davide-romanini avatar dependabot[bot] avatar dmtrrk avatar dreamescaper avatar eli-darkly avatar eseneckiy avatar ggradnig avatar gitfool avatar kashifsoofi avatar leolplex avatar noahlerner avatar paulssn avatar phillee007 avatar rwwilden avatar snyk-bot avatar stefh avatar steveland83 avatar subjectivereality avatar theramis avatar timurnes avatar tlevesque-ueat avatar vitaliydavydiak avatar volodymyr-fed avatar walidhaidarii avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

wiremock.net's Issues

New Feature: Callbacks

How about to add callback support for in-process server?
Or at least observable logging, etc?

SimMetrics.NET error when trying to install NuGet Package

Hi,

I wanted to try this for troubleshooting a development issue, but whatever .NET Framework I choose, installing the package always fails with:

Failed to retrieve information about 'SimMetrics.Net' from remote source 'https://api.nuget.org/v3-flatcontainer/simmetrics.net/index.json'.
Response status code does not indicate success: 504 (Gateway Timeout). 0

Any idea what could be done about this? Is it something I can fix on my end?

Kind regards,
Arwin

New feature request: Access to Owin pipeline

Hey Stef,

We are looking into using WireMock.net for UI tests for one of our products. To give it some context, we have a single page Aurelia Frontend application talking to a backend using WebAPI2.

We serve the frontend files (/index, etc) but we also have /api/xxx where our backend responds.
And /api/signalr, where the signalr connection lives.
All on the same url:port.

We created a POC to provide fake api data to the frontend using WireMock and that works.

We had to do a little bit of "trickery" to be able to still host our frontend files, by making a "StaticResourceResponseProvider" that allows us to server files from disk based on the URI.
So all uri's now go to the StaticResourceResponseProvider, except for /api/, using the regex "^(?!/api/.$).*".

Per UI test we have different Given/RespondWith setups we do based on what /api/xxx calls we expect and require.

If we had access to the Owin pipeline you use inside WireMock.net we could hook this up a bit nicer (and without fonts breaking, due to always being sent as string, instead of bytes with encoding, courtesy of the string Body property in ResponseMessage).

But why we "really" need access to the Owin pipeline is because we also want to hook up SignalR. We cannot use Response.Create().WithProxy as that breaks the SignalR connection. So ideally I would want to register that on the IAppBuilder, such as:

public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
}

We were looking at ways to accomplish this in WireMock.net, but found no readily available paths. One of the (least intrusive) solutions could be if IOwinSelfHost was public and it could be injected as an argument on the Start methods in FluentMockServer. Right now the private constructor there accepts settings and depending on the pragma NETSTANDARD, either AspNetCoreSelfHost or OwinSelfHost is spawned.

I could imagine creating my own implementation of OwinSelfHost where I can setup any Owin components I would like to use.

Or maybe you have a different/better idea, I am open to suggestions.

Issue with launching sample code (StandAlone server)

Dear WireMock team,

there is an issue with launching sample code:
Unhandled Exception: System.TypeLoadException: Could not load type 'WireMock.Settings.FluentMockServerSettings' from assembly 'WireMock.Net, Version=1.0.2.0, Culture=neutral, PublicKeyToken=null'.
at WireMock.Net.StandAlone.StandAloneApp.Start(String[] args)
at WireMock.Net.StandAlone.Program.Main(String[] args)

using System;
namespace WireMock.Net.StandAlone
{
    public class Program
    {
        static void Main(params string[] args)
        {
            StandAloneApp.Start(args);

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

Facing issue with WildcardMatcher and '?'

Hi
I'm building a mock response for the uri...
/config/api/foundation/economic-regions/search?channel=1&brand=2

though the mock is setup... I'm getting response for all characters except ? in the uri.
like,
/config/api/foundation/economic-regions/searchachannel=1&brand=2
/config/api/foundation/economic-regions/search.channel=1&brand=2

From the code here, I see the Regex Replace(@"?", ".")

How do I build the mock for my uri? Please Help.

Handlebar support

  • request.url - URL path and query

  • request.path - URL path

  • request.path.[]- URL path segment (zero indexed) e.g. request.path.[2]

  • request.query.- First value of a query parameter e.g. request.query.search

  • request.query..[]- nth value of a query parameter (zero indexed) e.g. request.query.search.[5]

  • request.headers.- First value of a request header e.g. request.headers.X-Request-Id

  • request.headers.[]- Header with awkward characters e.g. request.headers.[$?blah]

  • request.headers..[]- nth value of a header (zero indexed) e.g. request.headers.ManyThings.[1]

  • request.cookies. - Value of a request cookie e.g. request.cookies.JSESSIONID

  • request.body - Request body text (avoid for non-text bodies)

Where is SearchLogsFor method?

I saw SearchLogsFor sample code in the Wiki page. How can I use this feature?

This project was impressed me a lot. Thank for your work.

Interested in callbacks?

Hello again.

Having played with the API a bit I was struggling to implement a stub where I needed a tiny bit more logic in creating the response, for example to do string manipulation on the request in a more granular way than handlebars, or in generating new IDs say.

I have experimented with a callback API like this:

  server.Given(Request.Create()
                .WithPath("/foo")
                .UsingGet())
            .RespondWith(Response.Create()
                .WithCallback(req => new ResponseMessage {Body = req.Path + "Bar"}));

The minimal implementation is in my fork, see the comparison: https://github.com/WireMock-Net/WireMock.Net/compare/master...alastairtree:feat/callbacks?expand=1

Is this something you would be interested in? Happy to do some extra work if needed to get something like it adopted. I noticed it also came up in Mock4net (alexvictoor/mock4net#19)

Thanks for the great library

Alastair

Feature: Add RequestLogExpirationDuration and MaxRequestLogCount

RequestLogExpirationDuration is a (nullable) integer which defines in hours the time
MaxRequestLogCount is a (nullable) integer which defines the maximum number of requests to keep using LIFO design

Both settings should be exposed in the stand-alone console app.

How to implement a request body-dependent response?

Dear @StefH,

consider request body contains complex data (xml as plain text) in a certain known format.
I have to create corresponding mock response by parsing body and transforming it using known rules.
Is it possible to implement this logic by means of WireMock?

Regards

Is this the same as Mock4Net?

Hi there,

I was about to start my own project for a .Net version of WireMock when I found your repo. However, I also saw the Mock4Net project which looks much the same. Is yours a newer version of that, or is it just using some of the same code and enhancing it?

Essentially - should I use WireMock.Net or Mock4Net?

Thanks,
Phil

Multiple headers with same name

Do I understand correct that currently it's not possible to set multiple headers with same name to ResponseMessage?
In particular, I'm interested in providing multiple Set-Cookie headers.
Is it possible to add such functionality? I could submit PR with changing Headers property from 'IDictionary<string, string>' to something like 'IDictionary<string, string[]>', but not sure how great is that, considering that it is public member.

Bug: Server not listening after Start() returns (on macOS)

Hi, I just ported a project from .NET 4.5 to .NET Core 2.0 on macOS. I noticed that a unit test using FluentMockServer started failing with System.Net.Http.CurlException : Couldn't connect to server.

When I add Thread.Sleep(100) after starting the server, the error goes away. I'm assuming that, on macOS at least, the underlying server implementation is a bit more asynchronous than that on .NET proper (or on Mono). I notice that FluentMockServer.Start(...) calls StartAsync on its inner HTTP server. Is there a way to wait for that async start to finish that's more reliable than putting the test thread to sleep?

ProxyAndRecord does not save query-parameters, headers and body

When we try to record a request with HttpMethod as post, then we are getting error as below. Can someone please help me if I am missing anything.

I am starting server as below

string url = "http://localhost:1111/";
            var server = FluentMockServer.Start(new FluentMockServerSettings
            {
                Urls = new[] { url },
                StartAdminInterface = true,
                ReadStaticMappings=true,
                ProxyAndRecordSettings = new ProxyAndRecordSettings
                {
                    Url = "http://www.google.com/",
                    SaveMapping = true
                }
            });

Error is as below. But when I create a static mapping for the above serevr with Post as method then it works fine. Seeing the below issue only when we try to record it.

System.InvalidOperationException: Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.
   at System.Net.Http.Headers.HttpHeaders.CheckHeaderName(String name)
   at System.Net.Http.Headers.HttpHeaders.Add(String name, IEnumerable`1 values)
   at WireMock.Http.HttpClientHelper.<SendAsync>d__1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at WireMock.Server.FluentMockServer.<ProxyAndRecordAsync>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at WireMock.Mapping.<ResponseToAsync>d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   at WireMock.Owin.WireMockMiddleware.<Invoke>d__5.MoveNext()

Support of .Net 4.0

Hey @StefH, thanks for great library! Wanted to ask if it is planned to support .net 4.0 or there are some reasons or limitations to not support it?
Thanks

Feature request: Nuget package for standalone version

Was there an earlier version where the standalone console app was also available via a Nuget package?

I can't see one now, and it would be useful to have one. Yes it's easy to create my own console app and copy/paste the Wiremock.Standalone code into it, but would be even easier to have a nuget package for it :-)

Thanks,
Phil

Wrong Request Match result is returning

Hi - I downloaded the code and while running the ConsoleApplication Project inthe sulution with some changes i am getting some bizarre results.

In the attached sample code file - when i try to run the run application and accessing the URL from browser - like http://localhost:9091/search/query i am getting the result of path match for url "/testmatch".

If i register the url "/search/query" above "/testmatch" and try to browse http://localhost:9091/search/query i am getting the result of "/search/query" but if try "/testmatch" still getting the result of "search/query"

If i move the code up and down for registering urls, It is always returning the first one irrespective of path i am accessing from browser.

MainApp.txt

Admin static json mappings

Hi there,

I've downloaded the source zip, built the solution, and created an /__admin/mappings/ folder under the bin/debug folder for the WireMock.Net.StandAlone project. In there, I copied the basic json file from http://wiremock.org/docs/stubbing/ (as shown at the end) and named it test.json. I then ran the standalone project from the command line (after adding Newtonsoft.Json reference and restoring Nuget packages). The console runner shows the server is now listening on port 9090.

When I tried to browse to http://localhost:9090/some/thing it said "No mapping found", and also when I browse to http://localhost:9090/__admin/mappings it returned an empty array. Is it loading up the static json file mappings?

Thanks,
Phil

{
"request": {
"method": "GET",
"url": "/some/thing"
},
"response": {
"status": 200,
"body": "Hello world!",
"headers": {
"Content-Type": "text/plain"
}
}
}

Partial mapping

Great library, thanks! I cant see any docs/explanation on the "AllowPartialMapping" option? Have I missed them? What does it do?

Enhancement - Save/load request logs to/from disk

Just thinking, in one of the scenarios we have, the Wiremock standalone instance is used as either:

  • a fallback when one of our real services goes down in development, or
  • we just want to avoid depending on the real service.

Sometimes the service can run for days, or weeks. When this happens and there are multiple developers using the standalone mock service, the request logs can grow very large, and use a lot of memory. To address this, one option would be to manually clear them, however I was thinking I might (this will likely not be till October when I get back from holiday) instead provide a setting to have the request logs saved to disk instead, much like the mappings, and then when requests come to retrieve a log entry or a search, parse the files and return the matching ones.

Another scenario I can see this being useful for is where there is a long-running proxy/record instance.

I'm thinking that the RequestLogs collection could be changed into a custom List or IEnumerable implementation, which just stores the request id and filename. When GetEnumerator or other methods are called, it would then read the actual request files from disk and return them.

An alternative option would be to provide a setting such as RequestLogExpirationDuration, or MaxRequestLogCount, which could be used to ensure that request logs are purged when they reach a certain age, or when a certain amount build up. This might be easier, but is another way to address the same issue.

Thoughts Stef?

[Feature] Disable partial mappings by default in standalone version

In the standalone code, it has AllowPartialMapping set to true by default. Perhaps this should be set to false by default as it can be very confusing when debugging and seeing results being returned for things that you don't expect?

[SwitchArgument("AllowPartialMapping", true, Description = "Allow Partial Mapping (default set to true).", Optional = true)]
public bool AllowPartialMapping { get; set; }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.