Ejemplo n.º 1
0
 public Specification(string name, It it, bool isIgnored, FieldInfo fieldInfo)
 {
   _name = name;
   _it = it;
   _isIgnored = isIgnored;
   _fieldInfo = fieldInfo;
 }
    public BehaviorSpecification(string name,
                                 It it,
                                 bool isIgnored,
                                 FieldInfo fieldInfo,
                                 Context context,
                                 Behavior behavior)
      : base(name, it, isIgnored, fieldInfo)
    {
      _contextInstance = context.Instance;
      _behaviorInstance = behavior.Instance;

      _mapper = new ConventionMapper();
    }
Ejemplo n.º 3
0
    /// <summary>
    /// Starts worker in separate thread.
    /// After worker finished its work it should call "done" function passed to it.
    /// After worker called done "callback" function will be called in unity thread.
    /// Parameter passed to "done" function will be available in "callback" function.
    /// Note: All Unity function are threade unsave. You are not allowed to use them in the worker.
    /// Though you can use any Unity functions in "callback" function.
    /// </summary>
    /// <param name="worker">Worker.</param>
    /// <param name="callback">Callback.</param>
    /// <returns>Thread id</returns>
    public static int Start(Worker worker, It.Action<object> callback, System.TimeSpan? timeout /*= null*/, It.Action timeoutCallback /*= null*/)
    {
        if (_instance == null) {
            _instance = new GameObject("Threading").AddComponent<Threading>();
        }

        var id = _instance._id++;
        var info = new Info();
        info.id = id;
        info.callback = callback;
        info.worker = worker;
        info.thread = new System.Threading.Thread(info.Run);

        if (timeout.HasValue) {
            info.timeout = System.DateTime.Now + timeout.Value;
            info.timeoutCallback =  timeoutCallback;
        }

        _instance._threads[id] = info;
        info.thread.Start();
        return id;
    }
Ejemplo n.º 4
0
 public static int Start(Worker worker, It.Action<object> callback)
 {
     return Start(worker, callback, null, null);
 }
 public async Task DeleteReturnsCorrectViewWhenUserIsOrgAdmin()
 {
     var controller = CampaignControllerWithSummaryQuery(UserType.OrgAdmin.ToString(), It.IsAny<int>());
     Assert.IsType<ViewResult>(await controller.Delete(It.IsAny<int>()));
 }
        public async Task EditPostAddsErrorToModelStateWhenInvalidImageFormatIsSupplied()
        {
            var controller = CampaignControllerWithSummaryQuery(UserType.OrgAdmin.ToString(), It.IsAny<int>());
            var file = FormFile("");

            await controller.Edit(new CampaignSummaryModel { Name = "Foo", OrganizationId = It.IsAny<int>() }, file);

            Assert.False(controller.ModelState.IsValid);
            Assert.True(controller.ModelState.ContainsKey("ImageUrl"));
            //TODO: test that the value associated with the key is correct
        }
 public async Task EditPostReturnsHttpUnauthorizedResultWhenUserIsNotAnOrgAdmin()
 {
     var controller = CampaignControllerWithSummaryQuery(UserType.BasicUser.ToString(), It.IsAny<int>());
     var result = await controller.Edit(new CampaignSummaryModel { OrganizationId = It.IsAny<int>() }, null);
     Assert.IsType<HttpUnauthorizedResult>(result);
 }
 public async Task EditGetReturnsHttpUnauthorizedResultWhenUserIsNotAnOrgAdmin()
 {
     var controller = CampaignControllerWithSummaryQuery(UserType.BasicUser.ToString(), It.IsAny<int>());
     Assert.IsType<HttpUnauthorizedResult>(await controller.Edit(It.IsAny<int>()));
 }
 public async Task DetailsReturnsCorrectViewWhenViewModelIsNotNullAndUserIsOrgAdmin()
 {
     var controller = CampaignControllerWithDetailQuery(UserType.OrgAdmin.ToString(), It.IsAny<int>());
     Assert.IsType<ViewResult>(await controller.Details(It.IsAny<int>()));
 }
 public async Task DetailsReturnsHttpNotFoundResultWhenVieModelIsNull()
 {
     CampaignController controller;
     MockMediatorCampaignDetailQuery(out controller);
     Assert.IsType<HttpNotFoundResult>(await controller.Details(It.IsAny<int>()));
 }
Ejemplo n.º 11
0
        public void Should_Success_Get_All_Data_UnitExpenditure_for_Preparing()
        {
            var mockFacade = new Mock<IGarmentUnitExpenditureNoteFacade>();
            mockFacade.Setup(x => x.ReadForGPreparing(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<string>(), null, It.IsAny<string>()))
                .Returns(new ReadResponse<object>(new List<object>(), 0, new Dictionary<string, string>()));
            var mockFacadeUnitDO = new Mock<IGarmentUnitDeliveryOrderFacade>();

            var mockMapper = new Mock<IMapper>();
            mockMapper.Setup(x => x.Map<List<GarmentUnitExpenditureNoteViewModel>>(It.IsAny<List<GarmentUnitExpenditureNote>>()))
                .Returns(new List<GarmentUnitExpenditureNoteViewModel> { ViewModel });

            GarmentUnitExpenditureNoteController controller = GetController(mockFacade, mockFacadeUnitDO, null, mockMapper);
            var response = controller.GetForGarmentPreparing();
            Assert.Equal((int)HttpStatusCode.OK, GetStatusCode(response));
        }
