public void SubmitAttempt_WhenExistingAttemptCheckReturnsNull_AssignsUserIdAndScore()
        {
            // arrange
            var attemptDto = AutoFixture.Create <AttemptDto>();
            var userId     = AutoFixture.Create <string>();

            AutoFixture.Freeze <Mock <IAttemptRepository> >()
            .Setup(x => x.GetAttempt(It.IsAny <int>(), It.IsAny <string>()))
            .Returns((Attempt)null);

            var attempt = AutoFixture.Create <Attempt>();

            AutoFixture.Freeze <Mock <IMapper> >()
            .Setup(x => x.Map <Attempt>(It.IsAny <AttemptDto>()))
            .Returns(attempt);

            var score = AutoFixture.Create <int>();

            AutoFixture.Freeze <Mock <IAttemptScoreCalculator> >()
            .Setup(x => x.CalculateScore(It.IsAny <Attempt>()))
            .Returns(score);

            var repositoryMock = AutoFixture.Freeze <Mock <IAttemptRepository> >();

            // act
            var manager = AutoFixture.Create <AttemptSubmissionManager>();

            manager.SubmitAttempt(attemptDto, userId);

            //  assert
            repositoryMock.Verify(x => x.InsertAttempt(It.Is <Attempt>(param => param.UserId == userId && param.Score == score)));
        }
        public void SubmitAttempt_WhenExistingAttemptCheckReturnsNull_CallsIAttemptScoreCalculatorCalculateScoreOnce()
        {
            // arrange
            var attemptDto = AutoFixture.Create <AttemptDto>();
            var userId     = AutoFixture.Create <string>();

            AutoFixture.Freeze <Mock <IAttemptRepository> >()
            .Setup(x => x.GetAttempt(It.IsAny <int>(), It.IsAny <string>()))
            .Returns((Attempt)null);

            var attempt = AutoFixture.Create <Attempt>();

            AutoFixture.Freeze <Mock <IMapper> >()
            .Setup(x => x.Map <Attempt>(It.IsAny <AttemptDto>()))
            .Returns(attempt);

            var calculatorMock = AutoFixture.Freeze <Mock <IAttemptScoreCalculator> >();

            // act
            var manager = AutoFixture.Create <AttemptSubmissionManager>();

            manager.SubmitAttempt(attemptDto, userId);

            //  assert
            calculatorMock.Verify(x => x.CalculateScore(attempt), Times.Once);
        }
Ejemplo n.º 3
0
        public void FetchQuestions_WhenAttemptRepositoryReturnsQuestionIds_ExcludesAttemptedQuestionIdsFromResult()
        {
            // arrange
            var userId     = AutoFixture.Create <string>();
            var questionId = AutoFixture.Create <int>();

            var attempts = AutoFixture.Build <Attempt>()
                           .With(x => x.QuestionId, questionId)
                           .CreateMany()
                           .ToList();

            AutoFixture.Freeze <Mock <IAttemptRepository> >()
            .Setup(x => x.GetAttempts(It.IsAny <string>()))
            .Returns(attempts);

            var previouslyAttemptedQuestions = AutoFixture.Build <QuestionDto>()
                                               .With(x => x.QuestionId, questionId)
                                               .CreateMany()
                                               .ToList();
            var notPreviouslyAttemptedQuestions = AutoFixture.CreateMany <QuestionDto>(20).ToList();

            previouslyAttemptedQuestions.InsertRange(RandomGenerator.Next(previouslyAttemptedQuestions.Count), notPreviouslyAttemptedQuestions);
            AutoFixture.Freeze <Mock <IQuestionFilter> >()
            .Setup(x => x.FilterQuestions(It.IsAny <IEnumerable <QuestionDto> >()))
            .Returns(previouslyAttemptedQuestions);

            // act
            var fetcher  = AutoFixture.Create <FilteredLatestQuestionsFetcher>();
            var response = fetcher.FetchQuestions(userId);

            // assert
            response.Should().BeEquivalentTo(notPreviouslyAttemptedQuestions);
        }
