public async Task StubContainer_GetStubsAsync_ByTenant_HappyFlow()
        {
            // arrange
            var stubSource1 = new Mock <IStubSource>();
            var stubSource2 = new Mock <IStubSource>();

            var stub1 = new StubModel {
                Tenant = "tenant1"
            };
            var stub2 = new StubModel {
                Tenant = "tenant2"
            };
            var stub3 = new StubModel {
                Tenant = "TENaNT1"
            };

            stubSource1
            .Setup(m => m.GetStubsAsync())
            .ReturnsAsync(new[] { stub1, stub2 });

            stubSource2
            .Setup(m => m.GetStubsAsync())
            .ReturnsAsync(new[] { stub3 });

            _stubSources.Add(stubSource1.Object);
            _stubSources.Add(stubSource2.Object);

            // act
            var result = (await _context.GetStubsAsync("tenant1")).ToArray();

            // assert
            Assert.AreEqual(2, result.Length);
            Assert.AreEqual(stub1, result[0].Stub);
            Assert.AreEqual(stub3, result[1].Stub);
        }
        public Task <bool> WriteToResponseAsync(StubModel stub, ResponseModel response)
        {
            if (stub.Response?.File == null)
            {
                return(Task.FromResult(false));
            }

            string finalFilePath = null;

            if (_fileService.FileExists(stub.Response.File))
            {
                finalFilePath = stub.Response.File;
            }
            else
            {
                // File doesn't exist, but might exist in the file root folder.
                var yamlFilePath = _stubRootPathResolver.GetStubRootPath();
                var tempPath     = Path.Combine(yamlFilePath, stub.Response.File);
                if (_fileService.FileExists(tempPath))
                {
                    finalFilePath = tempPath;
                }
            }

            if (finalFilePath == null)
            {
                return(Task.FromResult(false));
            }

            response.Body         = _fileService.ReadAllBytes(finalFilePath);
            response.BodyIsBinary = true;

            return(Task.FromResult(true));
        }
        public async Task BasicAuthenticationHandler_HandleStubGenerationAsync_HappyFlow()
        {
            // Arrange
            const string username = "******";
            const string password = "******";
            var          auth     = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username}:{password}"));
            var          stub     = new StubModel
            {
                Conditions = { Headers = new Dictionary <string, string> {
                                   { "Authorization", auth }
                               } }
            };
            var request = new RequestResultModel
            {
                RequestParameters = new RequestParametersModel
                {
                    Headers = new Dictionary <string, string>
                    {
                        { "Authorization", auth }
                    }
                }
            };

            // Act
            var result = await _handler.HandleStubGenerationAsync(request, stub);

            // Assert
            Assert.IsTrue(result);
            Assert.AreEqual(username, stub.Conditions.BasicAuthentication.Username);
            Assert.AreEqual(password, stub.Conditions.BasicAuthentication.Password);
            Assert.IsFalse(stub.Conditions.Headers.Any());
        }
        public async Task StubContainer_AddStubAsync_HappyFlow()
        {
            // arrange
            var stubToBeAdded = new StubModel {
                Id = "new-stub-02"
            };
            var stubSource = new Mock <IWritableStubSource>();

            stubSource
            .Setup(m => m.AddStubAsync(stubToBeAdded))
            .Returns(Task.CompletedTask);

            var stub = new StubModel {
                Id = "new-stub-01"
            };
            var readOnlyStubSource = new Mock <IStubSource>();

            readOnlyStubSource
            .Setup(m => m.GetStubsAsync())
            .ReturnsAsync(new[] { stub });

            _stubSources.Add(stubSource.Object);
            _stubSources.Add(readOnlyStubSource.Object);

            // act
            await _context.AddStubAsync(stubToBeAdded);

            // assert
            stubSource.Verify(m => m.AddStubAsync(stubToBeAdded), Times.Once);
        }
        public void GetPageModel_PassInDocTypeAlias_CurrentPageNotExist_ShouldGetFirstNodeOfDocTypeAliasAndReturnPageModelWithInfoOfThatNode()
        {
            // Arrange
            const string docTypeAlias = "testAlias";

            var applicationService = new ApplicationService(QueryFactoryMock.Object, UmbracoContextFactoryMock.Object,
                                                            UmbracoHelperFactoryMock.Object, PublishedContentExtensionsWrapperFactoryMock.Object);

            var nodeMock = new Mock <INode>();

            nodeMock.Setup(x => x.NodeTypeAlias).Returns(docTypeAlias);
            QueryFactoryMock.Setup(x => x.GetCurrentNode()).Returns((INode)null);
            QueryFactoryMock.Setup(x => x.GetFirstNodeOfType(docTypeAlias)).Returns(nodeMock.Object);

            var stubModel = new StubModel();

            PublishedContentExtensionsWrapperMock.Setup(x => x.As <StubModel>(nodeMock.Object.Id)).Returns(stubModel);

            // Act
            var result = applicationService.GetPageModel <StubModel>(docTypeAlias);

            // Assert
            Assert.IsNotNull(result);
            Assert.AreEqual(stubModel, result);
        }