Ejemplo n.º 12
0
        public void Should_Error_Get_All_Data_By_User()
        {
            var mockFacade = new Mock<IGarmentUnitExpenditureNoteFacade>();

            mockFacade.Setup(x => x.Read(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<string>(), null, It.IsAny<string>()))
                .Returns(new ReadResponse<object>(new List<object>(), 0, new Dictionary<string, string>()));

            var mockMapper = new Mock<IMapper>();
            mockMapper.Setup(x => x.Map<List<GarmentUnitExpenditureNoteViewModel>>(It.IsAny<List<GarmentUnitExpenditureNote>>()))
                .Returns(new List<GarmentUnitExpenditureNoteViewModel> { ViewModel });

            var mockFacadeUnitDO = new Mock<IGarmentUnitDeliveryOrderFacade>();


            GarmentUnitExpenditureNoteController controller = new GarmentUnitExpenditureNoteController(GetServiceProvider().Object, mockMapper.Object, mockFacade.Object, mockFacadeUnitDO.Object);

            var response = controller.GetByUser();
            Assert.Equal((int)HttpStatusCode.InternalServerError, GetStatusCode(response));
        }
        private void Arrange()
        {
            var random = new Random();

            _localChannelNumber           = (uint)random.Next(0, int.MaxValue);
            _localWindowSize              = (uint)random.Next(0, int.MaxValue);
            _localPacketSize              = (uint)random.Next(0, int.MaxValue);
            _remoteChannelNumber          = (uint)random.Next(0, int.MaxValue);
            _remoteWindowSize             = (uint)random.Next(0, int.MaxValue);
            _remotePacketSize             = (uint)random.Next(0, int.MaxValue);
            _channelClosedRegister        = new List <ChannelEventArgs>();
            _channelExceptionRegister     = new List <ExceptionEventArgs>();
            _initialSessionSemaphoreCount = random.Next(10, 20);
            _sessionSemaphore             = new SemaphoreLight(_initialSessionSemaphoreCount);

            _sessionMock        = new Mock <ISession>(MockBehavior.Strict);
            _connectionInfoMock = new Mock <IConnectionInfo>(MockBehavior.Strict);

            _sequence = new MockSequence();
            _sessionMock.InSequence(_sequence).Setup(p => p.ConnectionInfo).Returns(_connectionInfoMock.Object);
            _connectionInfoMock.InSequence(_sequence).Setup(p => p.RetryAttempts).Returns(1);
            _sessionMock.Setup(p => p.SessionSemaphore).Returns(_sessionSemaphore);
            _sessionMock.InSequence(_sequence)
            .Setup(
                p =>
                p.SendMessage(
                    It.Is <ChannelOpenMessage>(
                        m =>
                        m.LocalChannelNumber == _localChannelNumber &&
                        m.InitialWindowSize == _localWindowSize && m.MaximumPacketSize == _localPacketSize &&
                        m.Info is SessionChannelOpenInfo)));
            _sessionMock.InSequence(_sequence)
            .Setup(p => p.WaitOnHandle(It.IsNotNull <WaitHandle>()))
            .Callback <WaitHandle>(
                w =>
            {
                _sessionMock.Raise(
                    s => s.ChannelOpenConfirmationReceived += null,
                    new MessageEventArgs <ChannelOpenConfirmationMessage>(
                        new ChannelOpenConfirmationMessage(
                            _localChannelNumber,
                            _remoteWindowSize,
                            _remotePacketSize,
                            _remoteChannelNumber)));
                w.WaitOne();
            });
            _sessionMock.Setup(p => p.IsConnected).Returns(true);
            _sessionMock.InSequence(_sequence)
            .Setup(
                p => p.TrySendMessage(It.Is <ChannelCloseMessage>(c => c.LocalChannelNumber == _remoteChannelNumber)))
            .Returns(false);

            _channel            = new ChannelSession(_sessionMock.Object, _localChannelNumber, _localWindowSize, _localPacketSize);
            _channel.Closed    += (sender, args) => _channelClosedRegister.Add(args);
            _channel.Exception += (sender, args) => _channelExceptionRegister.Add(args);
            _channel.Open();

            _sessionMock.Raise(
                p => p.ChannelCloseReceived += null,
                new MessageEventArgs <ChannelCloseMessage>(new ChannelCloseMessage(_localChannelNumber)));
        }
        public async Task TestIfDocumentsAreUpserted()
        {
            Mock<IBulkExecutor> mockBulkExecutor = new Mock<IBulkExecutor>();
            Mock<ILogger> mockLog = new Mock<ILogger>();
          
            AsyncCollector<Document> postMortemCol = new AsyncCollector<Document>();

            DocumentClient client = new DocumentClient(new Uri(configuration["EndPoint"]), configuration["AuthKey"]);

            DocumentCollection container = client.CreateDocumentCollectionQuery(UriFactory.CreateDatabaseUri(configuration["TargetDatabase"]))
                .Where(c => c.Id == configuration["TargetCollection"]).AsEnumerable().FirstOrDefault();

            IBulkExecutor bulkExecutor = new BulkExecutor(client, container);
            await bulkExecutor.InitializeAsync();

            IEnumerable<string> bulkDocs = Utilities.GenerateDocumentsWithRandomIdAndPk(5000);
            BulkImportResponse bulkImportResponse = await bulkExecutor.BulkImportAsync(bulkDocs, false);

            List<Document> fakeBadDocsBatch = new List<Document>();
            Document doc = new Document();
            doc.Id = "0f4adabc-d461-495f-bdd3-4f8877ae7f3f";

            for (int i = 0; i < 10; i++)
            {
                fakeBadDocsBatch.Add(doc);
            }

            ReadOnlyCollection<Document> readOnlyDocs = fakeBadDocsBatch.AsReadOnly();

            mockBulkExecutor.Setup(bulkExecutorFake => bulkExecutorFake.InitializeAsync())
                .Verifiable();

            mockBulkExecutor.Setup(bulkExecutorFake => bulkExecutorFake.BulkImportAsync(It.IsAny<ReadOnlyCollection<Document>>(), true, true, null, It.IsAny<int>(), It.IsAny<CancellationToken>()))
                .Returns(() => Task.FromResult(bulkImportResponse))

                //Add docs to the badInputDocuments list to test whether the post-mortem queue is employed
                .Callback(() => bulkImportResponse.BadInputDocuments.AddRange(fakeBadDocsBatch));

            DocumentFeedMigrator migrator = new DocumentFeedMigrator(mockBulkExecutor.Object);
            await migrator.Run(postMortemCol, readOnlyDocs, mockLog.Object);
          
            Assert.AreEqual(postMortemCol.Count(), 10);

            mockBulkExecutor.Verify(
                bulkExecutorFake => 
            bulkExecutorFake.BulkImportAsync(
                It.IsAny<ReadOnlyCollection<Document>>(),
                true,
                true,
                null,
                It.IsAny<int>(),
                It.IsAny<CancellationToken>()),
                Times.Exactly(1));
        }
        public async Task Create_POST_on_successful_validate_creates_holidayPeriod()
        {
            var redirectToActionResult = await controller.Create(new HolidayPeriod()) as RedirectToActionResult;

            holidayPeriodsRepository.Verify(x => x.CreateAsync(It.IsAny<HolidayPeriod>()), Times.Once);
        }
        public async Task AccountsAsync_WhenCalledWithStatusDate_AssertQueryAsyncWasCalledOnQueryBus()
        {
            Controller sut = CreateSut();

            int      accountingNumber = _fixture.Create <int>();
            DateTime statusDate       = DateTime.Now.AddDays(_random.Next(1, 365) * -1);
            await sut.AccountsAsync(accountingNumber, statusDate);

            _queryBusMock.Verify(m => m.QueryAsync <IGetAccountCollectionQuery, IAccountCollection>(It.Is <IGetAccountCollectionQuery>(value => value.AccountingNumber == accountingNumber && value.StatusDate == statusDate.Date)), Times.Once);
        }
		public void Observation(It observation)
		{
			if (Exception != null)
				throw Exception;

			observation();
		}
        public async Task AccountsAsync_WhenCalledWithoutStatusDate_AssertQueryAsyncWasCalledOnQueryBus()
        {
            Controller sut = CreateSut();

            int accountingNumber = _fixture.Create <int>();
            await sut.AccountsAsync(accountingNumber);

            _queryBusMock.Verify(m => m.QueryAsync <IGetAccountCollectionQuery, IAccountCollection>(It.Is <IGetAccountCollectionQuery>(value => value.AccountingNumber == accountingNumber && value.StatusDate == DateTime.Today)), Times.Once);
        }
        public async Task GetTeamDataStreamAsyncSuccesTest()
        {
            // Arrange
            var activityInstance = GetDataStreamFacade();
            var teamData = new TeamDataEntity();
            sentNotificationDataRepository
                .Setup(x => x.GetStreamsAsync(notificationId, null))
                .Returns(data.ToAsyncEnumerable());

            teamDataRepository.Setup(x => x.GetAsync(It.IsAny<string>(), It.IsAny<string>())).ReturnsAsync(teamData);

            // Act
            var userDataStream = activityInstance.GetTeamDataStreamAsync(notificationId);

            Func<Task> task = async () => await userDataStream.ForEachAsync(x => x.ToList());

            // Assert
            await task.Should().NotThrowAsync();
            sentNotificationDataRepository.Verify(x => x.GetStreamsAsync(It.Is<string>(x => x.Equals(notificationId)), null), Times.Once);
            teamDataRepository.Verify(x => x.GetAsync(It.Is<string>(x=>x.Equals(TeamDataTableNames.TeamDataPartition)),It.IsAny<string>()), Times.AtLeastOnce);
        }
 public async Task DetailsReturnsHttpUnauthorizedResultIfUserIsNotOrgAdmin()
 {
     var controller = CampaignControllerWithDetailQuery(UserType.BasicUser.ToString(), It.IsAny<int>());
     Assert.IsType<HttpUnauthorizedResult>(await controller.Details(It.IsAny<int>()));
 }
                        public async Task CreatesPackageOwnerRequestSendsEmailAndReturnsPendingState(Func <Fakes, User> getCurrentUser, Func <Fakes, User> getUserToAdd)
                        {
                            var fakes = Get <Fakes>();

                            var currentUser = getCurrentUser(fakes);
                            var userToAdd   = getUserToAdd(fakes);

                            var controller = GetController <JsonApiController>();

                            controller.SetCurrentUser(currentUser);

                            var packageOwnershipManagementServiceMock = GetMock <IPackageOwnershipManagementService>();
                            var messageServiceMock = GetMock <IMessageService>();

                            var pending = !(ActionsRequiringPermissions.HandlePackageOwnershipRequest.CheckPermissions(currentUser, userToAdd) == PermissionsCheckResult.Allowed);

                            if (pending)
                            {
                                packageOwnershipManagementServiceMock
                                .Setup(p => p.AddPackageOwnershipRequestAsync(fakes.Package, currentUser, userToAdd))
                                .Returns(Task.FromResult(new PackageOwnerRequest {
                                    ConfirmationCode = "confirmation-code"
                                }))
                                .Verifiable();

                                messageServiceMock
                                .Setup(m => m.SendMessageAsync(It.IsAny <PackageOwnershipRequestMessage>(), false, false))
                                .Callback <IEmailBuilder, bool, bool>((msg, copySender, discloseSenderAddress) =>
                                {
                                    var message = msg as PackageOwnershipRequestMessage;
                                    Assert.Equal(currentUser, message.FromUser);
                                    Assert.Equal(userToAdd, message.ToUser);
                                    Assert.Equal(fakes.Package, message.PackageRegistration);
                                    Assert.Equal(TestUtility.GallerySiteRootHttps + "packages/FakePackage/", message.PackageUrl);
                                    Assert.Equal(TestUtility.GallerySiteRootHttps + $"packages/FakePackage/owners/{userToAdd.Username}/confirm/confirmation-code", message.ConfirmationUrl);
                                    Assert.Equal(TestUtility.GallerySiteRootHttps + $"packages/FakePackage/owners/{userToAdd.Username}/reject/confirmation-code", message.RejectionUrl);
                                    Assert.Equal("Hello World! Html Encoded &lt;3", message.HtmlEncodedMessage);
                                    Assert.Equal(string.Empty, message.PolicyMessage);
                                })
                                .Returns(Task.CompletedTask)
                                .Verifiable();

                                foreach (var owner in fakes.Package.Owners)
                                {
                                    messageServiceMock
                                    .Setup(m => m.SendMessageAsync(
                                               It.Is <PackageOwnershipRequestInitiatedMessage>(
                                                   msg =>
                                                   msg.RequestingOwner == currentUser &&
                                                   msg.ReceivingOwner == owner &&
                                                   msg.NewOwner == userToAdd &&
                                                   msg.PackageRegistration == fakes.Package),
                                               false,
                                               false))
                                    .Returns(Task.CompletedTask)
                                    .Verifiable();
                                }
                            }
                            else
                            {
                                packageOwnershipManagementServiceMock
                                .Setup(p => p.AddPackageOwnerAsync(fakes.Package, userToAdd, true))
                                .Returns(Task.CompletedTask)
                                .Verifiable();

                                foreach (var owner in fakes.Package.Owners)
                                {
                                    messageServiceMock
                                    .Setup(m => m.SendMessageAsync(
                                               It.Is <PackageOwnerAddedMessage>(
                                                   msg =>
                                                   msg.ToUser == owner &&
                                                   msg.NewOwner == userToAdd &&
                                                   msg.PackageRegistration == fakes.Package),
                                               false,
                                               false))
                                    .Returns(Task.CompletedTask)
                                    .Verifiable();
                                }
                            }

                            JsonResult result = await controller.AddPackageOwner(fakes.Package.Id, userToAdd.Username, "Hello World! Html Encoded <3");

                            dynamic data = result.Data;
                            PackageOwnersResultViewModel model = data.model;

                            Assert.True(data.success);
                            Assert.Equal(userToAdd.Username, model.Name);
                            Assert.Equal(pending, model.Pending);

                            packageOwnershipManagementServiceMock.Verify();
                            messageServiceMock.Verify();
                        }
 public async Task EditGetReturnsHttpNotFoundResultWhenViewModelIsNull()
 {
     CampaignController controller;
     MockMediatorCampaignSummaryQuery(out controller);
     Assert.IsType<HttpNotFoundResult>(await controller.Edit(It.IsAny<int>()));
 }
                    public async Task RemovesExistingOwner(Func <Fakes, User> getCurrentUser, Func <Fakes, User> getUserToRemove)
                    {
                        // Arrange
                        var fakes        = Get <Fakes>();
                        var currentUser  = getCurrentUser(fakes);
                        var userToRemove = getUserToRemove(fakes);
                        var package      = fakes.Package;
                        var controller   = GetController <JsonApiController>();

                        controller.SetCurrentUser(currentUser);

                        var packageOwnershipManagementService = GetMock <IPackageOwnershipManagementService>();

                        packageOwnershipManagementService
                        .Setup(x => x.GetPackageOwnershipRequests(package, null, userToRemove))
                        .Returns(Enumerable.Empty <PackageOwnerRequest>());

                        // Act
                        var result = await controller.RemovePackageOwner(package.Id, userToRemove.Username);

                        dynamic data = result.Data;

                        // Assert
                        Assert.True(data.success);

                        packageOwnershipManagementService.Verify(x => x.RemovePackageOwnerAsync(package, currentUser, userToRemove, It.IsAny <bool>()));

                        GetMock <IMessageService>()
                        .Verify(x => x.SendMessageAsync(
                                    It.Is <PackageOwnerRemovedMessage>(
                                        msg =>
                                        msg.FromUser == currentUser &&
                                        msg.ToUser == userToRemove &&
                                        msg.PackageRegistration == package),
                                    false,
                                    false));
                    }
 public async Task EditPostReturnsBadRequestWhenCampaignIsNull()
 {
     var controller = CampaignControllerWithSummaryQuery(UserType.OrgAdmin.ToString(), It.IsAny<int>());
     var result = await controller.Edit(null, null);
     Assert.IsType<BadRequestResult>(result);
 }
