Giter VIP home page Giter VIP logo

httpmock's People

Contributors

adamreeve avatar adarsh-angadi avatar gregsochanik avatar hibri avatar jozefizso avatar knocte avatar lukasz-lysik avatar mattolenik avatar ntcoding avatar oschwald avatar rubms avatar tumbledwyer avatar wilversings 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

httpmock's Issues

RequestHandler getBody() when multiple requests have been handled

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.

Expose PortHelper functionality

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.

new WebClient().UploadString(("http://localhost:8080/api/v1/documents"), StudyId);

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);

WithURLConstraint is not stub-specific

        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".

NuGet dependency on Kayak should be versioned (was: Kayak causing System.TypeLoadException)

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'.

Duplicate params in query string

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.

Invalid GET request breaks server

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));
            }
        }
    }

Some thread seems to be running after test ends

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

Assembly does not have a strong name.

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.

Request handler invokes 2 times

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();
        }
        
    }
}

image

Support matching on request headers

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.

HttpMock not extensible

Could you please use Dependency Injection in HttpServer? For example, HttpServer(URI) has dependencies which cannot be extended.

Unclear licensing

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?

Unable to Dispose multiple servers

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.

Ignore Headers when Matching

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?

Dependency on NUnit

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.

.NET 4.0 support

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?

Dup query params

Could you please add support for dup query params? WithURLConstraint doesn't work to resolve this.

Duplicate query parameters not supported

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?

.Net Framework support Issue

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. ?

Creating/Disposing the same server

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.

HttpServer.Dispose unexpectedly disposes all http servers

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?

Summaries for API

It would be nice to have documentation for the public classes, at least in the form of XML comments.

AssertWasCalled.WithHeader not reusable after first request

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.

Kayak server not listening yet

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

AssertWasNotCalled & AssertWasCalled broken

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"));
    }

Regex issue

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

Program.txt

WithNewContext baseUri not being used

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?

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.