示例#6
0
        public async Task <FullStubModel> AddStubAsync(StubModel stub)
        {
            if (string.IsNullOrWhiteSpace(stub.Id))
            {
                // If no ID is sent, create one here.
                var id = HashingUtilities.GetMd5String(JsonConvert.SerializeObject(stub));
                stub.Id = $"stub-{id}";
            }

            // Check that a stub with the new ID isn't already added to a readonly stub source.
            var stubs = await GetStubsAsync(true);

            if (stubs.Any(s => string.Equals(stub.Id, s.Stub.Id, StringComparison.OrdinalIgnoreCase)))
            {
                throw new ConflictException($"Stub with ID '{stub.Id}'.");
            }

            var source = GetWritableStubSource();
            await source.AddStubAsync(stub);

            return(new FullStubModel {
                Stub = stub, Metadata = new StubMetadataModel {
                    ReadOnly = false
                }
            });
        }
示例#7
0
        public async Task StubResponseGenerator_GenerateResponseAsync_HappyFlow_ResponseWriterPriority()
        {
            // arrange
            var stub = new StubModel();
            var responseWriterMock1 = new Mock <IResponseWriter>();
            var responseWriterMock2 = new Mock <IResponseWriter>();

            responseWriterMock1
            .Setup(m => m.WriteToResponseAsync(stub, It.IsAny <ResponseModel>()))
            .Callback <StubModel, ResponseModel>((s, r) => r.StatusCode = 401)
            .ReturnsAsync(true);
            responseWriterMock1
            .Setup(m => m.Priority)
            .Returns(10);

            responseWriterMock2
            .Setup(m => m.WriteToResponseAsync(stub, It.IsAny <ResponseModel>()))
            .Callback <StubModel, ResponseModel>((s, r) => r.StatusCode = 404)
            .ReturnsAsync(false);
            responseWriterMock2
            .Setup(m => m.Priority)
            .Returns(-10);

            _responseWriters.Add(responseWriterMock1.Object);
            _responseWriters.Add(responseWriterMock2.Object);

            // act
            var result = await _generator.GenerateResponseAsync(stub);

            // assert
            Assert.AreEqual(404, result.StatusCode);
        }
    public void EnsureStubId_StubIdNotSet_ShouldSetStubId()
    {
        // Arrange
        var stub = new StubModel
        {
            Id         = null,
            Conditions = new StubConditionsModel
            {
                Url = new StubUrlConditionModel
                {
                    Path = "/path"
                }
            },
            Response = new StubResponseModel
            {
                Text = "OK!!"
            }
        };

        // Act
        var result = stub.EnsureStubId();

        // Assert
        Assert.AreEqual(stub.Id, result);
        Assert.AreEqual("generated-0636a401deba2996db19d55558faf594", result);
    }
    /// <inheritdoc />
    public async Task <StubModel> ConvertToStubAsync(OpenApiServer server, OpenApiLine line, string tenant)
    {
        var request = new HttpRequestModel
        {
            Body    = _openApiDataFiller.BuildRequestBody(line.Operation),
            Headers = _openApiDataFiller.BuildRequestHeaders(line.Operation),
            Method  = line.OperationType.ToString().ToUpper(),
            Url     = $"{_openApiDataFiller.BuildServerUrl(server)}{_openApiDataFiller.BuildRelativeRequestPath(line.Operation, line.PathKey)}"
        };
        var response = new HttpResponseModel
        {
            Content    = _openApiDataFiller.BuildResponseBody(line.Response),
            Headers    = _openApiDataFiller.BuildResponseHeaders(line.Response),
            StatusCode = _openApiDataFiller.BuildHttpStatusCode(line.ResponseKey)
        };
        var stub = new StubModel
        {
            Tenant      = tenant,
            Description = line.Operation.Summary,
            Conditions  = await _httpRequestToConditionsService.ConvertToConditionsAsync(request),
            Response    = await _httpResponseToStubResponseService.ConvertToResponseAsync(response),
        };

        stub.EnsureStubId();
        return(stub);
    }
        public async Task StubContainer_DeleteAllStubsAsync_HappyFlow()
        {
            // arrange
            var stubSource = new Mock <IWritableStubSource>();

            var stub1 = new StubModel {
                Id = "stub1", Tenant = "tenant1"
            };
            var stub2 = new StubModel {
                Id = "stub2", Tenant = "tenant2"
            };
            var stub3 = new StubModel {
                Id = "stub3", Tenant = "tenant1"
            };

            stubSource
            .Setup(m => m.GetStubsAsync())
            .ReturnsAsync(new[] { stub1, stub2, stub3 });

            _stubSources.Add(stubSource.Object);

            // act
            await _context.DeleteAllStubsAsync();

            // assert
            stubSource.Verify(m => m.DeleteStubAsync(stub1.Id), Times.Once);
            stubSource.Verify(m => m.DeleteStubAsync(stub2.Id), Times.Once);
            stubSource.Verify(m => m.DeleteStubAsync(stub3.Id), Times.Once);
        }
