Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix mocks being returned even when the condition script throws an error #128

Merged
merged 1 commit into from
Mar 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Mockaco.sln
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
README.md = README.md
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Mockaco.Tests", "test\Mockaco.AspNetCore.Tests\Mockaco.AspNetCore.Tests.csproj", "{EE57B1B4-29D2-4AE3-8F23-5E622302C30F}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Mockaco.AspNetCore.Tests", "test\Mockaco.AspNetCore.Tests\Mockaco.AspNetCore.Tests.csproj", "{EE57B1B4-29D2-4AE3-8F23-5E622302C30F}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Mockaco.AspNetCore", "src\Mockaco.AspNetCore\Mockaco.AspNetCore.csproj", "{7766C592-9887-4162-8B9C-51003ED30335}"
EndProject
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace Mockaco
{
Expand Down Expand Up @@ -43,12 +40,18 @@ public async Task<bool> IsMatch(HttpRequest httpRequest, Mock mock)
}

await conditionMatcherScriptContext.AttachRouteParameters(httpRequest, mock);
try
{
var template = await _templateTransformer.Transform(mock.RawTemplate, conditionMatcherScriptContext);

var template = await _templateTransformer.Transform(mock.RawTemplate, conditionMatcherScriptContext);

var isMatch = template.Request?.Condition ?? true;
var isMatch = template.Request?.Condition ?? true;

return isMatch;
return isMatch;
}
catch (Exception)
{
return false;
}
}

//TODO Remove redundant code
Expand Down
32 changes: 8 additions & 24 deletions src/Mockaco.AspNetCore/Templating/TemplateTransformer.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
using Microsoft.Extensions.Logging;
using Mono.TextTemplating;
using Newtonsoft.Json;
using System;
using System.Text;
using System.Threading.Tasks;