Ejemplo n.º 25
0
        public void HandleChannelException_should_update_topology_as_expected_on_network_error_or_timeout(
            string errorType, bool shouldUpdateTopology)
        {
            var       serverId     = new ServerId(_clusterId, _endPoint);
            var       connectionId = new ConnectionId(serverId);
            Exception innerMostException;

            switch (errorType)
            {
            case "MongoConnectionExceptionWithSocketTimeout":
                innerMostException = new SocketException((int)SocketError.TimedOut);
                break;

            case nameof(MongoConnectionException):
                innerMostException = new SocketException((int)SocketError.NetworkUnreachable);
                break;

            default: throw new ArgumentException("Unknown error type.");
            }

            var operationUsingChannelException = new MongoConnectionException(connectionId, "Oops", new IOException("Cry", innerMostException));
            var mockConnection = new Mock <IConnectionHandle>();
            var helloResult    = new HelloResult(new BsonDocument {
                { "compressors", new BsonArray() }, { "maxWireVersion", WireVersion.Server44 }
            });

            mockConnection.SetupGet(c => c.Description)
            .Returns(new ConnectionDescription(new ConnectionId(serverId, 0), helloResult));
            var mockConnectionPool = new Mock <IConnectionPool>();

            mockConnectionPool.Setup(p => p.AcquireConnection(It.IsAny <CancellationToken>())).Returns(mockConnection.Object);
            mockConnectionPool.Setup(p => p.AcquireConnectionAsync(It.IsAny <CancellationToken>())).ReturnsAsync(mockConnection.Object);
            var mockConnectionPoolFactory = new Mock <IConnectionPoolFactory>();

            mockConnectionPoolFactory
            .Setup(f => f.CreateConnectionPool(It.IsAny <ServerId>(), _endPoint, It.IsAny <IConnectionExceptionHandler>()))
            .Returns(mockConnectionPool.Object);
            var mockMonitorServerInitialDescription = new ServerDescription(serverId, _endPoint).With(reasonChanged: "Initial D", type: ServerType.Unknown);
            var mockServerMonitor = new Mock <IServerMonitor>();

            mockServerMonitor.SetupGet(m => m.Description).Returns(mockMonitorServerInitialDescription);
            mockServerMonitor.SetupGet(m => m.Lock).Returns(new object());
            var mockServerMonitorFactory = new Mock <IServerMonitorFactory>();

            mockServerMonitorFactory.Setup(f => f.Create(It.IsAny <ServerId>(), _endPoint)).Returns(mockServerMonitor.Object);
            var subject = new DefaultServer(_clusterId, _clusterClock, _clusterConnectionMode, _connectionModeSwitch, _directConnection, _settings, _endPoint, mockConnectionPoolFactory.Object, mockServerMonitorFactory.Object, _capturedEvents, _serverApi);

            subject.Initialize();
            var heartbeatDescription = mockMonitorServerInitialDescription.With(reasonChanged: "Heartbeat", type: ServerType.Standalone);

            mockServerMonitor.Setup(m => m.Description).Returns(heartbeatDescription);
            mockServerMonitor.Raise(
                m => m.DescriptionChanged += null,
                new ServerDescriptionChangedEventArgs(mockMonitorServerInitialDescription, heartbeatDescription));
            subject.Description.Should().Be(heartbeatDescription);

            subject.HandleChannelException(mockConnection.Object, operationUsingChannelException);

            if (shouldUpdateTopology)
            {
                subject.Description.Type.Should().Be(ServerType.Unknown);
                subject.Description.ReasonChanged.Should().Contain("ChannelException");
            }
            else
            {
                subject.Description.Should().Be(heartbeatDescription);
            }
        }
        public async Task EditPostRedirectsToCorrectActionWithCorrectRouteValuesWhenModelStateIsValid()
        {
            var controller = CampaignControllerWithSummaryQuery(UserType.OrgAdmin.ToString(), It.IsAny<int>());
            var result = await controller.Edit(new CampaignSummaryModel { Name = "Foo", OrganizationId = It.IsAny<int>() }, null);

            //TODO: test result for correct Action name and Route values
            Assert.IsType<RedirectToActionResult>(result);
        }