示例#11
0
        public async Task RestApiIntegration_Stub_Add_Json_StubIdAlreadyExistsInReadOnlySource_ShouldReturn409()
        {
            // arrange
            var request = new StubDto
            {
                Id = "situation-01"
            };

            var existingStub = new StubModel
            {
                Id = "situation-01"
            };

            ReadOnlyStubSource
            .Setup(m => m.GetStubsAsync())
            .ReturnsAsync(new[] { existingStub });

            // Act
            var exception = await Assert.ThrowsExceptionAsync <SwaggerException <ProblemDetails> >(() => GetFactory()
                                                                                                   .StubClient
                                                                                                   .AddAsync(request));

            // Assert
            Assert.AreEqual(409, exception.StatusCode);
        }
示例#12
0
        public async Task DynamicResponseWriter_WriteToResponseAsync_OnlyBodySet_ShouldParseBody()
        {
            // arrange
            var stub = new StubModel
            {
                Response = new StubResponseModel
                {
                    EnableDynamicMode = true
                }
            };
            const string body     = "this is the body";
            var          response = new ResponseModel
            {
                Body = Encoding.UTF8.GetBytes(body)
            };

            _variableParserMock
            .Setup(m => m.Parse(It.IsAny <string>()))
            .Returns <string>(i => i);

            // act
            var result = await _writer.WriteToResponseAsync(stub, response);

            // assert
            Assert.IsTrue(result);
            _variableParserMock.Verify(m => m.Parse(body), Times.Once);
        }
示例#13
0
        public async Task FileResponseWriter_WriteToResponseAsync_HappyFlow_FileFoundDirectly()
        {
            // arrange
            var body = new byte[] { 1, 2, 3 };
            var stub = new StubModel
            {
                Response = new StubResponseModel
                {
                    File = @"C:\tmp\image.png"
                }
            };

            var response = new ResponseModel();

            _fileServiceMock
            .Setup(m => m.FileExists(stub.Response.File))
            .Returns(true);

            _fileServiceMock
            .Setup(m => m.ReadAllBytes(stub.Response.File))
            .Returns(body);

            // act
            var result = await _writer.WriteToResponseAsync(stub, response);

            // assert
            Assert.IsTrue(result);
            Assert.AreEqual(body, response.Body);
        }
        public async Task HtmlResponseWriter_WriteToResponseAsync_HappyFlow_ContentTypeHeaderAlreadySet_HeaderShouldBeRespected()
        {
            // arrange
            const string responseText          = "<html>";
            var          expectedResponseBytes = Encoding.UTF8.GetBytes(responseText);
            var          stub = new StubModel
            {
                Response = new StubResponseModel
                {
                    Html = responseText
                }
            };

            var response = new ResponseModel();

            response.Headers.Add("Content-Type", "text/plain");

            // act
            var result = await _writer.WriteToResponseAsync(stub, response);

            // assert
            Assert.IsTrue(result);
            Assert.IsTrue(expectedResponseBytes.SequenceEqual(expectedResponseBytes));
            Assert.AreEqual("text/plain", response.Headers["Content-Type"]);
        }
示例#15
0
        public async Task TextResponseWriter_WriteToResponseAsync_HappyFlow_ContentTypeHeaderAlreadySet_HeaderShouldBeRespected()
        {
            // arrange
            const string text         = "bla123";
            var          expectedBody = Encoding.UTF8.GetBytes(text);
            var          stub         = new StubModel
            {
                Response = new StubResponseModel
                {
                    Text = text
                }
            };

            var response = new ResponseModel();

            response.Headers.Add("Content-Type", "text/xml");

            // act
            var result = await _writer.WriteToResponseAsync(stub, response);

            // assert
            Assert.IsTrue(result);
            Assert.IsTrue(expectedBody.SequenceEqual(response.Body));
            Assert.AreEqual("text/xml", response.Headers["Content-Type"]);
        }
示例#16
0
    /// <inheritdoc />
    public ConditionCheckResultModel Validate(StubModel stub)
    {
        var result = new ConditionCheckResultModel();

        if (stub.Conditions?.Json == null)
        {
            return(result);
        }

        var convertedJsonConditions = ConvertJsonConditions(stub.Conditions.Json);

        var body = _httpContextService.GetBody();

        try
        {
            var jToken     = JToken.Parse(body);
            var logResults = new List <string>();
            result.ConditionValidation = CheckSubmittedJson(convertedJsonConditions, jToken, logResults)
                ? ConditionValidationType.Valid
                : ConditionValidationType.Invalid;
            result.Log = string.Join(Environment.NewLine, logResults);
        }
        catch (JsonReaderException ex)
        {
            result.ConditionValidation = ConditionValidationType.Invalid;
            result.Log = ex.Message;
        }

        return(result);
    }
