GithubHelp home page GithubHelp logo

pact-foundation / pact-workshop-dotnet-core-v1 Goto Github PK

View Code? Open in Web Editor NEW
75.0 9.0 208.0 54 KB

A workshop for Pact using .NET Core

License: Apache License 2.0

C# 100.00%
pact pact-workshop xunit dotnet-core

pact-workshop-dotnet-core-v1's People

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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pact-workshop-dotnet-core-v1's Issues

Missing Packages AspNetCore.All and VisualStudio.Web.CodeGeneration.Tools

Trying to run dotnet restore whilst in YourSolution\Provider\src ... have repeated several times with same outcome. Two packages are not found:

PS C:\repos\other\pact-workshop-dotnet-core-v1\YourSolution\Provider\src> dotnet restore
  Restoring packages for C:\repos\other\pact-workshop-dotnet-core-v1\YourSolution\Provider\src\provider.csproj...
  Restoring packages for C:\repos\other\pact-workshop-dotnet-core-v1\YourSolution\Provider\src\provider.csproj...
  Retrying 'FindPackagesByIdAsyncCore' for source 'http://nuget/api/FindPackagesById()?id='Microsoft.AspNetCore.All'&semVerLevel=2.0.0'.
  Response status code does not indicate success: 404 (Not Found).
  Retrying 'FindPackagesByIdAsyncCore' for source 'http://nuget/api/FindPackagesById()?id='Microsoft.VisualStudio.Web.CodeGeneration.Tools'&semVerLevel=2.0.0'.
  Response status code does not indicate success: 404 (Not Found).
  Retrying 'FindPackagesByIdAsyncCore' for source 'http://nuget/api/FindPackagesById()?id='Microsoft.VisualStudio.Web.CodeGeneration.Tools'&semVerLevel=2.0.0'.
  Response status code does not indicate success: 404 (Not Found).
  Retrying 'FindPackagesByIdAsyncCore' for source 'http://nuget/api/FindPackagesById()?id='Microsoft.AspNetCore.All'&semVerLevel=2.0.0'.
  Response status code does not indicate success: 404 (Not Found).
C:\Program Files\dotnet\sdk\2.1.201\NuGet.targets(114,5): error : Failed to retrieve information about 'Microsoft.AspNetCore.All' from remote source 'http://nuget/api/FindPackagesById()?id='Microsoft.AspNetCore.All'&semVerLevel=2.0.0'. [C:\repos\other\pact-workshop-dotnet-core-v1\YourSolution\Provider\src\provider.csproj]
C:\Program Files\dotnet\sdk\2.1.201\NuGet.targets(114,5): error :   Response status code does not indicate success: 404 (Not Found). [C:\repos\other\pact-workshop-dotnet-core-v1\YourSolution\Provider\src\provider.csproj]

How to inject a mocked repository into the provider via the middleware (.net core)

In cases where the provider state needs to be set prior to the test (For instance when an entity needs to exist in the database with a specific id), what are the best practices to update the state of the provider? From my perspective, there should be a way to mock the repository so that data can be manipulated easily and quickly, if this is the right approach, how is it possible to inject a mocked repository into the provider?
Since, the test does not run the server and an instance of the Provider API needs to be run independently, I can't get my head around a solution, which allows dynamic injection of a mocked repository.
If this is not possible, then how is it possible to update the state in the Provider? Does it mean that the provider endpoints (i.e. POST) should be called or data should be inserted directly to the database from the middleware? Even if these approaches are implemented, the Id of the created object is auto incremented and would not match the contract. Does it mean that I have to use Matching in the contract? What is the best practice to implement tear down and cleanup the changes then?

ProviderStateMiddleware Synchronous IO operation throws error

When targetting netcoreapp3.1 in the workshop project, using the prescribed Startup file from the workshop along with the ProviderStateMiddleware leads to an error at the following call:

jsonRequestBody = reader.ReadToEnd();

The error message is:

Microsoft.AspNetCore.Server.Kestrel: Error: Connection id "0HM3LKBBJTAHT", Request id "0HM3LKBBJTAHT:00000001": An unhandled exception was thrown by the application.

System.InvalidOperationException: Synchronous operations are disallowed. Call ReadAsync or set AllowSynchronousIO to true instead.
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpRequestStream.Read(Byte[] buffer, Int32 offset, Int32 count)
at System.IO.StreamReader.ReadBuffer()
at System.IO.StreamReader.ReadToEnd()
at Waters.AuditLogAS.ContractTests.Middleware.ProviderStateMiddleware.HandleProviderStatesRequest(HttpContext context) in /home/ukafig/Repositories/auditlogas/ContractTests/Middleware/ProviderStateMiddleware.cs:line 47
at Waters.AuditLogAS.ContractTests.Middleware.ProviderStateMiddleware.Invoke(HttpContext context) in /home/ukafig/Repositories/auditlogas/ContractTests/Middleware/ProviderStateMiddleware.cs:line 28