Ejemplo n.º 27
0
        // private methods
        private Server SetupServer(bool exceptionOnConnectionOpen, bool exceptionOnConnectionAcquire)
        {
            var connectionId         = new ConnectionId(new ServerId(_clusterId, _endPoint));
            var mockConnectionHandle = new Mock <IConnectionHandle>();

            mockConnectionHandle
            .Setup(c => c.Fork())
            .Returns(mockConnectionHandle.Object);

            var mockConnectionPool = new Mock <IConnectionPool>();

            if (exceptionOnConnectionAcquire)
            {
                mockConnectionPool
                .Setup(p => p.AcquireConnection(It.IsAny <CancellationToken>()))
                .Throws(new TimeoutException("Timeout"));
                mockConnectionPool
                .Setup(p => p.AcquireConnectionAsync(It.IsAny <CancellationToken>()))
                .Throws(new TimeoutException("Timeout"));
                mockConnectionPool.Setup(p => p.Clear());
            }
            else if (exceptionOnConnectionOpen)
            {
                mockConnectionPool
                .Setup(p => p.AcquireConnection(It.IsAny <CancellationToken>()))
                .Throws(new MongoAuthenticationException(connectionId, "Invalid login."));
                mockConnectionPool
                .Setup(p => p.AcquireConnectionAsync(It.IsAny <CancellationToken>()))
                .Throws(new MongoAuthenticationException(connectionId, "Invalid login."));
                mockConnectionPool.Setup(p => p.Clear());
            }
            else
            {
                mockConnectionPool
                .Setup(p => p.AcquireConnection(It.IsAny <CancellationToken>()))
                .Returns(mockConnectionHandle.Object);
                mockConnectionPool
                .Setup(p => p.AcquireConnectionAsync(It.IsAny <CancellationToken>()))
                .Returns(Task.FromResult(mockConnectionHandle.Object));
                mockConnectionPool.Setup(p => p.Clear());
            }

            var mockConnectionPoolFactory = new Mock <IConnectionPoolFactory>();

            mockConnectionPoolFactory
            .Setup(f => f.CreateConnectionPool(It.IsAny <ServerId>(), _endPoint, It.IsAny <IConnectionExceptionHandler>()))
            .Returns(mockConnectionPool.Object);

            var server = new DefaultServer(
                _clusterId,
                _clusterClock,
                _clusterConnectionMode,
                _connectionModeSwitch,
                _directConnection,
                _settings,
                _endPoint,
                mockConnectionPoolFactory.Object,
                _mockServerMonitorFactory.Object,
                _capturedEvents,
                _serverApi);

            server.Initialize();

            return(server);
        }
 public async Task DeleteReturnsHttpNotFoundResultWhenCampaignIsNotFound()
 {
     CampaignController controller;
     MockMediatorCampaignSummaryQuery(out controller);
     Assert.IsType<HttpNotFoundResult>(await controller.Delete(It.IsAny<int>()));
 }