示例#17
0
    public async Task RestApiIntegration_Stub_Add_Json_StubIdAlreadyExistsInReadOnlySource_ShouldReturn409()
    {
        // arrange
        var stub = new StubDto {
            Id = "situation-01", Response = new StubResponseDto()
        };

        var existingStub = new StubModel {
            Id = "situation-01"
        };

        ReadOnlyStubSource
        .Setup(m => m.GetStubsAsync())
        .ReturnsAsync(new[] { existingStub });

        // Act
        var request = new HttpRequestMessage(HttpMethod.Post, $"{TestServer.BaseAddress}ph-api/stubs")
        {
            Content = new StringContent(JsonConvert.SerializeObject(stub), Encoding.UTF8, Constants.JsonMime)
        };

        using var response = await Client.SendAsync(request);

        // Assert
        Assert.AreEqual(HttpStatusCode.Conflict, response.StatusCode);
    }
        public async Task StubContainer_AddRequestResultAsync_HappyFlow()
        {
            // arrange
            var stubSource = new Mock <IWritableStubSource>();

            var stub = new StubModel {
                Id = "stub1", Tenant = "tenant1"
            };

            stubSource
            .Setup(m => m.GetStubsAsync())
            .ReturnsAsync(new[] { stub });

            var request = new RequestResultModel {
                ExecutingStubId = stub.Id
            };

            stubSource
            .Setup(m => m.AddRequestResultAsync(request))
            .Returns(Task.CompletedTask);

            _stubSources.Add(stubSource.Object);

            // act
            await _context.AddRequestResultAsync(request);

            // assert
            stubSource.Verify(m => m.AddRequestResultAsync(request), Times.Once);
            stubSource.Verify(m => m.CleanOldRequestResultsAsync(), Times.Once);

            Assert.AreEqual(stub.Tenant, request.StubTenant);
        }
        public Task <bool> HandleStubGenerationAsync(RequestResultModel request, StubModel stub)
        {
            var pair = request.RequestParameters.Headers.FirstOrDefault(p =>
                                                                        p.Key.Equals("Authorization", StringComparison.OrdinalIgnoreCase));

            if (string.IsNullOrWhiteSpace(pair.Value))
            {
                return(Task.FromResult(false));
            }

            var value = pair.Value;

            value = value.Replace("Basic ", string.Empty);
            var basicAuth = Encoding.UTF8.GetString(Convert.FromBase64String(value));
            var parts     = basicAuth.Split(':');

            if (parts.Length != 2)
            {
                return(Task.FromResult(false));
            }

            stub.Conditions.BasicAuthentication = new StubBasicAuthenticationModel
            {
                Username = parts[0],
                Password = parts[1]
            };

            // Make sure the original Authorization header is removed here.
            stub.Conditions.Headers = stub.Conditions.Headers
                                      .Where(h => !h.Key.Equals("Authorization", StringComparison.OrdinalIgnoreCase))
                                      .ToDictionary(d => d.Key, d => d.Value);

            return(Task.FromResult(true));
        }
        public async Task StubContainer_GetTenantNamesAsync_HappyFlow()
        {
            // arrange
            var stubSource = new Mock <IWritableStubSource>();

            var stub1 = new StubModel {
                Id = "stub1", Tenant = "tenant-2"
            };
            var stub2 = new StubModel {
                Id = "stub2", Tenant = "tenant-1"
            };
            var stub3 = new StubModel {
                Id = "stub3", Tenant = "tenant-1"
            };
            var stub4 = new StubModel {
                Id = "stub4", Tenant = null
            };
            var stub5 = new StubModel {
                Id = "stub5", Tenant = string.Empty
            };

            stubSource
            .Setup(m => m.GetStubsAsync())
            .ReturnsAsync(new[] { stub1, stub2, stub3, stub4, stub5 });

            _stubSources.Add(stubSource.Object);

            // act
            var result = await _context.GetTenantNamesAsync();

            // assert
            Assert.AreEqual(2, result.Count());
            Assert.AreEqual("tenant-1", result.ElementAt(0));
            Assert.AreEqual("tenant-2", result.ElementAt(1));
        }
示例#21
0
    /// <inheritdoc />
    public async Task <IEnumerable <FullStubModel> > GenerateCurlStubsAsync(string input, bool doNotCreateStub,
                                                                            string tenant)
    {
        _logger.LogDebug($"Creating stubs based on cURL command {input}.");
        var requests = _curlToHttpRequestMapper.MapCurlCommandsToHttpRequest(input);
        var results  = new List <FullStubModel>();

        foreach (var request in requests)
        {
            var conditions = await _httpRequestToConditionsService.ConvertToConditionsAsync(request);

            var stub = new StubModel
            {
                Tenant      = tenant,
                Description = $"{conditions.Method} request to path {conditions.Url?.Path}",
                Conditions  = conditions,
                Response    = { Text = "OK!" }
            };

            // Generate an ID based on the created stub.
            stub.EnsureStubId();
            results.Add(await CreateStub(doNotCreateStub, stub));
        }

        return(results);
    }
