Skip to content

Commit

Permalink
Merge pull request #25 from barzin144/feature/add-header-to-request
Browse files Browse the repository at this point in the history
Added header to request
  • Loading branch information
barzin144 authored Dec 2, 2024
2 parents ca9a702 + 1f29328 commit 93ad5b3
Show file tree
Hide file tree
Showing 7 changed files with 52 additions and 16 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ zus send post http://localhost:5000/api/Account/LoginWithFormData -x -d "usernam
```
| Options | Description |
| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| -d, --data | Data format: `Key:Value,Key:Value` and wrap your data in single or double quote. Data will be sent in Json format by default. By adding -x flag change format to form-urlencoded |
| -d, --data | Data format: `Key:Value,Key:Value` and wrap your data in single or double quote. Data will be sent in string format by default. By adding -x flag change format to form-urlencoded or -j for Json format|
| -a, --auth | Authentication Bearer Token |
| -n, --name | Name for saving the request |
| -x, --form-format | Convert Key:Value data to form-urlencoded format |
Expand Down
40 changes: 32 additions & 8 deletions Zus.Cli.Test/Commands/SendRequestTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -256,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, 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 @@ -271,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, 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 @@ -300,7 +300,7 @@ public async void SendAsync_Should_ReturnResult_When_HasPreRequest()
public async void SendAsync_Should_ReturnResult_When_HasVariable(string variableName)
{
//Arrange
Request request = new Request("http://test.com", null, RequestMethod.Post, $"requestData:{{var.{variableName}}}", false);
Request request = new Request("http://test.com", null, RequestMethod.Post, $"requestData:{{var.{variableName}}}", "", false);
_mockVariableService.Setup(x => x.GetDeserializeAsync()).ReturnsAsync(new List<LocalVariable> {
new LocalVariable(variableName, "abc")
});
Expand All @@ -316,7 +316,7 @@ public async void SendAsync_Should_ReturnResult_When_HasVariable(string variable
public async void SendAsync_Should_ReturnError_When_VariableNotFound()
{
//Arrange
Request request = new Request("http://test.com", null, RequestMethod.Post, "requestData:{var.data}", false);
Request request = new Request("http://test.com", null, RequestMethod.Post, "requestData:{var.data}", "", false);
_mockVariableService.Setup(x => x.GetDeserializeAsync()).ReturnsAsync(new List<LocalVariable>());
//Act
var result = await _target.SendAsync(request, null, false);
Expand All @@ -332,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, 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 @@ -357,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, 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 Down Expand Up @@ -387,7 +387,7 @@ public async void SendAsync_Should_AddProperHeaderToHttpClient(bool? formFormat,
{
//Arrange
string data = "requestData:data";
Request request = new Request("http://test.com", null, RequestMethod.Post, data, formFormat, jsonFormat);
Request request = new Request("http://test.com", null, RequestMethod.Post, data, "", formFormat, jsonFormat);

//Act & Assert
if (formFormat.HasValue && formFormat.Value == true)
Expand Down Expand Up @@ -460,11 +460,35 @@ public async void SendAsync_Should_AddAuthToHttpClientHeader()
_mockHttpHandler.Verify(x => x.AddHeader("Authorization", "Bearer abc"), Times.Once);
}

[Fact]
public async void SendAsync_Should_AddHeaderToGetHttpClientHeader()
{
//Arrange
Request request = new Request("http://test.com", null, RequestMethod.Get, "", "api-key:abc");
//Act
var result = await _target.SendAsync(request, null, false);
//Assert
_mockHttpHandler.Verify(x => x.GetAsync(It.IsAny<string>()), Times.Once);
_mockHttpHandler.Verify(x => x.AddHeader("api-key", "abc"), Times.Once);
}

[Fact]
public async void SendAsync_Should_AddHeaderToPostHttpClientHeader()
{
//Arrange
Request request = new Request("http://test.com", null, RequestMethod.Post, "propName:propValue", "api-key:abc");
//Act
var result = await _target.SendAsync(request, null, false);
//Assert
_mockHttpHandler.Verify(x => x.PostAsync(It.IsAny<string>(), It.IsAny<HttpContent>()), Times.Once);
_mockHttpHandler.Verify(x => x.AddHeader("api-key", "abc"), Times.Once);
}

[Fact]
public async void SendAsync_Should_SendRequest_When_RegexInDataIsNotValid()
{
//Arrange
Request request = new Request("http://test.com", null, RequestMethod.Post, "requestData:{prr.data}", false, 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
2 changes: 1 addition & 1 deletion Zus.Cli.Test/Models/RequestTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ public class RequestTests
public void Request_Should_SetIdAsName()
{
//Arrange
Request target = new("http://test.com", null, RequestMethod.Get);
Request target = new("http://test.com", null, RequestMethod.Get, "");
target.Name = "Test";
//Assert
Assert.Equal("Test", target.Id);
Expand Down
9 changes: 9 additions & 0 deletions Zus.Cli/Commands/SendRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,15 @@ private async Task<HttpResponseMessage> SendRequestAsync(Request request)
{
_httpHandler.AddHeader("Authorization", $"Bearer {request.Auth}");
}

if (string.IsNullOrEmpty(request.Header) == false)
{
foreach (var header in ExtensionMethods.ConvertStringDataToDictionary(request.Header))
{
_httpHandler.AddHeader(header.Key, header.Value);
}
}

if (string.IsNullOrEmpty(request.Data) == false)
{
if (request.FormFormat.HasValue && request.FormFormat == true)
Expand Down
2 changes: 1 addition & 1 deletion Zus.Cli/Helpers/ExtensionMethods.cs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ internal static Dictionary<string, string> ConvertStringDataToDictionary(string
{
Dictionary<string, string> dataDic = [];

Regex regex = new Regex(@"(?<KEY>\w+):(?<VALUE>(\[[^\]]*\])|(\{[^\}]*\})|([^,]*))");
Regex regex = new Regex(@"(?<KEY>[\w-_]+):(?<VALUE>(\[[^\]]*\])|(\{[^\}]*\})|([^,]*))");

MatchCollection matches = regex.Matches(data);

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,11 +10,12 @@ public enum RequestMethod
}
public class Request : IData
{
public Request(string url, string? auth, RequestMethod requestMethod, string data = "", bool? formFormat = false, bool? jsonFormat = false, string? preRequest = "")
public Request(string url, string? auth, RequestMethod requestMethod, string data = "", string? header = "", bool? formFormat = false, bool? jsonFormat = false, string? preRequest = "")
{
Url = url;
Auth = auth;
RequestMethod = requestMethod;
Header = header;
Data = data;
FormFormat = formFormat;
JsonFormat = jsonFormat;
Expand All @@ -25,6 +26,7 @@ public Request(string url, string? auth, RequestMethod requestMethod, string dat
public string Data { get; set; }
[JsonConverter(typeof(JsonStringEnumConverter<RequestMethod>))]
public RequestMethod RequestMethod { get; }
public string? Header { get; }
public string? Name { get; set; }
public bool? FormFormat { get; }
public bool? JsonFormat { get; }
Expand Down
9 changes: 5 additions & 4 deletions Zus.Cli/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,31 +6,32 @@

var app = CoconaApp.Create();


app.AddSubCommand("send", x =>
{
var sendRequest = ServiceFactory.GetSendRequestService();
x.AddCommand("get", async ([Argument] string url,
[Option('a', Description = "Authentication Bearer Token")] string? auth,
[Option('h', Description = "Add header to request, format: Key:Value,Key:Value and wrap your data in single quote.")] string? header,
[Option('n', Description = "Name for saving the request")] string? name,
[Option('p', Description = "Pre-request name")] string? preRequest,
[Option('f', Description = "Overwrite the existing request")] bool? force) =>
{
var request = new Request(url, auth, RequestMethod.Get, preRequest: preRequest);
var request = new Request(url, auth, RequestMethod.Get, header: header, preRequest: preRequest);
Display.Result(await sendRequest.SendAsync(request, name, force ?? false));
})
.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 single 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 string format by default. By adding -x flag change format to form-urlencoded or -j for Json format")] string data,
[Option('a', Description = "Authentication Bearer Token")] string? auth,
[Option('h', Description = "Add header to request, format: Key:Value,Key:Value and wrap your data in single quote.")] string? header,
[Option('n', Description = "Name for saving the request")] string? name,
[Option('p', Description = "Pre-request name")] string? preRequest,
[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, jsonFormat ?? false, preRequest);
var request = new Request(url, auth, RequestMethod.Post, data, header, 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 93ad5b3

Please sign in to comment.