Ejemplo n.º 4
0
        public void FetchQuestions_Always_CallsIQuestionFilterFilterQuestionsOnce()
        {
            // arrange
            var userId = AutoFixture.Create <string>();

            var questionDtos = AutoFixture.CreateMany <QuestionDto>().ToList();

            AutoFixture.Freeze <Mock <IStackExchangeClient> >()
            .Setup(x => x.GetLatestQuestions(It.IsAny <int>()))
            .Returns(questionDtos);

            var filteredQuestions = AutoFixture.CreateMany <QuestionDto>(20).ToList();
            var filterMock        = AutoFixture.Freeze <Mock <IQuestionFilter> >();

            filterMock
            .Setup(x => x.FilterQuestions(It.IsAny <IEnumerable <QuestionDto> >()))
            .Returns(filteredQuestions);

            // act
            var fetcher = AutoFixture.Create <FilteredLatestQuestionsFetcher>();

            fetcher.FetchQuestions(userId);

            // assert
            filterMock.Verify(x => x.FilterQuestions(questionDtos), Times.Once);
        }
        private static void ValidateSchema(SchemaValidationInfo validationInfo)
        {
            try
            {
                object entity = AutoFixture.Create(validationInfo.DataType);

                if (!File.Exists(validationInfo.SchemaFilePath))
                {
                    Assert.Fail($"Json Schema not found for type '{validationInfo.DataType.FullName}'.\n"
                                + $"Expected to find file: {validationInfo.SchemaFilePath}");
                }

                var schema = JsonSchema.FromFileAsync(validationInfo.SchemaFilePath).GetAwaiter().GetResult();

                var json = JsonConvert.SerializeObject(
                    entity,
                    Formatting.Indented,
                    new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore
                });

                ICollection <ValidationError> errors = schema.Validate(json);

                Assert.IsTrue(errors.Count == 0, $"Json Schema validation failed for type '{validationInfo.DataType.FullName}'.\n"
                              + $"Found {errors.Count} error(s).  See schema file: {validationInfo.SchemaFilePath}");
            }
            catch (Exception e)
            {
                Assert.Fail($"Error {validationInfo.DataType}: {e.Message}");
                throw;
            }
        }
Ejemplo n.º 6
0
        public async void WhenHandle()
        {
            // Arrange
            var subject              = Mocker.CreateInstance <GetAllLocationsHandler>();
            var cancellationToken    = AutoFixture.Create <CancellationToken>();
            var locations            = AutoFixture.Create <Location[]>().ToList();
            var getAllLocationsQuery = AutoFixture.Create <GetAllLocationsQuery>();
            var locationsResponse    = locations.Select(loc => new LocationResponse
            {
                Region  = loc.Region,
                Country = loc.Country
            });

            Mocker.GetMock <ILocationRepository>()
            .Setup(lr => lr.GetAllLocations())
            .ReturnsAsync(locations);
            Mocker.GetMock <IMapper>()
            .Setup(map => map.Map(locations))
            .Returns(locationsResponse.ToList());

            // Act
            var result = await subject.Handle(getAllLocationsQuery, cancellationToken);

            // Assert
            result.Should().BeEquivalentTo(locationsResponse);
        }
        public void CreateFilter_WhenIRestClientExecuteReturnsResponseWithZeroQuotaRemaining_ReturnsNull()
        {
            // arrange
            var client = new Mock <IRestClient>();
            var data   = AutoFixture.Build <ItemResponseDto <FilterDto> >()
                         .With(x => x.QuotaRemaining, 0)
                         .Create();
            var restResponse = AutoFixture.Build <RestResponse <ItemResponseDto <FilterDto> > >()
                               .With(x => x.Data, data)
                               .Create();

            client
            .Setup(x => x.Execute <ItemResponseDto <FilterDto> >(It.IsAny <IRestRequest>()))
            .Returns(restResponse);
            AutoFixture.Freeze <Mock <IRestSharpWrapper> >()
            .Setup(x => x.CreateRestClient(It.IsAny <string>()))
            .Returns(client.Object);

            // act
            var filterCreator = AutoFixture.Create <StackExchangeFilterCreator>();
            var response      = filterCreator.CreateFilter();

            // assert
            response.Should().BeNull();
        }