示例#22
0
        public async Task StubResponseGenerator_GenerateResponseAsync_HappyFlow()
        {
            // arrange
            var stub = new StubModel();
            var responseWriterMock1 = new Mock <IResponseWriter>();
            var responseWriterMock2 = new Mock <IResponseWriter>();

            responseWriterMock1
            .Setup(m => m.WriteToResponseAsync(stub, It.IsAny <ResponseModel>()))
            .Callback <StubModel, ResponseModel>((s, r) => r.StatusCode = 401)
            .ReturnsAsync(true);

            responseWriterMock2
            .Setup(m => m.WriteToResponseAsync(stub, It.IsAny <ResponseModel>()))
            .Callback <StubModel, ResponseModel>((s, r) => r.Headers.Add("X-Api-Key", "12345"))
            .ReturnsAsync(false);

            _responseWriters.Add(responseWriterMock1.Object);
            _responseWriters.Add(responseWriterMock2.Object);

            // act
            var result = await _generator.GenerateResponseAsync(stub);

            // assert
            Assert.AreEqual(401, result.StatusCode);
            Assert.AreEqual("12345", result.Headers["X-Api-Key"]);
        }
示例#23
0
        public Task <bool> HandleStubGenerationAsync(RequestResultModel request, StubModel stub)
        {
            var pair = request.RequestParameters.Headers.FirstOrDefault(p =>
                                                                        p.Key.Equals("Content-Type", StringComparison.OrdinalIgnoreCase));
            var contentType = pair.Value;

            if (string.IsNullOrWhiteSpace(contentType))
            {
                return(Task.FromResult(false));
            }

            if (!contentType.Equals("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase))
            {
                return(Task.FromResult(false));
            }

            // If the body condition is already set, clear it here.
            stub.Conditions.Body = new string[0];

            var reader = new FormReader(request.RequestParameters.Body);
            var form   = reader.ReadForm();

            stub.Conditions.Form = form.Select(f => new StubFormModel
            {
                Key   = f.Key,
                Value = f.Value
            });

            return(Task.FromResult(true));
        }
    /// <inheritdoc />
    public ConditionCheckResultModel Validate(StubModel stub)
    {
        var result = new ConditionCheckResultModel();
        var bodyConditions = stub.Conditions?.Body?.ToArray();
        if (bodyConditions == null || bodyConditions?.Any() != true)
        {
            return result;
        }

        var body = _httpContextService.GetBody();

        var validBodyConditions = 0;
        foreach (var condition in bodyConditions)
        {
            if (!StringHelper.IsRegexMatchOrSubstring(body, condition))
            {
                // If the check failed, it means the query string is incorrect and the condition should fail.
                result.Log = $"Body condition '{condition}' failed.";
                break;
            }

            validBodyConditions++;
        }

        // If the number of succeeded conditions is equal to the actual number of conditions,
        // the body condition is passed and the stub ID is passed to the result.
        result.ConditionValidation = validBodyConditions == bodyConditions.Length
            ? ConditionValidationType.Valid
            : ConditionValidationType.Invalid;

        return result;
    }
示例#25
0
    /// <inheritdoc />
    public ConditionCheckResultModel Validate(StubModel stub)
    {
        var result        = new ConditionCheckResultModel();
        var pathCondition = stub.Conditions?.Url?.Path;

        if (string.IsNullOrEmpty(pathCondition))
        {
            return(result);
        }

        var path = _httpContextService.Path;

        if (StringHelper.IsRegexMatchOrSubstring(path, pathCondition))
        {
            // The path matches the provided regex. Add the stub ID to the resulting list.
            result.ConditionValidation = ConditionValidationType.Valid;
        }
        else
        {
            result.Log = $"Condition '{pathCondition}' did not pass for request.";
            result.ConditionValidation = ConditionValidationType.Invalid;
        }

        return(result);
    }
    /// <inheritdoc />
    public ConditionCheckResultModel Validate(StubModel stub)
    {
        var result  = new ConditionCheckResultModel();
        var maxHits = stub.Conditions?.Scenario?.MaxHits;

        if (maxHits == null)
        {
            return(result);
        }

        var scenario       = stub.Scenario;
        var rawHitCount    = _scenarioService.GetHitCount(scenario);
        var actualHitCount = rawHitCount + 1; // Add +1 because the scenario is being hit right now but hit count has not been increased yet.

        if (actualHitCount == null)
        {
            result.Log = "No hit count could be found.";
            result.ConditionValidation = ConditionValidationType.Invalid;
        }
        else if (actualHitCount >= maxHits)
        {
            result.Log =
                $"Scenario '{scenario}' should have less than '{maxHits}' hits, but '{actualHitCount}' hits were counted.";
            result.ConditionValidation = ConditionValidationType.Invalid;
        }
        else if (actualHitCount < maxHits)
        {
            result.ConditionValidation = ConditionValidationType.Valid;
        }

        return(result);
    }
        public async Task StubContainer_AddStubAsync_NoIdSet_ShouldAssignHashedStubAsId()
        {
            // arrange
            var stubToBeAdded = new StubModel {
                Conditions = new StubConditionsModel {
                    Body = new[] { "test" }
                }
            };
            var stubSource = new Mock <IWritableStubSource>();

            stubSource
            .Setup(m => m.AddStubAsync(stubToBeAdded))
            .Returns(Task.CompletedTask);

            var stub = new StubModel {
                Id = "existing-stub"
            };
            var readOnlyStubSource = new Mock <IStubSource>();

            readOnlyStubSource
            .Setup(m => m.GetStubsAsync())
            .ReturnsAsync(new[] { stub });

            _stubSources.Add(stubSource.Object);
            _stubSources.Add(readOnlyStubSource.Object);

            // act
            await _context.AddStubAsync(stubToBeAdded);

            // assert
            Assert.AreEqual("stub-d96ca27805fccd40cc6f8a6e21dc669d", stubToBeAdded.Id);
        }
        public Task <bool> WriteToResponseAsync(StubModel stub, ResponseModel response)
        {
            if (stub.Response.EnableDynamicMode != true)
            {
                return(Task.FromResult(false));
            }


            // Try to parse and replace the variables in the body.
            if (!response.BodyIsBinary && response.Body != null)
            {
                var parsedBody = _variableParser.Parse(Encoding.UTF8.GetString(response.Body));
                response.Body = Encoding.UTF8.GetBytes(parsedBody);
            }

            // Try to parse and replace the variables in the header values.
            var keys = response.Headers.Keys.ToArray();

            foreach (var key in keys)
            {
                response.Headers[key] = _variableParser.Parse(response.Headers[key]);
            }

            return(Task.FromResult(true));
        }
        public async Task StubContainer_GetStubAsync_HappyFlow()
        {
            // arrange
            var stubSource1 = new Mock <IStubSource>();
            var stubSource2 = new Mock <IStubSource>();

            var stub1 = new StubModel {
                Id = "stub1"
            };
            var stub2 = new StubModel {
                Id = "stub2"
            };
            var stub3 = new StubModel {
                Id = "stub3"
            };

            stubSource1
            .Setup(m => m.GetStubsAsync())
            .ReturnsAsync(new[] { stub1, stub2 });

            stubSource2
            .Setup(m => m.GetStubsAsync())
            .ReturnsAsync(new[] { stub3 });

            _stubSources.Add(stubSource1.Object);
            _stubSources.Add(stubSource2.Object);

            // act
            var result = await _context.GetStubAsync("stub2");

            // assert
            Assert.AreEqual(stub2, result.Stub);
        }
示例#30
0
        public void ExecuteCommand_PlayChanges()
        {
            // init
            const int currentVersion = 0;
            const int expectedVerstion = currentVersion + 1;
            var model = new StubModel
            {
                AggregateId = new AggregateId<StubModel>("1"),
                BoolVal = false,
                LatestVersion = currentVersion
            };
            var expected = new StubChangeEvent(model.AggregateId, true) { Version = expectedVerstion };
            var command = new StubPostCommand(true);

            // run
            var actualEvt = command.ExecuteOn(model);
            Assert.AreEqual(expected.Id.Value, actualEvt.Id.Value);
            Assert.AreEqual(expected.Version, actualEvt.Version);
            Assert.AreEqual(expectedVerstion, actualEvt.Version);

            var player = new Player<StubModel>();
            player.PlayFor(model, actualEvt);

            Assert.AreEqual(true, model.BoolVal);
            Assert.AreEqual(expectedVerstion, model.LatestVersion);
            Assert.AreEqual(actualEvt.Version, model.LatestVersion);

            player.PlayFor(model, actualEvt);

            Assert.AreEqual(true, model.BoolVal);
            Assert.AreEqual(expectedVerstion, model.LatestVersion);
            Assert.AreEqual(actualEvt.Version, model.LatestVersion);
        }
示例#31
0
        public async Task HeadersResponseWriter_WriteToResponseAsync_HappyFlow()
        {
            // arrange
            var stub = new StubModel
            {
                Response = new StubResponseModel
                {
                    Headers = new Dictionary <string, string>
                    {
                        { "X-Api-Key", "1223" },
                        { "X-User-Secret", "abc" }
                    }
                }
            };

            var response = new ResponseModel();

            // act
            var result = await _writer.WriteToResponseAsync(stub, response);

            // assert
            Assert.IsTrue(result);
            Assert.AreEqual(2, response.Headers.Count);
            Assert.AreEqual("1223", response.Headers["X-Api-Key"]);
            Assert.AreEqual("abc", response.Headers["X-User-Secret"]);
        }
示例#32
0
        public void DeleteModelCommand()
        {
            // init
            const int currentVersion = 1;
            var model = new StubModel
            {
                AggregateId = new AggregateId<StubModel>("1"),
                BoolVal = false,
                LatestVersion = currentVersion
            };
            var command = new PlayDeleteCommand<StubModel>();
            var expected = new PlayDeletedEvent<StubModel>(model.AggregateId);

            // run
            var actual = command.ExecuteOn(model);
            Assert.AreEqual(expected.Id.Value, actual.Id.Value);
            Assert.AreEqual(expected.GetType(), actual.GetType());
        }
示例#33
0
        public void ExecuteCommand()
        {
            // init
            const int currentVersion = 0;
            const int expectedVerstion = currentVersion + 1;
            var model = new StubModel
                            {
                                AggregateId = new AggregateId<StubModel>(),
                                BoolVal = false,
                                LatestVersion = currentVersion
                            };
            var expected = new StubNoChangeEvent(model.AggregateId) { Version = expectedVerstion };
            var command = new StubCommand();

            // run
            var actual = command.ExecuteOn(model);
            Assert.AreEqual(expected.Id.Value, actual.Id.Value);
            Assert.AreEqual(expected.Version, actual.Version);
            Assert.AreEqual(1, actual.Version);

            Assert.AreEqual(false, model.BoolVal);
        }
        public void RegisterAndRunProcess()
        {
            // init
            var expected = new StubModel
            {
                AggregateId = new AggregateId<StubModel>("1"),
                LatestVersion = 1,
                Value = 1
            };

            string errCommandStr = Serializer.JsonSerialize(new StubAddCommand { AddValue = -1 });
            string commandStr = Serializer.JsonSerialize(new StubAddCommand { AddValue = 1 });

            // run
            Assert.Throws<InvalidOperationException>(() => this.cmdController.Index(expected.AggregateIdVal, errCommandStr));
            this.cmdController.Index(expected.AggregateIdVal, commandStr);
            var actual = (StubModel)this.cmdController.Get(expected.AggregateIdVal).Data;

            Assert.AreEqual(expected.AggregateIdVal, actual.AggregateIdVal);
            Assert.AreEqual(expected.LatestVersion, actual.LatestVersion);
            Assert.AreEqual(expected.Value, actual.Value);
        }
        public void Initialize(AcceptCancelDialog control)
        {
            // Setup initial conditions.
            control.Width = 800;
            control.Height = 600;

            // Get the sample DataTemplates.
            content1 = SampleTemplates.Instance.GetDataTemplate("AcceptCancelDialog.Content1");
            content2 = SampleTemplates.Instance.GetDataTemplate("AcceptCancelDialog.Content2");
            contentModel1 = new StubModel { Text = "My Content Model One" };
            contentModel2 = new StubModel { Text = "My Content Model Two" };

            // Create the view-model.
            viewModel = new AcceptCancelDialogViewModel(content1, contentModel1)
                            {
                                IsShowing = true,
                            };
            control.ViewModel = viewModel;

            // Wire up events.
            viewModel.AcceptClick += delegate { Debug.WriteLine("!! AcceptClick"); };
            viewModel.CancelClick += delegate { Debug.WriteLine("!! CancelClick"); };
        }
        public void AddCommand()
        {
            // init
            const int CurrentVersion = 0;
            const int ExpectedVersion = CurrentVersion + 1;
            const int AddValue = 1;

            var model = new StubModel
                            {
                                AggregateId = new AggregateId<StubModel>("1"),
                                LatestVersion = CurrentVersion,
                                Value = 1
                            };

            long expectedVal = model.Value + AddValue;

            var expectedEvt = new StubAddedEvent(new AggregateId<StubModel>("1"), AddValue) { Version = ExpectedVersion };
            // ----note the 'ed'---------^^

            // run

            // validation exception
            Assert.Throws<InvalidOperationException>(() => new StubAddCommand { AddValue = -1 }.ExecuteOn(model));

            // successful command
            var actualEvt = new StubAddCommand { AddValue = AddValue }.ExecuteOn(model);
            this.assertEvents(expectedEvt, actualEvt);

            // playback
            var player = new SimplePlayer<StubModel>();
            player.Load(actualEvt);
            player.PlayFor(model);

            // end value after playback
            Assert.AreEqual(expectedVal, model.Value);
        }
        public void LessThanOrEqualToShouldEvaluateExpectedResult()
        {
            // arrange
            var validator = new Validator();
            var instance = new StubModel() { StartDate = DateTime.Today, EndDate = DateTime.Today.AddDays( -1 ) };
            var context = validator.CreateContext( instance, null );
            var results = new List<IValidationResult>();

            validator.For<StubModel>().Property( m => m.StartDate ).LessThanOrEqualTo( m => m.EndDate );

            // act
            var valid = validator.TryValidateObject( instance, context, results );

            // assert
            Assert.False( valid );
            Assert.Equal( 1, results.Count );
            Assert.Equal( "The StartDate field must be less than or equal to the EndDate field.", results[0].ErrorMessage );
            Assert.True( results[0].MemberNames.SequenceEqual( new[] { "StartDate", "EndDate" } ) );
        }
        public void GreaterThanOrEqualToShouldEvaluateSuccess()
        {
            // arrange
            var validator = new Validator();
            var instance = new StubModel();
            var context = validator.CreateContext( instance, null );
            var results = new List<IValidationResult>();

            validator.For<StubModel>().Property( m => m.EndDate ).GreaterThanOrEqualTo( m => m.StartDate );

            // act
            var valid = validator.TryValidateObject( instance, context, results );

            // assert
            Assert.True( valid );
            Assert.Equal( 0, results.Count );
        }
        public void GreaterThanOrEqualToShouldEvaluateWithCustomErrorMessage()
        {
            // arrange
            var validator = new Validator();
            var instance = new StubModel() { StartDate = DateTime.Today, EndDate = DateTime.Today.AddDays( -1 ) };
            var context = validator.CreateContext( instance, null );
            var results = new List<IValidationResult>();
            var expected = "Invalid";

            validator.For<StubModel>().Property( m => m.EndDate ).GreaterThanOrEqualTo( m => m.StartDate, expected );

            // act
            var valid = validator.TryValidateObject( instance, context, results );

            // assert
            Assert.False( valid );
            Assert.Equal( 1, results.Count );
            Assert.Equal( expected, results[0].ErrorMessage );
            Assert.True( results[0].MemberNames.SequenceEqual( new[] { "EndDate", "StartDate" } ) );
        }
        public void LessThanShouldEvaluateSucess()
        {
            // arrange
            var validator = new Validator();
            var instance = new StubModel() { StartDate = DateTime.Today.AddDays( -1 ), EndDate = DateTime.Today };
            var context = validator.CreateContext( instance, null );
            var results = new List<IValidationResult>();

            validator.For<StubModel>().Property( m => m.StartDate ).LessThan( m => m.EndDate );

            // act
            var valid = validator.TryValidateObject( instance, context, results );

            // assert
            Assert.True( valid );
            Assert.Equal( 0, results.Count );
        }
        public void GreaterThanShouldEvaluateExpectedResult()
        {
            // arrange
            var validator = new Validator();
            var instance = new StubModel();
            var context = validator.CreateContext( instance, null );
            var results = new List<IValidationResult>();

            validator.For<StubModel>().Property( m => m.EndDate ).GreaterThan( m => m.StartDate );

            // act
            var valid = validator.TryValidateObject( instance, context, results );

            // assert
            Assert.False( valid );
            Assert.Equal( 1, results.Count );
            Assert.Equal( "The EndDate field must be greater than the StartDate field.", results[0].ErrorMessage );
            Assert.True( results[0].MemberNames.SequenceEqual( new[] { "EndDate", "StartDate" } ) );
        }
示例#42
0
        public void ExecuteCommand_PlayChanges_PlaySubscribedChanges()
        {
            // init
            const int currentVersion = 0;
            const int expectedVerstion = currentVersion + 1;
            var model = new StubModel
            {
                AggregateId = new AggregateId<StubModel>("1"),
                BoolVal = false,
                LatestVersion = currentVersion
            };

            StubSubscribedEvent.OnPlaybackApply(eventData => changeModel => changeModel.BoolVal = !eventData.boolVal);
            StubSubscribedEvent.OnPlaybackApply(eventData => changeModel => changeModel.BoolVal = eventData.boolVal);

            var expected = new StubSubscribedEvent(model.AggregateId, true) { Version = expectedVerstion };

            var command = new StubSubscribedCommand(true);

            // run
            var actualEvt = (StubSubscribedEvent)command.ExecuteOn(model);

            Assert.AreEqual(expected.Id.Value, actualEvt.Id.Value);
            Assert.AreEqual(expected.Version, actualEvt.Version);
            Assert.AreEqual(expectedVerstion, actualEvt.Version);

            var player = new Player<StubModel>();
            player.PlayFor(model, actualEvt);

            Assert.AreEqual(true, model.BoolVal);
            Assert.AreEqual(expectedVerstion, model.LatestVersion);
            Assert.AreEqual(actualEvt.Version, model.LatestVersion);

            player.PlayFor(model, actualEvt);

            Assert.AreEqual(true, model.BoolVal);
            Assert.AreEqual(expectedVerstion, model.LatestVersion);
            Assert.AreEqual(actualEvt.Version, model.LatestVersion);
        }
示例#43
0
        public void PerformCommand_ExceptionOnValidationError()
        {
            // init
            var command = new StubPostCommand(false);
            var model = new StubModel { AggregateId = new AggregateId<StubModel>("1"), BoolVal = false };

            // run
            Assert.Throws<Exception>(() => command.ExecuteOn(model));
        }