Ejemplo n.º 29
0
        public new void SetUp()
        {
            _discountRepo        = new Mock <IRepository <Discount> >();
            _complexDiscountRepo = new Mock <IRepository <ComplexDiscount> >();
            var discount1 = new Discount
            {
                Id                 = 1,
                DiscountType       = DiscountType.AssignedToCategories,
                Name               = "Discount 1",
                UsePercentage      = true,
                DiscountPercentage = 10,
                DiscountAmount     = 0,
                DiscountLimitation = DiscountLimitationType.Unlimited,
                LimitationTimes    = 0
            };
            var discount2 = new Discount
            {
                Id                 = 2,
                DiscountType       = DiscountType.AssignedToSkus,
                Name               = "Discount 2",
                UsePercentage      = false,
                DiscountPercentage = 0,
                DiscountAmount     = 5,
                RequiresCouponCode = true,
                CouponCode         = "SecretCode",
                DiscountLimitation = DiscountLimitationType.NTimesPerCustomer,
                LimitationTimes    = 3
            };

            _discountRepo.Setup(x => x.Table).Returns(new List <Discount> {
                discount1, discount2
            }.AsQueryable());

            _eventPublisher = new Mock <IEventPublisher>();
            _eventPublisher.Setup(x => x.Publish(It.IsAny <object>()));

            _storeContext    = new Mock <IStoreContext>();
            _customerService = new Mock <ICustomerService>();

            _categoryRepo = new Mock <IRepository <Category> >();
            _categoryRepo.Setup(x => x.Table).Returns(new List <Category>().AsQueryable());
            _manufacturerRepo = new Mock <IRepository <Manufacturer> >();
            _manufacturerRepo.Setup(x => x.Table).Returns(new List <Manufacturer>().AsQueryable());
            _productRepo = new Mock <IRepository <Product> >();
            _productRepo.Setup(x => x.Table).Returns(new List <Product>().AsQueryable());

            var cacheManager = new TestMemoryCacheManager(new Mock <IMemoryCache>().Object);

            _discountRequirementRepo = new Mock <IRepository <DiscountRequirement> >();
            _discountRequirementRepo.Setup(x => x.Table).Returns(new List <DiscountRequirement>().AsQueryable());

            _discountUsageHistoryRepo = new Mock <IRepository <DiscountUsageHistory> >();
            var pluginFinder = new PluginFinder(_eventPublisher.Object);

            _localizationService = new Mock <ILocalizationService>();
            _categoryService     = new Mock <ICategoryService>();

            _discountService = new DiscountService(_categoryService.Object,
                                                   _customerService.Object,
                                                   _eventPublisher.Object,
                                                   _localizationService.Object,
                                                   pluginFinder,
                                                   _categoryRepo.Object,
                                                   _discountRepo.Object,
                                                   _complexDiscountRepo.Object,
                                                   _discountRequirementRepo.Object,
                                                   _discountUsageHistoryRepo.Object,
                                                   _manufacturerRepo.Object,
                                                   _productRepo.Object,
                                                   cacheManager,
                                                   _storeContext.Object);
        }
 public async Task DetailConfirmedReturnsHttpUnauthorizedResultWhenUserIsNotOrgAdmin()
 {
     var controller = CampaignControllerWithSummaryQuery(UserType.BasicUser.ToString(), It.IsAny<int>());
     Assert.IsType<HttpUnauthorizedResult>(await controller.DeleteConfirmed(It.IsAny<int>()));
 }
