Skip to content

Commit

Permalink
fixed accept data in json format
Browse files Browse the repository at this point in the history
  • Loading branch information
barzin144 committed Oct 31, 2024
1 parent 6d33948 commit 61c7517
Show file tree
Hide file tree
Showing 5 changed files with 88 additions and 31 deletions.
82 changes: 62 additions & 20 deletions Zus.Cli.Test/Commands/SendRequestTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Net.Http.Headers;
using System.Text;
using Zus.Cli.Commands;
using Zus.Cli.Helpers;
using Zus.Cli.Models;
using Zus.Cli.Services;

Expand Down Expand Up @@ -255,7 +256,7 @@ public async void SendAsync_Should_ReturnResult(RequestMethod requestMethod)
public async void SendAsync_Should_ReturnError_When_PreRequestNameIsNotFound()
{
//Arrange
Request request = new Request("http://test.com", null, RequestMethod.Get, "", false, "preRequest_name");
Request request = new Request("http://test.com", null, RequestMethod.Get, "", false, false, "preRequest_name");
_mockFileService.Setup(x => x.GetAsync(It.IsAny<string>())).ReturnsAsync(null as Request);
//Act
var result = await _target.SendAsync(request, null, false);
Expand All @@ -270,7 +271,7 @@ public async void SendAsync_Should_ReturnError_When_PreRequestNameIsNotFound()
public async void SendAsync_Should_ReturnResult_When_HasPreRequest()
{
//Arrange
Request request = new Request("http://test.com", "{pr.token}", RequestMethod.Post, "requestData:{pr.data}", false, "preRequest_name");
Request request = new Request("http://test.com", "{pr.token}", RequestMethod.Post, "requestData:{pr.data}", false, false, "preRequest_name");
Request preRequest = new Request("http://prerequest.com", null, RequestMethod.Get);
_mockFileService.Setup(x => x.GetAsync("preRequest_name")).ReturnsAsync(preRequest);
_mockHttpHandler.Setup(x => x.GetAsync("http://prerequest.com"))
Expand Down Expand Up @@ -331,7 +332,7 @@ public async void SendAsync_Should_ReturnError_When_VariableNotFound()
public async void SendAsync_Should_ReturnError_When_PreRequestResponseIsString()
{
//Arrange
Request request = new Request("http://test.com", null, RequestMethod.Post, "requestData:{pr.data}", false, "preRequest_name");
Request request = new Request("http://test.com", null, RequestMethod.Post, "requestData:{pr.data}", false, false, "preRequest_name");
Request preRequest = new Request("http://prerequest.com", null, RequestMethod.Get);
_mockFileService.Setup(x => x.GetAsync("preRequest_name")).ReturnsAsync(preRequest);
_mockHttpHandler.Setup(x => x.GetAsync("http://prerequest.com"))
Expand All @@ -356,7 +357,7 @@ public async void SendAsync_Should_ReturnError_When_PreRequestResponseIsString()
public async void SendAsync_Should_ReturnResult_When_HasPreRequestWithStringContent()
{
//Arrange
Request request = new Request("http://test.com", null, RequestMethod.Post, "requestData:{pr.$}", false, "preRequest_name");
Request request = new Request("http://test.com", null, RequestMethod.Post, "requestData:{pr.$}", false, false, "preRequest_name");
Request preRequest = new Request("http://prerequest.com", null, RequestMethod.Get);
_mockFileService.Setup(x => x.GetAsync("preRequest_name")).ReturnsAsync(preRequest);
_mockHttpHandler.Setup(x => x.GetAsync("http://prerequest.com"))
Expand All @@ -376,32 +377,73 @@ public async void SendAsync_Should_ReturnResult_When_HasPreRequestWithStringCont
}

[Theory]
[InlineData(true, "application/x-www-form-urlencoded")]
[InlineData(false, "application/json")]
[InlineData(null, "application/json")]
public async void SendAsync_Should_AddProperHeaderToHttpClient(bool? formFormat, string headerValue)
[InlineData(true, false, "application/x-www-form-urlencoded")]
[InlineData(true, true, "application/x-www-form-urlencoded")]
[InlineData(true, null, "application/x-www-form-urlencoded")]
[InlineData(false, true, "application/json")]
[InlineData(false, false, "application/json")]
[InlineData(null, null, "application/json")]
public async void SendAsync_Should_AddProperHeaderToHttpClient(bool? formFormat, bool? jsonFormat, string headerValue)
{
//Arrange
string data = "requestData:data";
Request request = new Request("http://test.com", null, RequestMethod.Post, data, formFormat);
_mockHttpHandler.Setup(x => x.PostAsync(It.IsAny<string>(), It.IsAny<HttpContent>())).
Returns(Task.FromResult(
Request request = new Request("http://test.com", null, RequestMethod.Post, data, formFormat, jsonFormat);

//Act & Assert
if (formFormat.HasValue && formFormat.Value == true)
{
FormUrlEncodedContent formFormatData = data.ToFormUrlEncodedContent();
HttpContent capturedContent = new FormUrlEncodedContent([]);

_mockHttpHandler.Setup(x => x.PostAsync(It.IsAny<string>(), It.IsAny<HttpContent>())).
Callback((string url, HttpContent content) => capturedContent = content).
ReturnsAsync(
new HttpResponseMessage()
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent("{\"data\":\"def\"}")
}
));
//Act
var result = await _target.SendAsync(request, null, false);
//Assert
if (formFormat.HasValue && formFormat.Value == true)
});
//Act
await _target.SendAsync(request, null, false);

Assert.Equal(await formFormatData.ReadAsStringAsync(), await capturedContent.ReadAsStringAsync());
}
else if (jsonFormat.HasValue && jsonFormat.Value == true)
{
_mockHttpHandler.Verify(x => x.PostAsync(It.IsAny<string>(), It.IsAny<FormUrlEncodedContent>()), Times.Once);
StringContent jsonFormatData = data.ToJsonStringContent();
HttpContent capturedContent = new StringContent("");

_mockHttpHandler.Setup(x => x.PostAsync(It.IsAny<string>(), It.IsAny<HttpContent>())).
Callback((string url, HttpContent content) => capturedContent = content).
ReturnsAsync(
new HttpResponseMessage()
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent("{\"data\":\"def\"}")
});
//Act
await _target.SendAsync(request, null, false);

Assert.Equal(await jsonFormatData.ReadAsStringAsync(), await capturedContent.ReadAsStringAsync());
}
else
{
_mockHttpHandler.Verify(x => x.PostAsync(It.IsAny<string>(), It.IsAny<StringContent>()), Times.Once);
StringContent stringData = data.ToStringContent();
HttpContent capturedContent = new StringContent("");

_mockHttpHandler.Setup(x => x.PostAsync(It.IsAny<string>(), It.IsAny<HttpContent>())).
Callback((string url, HttpContent content) => capturedContent = content).
ReturnsAsync(
new HttpResponseMessage()
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent("{\"data\":\"def\"}")
});
//Act
await _target.SendAsync(request, null, false);

Assert.Equal(await stringData.ReadAsStringAsync(), await capturedContent.ReadAsStringAsync());

}
_mockHttpHandler.Verify(x => x.AddHeader(new MediaTypeWithQualityHeaderValue(headerValue)), Times.Once);
}
Expand All @@ -422,7 +464,7 @@ public async void SendAsync_Should_AddAuthToHttpClientHeader()
public async void SendAsync_Should_SendRequest_When_RegexInDataIsNotValid()
{
//Arrange
Request request = new Request("http://test.com", null, RequestMethod.Post, "requestData:{prr.data}", false, "preRequest_name");
Request request = new Request("http://test.com", null, RequestMethod.Post, "requestData:{prr.data}", false, false, "preRequest_name");
Request preRequest = new Request("http://prerequest.com", null, RequestMethod.Get);
_mockFileService.Setup(x => x.GetAsync("preRequest_name")).ReturnsAsync(preRequest);
_mockHttpHandler.Setup(x => x.GetAsync("http://prerequest.com"))
Expand Down
10 changes: 7 additions & 3 deletions Zus.Cli/Commands/SendRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ private async Task<HttpResponseMessage> SendRequestAsync(Request request)
case RequestMethod.Get:
return await GetAsync(request.Url);
case RequestMethod.Post:
return await PostAsync(request.Url, request.Data, request.FormFormat ?? false);
return await PostAsync(request.Url, request.Data, request.FormFormat ?? false, request.JsonFormat ?? false);
default:
throw new Exception("Request method is not valid.");
}
Expand All @@ -229,16 +229,20 @@ private async Task<HttpResponseMessage> GetAsync(string url)
return await _httpHandler.GetAsync(url);
}