namespace Mockaco
{
Expand All @@ -28,12 +26,12 @@ public async Task<Template> TransformAndSetVariables(IRawTemplate rawTemplate, I
}

public async Task<Template> Transform(IRawTemplate rawTemplate, IScriptContext scriptContext)
{
{
scriptContext.Global.DisableWriting();

var transformedTemplate = await Transform(rawTemplate.Content, scriptContext);

return JsonConvert.DeserializeObject<Template>(transformedTemplate);
return JsonConvert.DeserializeObject<Template>(transformedTemplate);
}

private async Task<string> Transform(string input, IScriptContext scriptContext)
Expand All @@ -57,23 +55,11 @@ private async Task<string> Transform(string input, IScriptContext scriptContext)
case State.Directive:
break;
case State.Expression:

object expressionResult;

try
{
expressionResult = await Run(tokeniser.Value, scriptContext);
}
catch (Exception)
{
expressionResult = string.Empty;
}

var expressionResult = await Run(tokeniser.Value, scriptContext);
output.Append(expressionResult);

break;
case State.Block:
await Run(tokeniser.Value, scriptContext);
await Run(tokeniser.Value, scriptContext);
break;
case State.Helper:
break;
Expand All @@ -95,21 +81,19 @@ private async Task<string> Transform(string input, IScriptContext scriptContext)

private async Task<object> Run(string code, IScriptContext scriptContext)
{
object result = null;

try
{
result = await _scriptRunnerFactory.Invoke<IScriptContext, object>(scriptContext, code);
var result = await _scriptRunnerFactory.Invoke<IScriptContext, object>(scriptContext, code);

_logger.LogDebug("Processed script {code} with result {result}", code, result);

return result;
}
catch (Exception ex)
{
_logger.LogError(ex, "Processed script {code} with error", code);
throw;
}

return result;
}

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
using FluentAssertions;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Moq;
using System.Net;

namespace Mockaco.AspNetCore.Tests.Templating.Request
{
public sealed class RequestConditionMatcherTest
{
private readonly IGlobalVariableStorage _globalVariableStorage;
private readonly ITemplateTransformer _templateTransformer;
private readonly IFakerFactory _fakerFactory;
private readonly ILogger<RequestConditionMatcher> _logger;
private readonly IRequestBodyFactory _requestBodyFactory;
private readonly IMockacoContext _mockacoContext;

public RequestConditionMatcherTest()
{
_templateTransformer = Moq.Mock.Of<ITemplateTransformer>();
_fakerFactory = Moq.Mock.Of<IFakerFactory>();
_requestBodyFactory = Moq.Mock.Of<IRequestBodyFactory>();
_mockacoContext = Moq.Mock.Of<IMockacoContext>();
_globalVariableStorage = Moq.Mock.Of<IGlobalVariableStorage>();
_logger = Moq.Mock.Of<ILogger<RequestConditionMatcher>>();
}

[Fact]
public async Task Condition_Does_Not_Match_On_Script_Error()
{
Moq.Mock.Get(_templateTransformer)
.Setup(n => n.Transform(It.IsAny<IRawTemplate>(), It.IsAny<IScriptContext>()))
.ThrowsAsync(new NotImplementedException());

Moq.Mock.Get(_mockacoContext).Setup(c => c.Errors).Returns(new List<Error>());

var conditionMatcher = new RequestConditionMatcher(
_templateTransformer, _fakerFactory, _requestBodyFactory, _mockacoContext, _globalVariableStorage, _logger);

var httpRequest = new Mock<HttpRequest>();
httpRequest.Setup(h => h.HttpContext)
.Returns(Moq.Mock.Of<HttpContext>(c => c.Request == httpRequest.Object));

var rawTemplate = Moq.Mock.Of<IRawTemplate>();
Moq.Mock.Get(rawTemplate).Setup(r => r.Content).Returns(@"");

var mock = new Mock("GET", "/ping", rawTemplate, true);

var isMatch = await conditionMatcher.IsMatch(httpRequest.Object, mock);

isMatch.Should().Be(false);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -68,16 +68,16 @@ private static void Assert(Template transformedTemplate)
transformedTemplate.Response.Headers.Should()
.HaveCount(2);

transformedTemplate.Response.Body["id"].ToString().Should()
transformedTemplate.Response.Body["id"]?.ToString().Should()
.Be("1");

transformedTemplate.Response.Body["message"].ToString().Should()
transformedTemplate.Response.Body["message"]?.ToString().Should()
.Be("Hello world");

transformedTemplate.Response.Body["createdAt"].Type.Should()
transformedTemplate.Response.Body["createdAt"]?.Type.Should()
.Be(JTokenType.Date);

transformedTemplate.Response.Body["createdAt"].Value<DateTime>().Should()
transformedTemplate.Response.Body["createdAt"]?.Value<DateTime>().Should()
.Be(new DateTime(2012, 04, 23, 18, 25, 43, 511, DateTimeKind.Utc));

transformedTemplate.Callback.Method.Should()
Expand All @@ -98,19 +98,19 @@ private static void Assert(Template transformedTemplate)
transformedTemplate.Callback.Headers.Should()
.HaveCount(2);

transformedTemplate.Callback.Body["key"].ToString().Should()
transformedTemplate.Callback.Body["key"]?.ToString().Should()
.Be("2");

transformedTemplate.Callback.Body["key"].Type.Should()
transformedTemplate.Callback.Body["key"]?.Type.Should()
.Be(JTokenType.Integer);

transformedTemplate.Callback.Body["topic"].ToString().Should()
transformedTemplate.Callback.Body["topic"]?.ToString().Should()
.Be("Hello callback");

transformedTemplate.Callback.Body["updatedAt"].Type.Should()
transformedTemplate.Callback.Body["updatedAt"]?.Type.Should()
.Be(JTokenType.Date);

transformedTemplate.Callback.Body["updatedAt"].Value<DateTime>().Should()
transformedTemplate.Callback.Body["updatedAt"]?.Value<DateTime>().Should()
.Be(new DateTime(2003, 02, 01, 19, 00, 00, DateTimeKind.Utc));
}

Expand Down
Loading