Ejemplo n.º 31
0
        public async Task Success()
        {
            // Arrange
            var challenges = CreateChallenges().ToList();

            var mockChallengeService = new Mock <IChallengeService>();

            mockChallengeService.Setup(
                challengeService => challengeService.GetMatchesAsync(
                    Game.LeagueOfLegends,
                    It.IsAny <PlayerId>(),
                    It.IsAny <DateTime?>(),
                    It.IsAny <DateTime?>(),
                    It.IsAny <IImmutableSet <string> >()))
            .ReturnsAsync(CreateChallengeMatches().ToList())
            .Verifiable();

            var mockServiceBusPublisher = new Mock <IServiceBusPublisher>();

            mockServiceBusPublisher.Setup(serviceBusPublisher => serviceBusPublisher.PublishAsync(It.IsAny <ChallengeSynchronizedIntegrationEvent>()))
            .Returns(Task.CompletedTask)
            .Verifiable();

            using var challengesHost = new ChallengesHostFactory().WithWebHostBuilder(
                      builder =>
            {
                builder.ConfigureTestContainer <ContainerBuilder>(
                    container =>
                {
                    container.RegisterInstance(mockServiceBusPublisher.Object).As <IServiceBusPublisher>().SingleInstance();
                });
            });

            challengesHost.Server.CleanupDbContext();

            await challengesHost.Server.UsingScopeAsync(
                async scope =>
            {
                var repository = scope.GetRequiredService <IChallengeRepository>();

                repository.Create(challenges);

                await repository.CommitAsync(false);
            });

            using var gamesHost = new GamesHostFactory().WithWebHostBuilder(
                      builder =>
            {
                builder.ConfigureTestContainer <ContainerBuilder>(
                    container =>
                {
                    container.RegisterInstance(mockChallengeService.Object).As <IChallengeService>().SingleInstance();
                });
            });

            var recurringJob = new ChallengeRecurringJob(
                new ChallengeService.ChallengeServiceClient(challengesHost.CreateChannel()),
                new GameService.GameServiceClient(gamesHost.CreateChannel()));

            // Act
            await recurringJob.SynchronizeChallengesAsync(EnumGame.LeagueOfLegends);

            // Assert
            mockServiceBusPublisher.Verify(
                serviceBusPublisher => serviceBusPublisher.PublishAsync(It.IsAny <ChallengeSynchronizedIntegrationEvent>()),
                Times.Exactly(2));

            mockChallengeService.Verify(
                challengeService => challengeService.GetMatchesAsync(
                    Game.LeagueOfLegends,
                    It.IsAny <PlayerId>(),
                    It.IsAny <DateTime?>(),
                    It.IsAny <DateTime?>(),
                    It.IsAny <IImmutableSet <string> >()),
                Times.Exactly(4));
        }
        public void LlenarDTOEvento_AsignarValorPropiedadcExpresionTiempo_PropiedadcExpresionTiempoIgualA10Minutos()
        {
            //Arrange
            DateTime dtFechaBase = new DateTime(2020, 01, 10, 20, 45, 000);
            PaqueteEnviado Paquete = new PaqueteEnviado() { dtFechaActual = dtFechaBase, dtFechaEntrega = new DateTime(2020, 01, 10, 20, 55, 000) };
            var DOCEvaluadorFechaAnterior = new Mock<IEvaluadorFechaAnterior>();
            DOCEvaluadorFechaAnterior.Setup((s) => s.EvaluarFechaAnterior(It.IsAny<DateTime>(), It.IsAny<DateTime>())).Returns(false);
            var DOCRecuperadorTiempo = new Mock<IObtenedorTiempo>();
            DOCRecuperadorTiempo.Setup((s) => s.RecuperarExpresionTiempo().ProcesarTiempo(Paquete.dtFechaActual, Paquete.dtFechaEntrega)).Returns("10 Minutos");
            var SUT = new CompletadorDatosDTO(DOCEvaluadorFechaAnterior.Object, DOCRecuperadorTiempo.Object);

            //Act
            SUT.LlenarDTOPaquete(Paquete);

            //Assert
            Assert.AreEqual("10 Minutos", Paquete.cExpresionTiempo);
        }