private async Task<HttpResponseMessage> PostAsync(string url, string data, bool form)
private async Task<HttpResponseMessage> PostAsync(string url, string data, bool form, bool json)
{
if (form)
{
return await _httpHandler.PostAsync(url, data.ToFormUrlEncodedContent());
}
else
else if (json)
{
return await _httpHandler.PostAsync(url, data.ToJsonStringContent());
}
else
{
return await _httpHandler.PostAsync(url, data.ToStringContent());
}
}

[GeneratedRegex(@"\{pr\.(?<PR>(\w+|\$))\}", RegexOptions.Compiled)]
Expand Down
16 changes: 12 additions & 4 deletions Zus.Cli/Helpers/ExtensionMethods.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Net.Http.Json;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.RegularExpressions;

namespace Zus.Cli.Helpers;

Expand Down Expand Up @@ -67,6 +68,11 @@ internal static async Task<JsonElement> ToJsonElement(this HttpResponseMessage r
}
}

internal static StringContent ToStringContent(this string data)
{
return new StringContent(data, Encoding.UTF8, "application/json");
}

internal static StringContent ToJsonStringContent(this string data)
{
var dataDic = ConvertStringDataToDictionary(data);
Expand All @@ -84,11 +90,13 @@ internal static Dictionary<string, string> ConvertStringDataToDictionary(string
{
Dictionary<string, string> dataDic = [];

string[] keyValueList = data.Split(',');
foreach (var keyValue in keyValueList)
Regex regex = new Regex(@"(?<KEY>\w+):(?<VALUE>(\[[^\]]*\])|(\{[^\}]*\})|([^,]*))");

MatchCollection matches = regex.Matches(data);

foreach (Match match in matches)
{
string[] separatedKeyValue = keyValue.Split(':');
dataDic.Add(separatedKeyValue[0], separatedKeyValue[1]);
dataDic.Add(match.Groups["KEY"].Value, match.Groups["VALUE"].Value);
}

return dataDic;
Expand Down
4 changes: 3 additions & 1 deletion Zus.Cli/Models/Request.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,14 @@ public enum RequestMethod
}
public class Request : IData
{
public Request(string url, string? auth, RequestMethod requestMethod, string data = "", bool? formFormat = false, string? preRequest = "")
public Request(string url, string? auth, RequestMethod requestMethod, string data = "", bool? formFormat = false, bool? jsonFormat = false, string? preRequest = "")
{
Url = url;
Auth = auth;
RequestMethod = requestMethod;
Data = data;
FormFormat = formFormat;
JsonFormat = jsonFormat;
PreRequest = preRequest;
}
public string Url { get; set; }
Expand All @@ -26,6 +27,7 @@ public Request(string url, string? auth, RequestMethod requestMethod, string dat
public RequestMethod RequestMethod { get; }
public string? Name { get; set; }
public bool? FormFormat { get; }
public bool? JsonFormat { get; }
public string? PreRequest { get; }
public string Id { get => Name ?? string.Empty; set => Name = value; }
}
7 changes: 4 additions & 3 deletions Zus.Cli/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,15 @@
.WithDescription("Send a Get request");

x.AddCommand("post", async ([Argument] string url,
[Option('d', Description = "Data format: Key:Value,Key:Value and wrap your data in double quote. Data will be sent in Json format by default. By adding -x flag change format to form-urlencoded")] string data,
[Option('d', Description = "Data format: Key:Value,Key:Value and wrap your data in single quote. Data will be sent in Json format by default. By adding -x flag change format to form-urlencoded")] string data,
[Option('a', Description = "Authentication Bearer Token")] string? auth,
[Option('n', Description = "Name for saving the request")] string? name,
[Option('p', Description = "Pre-request name")] string? preRequest,
[Option('x', Description = "Send data in form-urlencoded")] bool? formFormat,
[Option('x', Description = "Convert Key:Value data to form-urlencoded")] bool? formFormat,
[Option('j', Description = "Convert Key:Value data to Json format")] bool? jsonFormat,
[Option('f', Description = "Overwrite the existing request")] bool? force) =>
{
var request = new Request(url, auth, RequestMethod.Post, data, formFormat ?? false, preRequest);
var request = new Request(url, auth, RequestMethod.Post, data, formFormat ?? false, jsonFormat ?? false, preRequest);
Display.Result(await sendRequest.SendAsync(request, name, force ?? false));
})
.WithDescription("Send a Post request");
Expand Down

0 comments on commit 61c7517

Please sign in to comment.