The issue pertains to the following dotnet/aspnetcore#7644.

The solution is to add the following to ConfigureServices:

services.Configure(options =>
{
options.AllowSynchronousIO = true;
});

I am happy to submit a PR with the above to ensure workshop code is compatible with .net core 3.1.

The following constructor parameters did not have matching fixture data: ConsumerPactClassFixture fixture

Getting error when I try to run consumer test using "dotnet test" after Step 3.3.2
Appreciate any help to fix this issue-

\YourSolution\Consumer\tests> dotnet test
Build started, please wait...
Build completed.

Test run for C:\Users....\Source\Repos\Pactnet\pact-workshop-dotnet-core-v1\YourSolution\Consumer\tests\bin\Debug\netcoreapp2.1\tests.dll(.NETCoreApp,Version=v2.1)
Microsoft (R) Test Execution Command Line Tool Version 15.8.0
Copyright (c) Microsoft Corporation. All rights reserved.

Starting test execution, please wait...
[xUnit.net 00:01:00.1009644] tests.ConsumerPactTests.ItHandlesInvalidDateParam [FAIL]
Failed tests.ConsumerPactTests.ItHandlesInvalidDateParam
Error Message:
System.AggregateException : One or more errors occurred. (One or more errors occurred. (No connection could be made because the target machine actively refused it)) (The following constructor parameters did not have matching fixture data: ConsumerPactClassFixture fixture)
---- System.AggregateException : One or more errors occurred. (No connection could be made because the target machine actively refused it)
-------- System.Net.Http.HttpRequestException : No connection could be made because the target machine actively refused it
------------ System.Net.Sockets.SocketException : No connection could be made because the target machine actively refused it
---- The following constructor parameters did not have matching fixture data: ConsumerPactClassFixture fixture

'No test is available' at step 4.3.2

I'm working through your workshop on OSX. All good until 4.3.2, when I get the error message:
No test is available in /Users/seb/Projects/pact-workshop-dotnet-core-v1/YourSolution/Provider/tests/bin/Debug/netcoreapp2.0/tests.dll. Make sure that test discoverer & executors are registered and platform & framework version settings are appropriate and try again.

Other information

  • I get the same problem when running dotnet test in CompletedSolution/Provider/tests
  • I've tried giving an explicit path to XUnit using dotnet test -a ..... but that didn't help.
  • The command dotnet test works fine in Consumer/tests

This is the output from dotnet --info
.NET Command Line Tools (2.0.0)

Product Information:
Version: 2.0.0
Commit SHA-1 hash: cdcd1928c9

Runtime Environment:
OS Name: Mac OS X
OS Version: 10.13
OS Platform: Darwin
RID: osx.10.12-x64
Base Path: /usr/local/share/dotnet/sdk/2.0.0/

Microsoft .NET Core Shared Framework Host

Version : 2.0.0
Build : e8b8861ac7faf042c87a5c2f9f2d04c98b69f28d

Provider test could be improved slightly

Hello

Firstly thanks for a great resource, it has been very helpful. I have a suggestion.
When you run the provider tests, you suggest running the api using dotnet run and then in another command window, running the tests using dotnet test.

My suggestion is that the provider test could instead start the API under test using Webhost.CreateDefaultBuilder()

Then you wouldn't need to dotnet run, you could test it all using dotnet test. Example:

public ProviderApiTests(ITestOutputHelper output)
{
    _outputHelper = output;

    _pactServiceUri = "http://localhost:9001";
    _providerStateHost = WebHost.CreateDefaultBuilder()
        .UseUrls(_pactServiceUri)
        .UseStartup<TestStartup>()
        .Build();

    _providerStateHost.Start();

    _providerUri = "http://localhost:9000";
    _sut = WebHost.CreateDefaultBuilder()
        .UseUrls(_providerUri)
        .UseStartup<Startup>()
        .Build();

    _sut.Start();
}

I actually just wasted half a day trying to get it to run using the new ASP.NET Core 2.1 WebApplicationFactory, ala https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-2.1

The problem with using WebApplicationFactory is that when you create a client via var client = _factory.CreateClient(), it seems that only that client can access the TestServer - it's not accessible to other clients such as your local browser, or the PactVerifier. Therefore I had to use WebHost.CreateDefaultBuilder() as you have done.

Provider Test - 500 response from Pact service

Hi, thanks for making this tutorial, it's really helped my understanding.

I get a 500 error from the tests when running the provider test - the same result when I run my own solution, the completed solution, and I've now tried it on 2 machines (fresh repo each time).

I've managed to establish that the issue is in the middleware. By putting in a try catch the tests ran successfully, except for this test which I had to remove: "A invalid GET request for Date Validation with invalid date parameter", which was getting a 200 instead of a 400.