Ejemplo n.º 33
0
        public void IsValid_WhenPropertiesIsNotNull_ReturnsTrue()
        {
            // Arrange.
            decimal decimalValue = 111;
            float   floatValue   = 112;
            double  doubleValue  = 113;
            short   shortValue   = 114;
            int     intValue     = 115;
            long    longValue    = 116;
            ushort  ushortValue  = 117;
            uint    uintValue    = 118;
            ulong   ulongValue   = 119;

            var properties = new Dictionary <string, object>
            {
                { "property_1", "value1" },
                { "property_2", new ParsedSplit() },
                { "property_3", false },
                { "property_4", null },
                { "property_5", decimalValue },
                { "property_6", floatValue },
                { "property_7", doubleValue },
                { "property_8", shortValue },
                { "property_9", intValue },
                { "property_10", longValue },
                { "property_11", ushortValue },
                { "property_12", uintValue },
                { "property_13", ulongValue }
            };

            var sizeExpected = 1024L;

            foreach (var item in properties)
            {
                sizeExpected += item.Key.Length;

                if (item.Value is string)
                {
                    sizeExpected += ((string)item.Value).Length;
                }
            }

            // Act.
            var result = eventPropertiesValidator.IsValid(properties);

            // Assert.
            Assert.IsTrue(result.Success);
            Assert.IsNotNull(result.Value);

            var dicResult = (Dictionary <string, object>)result.Value;

            Assert.AreEqual("value1", dicResult["property_1"]);
            Assert.IsNull(dicResult["property_2"]);
            Assert.IsFalse((bool)dicResult["property_3"]);
            Assert.IsNull(dicResult["property_4"]);
            Assert.AreEqual(decimalValue, dicResult["property_5"]);
            Assert.AreEqual(floatValue, dicResult["property_6"]);
            Assert.AreEqual(doubleValue, dicResult["property_7"]);
            Assert.AreEqual(shortValue, dicResult["property_8"]);
            Assert.AreEqual(intValue, dicResult["property_9"]);
            Assert.AreEqual(longValue, dicResult["property_10"]);
            Assert.AreEqual(ushortValue, dicResult["property_11"]);
            Assert.AreEqual(uintValue, dicResult["property_12"]);
            Assert.AreEqual(ulongValue, dicResult["property_13"]);
            Assert.IsTrue(result.EventSize == sizeExpected);

            _log.Verify(mock => mock.Warn($"Property Splitio.Domain.ParsedSplit is of invalid type. Setting value to null"), Times.Exactly(1));
            _log.Verify(mock => mock.Warn(It.IsAny <string>()), Times.Exactly(1));
            _log.Verify(mock => mock.Error(It.IsAny <string>()), Times.Exactly(0));
        }