Ejemplo n.º 8
0
        public void When_MapHotelAvailabilityResponse()
        {
            // Arrange
            var subject                    = Mocker.CreateInstance <Mapper>();
            var hotelAvailability          = AutoFixture.Create <HotelAvailability>();
            var hotelsAvailabilityResponse = new HotelAvailabilityResponse {
                Id           = hotelAvailability.Id,
                HotelId      = hotelAvailability.HotelId,
                Infants      = hotelAvailability.Infants,
                Children     = hotelAvailability.Children,
                Adults       = hotelAvailability.Adults,
                HotelName    = hotelAvailability.HotelName,
                Meal         = hotelAvailability.Meal,
                Room         = hotelAvailability.Room,
                CurrencyCode = hotelAvailability.CurrencyCode,
                NetPrice     = hotelAvailability.NetPrice,
                StayDate     = hotelAvailability.StayDate,
                EndDate      = hotelAvailability.EndDate,
                AirportCode  = hotelAvailability.AirportCode,
                Region       = hotelAvailability.Region,
                Country      = hotelAvailability.Country
            };

            // Act
            var result = subject.Map(hotelAvailability);

            // Assert
            result.Should().BeEquivalentTo(hotelsAvailabilityResponse);
        }
Ejemplo n.º 9
0
        public void FetchAttemptedQuestion_Always_ReturnsAttemptedQuestion()
        {
            // arrange
            var userId     = AutoFixture.Create <string>();
            var questionId = AutoFixture.Create <int>();

            var attemptDto = AutoFixture.Create <AttemptDto>();

            AutoFixture.Freeze <Mock <IMapper> >()
            .Setup(x => x.Map <AttemptDto>(It.IsAny <Attempt>()))
            .Returns(attemptDto);

            var questionDto = AutoFixture.Create <QuestionDto>();

            AutoFixture.Freeze <Mock <IStackExchangeClient> >()
            .Setup(x => x.GetQuestion(It.IsAny <int>()))
            .Returns(questionDto);

            // act
            var fetcher  = AutoFixture.Create <PreviouslyAttemptedQuestionFetcher>();
            var response = fetcher.FetchAttemptedQuestion(userId, questionId);

            // assert
            response.AttemptDto.Should().Be(attemptDto);
            response.QuestionDto.Should().Be(questionDto);
        }
Ejemplo n.º 10
0
        public void FetchQuestions_Always_CallsIAttemptedQuestionDtoAssemblerAssembleAttemptedQuestionsOnce()
        {
            // arrange
            var userId = AutoFixture.Create <string>();

            var questionDtos = AutoFixture.CreateMany <QuestionDto>().ToList();

            AutoFixture.Freeze <Mock <IStackExchangeClient> >()
            .Setup(x => x.GetQuestions(It.IsAny <List <int> >()))
            .Returns(questionDtos);

            var attemptDtos = AutoFixture.CreateMany <AttemptDto>().ToList();

            AutoFixture.Freeze <Mock <IMapper> >()
            .Setup(x => x.Map <IEnumerable <AttemptDto> >(It.IsAny <IEnumerable <Attempt> >()))
            .Returns(attemptDtos);

            var assemblerMock = AutoFixture.Freeze <Mock <IAttemptedQuestionDtoAssembler> >();

            // act
            var fetcher = AutoFixture.Create <PreviouslyAttemptedQuestionFetcher>();

            fetcher.FetchAttemptedQuestions(userId);

            // assert
            assemblerMock.Verify(x => x.AssembleAttemptedQuestions(attemptDtos, questionDtos), Times.Once);
        }
        public void CalculateScore_GivenIncorrectAnswer_ReturnsRatioOfSameAttemptsDividedByTotalAttemptsOnQuestion()
        {
            // arrange
            var attempt = AutoFixture.Create <Attempt>();

            var matchingAttempts = AutoFixture.Build <Attempt>()
                                   .With(x => x.AnswerId, attempt.AnswerId)
                                   .CreateMany()
                                   .ToList();
            var nonMatchingAttempts = AutoFixture.CreateMany <Attempt>().ToList();

            nonMatchingAttempts.InsertRange(RandomGenerator.Next(nonMatchingAttempts.Count), matchingAttempts);
            AutoFixture.Freeze <Mock <IAttemptRepository> >()
            .Setup(x => x.GetAttemptsForQuestion(It.IsAny <int>()))
            .Returns(nonMatchingAttempts);

            // act
            var calculator = AutoFixture.Create <AttemptScoreCalculator>();
            var response   = calculator.CalculateScore(attempt);

            //  assert
            var score = (double)(matchingAttempts.Count - 1) / nonMatchingAttempts.Count * 100;

            response.Should().Be((int)Math.Round(score));
        }