Presumably it has something with that test doing the "There is no data" provider state. I'll have another go this week at figuring out what the issue is. I just wanted to put this here in case anyone else ran into the same thing.

Error while running dotnet test command

Getting below error while running dotnet test command for consumer tests

D:\pact-workshop-dotnet-core-v1-master\pact-workshop-dotnet-core-v1-master\YourSolution\Consumer\tests>dotnet test
Build started, please wait...
Build completed.

Test run for D:\pact-workshop-dotnet-core-v1-master\pact-workshop-dotnet-core-v1-master\YourSolution\Consumer\tests\bin\Debug\netcoreapp2.2\tests.dll(.NETCoreApp,Version=v2.2)
Microsoft (R) Test Execution Command Line Tool Version 15.9.0
Copyright (c) Microsoft Corporation. All rights reserved.

Starting test execution, please wait...
[xUnit.net 00:00:59.94] tests.ConsumerPactTests.ItHandlesInvalidDateParam [FAIL]
Failed tests.ConsumerPactTests.ItHandlesInvalidDateParam
Error Message:
System.AggregateException : One or more errors occurred. (One or more errors occurred. (No connection could be made because the target machine actively refused it)) (The following constructor parameters did not have matching fixture data: ConsumerPactClassFixture fixture)
---- System.AggregateException : One or more errors occurred. (No connection could be made because the target machine actively refused it)
-------- System.Net.Http.HttpRequestException : No connection could be made because the target machine actively refused it
------------ System.Net.Sockets.SocketException : No connection could be made because the target machine actively refused it
---- The following constructor parameters did not have matching fixture data: ConsumerPactClassFixture fixture
Stack Trace:

----- Inner Stack Trace #1 (System.AggregateException) -----
at PactNet.Mocks.MockHttpService.Host.RubyHttpHost.Start() in C:\projects\pact-net\PactNet\Mocks\MockHttpService\Host\RubyHttpHost.cs:line 65
at PactNet.PactBuilder.MockService(Int32 port, JsonSerializerSettings jsonSerializerSettings, Boolean enableSsl, IPAddress host) in C:\projects\pact-net\PactNet\PactBuilder.cs:line 88
at PactNet.PactBuilder.MockService(Int32 port, Boolean enableSsl, IPAddress host) in C:\projects\pact-net\PactNet\PactBuilder.cs:line 59
at tests.ConsumerPactClassFixture..ctor() in D:\pact-workshop-dotnet-core-v1-master\pact-workshop-dotnet-core-v1-master\YourSolution\Consumer\tests\ConsumerPactClassFixture.cs:line 39
----- Inner Stack Trace -----
at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
at System.Threading.Tasks.ValueTask1.get_Result() at System.Net.Http.HttpConnectionPool.CreateConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Threading.Tasks.ValueTask1.get_Result()
at System.Net.Http.HttpConnectionPool.WaitForCreatedConnectionAsync(ValueTask1 creationTask) at System.Threading.Tasks.ValueTask1.get_Result()
at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
----- Inner Stack Trace -----
at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
----- Inner Stack Trace #2 (Xunit.Sdk.TestClassException) -----

Total tests: 1. Passed: 0. Failed: 1. Skipped: 0.
Test Run Failed.
Test execution time: 1.0123 Minutes

D:\pact-workshop-dotnet-core-v1-master\pact-workshop-dotnet-core-v1-master\YourSolution\Consumer\tests>dotnet test
Build started, please wait...
Build completed.

Test run for D:\pact-workshop-dotnet-core-v1-master\pact-workshop-dotnet-core-v1-master\YourSolution\Consumer\tests\bin\Debug\netcoreapp2.2\tests.dll(.NETCoreApp,Version=v2.2)
Microsoft (R) Test Execution Command Line Tool Version 15.9.0
Copyright (c) Microsoft Corporation. All rights reserved.

Starting test execution, please wait...
[xUnit.net 00:01:01.12] tests.ConsumerPactTests.ItHandlesInvalidDateParam [FAIL]
Failed tests.ConsumerPactTests.ItHandlesInvalidDateParam
Error Message:
System.AggregateException : One or more errors occurred. (One or more errors occurred. (No connection could be made because the target machine actively refused it)) (The following constructor parameters did not have matching fixture data: ConsumerPactClassFixture fixture)
---- System.AggregateException : One or more errors occurred. (No connection could be made because the target machine actively refused it)
-------- System.Net.Http.HttpRequestException : No connection could be made because the target machine actively refused it
------------ System.Net.Sockets.SocketException : No connection could be made because the target machine actively refused it
---- The following constructor parameters did not have matching fixture data: ConsumerPactClassFixture fixture
Stack Trace:

