hibri / httpmock Goto Github PK
View Code? Open in Web Editor NEWA library for creating Http servers on the fly in tests and stubbing responses
License: MIT License
A library for creating Http servers on the fly in tests and stubbing responses
License: MIT License
getBody() does a peek on the queue, so if we are testing multiple requests in a row getBody() will only return the first. Example would be receiving an acknowledgement callback and then a result callback on the same url.
Would a getBody(int count) or List getBodies() or have getBody() do a dequeue make sense?
I haven't delved into it too much, so is there a way to define your own IRequestHandler, but I haven't gotten there yet.
stubHttp.Stub(x => x.Get("/api/path")).Return("PATH").OK();
stubHttp.Stub(x => x.Get("/api/path/one")).Return(expectedResponse).OK();
var result = new WebClient().DownloadString(string.Format("{0}/api/path/one", _hostUrl));
Assert.That(result, Is.EqualTo(expectedResponse));
It would be great to be able to run the server on a random open port to prevent possible collisions due to hard coding a particular port. I notice that you already have this functionality for your internal unit tests. It would be nice if it was exposed to users of the library in some way so that we don't have to duplicate that code ourselves.
Hi,
Request you to put an example on the main page of how to mock POST request which contains BODY.
If there are any restrictions on placing it there, please mail me [email protected]
Thanks,
Ravi.
Bit urgent:
Getting The remote server returned an error 404 not found..could any help in this pls.
study Id is a string .
new WebClient().UploadString(("http://localhost:8080/api/v1/documents"), StudyId);
new WebClient().UploadFile("http://localhost:8080/api/v1/documents", filename);
the above 2 lines are giving problem.
string StudyId = "{TrialId : 223344}";
string Result = "Object Id: ,BaseObjectId";
Dictionary<string, string> param = new Dictionary<string, string>()
{
{"admin", "lib"}
};
string filename = CreateFile();
var r = StubHttp.Stub(x => x.Post(endpoint));
r.WithParams(param);
r.AddHeader("multipartform-data", "11");
r.Return(Result).OK();
new WebClient().UploadString(("http://localhost:8080/api/v1/documents"), StudyId);
new WebClient().UploadFile("http://localhost:8080/api/v1/documents", filename);
I don't see a feature to put a constraint on the POST body when writing a stub.
IHttpServer serverA = null;
serverA = HttpMockRepository.At("http://localhost:10100");
serverA.Stub(x => x.Get("/PingList")).WithUrlConstraint(u => u.Contains("date=1-2")).Return("1").OK();
serverA.Stub(x => x.Get("/PingList")).WithUrlConstraint(u => u.Contains("date=1-2-3")).Return("2").OK();
var client = new RestClient("http://localhost:10100");
var request = new RestRequest("PingList", Method.GET);
request.AddQueryParameter("date", "1-2");
var resp = client.Execute(request);
resp.Content.Should().Contain("1");
request = new RestRequest("PingList", Method.GET);
request.AddQueryParameter("date", "1-2-3");
resp = client.Execute(request);
resp.Content.Should().Contain("2");
serverA = serverA.WithNewContext();
serverA.Stub(x => x.Get("/PingList")).WithUrlConstraint(u => u.Contains("date=1-2")).Return("1").OK();
serverA.Stub(x => x.Get("/PingList")).WithUrlConstraint(u => u.Contains("date=1-2-3")).Return("2").OK();
request = new RestRequest("PingList", Method.GET);
request.AddQueryParameter("date", "1-2");
resp = client.Execute(request);
resp.Content.Should().Contain("1");
request = new RestRequest("PingList", Method.GET);
request.AddQueryParameter("date", "1-2-3");
resp = client.Execute(request);
resp.Content.Should().Contain("2");
serverA.Dispose();
Result Message: Expected string "1" to contain "2".
This is a follow-up to my comment in #18. I created a test repo with a project that exhibits the issue for me with VS 2015. The dependencies were all installed with NuGet.
The full output when run by the NUnit runner is:
Test Name: SUT_should_return_stubbed_response
Test FullName: ClassLibrary1.Class1.SUT_should_return_stubbed_response
Test Source: c:\users\gregory\documents\visual studio 2015\Projects\ClassLibrary2\ClassLibrary2\Class1.cs : line 15
Test Outcome: Failed
Test Duration: 0:00:00.039
Result StackTrace:
at HttpMock.HttpServer..ctor(Uri uri)
at HttpMock.HttpServerFactory.Create(Uri uri) in c:\dev\HttpMock\src\HttpMock\HttpServerFactory.cs:line 23
at HttpMock.HttpServerFactory.Get(Uri uri) in c:\dev\HttpMock\src\HttpMock\HttpServerFactory.cs:line 16
at HttpMock.HttpMockRepository.At(Uri uri) in c:\dev\HttpMock\src\HttpMock\HttpMockRepository.cs:line 19
at HttpMock.HttpMockRepository.At(String uri) in c:\dev\HttpMock\src\HttpMock\HttpMockRepository.cs:line 14
at ClassLibrary1.Class1.SUT_should_return_stubbed_response() in c:\users\gregory\documents\visual studio 2015\Projects\ClassLibrary2\ClassLibrary2\Class1.cs:line 16
Result Message: System.TypeLoadException : Could not load type 'Kayak.KayakScheduler' from assembly 'Kayak, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
WithParams doesn't support dup query params. I couldn't find a workaround.
In QueryParamMatch, there is...
if (!String.Equals(requestQueryParams[queryParam.Key], queryParam.Value, StringComparison.OrdinalIgnoreCase)) {
return false;
}
Could you please change it such that it uses requestQueryParams.Values given a key? That way, it can support dup query params polymorphically.
In EndpointMatchingRule,
var requestQueryParams = valueCollection.AllKeys
.Where(k => !string.IsNullOrEmpty(k))
.ToDictionary(k => k, k => valueCollection[k]);
This seems to ignore dup query params when it does ToDictionary.
A GET request with a trailing ampersand (&) causes the mock server to return no data. If you paste the below tests into the end of MultipleTestsUsingTheSameStubServerAndDifferentUris.cs you can see the issue. It could be this is a kayak issue...
The spec is clear that this should be supported despite the url not being properly formatted.
// Should pass and does pass
[Test]
public void Should_get_with_parameters()
{
_httpMockRepository
.Stub(x => x.Get("/endpoint"))
.Return("I am a GET")
.OK();
AssertResponse("GET", "I am a GET", "/endpoint?a=b&c=d");
}
// Should pass but does not pass
[Test]
public void Should_get_with_parameters_and_trailing_ampersand()
{
_httpMockRepository
.Stub(x => x.Get("/endpoint"))
.Return("I am a GET")
.OK();
AssertResponse("GET", "I am a GET", "/endpoint?a=b&c=d&");
}
private void AssertResponse(string method, string expected, string uri)
{
var webRequest = (HttpWebRequest)WebRequest.Create("Http://localhost:8080"+uri);
webRequest.Method = method;
using (var response = webRequest.GetResponse())
{
using (var sr = new StreamReader(response.GetResponseStream()))
{
string readToEnd = sr.ReadToEnd();
Assert.That(readToEnd, Is.EqualTo(expected));
}
}
}
I created a very simple test as shown below, At the end of it I get this:
System.AppDomainUnloadedException: Attempted to access an unloaded AppDomain. This can happen if the test(s) started a thread but did not stop it. Make sure that all the threads started by the test(s) are stopped before completion.
[TestMethod]
public void MockHttpServer()
{
var stubHttp = HttpMockRepository.At("http://localhost:8888");
stubHttp.Stub(x => x.Post("/somepath")).Return("OK").OK();
}
Is there a way to explicitly shutdown the server before exiting?
thanks
The routes disappeared. Getting empty response.
And also provide the info on HttpWebResponce
when I reference HttpMock nuget package from a signed assembly, the following error appears during build:
CS8002 Referenced assembly 'HttpMock, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' does not have a strong name.
Hi!
When i tried to use this library, i found some intresting issue: when i call a handler, it invokes twice.
This problem reproduces when i make a call with Fiddler, Postman or by Opera browser.
Sources of test:
using System;
using System.Threading;
using HttpMock;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var delaySeconds = TimeSpan.FromSeconds(2);
var serverAddr = "http://localhost:9191";
var apiPath = "/profileImporter/invoke";
var url = serverAddr + apiPath;
Console.WriteLine($"{nameof(url)} : {url}");
var mockApi = HttpMockRepository.At(serverAddr);
mockApi.Stub(x => x.Get("")).Return(() =>
{
Console.WriteLine($"{DateTime.Now:yyyyMMdd HH:mm:ss} - server called");
Console.WriteLine($"Delay: {delaySeconds}");
Thread.Sleep(delaySeconds);
Console.WriteLine($"{DateTime.Now:yyyyMMdd HH:mm:ss} - delay ended");
Console.WriteLine();
Console.WriteLine();
return "TEST_GET_RESULT";
}).OK();
Console.WriteLine("Press any key to exit this shit...");
Console.ReadKey();
}
}
}
It would be useful to be able to match a request header so that different responses could be returned depending on the header value. For example a different response could be configured for different values of the Accept-Language header. I'd be happy to implement this if you're OK with adding this feature.
Could you please use Dependency Injection in HttpServer? For example, HttpServer(URI) has dependencies which cannot be extended.
It'd be great if IRequestStub returned IRequestVerify on OK, WithStatus and NotFound.
Otherwise it's necessary either cast or use FindHandler
This library looks great, but the license does not appear to grant permission to use or copy the software. Would you consider putting this under a standard license such as MIT or ISC?
could any one give provide information about the issue
Getting NullRefernceException at " httpserver.AssertWasCalled(x=>x.Get("/Hello")** " line.
Works for two, but not for three...
at Kayak.KayakServerState.SetClosing() in h:\kayak\Kayak\Net\Server\KayakServerState.cs:line 88
at Kayak.DefaultKayakServer.Close() in h:\kayak\Kayak\Net\Server\KayakServer.cs:line 63
at Kayak.DefaultKayakServer.b__0() in h:\kayak\Kayak\Net\Server\KayakServer.cs:line 58
at Kayak.Disposable.Dispose() in h:\kayak\Kayak\Disposable.cs:line 19
at HttpMock.HttpServer.Dispose() in
System.InvalidOperationException : The server was closing.
If you update NUnit in the IntegrationTests project then the HttpExcpectationTests fail with a System.IO.FileLoadException and the message:
'Could not load file or assembly 'nunit.framework, Version=2.6.2.12296...'
The reference to NUnit in the HttpMock project has the property 'Specific Version' set to true.
I am setting a json in the body. I want to check the received request body. I see that the body is truncated.
Are there any plans to release a version with .NET Core support?
Hi, I'm using this library to test my application and it works great, but it looks like in order to stub out an endpoint successfully I need to list all the headers that get sent in WithHeaders
. Unfortunately our application sends out GUID correlation id's in the header so it's easy to predict their values.
Is it (or would it be) possible to stub out an endpoint ignoring any given headers?
These files have a dependency on NUnit for it's Assert.That(..) method:
RequestHandlerExpectExtensions.cs
RequestWasCalled.cs
RequestWasNotCalled.cs
For library consumers, they have to bring in NUnit even if they are using a different unit testing framework. This is a bit strange.
Isn't compatible with NUnit 3.x. Could you please upgrade NUnit? Otherwise, AssertWasCalled isn't usable.
I am expecting a response along with the response header having eTag Value in it. How could it we achieve ?
It looks like NuGet is build for .NET 4.5 (even though the folder in which assembly is suggests that this is build for .NET 4.0: packages\HttpMock.1.3.0\lib\net40\HttpMock.dll). Any way that can be fixed?
Could you please add support for dup query params? WithURLConstraint doesn't work to resolve this.
When I use withParams(queryParams), the duplicate query parameter overrides the original query parameter. I would like to have something like ?date=123&date=678. Is there an elegant work-around?
Example:
/resource('2222')
Seems like MatchPath's regex doesn't escape parentheses.
Hey,
I was trying to install HttpMock 2.1.0 on existing project that is targetted on .NETFramework,Version=v4.0,Profile=Client, I am getting below error:
Could not install package 'HttpMock 2.1.0'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.0,Profile=Client', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.
Any solution or fix required in order to use this library with current targetted framework.
Let me know, how could i achieve this. ?
Times, WithHeader return void. Could you please make this fluent? For example, server.AssertWasCalled(x => x.Get("/endpoint").WithHeader("header",Is.EqualTo("ABC")).Times(1).
I have a test suite which creates/disposes a server multiple times. Server.IsAvailable() returns true, but the HTTP request hangs until timeout. When I ran the tests individually, they pass.
I noticed that calling dispose on one server, disposes the other servers. I verified with IsAvailable that the other servers were shutdown.
public void Dispose()
{
if (_scheduler != null)
{
_scheduler.Stop();
_scheduler.Dispose();
}
if (_disposableServer != null)
{
_disposableServer.Dispose();
}
}
_disposableServer = KayakServer.Factory
.CreateHttp(_requestProcessor, _scheduler)
.Listen(ipEndPoint);
Seems to be due to same IP?
This would be very helpful to see for debugging purposes.
Hi,
I am facing issue while mocking the the request url containing query strings. e.g., url is given below.
https://localhost:xxxxx/api/menu?someName=someValue&someId=someIdValue
Is there any specific way to implement that?
Thanks in advance.
Regards,
Ravi.
It would be nice to have documentation for the public classes, at least in the form of XML comments.
Cannot use more than one url constraint for the same endpoint.
WithHeader only looks at the last request. Hence, AssertWithCall(x=>x.Post("/").WithHeader("a",...) and AssertWithCall(x=>x.Post("/").WithHeader("b",...) doesn't work. The error says that the the second request did not have the expected header b.
Diving into the code, it seems that the RequestVerify looks for the first handler that matches the path.
Hey,
I'm getting the System.InvalidOperationException : Kayak server not listening yet.
- any idea what could be the issue?
I'm using the example from the readme file, and it is working just fine on my Mac, however on Windows, it looks like the Kayak servers is not starting... Turned off the Windows Firewall - the same issue.
Thanks,
Marek
The two Assert methods (AssertWasNotCalled & AssertWasCalled) in HttpServer are both broken. Debugging shows that the path and method parameters are called the wrong way round so in the test below path comes through as "POST" whilst method comes through as "/api/echo" or "/api/status". The simple nunit test method below shows AssertWasNotCalled returning true when it should return false.
[Test]
public void showAssertNotCalledBrokenTest()
{
var stubHttp = HttpMockRepository.At("http://localhost:11235");
stubHttp.Stub(x => x.Get("/api/status")).Return("OK").OK();
stubHttp.Stub(x => x.Get("/api/echo")).Return("OK").OK();
new WebClient().DownloadString("http://localhost:11235/api/status");
// Should pass and does
stubHttp.AssertWasNotCalled(x => x.Get("/api/echo"));
// Should fail but passes
stubHttp.AssertWasNotCalled(x => x.Get("/api/status"));
}
Hi, I am using HttpMock in our UnitTests.
I had a problem with a large Url request. (404 Not Found)
On EndpointMatchingRule.cs #line 42 and for pathMatch.IsMatch(pathToMatch) is returning false
The interesting is if I send a request with more than 5K of "A" like "http://localhost:9191/AAAAAAAAA....
I have no problem.
I am attaching my example.
Thank you
Marcelo
Hi
I'm getting a SocketException at the end of my test run. Is this normal?
Can you confirm that I should be Disposing the IHttpServer instance?
Thanks
George
Could you please add a method like request.getBody():string?
Looking at the code the baseUri parameter for WithNewContext is not being used. Apart from clearing the handlers in the request processor, what is the expectation when that is set? Should it start and listen to the new uri? Or is this an obsolete overload?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.