Ejemplo n.º 12
0
        public void WhenGet()
        {
            //Arrange
            var serviceCollections = new ServiceCollection();
            var roundName          = AutoFixture.Create <string>();
            var score = AutoFixture.Create <int>();
            var queryStringParameters = new Dictionary <string, string>();

            queryStringParameters.Add("Score", score.ToString());
            queryStringParameters.Add("RoundName", roundName);

            var request       = AutoFixture.Build <APIGatewayProxyRequest>().With(rq => rq.QueryStringParameters, queryStringParameters).Create();
            var proxyResponse = AutoFixture.Create <APIGatewayProxyResponse>();
            var getClassificationFromScoreMock = new Mock <IGetClassificationFromScore>();

            getClassificationFromScoreMock.Setup(sp => sp.GetClassification(score, roundName)).Returns(proxyResponse);
            serviceCollections.AddScoped(provider => getClassificationFromScoreMock.Object);
            var serviceProvider = serviceCollections.BuildServiceProvider();

            var subject = new ScoreClassificationService(serviceProvider);
            //Act
            var result = subject.GetClassification(request);

            //Assert
            result.Should().Be(proxyResponse);
        }
Ejemplo n.º 13
0
        public void WhenWriteRdb()
        {
            //Arrange
            var subject = Mocker.CreateInstance <RenderRdb>();
            var data    = AutoFixture.Create <RdbNets>();
            var points  = data.Nets.SelectMany(net =>
                                               net.pins.Select(pin =>
                                                               new Point {
                X = pin.x, Y = pin.y
            }));

            //Act
            var result = subject.Convert(data);

            //Assert
            result.Width.Should().Be(800);
            result.Height.Should().Be(600);
            var bitmap = (Bitmap)result;

            foreach (var point in points)
            {
                if (
                    point.X >= 0 &&
                    point.Y >= 0 &&
                    point.X < bitmap.Width &&
                    point.Y < bitmap.Height)
                {
                    var pixel = bitmap.GetPixel((int)point.X, (int)point.Y);
                    pixel.R.Should().Be(255);
                    pixel.G.Should().Be(255);
                    pixel.B.Should().Be(255);
                    pixel.A.Should().Be(255);
                }
            }
        }