----- Inner Stack Trace #1 (System.AggregateException) -----
at PactNet.Mocks.MockHttpService.Host.RubyHttpHost.Start() in C:\projects\pact-net\PactNet\Mocks\MockHttpService\Host\RubyHttpHost.cs:line 65
at PactNet.PactBuilder.MockService(Int32 port, JsonSerializerSettings jsonSerializerSettings, Boolean enableSsl, IPAddress host) in C:\projects\pact-net\PactNet\PactBuilder.cs:line 88
at PactNet.PactBuilder.MockService(Int32 port, Boolean enableSsl, IPAddress host) in C:\projects\pact-net\PactNet\PactBuilder.cs:line 59
at tests.ConsumerPactClassFixture..ctor() in D:\pact-workshop-dotnet-core-v1-master\pact-workshop-dotnet-core-v1-master\YourSolution\Consumer\tests\ConsumerPactClassFixture.cs:line 39
----- Inner Stack Trace -----
at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
at System.Threading.Tasks.ValueTask1.get_Result() at System.Net.Http.HttpConnectionPool.CreateConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Threading.Tasks.ValueTask1.get_Result()
at System.Net.Http.HttpConnectionPool.WaitForCreatedConnectionAsync(ValueTask1 creationTask) at System.Threading.Tasks.ValueTask1.get_Result()
at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
----- Inner Stack Trace -----
at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
----- Inner Stack Trace #2 (Xunit.Sdk.TestClassException) -----

Total tests: 1. Passed: 0. Failed: 1. Skipped: 0.
Test Run Failed.
Test execution time: 1.0320 Minutes

D:\pact-workshop-dotnet-core-v1-master\pact-workshop-dotnet-core-v1-master\YourSolution\Consumer\tests>dotnet test
Build started, please wait...
Build completed.

Test run for D:\pact-workshop-dotnet-core-v1-master\pact-workshop-dotnet-core-v1-master\YourSolution\Consumer\tests\bin\Debug\netcoreapp2.2\tests.dll(.NETCoreApp,Version=v2.2)
Microsoft (R) Test Execution Command Line Tool Version 15.9.0
Copyright (c) Microsoft Corporation. All rights reserved.

Starting test execution, please wait...
[xUnit.net 00:01:01.09] tests.ConsumerPactTests.ItHandlesInvalidDateParam [FAIL]
Failed tests.ConsumerPactTests.ItHandlesInvalidDateParam
Error Message:
System.AggregateException : One or more errors occurred. (One or more errors occurred. (No connection could be made because the target machine actively refused it)) (The following constructor parameters did not have matching fixture data: ConsumerPactClassFixture fixture)
---- System.AggregateException : One or more errors occurred. (No connection could be made because the target machine actively refused it)
-------- System.Net.Http.HttpRequestException : No connection could be made because the target machine actively refused it
------------ System.Net.Sockets.SocketException : No connection could be made because the target machine actively refused it
---- The following constructor parameters did not have matching fixture data: ConsumerPactClassFixture fixture
Stack Trace:

----- Inner Stack Trace #1 (System.AggregateException) -----
at PactNet.Mocks.MockHttpService.Host.RubyHttpHost.Start() in C:\projects\pact-net\PactNet\Mocks\MockHttpService\Host\RubyHttpHost.cs:line 65
at PactNet.PactBuilder.MockService(Int32 port, JsonSerializerSettings jsonSerializerSettings, Boolean enableSsl, IPAddress host) in C:\projects\pact-net\PactNet\PactBuilder.cs:line 88
at PactNet.PactBuilder.MockService(Int32 port, Boolean enableSsl, IPAddress host) in C:\projects\pact-net\PactNet\PactBuilder.cs:line 59
at tests.ConsumerPactClassFixture..ctor() in D:\pact-workshop-dotnet-core-v1-master\pact-workshop-dotnet-core-v1-master\YourSolution\Consumer\tests\ConsumerPactClassFixture.cs:line 39
----- Inner Stack Trace -----
at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
at System.Threading.Tasks.ValueTask1.get_Result() at System.Net.Http.HttpConnectionPool.CreateConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Threading.Tasks.ValueTask1.get_Result()
at System.Net.Http.HttpConnectionPool.WaitForCreatedConnectionAsync(ValueTask1 creationTask) at System.Threading.Tasks.ValueTask1.get_Result()
at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
----- Inner Stack Trace -----
at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
----- Inner Stack Trace #2 (Xunit.Sdk.TestClassException) -----

Total tests: 1. Passed: 0. Failed: 1. Skipped: 0.
Test Run Failed.
Test execution time: 1.0311 Minutes

Update goo.gl links

There is a lot of goo.gl URL links in the readme. Since Google has shut down the URL shorner service the links will become inaccessible by April 2020. Need to update the links, if there is no update on documentation by then.

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.