Skip to content

Commit 457fb55

Browse files
authored
CreateHttpRequest override that accepts HttpRequest object
1 parent 408e2d3 commit 457fb55

File tree

5 files changed

+195
-9
lines changed

5 files changed

+195
-9
lines changed

Directory.Build.props

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
<Project>
22
<PropertyGroup>
3-
<Version>0.2.6</Version>
3+
<Version>0.2.8</Version>
44
</PropertyGroup>
55
</Project>

README.md

Lines changed: 45 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,17 @@
33
[![CodeQL](https://github.com/qatoolkit/qatoolkit-engine-httptester-net/workflows/CodeQL%20Analyze/badge.svg)](https://github.com/qatoolkit/qatoolkit-engine-httptester-net/security/code-scanning)
44
[![Sonarcloud Quality gate](https://github.com/qatoolkit/qatoolkit-engine-httptester-net/workflows/Sonarqube%20Analyze/badge.svg)](https://sonarcloud.io/dashboard?id=qatoolkit_qatoolkit-engine-httptester-net)
55
[![NuGet package](https://img.shields.io/nuget/v/QAToolKit.Engine.HttpTester?label=QAToolKit.Engine.HttpTester)](https://www.nuget.org/packages/QAToolKit.Engine.HttpTester/)
6+
[![Discord](https://img.shields.io/discord/787220825127780354?color=%23267CB9&label=Discord%20chat)](https://discord.com/invite/tu3WDV5Z?utm_source=Discord%20Widget&utm_medium=Connect)
67

78
## Description
89
`QAToolKit.Engine.HttpTester` is a .NET Standard 2.1 library, that that contains an implementation of `IHttpTesterClient` that is a thin wrapper around .NET `HttpClient` to allow to write easy Http Request calls.
910

1011
Supported .NET frameworks and standards: `netstandard2.0`, `netstandard2.1`, `netcoreapp3.1`, `net5.0`
1112

13+
Get in touch with me on:
14+
15+
[![Discord](https://img.shields.io/discord/787220825127780354?color=%23267CB9&label=Discord%20chat)](https://discord.com/invite/tu3WDV5Z?utm_source=Discord%20Widget&utm_medium=Connect)
16+
1217
### HttpTesterClient
1318

1419
A sample on how to easily call the HTTP request with .NET `HttpClient`:
@@ -70,6 +75,7 @@ using (var client = new HttpTesterClient())
7075
```
7176

7277
**POST File Upload request**
78+
7379
You can upload files with `multipart/form-data` content type like shown below.
7480
There are 2 overloads of `WithMultipart`, one for uploading binary data and the other for string data.
7581

@@ -92,7 +98,44 @@ using (var client = new HttpTesterClient())
9298
}
9399
```
94100

95-
There is double content-type safety built-in and you can not do `WithMultipart` and `WithJsonBody` in the same request.
101+
There is content-type safety built-in and you can not do `WithMultipart` and `WithJsonBody` in the same request.
102+
103+
**Create Tester client from QAToolKit Swagger request**
104+
105+
If you are using QAToolKit Swagger library to generate `HttpRequest` object you can use a `CreateHttpRequest` override.
106+
107+
In this sample below, `CreateHttpRequest` accepts a first request from the list of requests generated by Swagger library.
108+
109+
```csharp
110+
//GET Requests from Swagger file
111+
var urlSource = new SwaggerUrlSource();
112+
113+
var requests = await urlSource.Load(new Uri[] {
114+
new Uri("https://qatoolkitapi.azurewebsites.net/swagger/v1/swagger.json")
115+
});
116+
117+
using (var client = new HttpTesterClient())
118+
{
119+
var response = await client
120+
.CreateHttpRequest(requests.FirstOrDefault())
121+
.Start();
122+
....
123+
}
124+
```
125+
126+
The `CreateHttpRequest` override will assign only `BaseUrl`, `Path`, `HttpMethod`, `Query parameters` and `Header parameters`. You need to assign `HttpBody` manually with `WithJsonBody`.
127+
For example:
128+
129+
```csharp
130+
using (var client = new HttpTesterClient())
131+
{
132+
var response = await client
133+
.CreateHttpRequest(requests.FirstOrDefault())
134+
.WithJsonBody(object)
135+
.Start();
136+
....
137+
}
138+
```
96139

97140
#### HttpTesterClient Authentication
98141

@@ -124,7 +167,7 @@ Currently `HttpTesterClient` supports:
124167
var response = await client
125168
.CreateHttpRequest(new Uri("https://qatoolkitapi.azurewebsites.net"))
126169
....
127-
.WithNTKMAuthentication("user", "pass") // or default security context .WithNTKMAuthentication()
170+
.WithNTLMAuthentication("user", "pass") // or default security context .WithNTLMAuthentication()
128171
.Start();
129172
```
130173

src/QAToolKit.Engine.HttpTester.Test/HttpTesterClientTests.cs

Lines changed: 69 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -333,11 +333,10 @@ public async Task HttpTesterClientPostStringBodyWithFulUrl_Success()
333333
.WithMethod(HttpMethod.Post)
334334
.Start();
335335

336-
var msg = await response.Content.ReadAsStringAsync();
336+
var msg = await response.GetResponseBodyString();
337337

338338
Assert.True(client.Duration < 2000);
339339
Assert.True(response.IsSuccessStatusCode);
340-
//Assert.Equal("Giant", msg.brand.ToString());
341340
}
342341
}
343342

@@ -460,7 +459,7 @@ public async Task HttpTesterClientFileUpload_Success()
460459

461460
var msg = await response.GetResponseBodyString();
462461

463-
Assert.Equal("File name: miha.txt, length: 119305", msg);
462+
Assert.Equal("\"File name: miha.txt, length: 119305\"", msg);
464463
Assert.True(response.IsSuccessStatusCode);
465464
}
466465
}
@@ -483,7 +482,7 @@ public async Task HttpTesterClientFileUpload2_Success()
483482

484483
var msg = await response.GetResponseBodyString();
485484

486-
Assert.Equal("File name: miha.txt, length: 119305", msg);
485+
Assert.Equal("\"File name: miha.txt, length: 119305\"", msg);
487486
Assert.True(response.IsSuccessStatusCode);
488487
}
489488
}
@@ -508,7 +507,7 @@ public async Task HttpTesterClientBrochureUpload_Success()
508507

509508
var msg = await response.GetResponseBodyString();
510509

511-
Assert.Equal("File name: Brochure 2000, image name: miha.txt, length: 119305", msg);
510+
Assert.Equal("\"File name: Brochure 2000, image name: miha.txt, length: 119305\"", msg);
512511
Assert.True(response.IsSuccessStatusCode);
513512
}
514513
}
@@ -553,5 +552,70 @@ public void HttpTesterClientBrochureUploadMultipartPresent_Fails()
553552
Assert.StartsWith("Body multipart/form-data already defined", exception.Message);
554553
}
555554
}
555+
556+
[Fact]
557+
public async Task HttpTesterClientAddPostHttpRequest_Success()
558+
{
559+
var urlSource = new SwaggerUrlSource(options =>
560+
{
561+
options.AddBaseUrl(new Uri("https://qatoolkitapi.azurewebsites.net/"));
562+
options.AddRequestFilters(new RequestFilter()
563+
{
564+
EndpointNameWhitelist = new string[] { "NewBike" }
565+
});
566+
options.UseSwaggerExampleValues = true;
567+
});
568+
569+
var requests = await urlSource.Load(new Uri[] {
570+
new Uri("https://qatoolkitapi.azurewebsites.net/swagger/v1/swagger.json")
571+
});
572+
573+
using (var client = new HttpTesterClient())
574+
{
575+
var response = await client
576+
.CreateHttpRequest(requests.FirstOrDefault())
577+
.WithJsonBody(BicycleFixture.Get())
578+
.Start();
579+
580+
var msg = await response.GetResponseBody<Bicycle>();
581+
582+
Assert.True(client.Duration < 2000);
583+
Assert.True(response.IsSuccessStatusCode);
584+
Assert.Equal("Giant", msg.Brand);
585+
}
586+
}
587+
588+
[Fact]
589+
public async Task HttpTesterClientAddGetHttpRequest_Success()
590+
{
591+
var urlSource = new SwaggerUrlSource(options =>
592+
{
593+
options.AddBaseUrl(new Uri("https://qatoolkitapi.azurewebsites.net/"));
594+
options.AddRequestFilters(new RequestFilter()
595+
{
596+
EndpointNameWhitelist = new string[] { "GetAllBikes" }
597+
});
598+
options.UseSwaggerExampleValues = true;
599+
});
600+
601+
var requests = await urlSource.Load(new Uri[] {
602+
new Uri("https://qatoolkitapi.azurewebsites.net/swagger/v1/swagger.json")
603+
});
604+
605+
using (var client = new HttpTesterClient())
606+
{
607+
var response = await client
608+
.CreateHttpRequest(requests.FirstOrDefault())
609+
.Start();
610+
611+
var msg = await response.GetResponseBody<List<Bicycle>>();
612+
613+
var expecterResponse = BicycleFixture.GetBicycles().ToExpectedObject();
614+
expecterResponse.ShouldEqual(msg);
615+
616+
Assert.True(client.Duration < 2000);
617+
Assert.True(response.IsSuccessStatusCode);
618+
}
619+
}
556620
}
557621
}

src/QAToolKit.Engine.HttpTester/HttpTesterClient.cs

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
using Newtonsoft.Json;
2+
using QAToolKit.Core.Models;
23
using QAToolKit.Engine.HttpTester.Exceptions;
34
using QAToolKit.Engine.HttpTester.Interfaces;
45
using System;
56
using System.Collections.Generic;
67
using System.Diagnostics;
78
using System.IO;
9+
using System.Linq;
810
using System.Net;
911
using System.Net.Http;
1012
using System.Net.Http.Headers;
@@ -253,6 +255,75 @@ public IHttpTesterClient WithMultipart(string httpContentName, string value)
253255
return this;
254256
}
255257

258+
/// <summary>
259+
/// Create a HTTP tester client from QAToolKit HttpRequest object
260+
/// </summary>
261+
/// <param name="httpRequest">Create tester client with BaseUrl, Path, HttpMethod, Headers and URL Query paramteres read from HttpRequest object. Specify other values and parameters manually.</param>
262+
/// <param name="validateCertificate"></param>
263+
/// <returns></returns>
264+
public IHttpTesterClient CreateHttpRequest(HttpRequest httpRequest, bool validateCertificate = true)
265+
{
266+
if (httpRequest == null)
267+
{
268+
throw new QAToolKitEngineHttpTesterException("'HttpRequest' is null. Pass in the valid object.");
269+
}
270+
271+
if (HttpClient != null)
272+
{
273+
throw new QAToolKitEngineHttpTesterException("HttpClient is already instantiated. Create new 'HttpTesterClient'.");
274+
}
275+
276+
var baseAddress = new Uri(httpRequest.BasePath);
277+
278+
HttpHandler = new HttpClientHandler();
279+
280+
if (!validateCertificate &&
281+
(baseAddress.Scheme == Uri.UriSchemeHttp || baseAddress.Scheme == Uri.UriSchemeHttps))
282+
{
283+
HttpHandler.ClientCertificateOptions = ClientCertificateOption.Manual;
284+
HttpHandler.ServerCertificateCustomValidationCallback =
285+
(httpRequestMessage, cert, cetChain, policyErrors) =>
286+
{
287+
return true;
288+
};
289+
}
290+
291+
HttpClient = new HttpClient(HttpHandler)
292+
{
293+
BaseAddress = baseAddress
294+
};
295+
296+
297+
if (string.IsNullOrEmpty(httpRequest.Path))
298+
{
299+
throw new QAToolKitEngineHttpTesterException("HttpRequest Path is required.");
300+
}
301+
302+
_path = httpRequest.Path;
303+
304+
_httpMethod = httpRequest.Method;
305+
306+
//Query parameters
307+
if (_queryParameters == null)
308+
_queryParameters = new Dictionary<string, string>();
309+
310+
foreach (var parameter in httpRequest.Parameters.Where(t => t.Location == Location.Query && t.Value != null))
311+
{
312+
_queryParameters.Add(parameter.Name, parameter.Value);
313+
}
314+
315+
//Headers
316+
if (_headers == null)
317+
_headers = new Dictionary<string, string>();
318+
319+
foreach (var header in httpRequest.Parameters.Where(t => t.Location == Location.Header && t.Value != null))
320+
{
321+
_headers.Add(header.Name, header.Value);
322+
}
323+
324+
return this;
325+
}
326+
256327
/// <summary>
257328
/// Start the HTTP request
258329
/// </summary>

src/QAToolKit.Engine.HttpTester/Interfaces/IHttpTesterClient.cs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
using System;
1+
using QAToolKit.Core.Models;
2+
using System;
23
using System.Collections.Generic;
34
using System.Net.Http;
45
using System.Threading.Tasks;
@@ -18,6 +19,13 @@ public interface IHttpTesterClient
1819
/// <returns></returns>
1920
IHttpTesterClient CreateHttpRequest(Uri baseAddress, bool validateCertificate = true);
2021
/// <summary>
22+
/// Create a HTTP request client from QAToolKit HttpRequest object
23+
/// </summary>
24+
/// <param name="httpRequest"></param>
25+
/// <param name="validateCertificate"></param>
26+
/// <returns></returns>
27+
IHttpTesterClient CreateHttpRequest(HttpRequest httpRequest, bool validateCertificate = true);
28+
/// <summary>
2129
/// Add URL path to the HTTP client
2230
/// </summary>
2331
/// <param name="urlPath"></param>

0 commit comments

Comments
 (0)