Ejemplo n.º 14
0
        public void WhenGetNewCoordinate()
        {
            var subject   = AutoFixture.Create <Coordinate>();
            var point     = AutoFixture.Create <Point>();
            var distance  = AutoFixture.Create <int>();
            var expectedX = subject.X;
            var expectedY = subject.Y;

            switch (point)
            {
            case Point.North:
                expectedX += distance;
                break;

            case Point.East:
                expectedY += distance;
                break;

            case Point.South:
                expectedX -= distance;
                break;

            case Point.West:
                expectedY -= distance;
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            var result = subject.GetNewCoordinate(point, distance);

            result.X.Should().Be(expectedX);
            result.Y.Should().Be(expectedY);
        }
        public void CreateFilter_WhenIRestClientExecuteReturnsValidResponse_ReturnsResponseData()
        {
            // arrange
            var client = new Mock <IRestClient>();
            var data   = AutoFixture.Build <ItemResponseDto <FilterDto> >()
                         .With(x => x.QuotaRemaining, RandomGenerator.Next(1, 100))
                         .Create();
            var restResponse = AutoFixture.Build <RestResponse <ItemResponseDto <FilterDto> > >()
                               .With(x => x.Data, data)
                               .Create();

            client
            .Setup(x => x.Execute <ItemResponseDto <FilterDto> >(It.IsAny <IRestRequest>()))
            .Returns(restResponse);
            AutoFixture.Freeze <Mock <IRestSharpWrapper> >()
            .Setup(x => x.CreateRestClient(It.IsAny <string>()))
            .Returns(client.Object);

            // act
            var filterCreator = AutoFixture.Create <StackExchangeFilterCreator>();
            var response      = filterCreator.CreateFilter();

            // assert
            response.Should().BeEquivalentTo(data.Items.FirstOrDefault()?.Filter);
        }
Ejemplo n.º 16
0
        public void When_MapFlightAvailabilityResponse()
        {
            // Arrange
            var subject                    = Mocker.CreateInstance <Mapper>();
            var flightAvailability         = AutoFixture.Create <FlightAvailability>();
            var flightAvailabilityResponse = new FlightAvailabilityResponse
            {
                Id                       = flightAvailability.Id,
                Scheduled                = flightAvailability.Scheduled,
                ScheduledTimeDate        = flightAvailability.ScheduledTimeDate,
                Arrival                  = flightAvailability.Arrival,
                ArrivalTimeDate          = flightAvailability.ArrivalTimeDate,
                FlightIdentifier         = flightAvailability.FlightIdentifier,
                DepartureAirportCode     = flightAvailability.DepartureAirportCode,
                DepartureAirport         = flightAvailability.DepartureAirport,
                DepartureAirportTimezone = flightAvailability.DepartureAirportTimezone,
                ArrivalAirportCode       = flightAvailability.ArrivalAirportCode,
                ArrivalAirport           = flightAvailability.ArrivalAirport,
                ArrivalAirportTimezone   = flightAvailability.ArrivalAirportTimezone,
                AirportCity              = flightAvailability.AirportCity,
                AirportCountry           = flightAvailability.AirportCountry,
                Terminal                 = flightAvailability.Terminal,
                Seats                    = flightAvailability.Seats,
                Gate                     = flightAvailability.Gate,
                AirlineIata              = flightAvailability.AirlineIata,
                AirlineName              = flightAvailability.AirlineName,
                FlightBound              = flightAvailability.FlightBound
            };

            // Act
            var result = subject.Map(flightAvailability);

            // Assert
            result.Should().BeEquivalentTo(flightAvailabilityResponse);
        }
Ejemplo n.º 17
0
        public void Execute_ShouldLaunchProcessAndWaitForExitEvent()
        {
            var task = AutoFixture.Create <Task>();
            var expectedTaskResult = new TaskExecutionResult(TaskExecutionResult.TaskExecutionStatus.Failed, task.WorkItemId, null);

            expectedTaskResult.AddLogEntry(TaskExecutor.RunnerNotFoundOnAgent.FormatWith(new { task.Runner }));

            const int millisecondsBeforeExit = 3000;
            Action <ProcessStartInfo, EventHandler <string>, EventHandler <string> > startProcess = (info, exitHandler, outputHandler) =>
            {
                var process = CreateProcess(millisecondsBeforeExit);
                process.Exited += exitHandler;
                process.Start();
            };

            _processRunner.Setup(p => p.Start(It.IsAny <ProcessStartInfo>(), It.IsAny <EventHandler <string> >(), It.IsAny <EventHandler <string> >())).Callback(startProcess);

            _fileSystemMock.Setup(s => s.Exists(It.IsAny <string>())).Returns(true);


            var ms = TimeExecution(() => _taskExecutor.Execute(task));

            _processRunner.Verify(p => p.Start(It.IsAny <ProcessStartInfo>(), It.IsAny <EventHandler <string> >(), It.IsAny <EventHandler <string> >()), Times.Once());
            ms.Should().BeGreaterOrEqualTo(TimeSpan.FromMilliseconds(millisecondsBeforeExit - 100));
        }
Ejemplo n.º 18
0
        public async void When_SearchHotelAvailability_AndNoResults()
        {
            // Arrange
            var subject = Mocker.CreateInstance <HotelAvailabilityRepository>();
            var searchHotelAvailabilityQuery = AutoFixture.Create <SearchHotelAvailabilityQuery>();
            var elasticsearchConfig          = AutoFixture.Create <ElasticsearchConfig>();
            var mockSearchResponse           = new Mock <ISearchResponse <HotelAvailability> >();
            var mockElasticClient            = new Mock <IElasticClient>();

            Mocker.GetMock <IOptions <ElasticsearchConfig> >()
            .Setup(esc => esc.Value)
            .Returns(elasticsearchConfig);
            Mocker.GetMock <IElasticSearchClient>()
            .Setup(esc => esc.CreateElasticClient(elasticsearchConfig.Url))
            .Returns(mockElasticClient.Object);
            mockSearchResponse.Setup(x => x.Documents).Returns((List <HotelAvailability>)null);
            mockElasticClient
            .Setup(ec => ec.SearchAsync(
                       It.IsAny <Func <SearchDescriptor <HotelAvailability>, ISearchRequest> >(),
                       It.IsAny <CancellationToken>()))
            .ReturnsAsync(mockSearchResponse.Object);

            // Act
            var result = await subject.SearchHotelAvailability(searchHotelAvailabilityQuery);

            // Assert
            result.Should().BeEquivalentTo(null);
        }
Ejemplo n.º 19
0
        public void WhenGetNewPosition()
        {
            var subject                     = AutoFixture.Create <Position>();
            var instruction                 = AutoFixture.Create <Instruction>();
            var expectedPoint               = subject.Point.Turn(instruction.Direction);
            var expectedCoordinate          = subject.Coordinate.GetNewCoordinate(expectedPoint, instruction.Distance);
            var expectedPreviousCoordinates = subject.Coordinate.GetCoordinatesBetween(expectedPoint,
                                                                                       instruction.Distance);
            var previousLength = subject.PreviousCoordinates.Count + instruction.Distance;


            var result = subject.GetNewPosition(instruction);

            result.Point.Should().Be(expectedPoint);
            result.Coordinate.X.Should().Be(expectedCoordinate.X);
            result.Coordinate.Y.Should().Be(expectedCoordinate.Y);
            result.PreviousCoordinates.Count.Should().Be(previousLength);
            result.PreviousCoordinates.Count(
                coord => subject.PreviousCoordinates.Any(prev => prev.X == coord.X && prev.Y == coord.Y))
            .Should()
            .Be(subject.PreviousCoordinates.Count);
            result.PreviousCoordinates.Any(coord => coord.X == subject.Coordinate.X && coord.Y == subject.Coordinate.Y)
            .Should()
            .BeTrue();
            result.PreviousCoordinates.Count(
                coord => expectedPreviousCoordinates.Any(prev => prev.X == coord.X && prev.Y == coord.Y))
            .Should()
            .Be(expectedPreviousCoordinates.Count);
        }
        public async void WhenHandle()
        {
            // Arrange
            var subject           = Mocker.CreateInstance <SearchHotelsHandler>();
            var searchHotelQuery  = AutoFixture.Create <SearchHotelsQuery>();
            var cancellationToken = AutoFixture.Create <CancellationToken>();
            var hotels            = AutoFixture.Create <Hotel[]>().ToList();
            var hotelsResponse    = hotels.Select(hot => new HotelResponse
            {
                Id      = hot.Id,
                Name    = hot.Name,
                Code    = hot.Code,
                Country = hot.Country
            });

            Mocker.GetMock <IHotelRepository>()
            .Setup(lr => lr.SearchHotels(searchHotelQuery))
            .ReturnsAsync(hotels);
            Mocker.GetMock <IMapper>()
            .Setup(map => map.Map(hotels))
            .Returns(hotelsResponse.ToList());

            // Act
            var result = await subject.Handle(searchHotelQuery, cancellationToken);

            // Assert
            result.Should().BeEquivalentTo(hotelsResponse);
        }
        public void FetchAnswersForQuestions_Always_SetsAttemptCountEqualToCountFromIAttemptRepositoryGetAttemptsForAnswer()
        {
            // arrange
            var questionId = AutoFixture.Create <int>();

            var answerDtos = AutoFixture.CreateMany <AnswerDto>().ToList();

            AutoFixture.Freeze <Mock <IStackExchangeClient> >()
            .Setup(x => x.GetAnswers(It.IsAny <int>()))
            .Returns(answerDtos);

            var attempts = AutoFixture.CreateMany <Attempt>().ToList();

            AutoFixture.Freeze <Mock <IAttemptRepository> >()
            .Setup(x => x.GetAttemptsForAnswer(It.IsAny <int>()))
            .Returns(attempts);

            // act
            var controller = AutoFixture.Create <QuestionController>();

            controller.FetchAnswersForQuestion(questionId);

            // assert
            foreach (var answerDto in answerDtos)
            {
                answerDto.AttemptCount.Should().Be(attempts.Count);
            }
        }
        public async void WhenHandle()
        {
            // Arrange
            var subject            = Mocker.CreateInstance <SearchAirlinesHandler>();
            var searchAirlineQuery = AutoFixture.Create <SearchAirlinesQuery>();
            var cancellationToken  = AutoFixture.Create <CancellationToken>();
            var airlines           = AutoFixture.Create <Airline[]>().ToList();
            var airlinesResponse   = airlines.Select(air => new AirlineResponse
            {
                Name    = air.Name,
                Code    = air.Code,
                Country = air.Country
            });

            Mocker.GetMock <IAirlineRepository>()
            .Setup(lr => lr.SearchAirlines(searchAirlineQuery))
            .ReturnsAsync(airlines);
            Mocker.GetMock <IMapper>()
            .Setup(map => map.Map(airlines))
            .Returns(airlinesResponse.ToList());

            // Act
            var result = await subject.Handle(searchAirlineQuery, cancellationToken);

            // Assert
            result.Should().BeEquivalentTo(airlinesResponse);
        }
Ejemplo n.º 23
0
        public void WhenGetAndUnexpectedChar()
        {
            var subject = Mocker.CreateInstance <GetDirection>();
            var input   = AutoFixture.Create <int>().ToString()[0];

            Assert.Throws <ArgumentOutOfRangeException>(() => subject.Get(input));
        }
        public void Execute_Always_CallsIRestRequestAddParameterForFilter()
        {
            // arrange
            var resourceEnum = AutoFixture.Create <StackExchangeResourceEnum>();
            var parameters   = AutoFixture.CreateMany <object>().ToList();
            var data         = AutoFixture.Create <Dictionary <string, object> >();

            var filter = AutoFixture.Create <string>();

            AutoFixture.Freeze <Mock <IStackExchangeFilterCreator> >()
            .Setup(x => x.CreateFilter())
            .Returns(filter);

            var restRequestMock = new Mock <IRestRequest>();

            AutoFixture.Freeze <Mock <IRestSharpWrapper> >()
            .Setup(x => x.CreateRestRequest(It.IsAny <string>()))
            .Returns(restRequestMock.Object);

            // act
            var requestHandler = AutoFixture.Create <StackExchangeRequestHandler>();

            requestHandler.Execute <QuestionDto>(resourceEnum, parameters, data);

            // assert
            restRequestMock.Verify(x => x.AddParameter("filter", filter), Times.Once);
        }
        public async void When_SearchAirlines()
        {
            // Arrange
            var subject             = Mocker.CreateInstance <AirlineRepository>();
            var elasticsearchConfig = AutoFixture.Create <ElasticsearchConfig>();
            var airlinesResponse    = AutoFixture.Create <Airline[]>().ToList();
            var airlinesRequest     = AutoFixture.Create <SearchAirlinesQuery>();
            var mockSearchResponse  = new Mock <ISearchResponse <Airline> >();
            var mockElasticClient   = new Mock <IElasticClient>();

            Mocker.GetMock <IOptions <ElasticsearchConfig> >()
            .Setup(esc => esc.Value)
            .Returns(elasticsearchConfig);
            Mocker.GetMock <IElasticSearchClient>()
            .Setup(esc => esc.CreateElasticClient(elasticsearchConfig.Url))
            .Returns(mockElasticClient.Object);
            mockSearchResponse.Setup(x => x.Documents).Returns(airlinesResponse);
            mockElasticClient
            .Setup(ec => ec.SearchAsync(
                       It.IsAny <Func <SearchDescriptor <Airline>, ISearchRequest> >(),
                       It.IsAny <CancellationToken>()))
            .ReturnsAsync(mockSearchResponse.Object);

            // Act
            var result = await subject.SearchAirlines(airlinesRequest);

            // Assert
            result.Should().BeEquivalentTo(airlinesResponse);
        }
        public void CreateFilter_WhenIRestClientExecuteReturnsValidResponse_ReturnsResponseData()
        {
            // arrange
            var resourceEnum = AutoFixture.Create <StackExchangeResourceEnum>();
            var parameters   = AutoFixture.CreateMany <object>().ToList();
            var data         = AutoFixture.Create <Dictionary <string, object> >();

            var client       = new Mock <IRestClient>();
            var responseData = AutoFixture.Build <ItemResponseDto <QuestionDto> >()
                               .With(x => x.QuotaRemaining, RandomGenerator.Next(1, 100))
                               .Create();
            var restResponse = AutoFixture.Build <RestResponse <ItemResponseDto <QuestionDto> > >()
                               .With(x => x.Data, responseData)
                               .Create();

            client
            .Setup(x => x.Execute <ItemResponseDto <QuestionDto> >(It.IsAny <IRestRequest>()))
            .Returns(restResponse);
            AutoFixture.Freeze <Mock <IRestSharpWrapper> >()
            .Setup(x => x.CreateRestClient(It.IsAny <string>()))
            .Returns(client.Object);

            // act
            var requestHandler = AutoFixture.Create <StackExchangeRequestHandler>();
            var response       = requestHandler.Execute <QuestionDto>(resourceEnum, parameters, data);

            // assert
            response.Should().BeEquivalentTo(responseData.Items);
        }
        public void CreateFilter_WhenIRestClientExecuteReturnsResponseWithNullData_ReturnsNull()
        {
            // arrange
            var resourceEnum = AutoFixture.Create <StackExchangeResourceEnum>();
            var parameters   = AutoFixture.CreateMany <object>().ToList();
            var data         = AutoFixture.Create <Dictionary <string, object> >();

            var client       = new Mock <IRestClient>();
            var restResponse = AutoFixture.Build <RestResponse <ItemResponseDto <QuestionDto> > >()
                               .Without(x => x.Data)
                               .Create();

            client
            .Setup(x => x.Execute <ItemResponseDto <QuestionDto> >(It.IsAny <IRestRequest>()))
            .Returns(restResponse);
            AutoFixture.Freeze <Mock <IRestSharpWrapper> >()
            .Setup(x => x.CreateRestClient(It.IsAny <string>()))
            .Returns(client.Object);

            // act
            var requestHandler = AutoFixture.Create <StackExchangeRequestHandler>();
            var response       = requestHandler.Execute <QuestionDto>(resourceEnum, parameters, data);

            // assert
            response.Should().BeNull();
        }
Ejemplo n.º 28
0
        public void Cancel_ShouldCancelAllWorkItems()
        {
            var command     = AutoFixture.Create <AddJobRequest>();
            var addResponse = ServerChannel.SendRequest <CreateEntityResponse <int> >(UriFactory.Create(EndPoint.QueueJob),
                                                                                      command);

            addResponse.Succeeded.Should().BeTrue();

            var cancelcommand = new CancelJobRequest()
            {
                JobId = addResponse.EntityIdentifier
            };
            var cancelResponse = ServerChannel.SendRequest <Response>(UriFactory.Create(EndPoint.CancelJob),
                                                                      cancelcommand);

            cancelResponse.Succeeded.Should().BeTrue();

            using (var session = DocumentStore.OpenSession())
            {
                var job = session.Load <Job>(addResponse.EntityIdentifier);

                job.Should().NotBeNull();
                var workItems = session.Query <WorkItem>().Where(w => w.Job.Id.Equals(job.Id)).ToList();

                workItems.All(t => t.Status.Equals(WorkItemStatus.Cancelled)).Should().BeTrue();
            }
        }
        public WhenRetrievingStatusTestFixtures()
        {
            HttpHelper.Setup(x => x.GetAsync <ReservationAllocationStatusResult>(It.IsAny <string>(),
                                                                                 null, It.IsAny <CancellationToken>()))
            .ReturnsAsync(new ReservationAllocationStatusResult());

            _request = AutoFixture.Create <ReservationAllocationStatusMessage>();
        }
Ejemplo n.º 30
0
        public void ShouldMaintainLinkWithOriginalDocumentId()
        {
            var job      = AutoFixture.Create <Job>();
            var workItem = new WorkItem(job);

            job.Id = 30912831;
            workItem.Job.Id.Should().Be(job.Id);
        }