Ejemplo n.º 34
0
        public async Task Success2()
        {
            // Arrange
            using var gamesHost = new GamesHostFactory();

            var gamesServiceClient = new GameService.GameServiceClient(gamesHost.CreateChannel());

            var findChallengeScoringRequest = new FindChallengeScoringRequest
            {
                Game = EnumGame.LeagueOfLegends
            };

            var findChallengeScoringResponse = await gamesServiceClient.FindChallengeScoringAsync(findChallengeScoringRequest);

            var createdAt = new DateTimeProvider(
                new DateTime(
                    2019,
                    12,
                    30,
                    21,
                    9,
                    22,
                    DateTimeKind.Utc));

            var startedAt = new DateTimeProvider(
                new DateTime(
                    2019,
                    12,
                    30,
                    22,
                    42,
                    50,
                    DateTimeKind.Utc));

            var challenge = new Challenge(
                new ChallengeId(),
                new ChallengeName("TEST CHALLENGE"),
                Game.LeagueOfLegends,
                BestOf.One,
                Entries.Two,
                new ChallengeTimeline(createdAt, ChallengeDuration.OneDay),
                new Scoring(
                    findChallengeScoringResponse.Scoring.Items.OrderBy(scoring => scoring.Order)
                    .ToDictionary(scoring => scoring.StatName, scoring => scoring.StatWeighting)));

            var participant = new Participant(
                new ParticipantId(),
                new UserId(),
                PlayerId.Parse("V1R8S4W19KGdqSTn-rRO-pUGv6lfu2BkdVCaz_8wd-m6zw"),
                new DateTimeProvider(createdAt.DateTime + TimeSpan.FromMinutes(5)));

            challenge.Register(participant);

            challenge.Register(
                new Participant(
                    new ParticipantId(),
                    new UserId(),
                    new PlayerId(),
                    new DateTimeProvider(createdAt.DateTime + TimeSpan.FromMinutes(10))));

            challenge.Start(startedAt);

            var mockServiceBusPublisher = new Mock <IServiceBusPublisher>();

            mockServiceBusPublisher.Setup(serviceBusPublisher => serviceBusPublisher.PublishAsync(It.IsAny <ChallengeSynchronizedIntegrationEvent>()))
            .Returns(Task.CompletedTask)
            .Verifiable();

            using var challengesHost = new ChallengesHostFactory().WithWebHostBuilder(
                      builder =>
            {
                builder.ConfigureTestContainer <ContainerBuilder>(
                    container =>
                {
                    container.RegisterInstance(mockServiceBusPublisher.Object).As <IServiceBusPublisher>().SingleInstance();
                });
            });

            challengesHost.Server.CleanupDbContext();

            await challengesHost.Server.UsingScopeAsync(
                async scope =>
            {
                var repository = scope.GetRequiredService <IChallengeRepository>();

                repository.Create(challenge);

                await repository.CommitAsync(false);
            });

            var recurringJob = new ChallengeRecurringJob(
                new ChallengeService.ChallengeServiceClient(challengesHost.CreateChannel()),
                new GameService.GameServiceClient(gamesHost.CreateChannel()));

            // Act
            await recurringJob.SynchronizeChallengesAsync(EnumGame.LeagueOfLegends);

            // Assert
            await challengesHost.Server.UsingScopeAsync(
                async scope =>
            {
                var repository = scope.GetRequiredService <IChallengeRepository>();

                var persistentChallenge = await repository.FindChallengeAsync(challenge.Id);

                persistentChallenge.FindParticipant(participant.PlayerId).Matches.Should().HaveCount(2);
            });

            mockServiceBusPublisher.Verify(
                serviceBusPublisher => serviceBusPublisher.PublishAsync(It.IsAny <ChallengeSynchronizedIntegrationEvent>()),
                Times.Exactly(1));
        }
        private Controller CreateSut(IAccountCollection accountCollection = null)
        {
            _queryBusMock.Setup(m => m.QueryAsync <IGetAccountCollectionQuery, IAccountCollection>(It.IsAny <IGetAccountCollectionQuery>()))
            .Returns(Task.FromResult(accountCollection ?? _fixture.BuildAccountCollectionMock().Object));

            return(new Controller(_commandBusMock.Object, _queryBusMock.Object));
        }