public void Setup() { List <Domain.Entities.Message> myList = new List <Domain.Entities.Message>() { new Domain.Entities.Message() { InstanceId = Me.GetInstance().Id, RequestId = Guid.NewGuid(), Title = "Hello World! (Test)", Content = "Hello World! (Test)" }, new Domain.Entities.Message() { InstanceId = Me.GetInstance().Id, RequestId = Guid.NewGuid(), Title = "Hello World! (Test 2)", Content = "Hello World! (Test 2)" } }; List <Domain.Entities.Message> otherList = new List <Domain.Entities.Message>() { new Domain.Entities.Message() { InstanceId = Guid.NewGuid(), RequestId = Guid.NewGuid(), Title = "Hello World! (Test Other)", Content = "Hello World! (Test Other)" } }; _moqRepository.Setup(p => p.GetMessagesByInstance(It.IsIn <Guid>(Me.GetInstance().Id))).ReturnsAsync(() => myList); _moqRepository.Setup(p => p.GetMessagesByInstance(It.IsNotIn <Guid>(Me.GetInstance().Id))).ReturnsAsync(() => new List <Domain.Entities.Message>()); _moqRepository.Setup(p => p.GetMessagesByNotInstance(It.IsIn <Guid>(Me.GetInstance().Id))).ReturnsAsync(() => otherList); _moqRepository.Setup(p => p.GetMessagesByNotInstance(It.IsNotIn <Guid>(Me.GetInstance().Id))).ReturnsAsync(() => new List <Domain.Entities.Message>()); }
public void SetDataAsyncWithoutSaveFromRepositoryReturnsNotFoundResult() { //Mock the repository var repository = new Mock <IStagingRepository <MassTerminationModelSerialized> >(MockBehavior.Strict); var qRepo = new Mock <IQueueRepository>(MockBehavior.Strict); repository.Setup(r => r.SetDataAsync(It.IsAny <UserContext>(), It.IsAny <List <MassTerminationModelSerialized> >())) .ReturnsAsync(new List <DataloadBatch>()); //Mock data factory var dataFactory = new Mock <IDataFactory>(MockBehavior.Strict); dataFactory.Setup(d => d.GetMassTerminateRepository()).Returns(repository.Object); dataFactory.Setup(d => d.GetQueueRepository()).Returns(qRepo.Object); //Mapping factory IMappingFactory mapFactory = new MappingFactory(); //Mock Auth var authorization = new Mock <IAuthorizationProvider>(MockBehavior.Strict); authorization.Setup(s => s.IsAuthorized(It.IsIn <string>(new List <string>() { "426" }))).Returns(true); var controller = new MassTerminateController(dataFactory.Object, authorization.Object, mapFactory); Task <IHttpActionResult> actionResult = controller.SetDataAsync("426", models); Assert.IsInstanceOfType(actionResult.Result, typeof(NotFoundResult)); }
public void SendMessageBatchAsync_AnySendMessageBatchRequest_CallsMessageServiceToRequestBodyForEachEntry() { var clientMock = new Mock <IAmazonSQS>(); var messageServiceMock = new Mock <IMessageService>(); var values = new[] { (string)new Sentence(), (string)new Sentence() }; var entries = new List <SendMessageBatchRequestEntry> { new SendMessageBatchRequestEntry("id1", values[0]), new SendMessageBatchRequestEntry("id2", values[1]) }; var request = new SendMessageBatchRequest("url", entries); var token = new CancellationToken(); var subject = new AmazonSQSCompressingClientWithTestableMessageService( clientMock.Object, messageServiceMock.Object ); var result = subject.SendMessageBatchAsync(request, token); messageServiceMock.Verify( x => x.ToRequestBody(It.IsIn(values)), Times.Exactly(entries.Count) ); }
public void OrdinaryMethodCalls() { var mock = new Mock <IFoo>(); //mock.Setup(foo => foo.DoSomething("ping")).Returns(true); //mock.Setup(foo => foo.DoSomething("pong")).Returns(true); //mock.Setup(foo => foo.DoSomething(It.IsIn("ping", "pong"))) // .Returns(true); // same as above, but lazy evaluated mock.Setup(foo => foo.DoSomething( It.IsIn("ping", "pong"))).Returns(() => true); // MATCHING METHOD INPUT VALUES // support for different argument values Assert.That(mock.Object.DoSomething("ping"), Is.True); Assert.That(mock.Object.DoSomething("pong"), Is.True); // if unspecified, this will yield default(T) Assert.That(mock.Object.DoSomething("something else"), Is.False); // value can be null, don't worry! Assert.That(mock.Object.DoSomething(null), Is.False); }
public void PersonParserPlainTest() { var splitter = new Mock <IPersonSplitter>(); var validator = new Mock <IPersonValidator>(); var mapper = new Mock <IPersonMapper>(); var tmpIn = inputs[0].Split(","); var tmpOut = tmpPersonArray.Concat(tmpPersonArray); splitter .Setup(s => s.Split(It.IsIn(inputs.SkipLast(1)))) .Returns(tmpIn); splitter .Setup(s => s.Split(inputs.Last())) .Returns(new[] { inputs.Last() }); validator .Setup(v => v.Validate(tmpIn)) .Returns(true); validator .Setup(v => v.Validate(new[] { inputs.Last() })) .Returns(false); mapper .Setup(m => m.Map(tmpIn)) .Returns(tmpPersonArray[0]); var parser = new PersonParserPlain(splitter.Object, validator.Object, mapper.Object); var res = parser.ParseToPersonEntity(inputs); Assert.Equal(tmpOut, res); Assert.Throws <ArgumentNullException>( "splitter", () => new PersonParserPlain(null, validator.Object, mapper.Object)); Assert.Throws <ArgumentNullException>( "validator", () => new PersonParserPlain(splitter.Object, null, mapper.Object)); Assert.Throws <ArgumentNullException>( "mapper", () => new PersonParserPlain(splitter.Object, validator.Object, null)); }
public void SaveRouteCommnad_Ok() { //Arrenge SaveRouteRequest request = new SaveRouteRequest { PointFromCode = "test_from", PointToCode = "teste_to", Cost = 1, Time = 10 }; _routedataMock.Setup(p => p.GetRoute(It.IsIn(request.PointFromCode), It.IsIn(request.PointToCode))); //Act new SaveRouteCommand(_routedataMock.Object).Execute(request); //Assert _routedataMock.Verify(p => p.Save(It.Is((Route r) => r.PointFromCode.Equals(request.PointFromCode) && r.PointToCode.Equals(request.PointToCode) && r.Cost == request.Cost && r.Time == request.Time ))); }
public void IssueContactReminders_OnOneRecordProcessingFailure_LogsErrors_And_Continues() { // Arrange var service = new ContractReminderProcessingService(_contractNotificationService, _loggerAdapter, _auditService); var result = GetContracts(); var emptyResult = new ContractReminders(); SetupContractReminderServiceGetContracts(result, emptyResult); SetupLoggerInformation(); SetupLoggerError <InvalidOperationException>(); Mock.Get(_contractNotificationService) .SetupSequence(p => p.QueueContractEmailReminderMessage(It.IsIn <Contract>(result.Contracts))) .Returns(Task.CompletedTask) .Throws <InvalidOperationException>() .Returns(Task.CompletedTask); Mock.Get(_contractNotificationService) .Setup(p => p.NotifyContractReminderSent(It.IsIn <Contract>(result.Contracts))) .Returns(Task.CompletedTask) .Verifiable(); Mock.Get(_auditService) .Setup(p => p.TrySendAuditAsync(It.IsAny <Audit.Api.Client.Models.Audit>())) .Returns(Task.CompletedTask) .Verifiable(); // Act Func <Task> act = async() => await service.IssueContractReminders(); // Assert act.Should().NotThrow(); Mock.Get(_contractNotificationService).Verify(); Mock.Get(_loggerAdapter).Verify(); }
public async Task Delete_ThumbnailOptionIds_DeletedThumbnailTasksWithPassedIds() { var taskEntities = ThumbnailTaskEntitysDataSource.ToList(); var ids = taskEntities.Select(t => t.Id).ToArray(); var mock = new Mock <IThumbnailRepository>(); mock.SetupGet(x => x.UnitOfWork).Returns(new Mock <IUnitOfWork>().Object); mock.Setup(r => r.RemoveThumbnailTasksByIdsAsync(It.IsIn <string[]>(ids))).Callback( (string[] arr) => { var entities = taskEntities.Where(e => arr.Contains(e.Id)).ToList(); foreach (var entity in entities) { taskEntities.Remove(entity); } }); var sut = new ThumbnailTaskService(() => mock.Object); await sut.RemoveByIdsAsync(ids); Assert.Empty(taskEntities); }
public async Task GetClientByClientIdQuery_Ok() { //Arrenge string clientId = "testSuccess"; _identityClientDataMock.Setup(p => p.GetIdentityClientByClientIdAsync(It.IsIn(clientId))) .ReturnsAsync(new IdentityClient { ClientSecret = clientId, ClientId = clientId, }); //Act IdentityClient client = await new GetClientByClientIdQuery(_identityClientDataMock.Object).ExecuteAsync( new GetClientByClientIdQueryRequest { ClientId = clientId }); //Assert Assert.IsNotNull(client); Assert.IsTrue(client.ClientSecret.Equals(clientId)); Assert.IsTrue(client.ClientId.Equals(clientId)); }
public void QueenCanCaptureEnemiesButCantJumpThroughThem() { //BQ - black queen //PM - possible move //EP - enemy piece //7 //6 //5 EP PM PM BQ PM //4 //3 //2 //1 //0 // 0 1 2 3 4 5 6 7 var boardMock = new Mock <IChessBoard>(MockBehavior.Strict); var queenMock = new Mock <IReadOnlyChessPiece>(MockBehavior.Strict); var queenPosition = new Position(6, 5); var enemyPosition = new Position(3, 5); var availableFinishPosition1 = new Position(4, 5); var availableFinishPosition2 = new Position(5, 5); var availableFinishPosition3 = new Position(7, 5); var availableFinishPositions = new List <Position>() { availableFinishPosition1, availableFinishPosition2, availableFinishPosition3 }; queenMock .SetupGet(p => p.Color) .Returns(ChessColor.Black); queenMock .SetupGet(p => p.PieceType) .Returns(ChessPieceType.Queen); queenMock .SetupGet(p => p.Position) .Returns(queenPosition); queenMock .SetupGet(p => p.HasMoved) .Returns(true); boardMock .Setup(b => b.IsPositionTaken(enemyPosition)) .Returns(true); boardMock .Setup(b => b.IsPositionTaken(It.IsIn <Position>(availableFinishPositions))) .Returns(false); boardMock .Setup(b => b.IsEnemyOnPosition(enemyPosition, ChessColor.White)) .Returns(true); boardMock .Setup(b => b.IsEnemyOnPosition(It.IsIn <Position>(availableFinishPositions), ChessColor.White)) .Returns(false); var movement = new HorizontalMovement(boardMock.Object); var availableMoves = movement.GetAvailableMoves(queenMock.Object); Assert.AreEqual(4, availableMoves.Count()); Assert.IsTrue(availableMoves.All(m => m.StartingPosition == queenPosition)); var finishedPositions = availableMoves .Select(m => m.FinishedPosition) .ToList(); Assert.Contains(availableFinishPosition1, finishedPositions); Assert.Contains(availableFinishPosition2, finishedPositions); Assert.Contains(availableFinishPosition3, finishedPositions); Assert.Contains(enemyPosition, finishedPositions); }
public void AddPayloadPropertyDoesNotAddDuplicatesIfKeyAndValueEqualsAtIndexedValues() { var healthReporterMock = new Mock <IHealthReporter>(); var data = new EventData(); data.AddPayloadProperty("prop", "value1", healthReporterMock.Object, "tests"); data.AddPayloadProperty("prop", "value2", healthReporterMock.Object, "tests"); data.AddPayloadProperty("prop", "value3", healthReporterMock.Object, "tests"); data.AddPayloadProperty("prop", "value3", healthReporterMock.Object, "tests"); Assert.Equal(3, data.Payload.Keys.Count); object value; Assert.True(data.TryGetPropertyValue("prop", out value)); Assert.Equal("value1", value); Assert.True(data.TryGetPropertyValue("prop_1", out value)); Assert.Equal("value2", value); Assert.True(data.TryGetPropertyValue("prop_2", out value)); Assert.Equal("value3", value); healthReporterMock.Verify(m => m.ReportWarning(It.Is <string>(s => s.StartsWith("The property with the key 'prop' already exist in the event payload with equivalent value under key 'prop_2'")), It.IsIn("tests"))); }
public async Task ConnectionResetMidRequestIsLoggedAsDebug() { var requestStarted = new SemaphoreSlim(0); var connectionReset = new SemaphoreSlim(0); var connectionClosing = new SemaphoreSlim(0); var loggedHigherThanDebug = false; var mockLogger = new Mock <ILogger>(); mockLogger .Setup(logger => logger.IsEnabled(It.IsAny <LogLevel>())) .Returns(true); mockLogger .Setup(logger => logger.Log(It.IsAny <LogLevel>(), It.IsAny <EventId>(), It.IsAny <object>(), It.IsAny <Exception>(), It.IsAny <Func <object, Exception, string> >())) .Callback <LogLevel, EventId, object, Exception, Func <object, Exception, string> >((logLevel, eventId, state, exception, formatter) => { Logger.Log(logLevel, eventId, state, exception, formatter); if (eventId.Id == _connectionResetEventId) { connectionReset.Release(); } if (logLevel > LogLevel.Debug) { loggedHigherThanDebug = true; } }); var mockLoggerFactory = new Mock <ILoggerFactory>(); mockLoggerFactory .Setup(factory => factory.CreateLogger(It.IsAny <string>())) .Returns(Logger); mockLoggerFactory .Setup(factory => factory.CreateLogger(It.IsIn("Microsoft.AspNetCore.Server.Kestrel", "Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv", "Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets"))) .Returns(mockLogger.Object); using (var server = new TestServer(async context => { requestStarted.Release(); await connectionClosing.WaitAsync(); }, new TestServiceContext(mockLoggerFactory.Object))) { using (var connection = server.CreateConnection()) { await connection.SendEmptyGet(); // Wait until connection is established Assert.True(await requestStarted.WaitAsync(TestConstants.DefaultTimeout), "request should have started"); connection.Reset(); } // If the reset is correctly logged as Debug, the wait below should complete shortly. // This check MUST come before disposing the server, otherwise there's a race where the RST // is still in flight when the connection is aborted, leading to the reset never being received // and therefore not logged. Assert.True(await connectionReset.WaitAsync(TestConstants.DefaultTimeout), "Connection reset event should have been logged"); connectionClosing.Release(); } Assert.False(loggedHigherThanDebug, "Logged event should not have been higher than debug."); }
public void ValidateCredentials_ChecksEachServer() { //Arrange var creds = new GenericCredentialInfo(); var serverNames = new[] { "localhost", "localhost2", "localhost3" }; var servers = serverNames.Select(sn => new Server { ServerName = sn, ServerType = ServerType.Database }).ToList(); this.administrationInstallationRepositoryMock.Setup(x => x.HasDbccPermissions(It.IsIn(serverNames), creds)).Returns(true); _serverRepositoryMock.Setup(x => x.ReadAllActive()) .Returns(servers); //Act this.administrationInstallationService.CredentialsAreValid(creds); //Assert this.administrationInstallationRepositoryMock.Verify(x => x.HasDbccPermissions(It.IsIn(serverNames), creds), Times.Exactly(3)); }
public async Task Should_not_unsubscribe_judge_from_conference_channels() { const int numOfConferences = 10; const int numOfConferencesWithUser = 2; var conferenceIds = SetupJudgeConferences(numOfConferences, numOfConferencesWithUser); await Hub.OnDisconnectedAsync(null); GroupManagerMock.Verify( x => x.RemoveFromGroupAsync(HubCallerContextMock.Object.ConnectionId, It.IsIn(conferenceIds), CancellationToken.None), Times.Never); }
public async Task Add_Two_UserAccessPermission_TwoDifferentRegions_singleBusinessRoleWithLabels_SingleCost_Pass() { var grantAccessResponse = new GrantAccessResponse { UserGroup = new UserGroup(), New = true, UserGroups = new[] { Guid.NewGuid().ToString() } }; var userBeingUpdated = _users.First(user => user.Id == _userNoRoles); var firstCost = _costs.First(a => a.CostNumber == "number1"); var secondCost = _costs.First(a => a.CostNumber == "number2"); var thirdCost = _costs.First(a => a.CostNumber == "number3"); //Same Role is used here on purpose! //We are checking if the Business Role gains extra labels! var updateUserModel = new UpdateUserModel { AccessDetails = new List <AccessDetail> { new AccessDetail { ObjectType = core.Constants.AccessObjectType.Region, BusinessRoleId = _businessRoles.First(a => a.Value == Constants.BusinessRole.AgencyFinanceManager).Id, LabelName = "RegionTwo" }, new AccessDetail { ObjectType = core.Constants.AccessObjectType.Region, BusinessRoleId = _businessRoles.First(a => a.Value == Constants.BusinessRole.AgencyFinanceManager).Id, LabelName = "RegionOne" } } }; EfContext.AbstractType.AddRange(_abstractTypes); EfContext.Role.AddRange(_roles); EfContext.BusinessRole.AddRange(_businessRoles); EfContext.CostUser.AddRange(_users); EfContext.Cost.AddRange(_costs); EfContext.SaveChanges(); _costStageRevisionServiceMock.Setup(a => a.GetStageDetails <PgStageDetailsForm>(firstCost.LatestCostStageRevision)) .Returns(_costStageReviDetailsFormFirstCost); _costStageRevisionServiceMock.Setup(a => a.GetStageDetails <PgStageDetailsForm>(secondCost.LatestCostStageRevision)) .Returns(_costStageReviDetailsFormSecondCost); _costStageRevisionServiceMock.Setup(a => a.GetStageDetails <PgStageDetailsForm>(thirdCost.LatestCostStageRevision)) .Returns(_costStageReviDetailsFormThirdCost); _permissionServiceMock.Setup(a => a.CheckHasAccess(_xUserId, userBeingUpdated.Id, AclActionType.Edit, "user")).ReturnsAsync(true); _permissionServiceMock .Setup(a => a.GrantUserAccess <Cost>(It.IsAny <Guid>(), It.IsAny <Guid>(), userBeingUpdated, BuType.Pg, null, It.IsAny <string>(), It.IsAny <bool>())) .ReturnsAsync(grantAccessResponse); _permissionServiceMock.Setup(a => a.RevokeAccessForSubjectWithRole(It.IsAny <Guid>(), It.IsAny <Guid>(), It.IsAny <Guid>(), null, It.IsAny <bool>())) .ReturnsAsync(new[] { Guid.NewGuid().ToString() }); // Act var result = await _pgUserService.UpdateUser(User, userBeingUpdated.Id, updateUserModel, BuType.Pg); // Assert result.Messages.First().Should().Be("User updated."); result.Success.Should().Be(true); var verifyUser = EfContext.CostUser.First(a => a.Id == userBeingUpdated.Id); verifyUser.UserBusinessRoles.Count.Should().Be(1); verifyUser.UserBusinessRoles.First().Labels.Length.Should().Be(2); verifyUser.UserBusinessRoles.First().Labels.Any(a => a.Contains("RegionTwo")).Should().BeTrue(); verifyUser.UserBusinessRoles.First().Labels.Any(a => a.Contains("RegionOne")).Should().BeTrue(); _permissionServiceMock.Verify( a => a.GrantUserAccess <Cost>(It.IsAny <Guid>(), It.IsIn(firstCost.Id, secondCost.Id, thirdCost.Id), userBeingUpdated, BuType.Pg, null, It.IsIn(_costStageReviDetailsFormFirstCost.BudgetRegion.Name, _costStageReviDetailsFormSecondCost.BudgetRegion.Name, _costStageReviDetailsFormThirdCost.BudgetRegion.Name), It.IsAny <bool>()), Times.Once); }
public void CanInitialize() { _fixture.MockSourceFactory.Verify( m => m.InstantiateSource(It.IsIn(_fixture.PackageSources.ToArray())), Times.Exactly(_fixture.PackageSources.Count)); }
public void RollbackAsyncSucceeds() { var mockedTransaction = new Mock <IDbContextTransaction>(); var transaction = new EntityFrameworkTransaction(mockedTransaction.Object); var cancellationToken = new CancellationToken(); transaction.RollbackAsync(cancellationToken).Wait(cancellationToken); mockedTransaction.Verify(contextTransaction => contextTransaction.RollbackAsync(It.IsIn(cancellationToken)), Times.Once); }
public void SearchAssociatedProducts_ReturnsProducts() { // Arrange var verifySet = new[] { "prod-1", "prod-2", "prod-3", "prod-4" }.Select(x => new domainModel.CatalogProduct { Id = x }).ToArray(); var criteria = new ProductAssociationSearchCriteria { ObjectIds = new[] { "prod-1" }, ResponseGroup = domainModel.ItemResponseGroup.ItemInfo.ToString(), Sort = "Id" }; var catalogRepository = new Mock <ICatalogRepository>(); catalogRepository.Setup(x => x.Associations).Returns(TestAssociationEntities.AsQueryable()); catalogRepository.Setup(x => x.Items).Returns(TestItemEntities.AsQueryable()); catalogRepository.Setup(x => x.GetAllChildrenCategoriesIds(It.Is <string[]>(ids => ids.SequenceEqual(new [] { "cat-1" })))).Returns(TestChildCategories); var itemService = new Mock <IItemService>(); itemService.Setup(x => x.GetByIds(It.Is <string[]>(ids => ids.SequenceEqual(verifySet.Select(p => p.Id))), It.IsIn(domainModel.ItemResponseGroup.ItemInfo), It.IsAny <string>())) .Returns(verifySet); var sut = new ProductAssociationSearchService(() => catalogRepository.Object, itemService.Object); // Act var result = sut.SearchProductAssociations(criteria); // Assert Assert.True(result.TotalCount == 4); Assert.Equal(result.Results, verifySet); }
public async Task Should_unsubscribe_admin_from_all_conferences() { var numOfConferences = 10; var conferences = SetupAdminConferences(numOfConferences); var conferenceIds = conferences.Select(c => c.Id.ToString()).ToArray(); await Hub.OnDisconnectedAsync(null); GroupManagerMock.Verify( x => x.RemoveFromGroupAsync(HubCallerContextMock.Object.ConnectionId, It.IsIn(conferenceIds), CancellationToken.None), Times.Exactly(numOfConferences)); }
private void MockAuthorizationService(AuthorizationResult result) { var policyToCall = StartechPolicyHelper.GetPolicyName(Startechs.Dotnet, MustBeLeader: true); AuthorizationService.Setup(x => x.AuthorizeAsync(It.IsAny <ClaimsPrincipal>(), It.IsAny <object>(), It.IsIn <string>(policyToCall))) .Returns(Task.Factory.StartNew(() => result)); }
public void ShouldSendCancellationEmails() { var cancellationData = new List <MpChildcareCancelledNotification> { new MpChildcareCancelledNotification { ChildcareContactEmail = "*****@*****.**", ChildcareContactId = 1, ChildcareEventDate = DateTime.Now, ChildGroupId = 1234, ChildGroupParticipantId = 5678, ChildLastname = "Woodcomb", ChildNickname = "Grunka", EnrollerContactId = 14, EnrollerNickname = "Ellie", EnrollerEmail = "*****@*****.**", EnrollerGroupName = "Mom's Oakley", EnrollerGroupLocationId = 1, EnrollerGroupLocationName = "Oakley" }, new MpChildcareCancelledNotification { ChildcareContactEmail = "*****@*****.**", ChildcareContactId = 1, ChildcareEventDate = DateTime.Now, ChildGroupId = 1234, ChildGroupParticipantId = 5679, ChildLastname = "Grimes", ChildNickname = "Morgan", EnrollerContactId = 15, EnrollerNickname = "Chuck", EnrollerEmail = "*****@*****.**", EnrollerGroupName = "Father's Oakley", EnrollerGroupLocationId = 1, EnrollerGroupLocationName = "Oakley" }, new MpChildcareCancelledNotification { ChildcareContactEmail = "*****@*****.**", ChildcareContactId = 1, ChildcareEventDate = DateTime.Now, ChildGroupId = 1234, ChildGroupParticipantId = 5680, ChildLastname = "Woodcomb", ChildNickname = "Devin", EnrollerContactId = 14, EnrollerNickname = "Ellie", EnrollerEmail = "*****@*****.**", EnrollerGroupName = "Mom's Oakley", EnrollerGroupLocationId = 1, EnrollerGroupLocationName = "Oakley" } }; _communicationService.Setup(c => c.GetTemplate(It.IsAny <int>())).Returns(new MpMessageTemplate()); _communicationService.Setup(c => c.SendMessage(It.IsAny <MpCommunication>(), false)); _childcareRepository.Setup(r => r.GetChildcareCancellations()).Returns(cancellationData); _groupService.Setup(g => g.endDateGroupParticipant(1234, It.IsIn(5678, 5679, 5680))); _fixture.SendChildcareCancellationNotification(); _communicationService.Verify(c => c.SendMessage(It.IsAny <MpCommunication>(), false), Times.Exactly(2)); _childcareRepository.VerifyAll(); _groupService.Verify(g => g.endDateGroupParticipant(1234, It.IsIn(5678, 5679, 5680)), Times.Exactly(3)); }
public async Task UpdateAsyncTest() { IServiceCollection services = new ServiceCollection(); services.AddAuthorizationExtension(); services.AddScoped <ISystemPermissionRoleStore <SystemPermissionRole> >(sp => new Mock <ISystemPermissionRoleStore <SystemPermissionRole> >().Object); services.AddScoped <ISystemPermissionUserStore <SystemPermissionUser> >(sp => new Mock <ISystemPermissionUserStore <SystemPermissionUser> >().Object); services.AddScoped <ISystemPermissionStore <SystemPermission> >(sp => { var mockSystemPermissionStore = new Mock <ISystemPermissionStore <SystemPermission> >(); mockSystemPermissionStore.Setup(s => s.UpdateAsync(It.IsAny <SystemPermission>(), It.IsAny <CancellationToken>())) .Returns((SystemPermission p, CancellationToken _) => Task.FromResult(p)); SystemPermission[] permissions = new SystemPermission[] { new SystemPermission() { Id = "permission0", Name = "permission0", AllowedAllRoles = true }, new SystemPermission() { Id = "permission1", Name = "permission1", AllowedAnonymous = true }, new SystemPermission() { Id = "permission2", Name = "permission2", DeniedAll = true }, new SystemPermission() { Id = "permission3", Name = "permission3" }, }; mockSystemPermissionStore.Setup(s => s.FindByIdAsync(It.IsIn("permission0", "permission1", "permission2", "permission3", "permission4"), It.IsAny <CancellationToken>())) .Returns((string id, CancellationToken _) => Task.FromResult(permissions.FirstOrDefault(p => p.Id == id))); return(mockSystemPermissionStore.Object); }); var mockPermissionMonitor = new Mock <IPermissionMonitor>(); services.AddScoped <IPermissionMonitor>(sp => { mockPermissionMonitor.Setup(p => p.OnPermissionChangedAsync(It.IsAny <string>())); return(mockPermissionMonitor.Object); }); IServiceProvider serviceProvider = services.BuildServiceProvider(); using IServiceScope serviceScope = serviceProvider.CreateScope(); ISystemPermissionService <SystemPermission> systemPermissionService = serviceScope.ServiceProvider.GetRequiredService <ISystemPermissionService <SystemPermission> >(); CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); await systemPermissionService.UpdateAsync(new SystemPermission() { Id = "permission0", Name = "permission00", AllowedAllRoles = true }, cancellationTokenSource.Token); mockPermissionMonitor.Verify(p => p.OnPermissionChangedAsync("permission0"), Times.Never(), "未改动相关属性,触发调用了OnPermissionChangedAsync(\"permission0\")"); await systemPermissionService.UpdateAsync(new SystemPermission() { Id = "permission0", Name = "permission00", AllowedAllRoles = false }, cancellationTokenSource.Token); mockPermissionMonitor.Verify(p => p.OnPermissionChangedAsync("permission0"), Times.AtLeastOnce(), "改动相关属性AllowedAllRoles,未调用OnPermissionChangedAsync(\"permission0\")"); await systemPermissionService.UpdateAsync(new SystemPermission() { Id = "permission1", Name = "permission1", AllowedAnonymous = false }, cancellationTokenSource.Token); mockPermissionMonitor.Verify(p => p.OnPermissionChangedAsync("permission1"), Times.AtLeastOnce(), "改动相关属性AllowedAnonymous,未调用OnPermissionChangedAsync(\"permission1\")"); await systemPermissionService.UpdateAsync(new SystemPermission() { Id = "permission2", Name = "permission2", DeniedAll = false }, cancellationTokenSource.Token); mockPermissionMonitor.Verify(p => p.OnPermissionChangedAsync("permission2"), Times.AtLeastOnce(), "改动相关属性DeniedAll,未调用OnPermissionChangedAsync(\"permission2\")"); await systemPermissionService.UpdateAsync(new SystemPermission() { Id = "permission3", Name = "permission3", AllowedAllRoles = true, AllowedAnonymous = true, DeniedAll = true }, cancellationTokenSource.Token); mockPermissionMonitor.Verify(p => p.OnPermissionChangedAsync("permission3"), Times.AtLeastOnce(), "改动相关属性,未调用OnPermissionChangedAsync(\"permission3\")"); Task task = systemPermissionService.UpdateAsync(new SystemPermission() { Id = "permission4", Name = "permission3", AllowedAllRoles = true, AllowedAnonymous = true, DeniedAll = true }, cancellationTokenSource.Token); await ShouldThrowAsyncExtensions.ShouldThrowAsync <Exception>(task); // cacheManager.Set() //await systemPermissionRoleService.AddToRoleAsync(permissionId,roleId,CancellationToken.None); }
public async Task ConnectionResetBetweenRequestsIsLoggedAsDebug() { var connectionReset = new SemaphoreSlim(0); var loggedHigherThanDebug = false; var mockLogger = new Mock <ILogger>(); mockLogger .Setup(logger => logger.IsEnabled(It.IsAny <LogLevel>())) .Returns(true); mockLogger .Setup(logger => logger.Log(It.IsAny <LogLevel>(), It.IsAny <EventId>(), It.IsAny <object>(), It.IsAny <Exception>(), It.IsAny <Func <object, Exception, string> >())) .Callback <LogLevel, EventId, object, Exception, Func <object, Exception, string> >((logLevel, eventId, state, exception, formatter) => { Logger.Log(logLevel, eventId, state, exception, formatter); if (eventId.Id == _connectionResetEventId) { connectionReset.Release(); } if (logLevel > LogLevel.Debug) { loggedHigherThanDebug = true; } }); var mockLoggerFactory = new Mock <ILoggerFactory>(); mockLoggerFactory .Setup(factory => factory.CreateLogger(It.IsAny <string>())) .Returns(Logger); mockLoggerFactory .Setup(factory => factory.CreateLogger(It.IsIn("Microsoft.AspNetCore.Server.Kestrel", "Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv", "Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets"))) .Returns(mockLogger.Object); using (var server = new TestServer(context => Task.CompletedTask, new TestServiceContext(mockLoggerFactory.Object))) { using (var connection = server.CreateConnection()) { await connection.Send( "GET / HTTP/1.1", "Host:", "", ""); // Make sure the response is fully received, so a write failure (e.g. EPIPE) doesn't cause // a more critical log message. await connection.Receive( "HTTP/1.1 200 OK", $"Date: {server.Context.DateHeaderValue}", "Content-Length: 0", "", ""); connection.Reset(); // Force a reset } // If the reset is correctly logged as Debug, the wait below should complete shortly. // This check MUST come before disposing the server, otherwise there's a race where the RST // is still in flight when the connection is aborted, leading to the reset never being received // and therefore not logged. Assert.True(await connectionReset.WaitAsync(TestConstants.DefaultTimeout)); } Assert.False(loggedHigherThanDebug); }
public void MethodsWithArgumentMatchingTests() { var userList = Fixture .Build <UserModel>() .With(x => x.Address, Fixture.Create <Address>()) .CreateMany(10).ToList <IUserModel>(); var user1 = new Mock <IUserModel>(); var user2 = new Mock <IUserModel>(); var user3 = new Mock <IUserModel>(); // Matching without parameters var mock = new Mock <IRepository>(); mock.Setup(x => x.ActiveUsers()).Returns(userList); mock.Object.ActiveUsers().Should().BeEquivalentTo(userList); // Matching by value mock = new Mock <IRepository>(); mock.Setup(x => x.SearchById(1)).Returns(user1.Object); mock.Setup(x => x.SearchById(5)).Returns(user2.Object); mock.Object.SearchById(1).Should().Be(user1.Object); mock.Object.SearchById(5).Should().Be(user2.Object); mock.Object.SearchById(2).Should().BeNull(); // Matching any value mock = new Mock <IRepository>(); mock.Setup(x => x.SearchById(It.IsAny <int>())).Returns(user1.Object); mock.Object.SearchById(234).Should().Be(user1.Object); // Matching by inline custom matcher mock = new Mock <IRepository>(); mock.Setup(x => x.SearchById(It.Is <int>(i => i < 10))).Returns(user2.Object); mock.Setup(x => x.SearchById(It.Is <int>(i => i >= 10))).Returns(user3.Object); mock.Object.SearchById(3).Should().Be(user2.Object); mock.Object.SearchById(30).Should().Be(user3.Object); // Matching by range mock = new Mock <IRepository>(); mock.Setup(x => x.SearchById(It.IsInRange(0, 10, Range.Inclusive))).Returns(user3.Object); mock.Object.SearchById(3).Should().Be(user3.Object); mock.Object.SearchById(44).Should().BeNull(); // Matching by enumerable mock = new Mock <IRepository>(); mock.Setup(x => x.SearchById(It.IsIn(Enumerable.Range(1, 5)))).Returns(user3.Object); mock.Object.SearchById(4).Should().Be(user3.Object); mock.Object.SearchById(44).Should().BeNull(); // Matching by enumerable not in mock = new Mock <IRepository>(); mock.Setup(x => x.SearchById(It.IsNotIn(Enumerable.Range(1, 5)))).Returns(user3.Object); mock.Object.SearchById(44).Should().Be(user3.Object); mock.Object.SearchById(4).Should().BeNull(); // Matching by value string mock = new Mock <IRepository>(); mock.Setup(x => x.Search("hola")).Returns(userList); mock.Object.Search("hola").Should().HaveCount(userList.Count); mock.Object.Search("asda").Should().BeNull(); // Matching by not null value mock = new Mock <IRepository>(); mock.Setup(x => x.Search(It.IsNotNull <string>())).Returns(userList.Take(2).ToList()); mock.Object.Search("holad").Should().HaveCount(2); // Matching by regex mock = new Mock <IRepository>(); mock.Setup(x => x.Search(It.IsRegex("abc"))).Returns(userList.Skip(2).Take(3).ToList()); mock.Object.Search("abc").Should().HaveCount(3); mock.Object.Search("asda").Should().BeNull(); // Matching by custom matcher mock = new Mock <IRepository>(); mock.Setup(x => x.Search(IsLarge())).Returns(userList.Skip(3).Take(4).ToList()); mock.Object.Search("hola").Should().HaveCount(4); mock.Object.Search("as").Should().BeNull(); // Matching by type mock = new Mock <IRepository>(); mock.Setup(x => x.Add(It.IsAny <IUserModel>())).Returns(true); mock.Object.Add(new UserModel()).Should().BeTrue(); // Matching for any argument // There is no option here }
public async Task ServerCanAbortConnectionAfterUnobservedClose(ListenOptions listenOptions) { const int connectionPausedEventId = 4; const int connectionFinSentEventId = 7; const int maxRequestBufferSize = 4096; var readCallbackUnwired = new TaskCompletionSource <object>(TaskCreationOptions.RunContinuationsAsynchronously); var clientClosedConnection = new TaskCompletionSource <object>(TaskCreationOptions.RunContinuationsAsynchronously); var serverClosedConnection = new TaskCompletionSource <object>(TaskCreationOptions.RunContinuationsAsynchronously); var appFuncCompleted = new TaskCompletionSource <object>(TaskCreationOptions.RunContinuationsAsynchronously); var mockLogger = new Mock <ILogger>(); mockLogger .Setup(logger => logger.IsEnabled(It.IsAny <LogLevel>())) .Returns(true); mockLogger .Setup(logger => logger.Log(It.IsAny <LogLevel>(), It.IsAny <EventId>(), It.IsAny <object>(), It.IsAny <Exception>(), It.IsAny <Func <object, Exception, string> >())) .Callback <LogLevel, EventId, object, Exception, Func <object, Exception, string> >((logLevel, eventId, state, exception, formatter) => { if (eventId.Id == connectionPausedEventId) { readCallbackUnwired.TrySetResult(null); } else if (eventId.Id == connectionFinSentEventId) { serverClosedConnection.SetResult(null); } Logger.Log(logLevel, eventId, state, exception, formatter); }); var mockLoggerFactory = new Mock <ILoggerFactory>(); mockLoggerFactory .Setup(factory => factory.CreateLogger(It.IsAny <string>())) .Returns(Logger); mockLoggerFactory .Setup(factory => factory.CreateLogger(It.IsIn("Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv", "Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets"))) .Returns(mockLogger.Object); var mockKestrelTrace = new Mock <IKestrelTrace>(); var testContext = new TestServiceContext(mockLoggerFactory.Object, mockKestrelTrace.Object) { ServerOptions = { Limits = { MaxRequestBufferSize = maxRequestBufferSize, MaxRequestLineSize = maxRequestBufferSize, MaxRequestHeadersTotalSize = maxRequestBufferSize, } } }; var scratchBuffer = new byte[maxRequestBufferSize * 8]; using (var server = new TestServer(async context => { await clientClosedConnection.Task; context.Abort(); await serverClosedConnection.Task; appFuncCompleted.SetResult(null); }, testContext, listenOptions)) { using (var connection = server.CreateConnection()) { await connection.Send( "POST / HTTP/1.1", "Host:", $"Content-Length: {scratchBuffer.Length}", "", ""); var ignore = connection.Stream.WriteAsync(scratchBuffer, 0, scratchBuffer.Length); // Wait until the read callback is no longer hooked up so that the connection disconnect isn't observed. await readCallbackUnwired.Task.DefaultTimeout(); } clientClosedConnection.SetResult(null); await appFuncCompleted.Task.DefaultTimeout(); } mockKestrelTrace.Verify(t => t.ConnectionStop(It.IsAny <string>()), Times.Once()); }
public void LogExceptionAsync_WithInner() { VolatileErrorsReportingDataset store = new VolatileErrorsReportingDataset(); Mock <IErrorsReportingService> mockService = new Mock <IErrorsReportingService>(); mockService.Setup(s => s.LogExceptionAsync(It.IsIn <int>(store.Applications.Select(a => a.Id)), It.IsAny <Exception>(), It.IsAny <string>())) .Callback <int, Exception, string>((idApplicaton, exception, errorCode) => { store.Exceptions.Add(new ErrorReportException { Id = 1, IdApplication = idApplicaton, Type = exception.GetType().ToString(), Message = exception.Message, Source = exception.Source, SiteModule = (exception.TargetSite != null && exception.TargetSite.Module != null) ? exception.TargetSite.Module.Name : null, SiteName = exception.TargetSite.Name, StackTrace = exception.StackTrace, HelpLink = exception.HelpLink, Date = DateTime.Now, CustomErrorType = errorCode, IdInnerException = 2 }); store.Exceptions.Add(new ErrorReportException { Id = 2, IdApplication = idApplicaton, Type = exception.InnerException.GetType().ToString(), Message = exception.InnerException.Message, Source = exception.InnerException.Source, SiteModule = (exception.InnerException.TargetSite != null && exception.InnerException.TargetSite.Module != null) ? exception.InnerException.TargetSite.Module.Name : null, SiteName = exception.InnerException.TargetSite.Name, StackTrace = exception.InnerException.StackTrace, HelpLink = exception.InnerException.HelpLink, Date = DateTime.Now, CustomErrorType = errorCode }); }) .Returns(Task.FromResult <int?>(1)); IErrorsReportingService service = mockService.Object; try { ExceptionGenerator.ThrowsTwo(); } catch (Exception exception) { int?id = null; Assert.That(async() => { id = await service.LogExceptionAsync(store.Applications.First().Id, exception, "ErrorType.Specific"); }, Throws.Nothing); Assert.IsNotNull(id); Assert.AreEqual("One", store.Exceptions.ElementAt(1).Message); Assert.AreEqual("Two", store.Exceptions.ElementAt(0).Message); } }
public void Should_call_serializer_with_same_fields_when_fields_passed() { //Arrange var returnedDevicesList = new List <Device>(); var parameters = new DevicesParametersModel { Fields = "id,email" }; _deviceApiService.Setup(x => x.GetDevices(parameters.Ids, parameters.Limit, parameters.Page, parameters.SinceId, parameters.CreatedAtMin, parameters.CreatedAtMax, parameters.Status)).Returns(returnedDevicesList); //Act _devicesController.GetDevices(parameters).GetAwaiter().GetResult(); //Assert _jsonFieldsSerializer.Verify(x => x.Serialize(It.IsAny <DevicesRootObject>(), It.IsIn(parameters.Fields), null)); }
protected override void Load(ContainerBuilder builder) { var blobRepository = new Mock <IMarginTradingBlobRepository>(); blobRepository.Setup(s => s.ReadWithTimestampAsync <List <Order> >(It.IsAny <string>(), It.IsAny <string>())) .ReturnsAsync((new List <Order>(), DateTime.UtcNow)); blobRepository.Setup(s => s.ReadWithTimestampAsync <List <Position> >(It.IsAny <string>(), It.IsAny <string>())) .ReturnsAsync((new List <Position>(), DateTime.UtcNow)); var orderHistoryRepository = new Mock <IOrdersHistoryRepository>(); orderHistoryRepository.Setup(s => s.GetLastSnapshot(It.IsAny <DateTime>())) .ReturnsAsync(new List <IOrderHistory>()); var positionHistoryRepository = new Mock <IPositionsHistoryRepository>(); var accountHistoryRepository = new Mock <IAccountHistoryRepository>(); positionHistoryRepository.Setup(s => s.GetLastSnapshot(It.IsAny <DateTime>())) .ReturnsAsync(new List <IPositionHistory>()); accountHistoryRepository.Setup(s => s.GetSwapTotalPerPosition(It.IsAny <IEnumerable <string> >())) .ReturnsAsync(new Dictionary <string, decimal>()); var riskSystemCommandsLogRepository = new Mock <IRiskSystemCommandsLogRepository>(); var accountMarginFreezingRepository = new Mock <IAccountMarginFreezingRepository>(); var accountMarginUnconfirmedRepository = new Mock <IAccountMarginUnconfirmedRepository>(); var operationExecutionInfoRepositoryMock = new Mock <IOperationExecutionInfoRepository>(); var snapshotsRepository = new Mock <ITradingEngineSnapshotsRepository>(); operationExecutionInfoRepositoryMock.Setup(s => s.GetOrAddAsync(It.IsIn("AccountsProjection"), It.IsAny <string>(), It.IsAny <Func <IOperationExecutionInfo <OperationData> > >())) .ReturnsAsync((new OperationExecutionInfo <OperationData>( operationName: "AccountsProjection", id: Guid.NewGuid().ToString(), lastModified: DateTime.UtcNow, data: new OperationData { State = OperationState.Initiated } ), true)); accountMarginFreezingRepository.Setup(x => x.GetAllAsync()) .ReturnsAsync(new List <IAccountMarginFreezing>().AsReadOnly()); accountMarginUnconfirmedRepository.Setup(x => x.GetAllAsync()) .ReturnsAsync(new List <IAccountMarginFreezing>().AsReadOnly()); builder.RegisterInstance(new LogToMemory()).As <ILog>(); builder.RegisterInstance( new MarginTradingAccountStatsRepository(new NoSqlTableInMemory <MarginTradingAccountStatsEntity>())) .As <IMarginTradingAccountStatsRepository>().SingleInstance(); builder.RegisterType <MatchingEngineInMemoryRepository>().As <IMatchingEngineRepository>().SingleInstance(); //mocks builder.RegisterInstance(blobRepository.Object).As <IMarginTradingBlobRepository>().SingleInstance(); builder.RegisterInstance(orderHistoryRepository.Object).As <IOrdersHistoryRepository>() .SingleInstance(); builder.RegisterInstance(positionHistoryRepository.Object).As <IPositionsHistoryRepository>() .SingleInstance(); builder.RegisterInstance(accountHistoryRepository.Object).As <IAccountHistoryRepository>() .SingleInstance(); builder.RegisterInstance(riskSystemCommandsLogRepository.Object).As <IRiskSystemCommandsLogRepository>() .SingleInstance(); builder.RegisterInstance(accountMarginFreezingRepository.Object).As <IAccountMarginFreezingRepository>() .SingleInstance(); builder.RegisterInstance(accountMarginUnconfirmedRepository.Object).As <IAccountMarginUnconfirmedRepository>() .SingleInstance(); builder.RegisterInstance(operationExecutionInfoRepositoryMock.Object) .As <IOperationExecutionInfoRepository>().SingleInstance(); builder.RegisterInstance(snapshotsRepository.Object) .As <ITradingEngineSnapshotsRepository>().SingleInstance(); }
public override void ConfigureServices(ServiceConfigurationContext context) { var interestedEvent = new IrreversibleBlockFound(); var logEvent = interestedEvent.ToLogEvent(SampleAddress.AddressList[0]); context.Services.AddTransient(provider => { var mockBlockChainService = new Mock <IBlockchainService>(); mockBlockChainService.Setup(m => m.GetChainAsync()).Returns(() => { var chain = new Chain { LastIrreversibleBlockHeight = 10, LastIrreversibleBlockHash = Hash.FromString("LastIrreversibleBlockHash") }; return(Task.FromResult(chain)); }); mockBlockChainService.Setup(m => m.GetBlockByHashAsync(It.IsAny <Hash>())).Returns(Task.FromResult( new Block { Header = new BlockHeader { Bloom = ByteString.CopyFrom(logEvent.GetBloom().Data), Height = 15 }, Body = new BlockBody { TransactionIds = { Hash.FromString("not exist"), Hash.FromString("failed case"), Hash.FromString("mined case") } } } )); mockBlockChainService.Setup(m => m.GetBlockHashByHeightAsync(It.IsAny <Chain>(), It.IsAny <long>(), It.IsAny <Hash>())) .Returns(Task.FromResult(new Hash())); return(mockBlockChainService.Object); }); context.Services.AddTransient(provider => { var mockService = new Mock <ITransactionResultQueryService>(); mockService.Setup(m => m.GetTransactionResultAsync(It.IsIn(Hash.FromString("not exist")))) .Returns(Task.FromResult <TransactionResult>(null)); mockService.Setup(m => m.GetTransactionResultAsync(It.IsIn(Hash.FromString("failed case")))) .Returns(Task.FromResult(new TransactionResult { Error = "failed due to some reason", Status = TransactionResultStatus.Failed })); mockService.Setup(m => m.GetTransactionResultAsync(It.IsIn(Hash.FromString("mined case")))) .Returns(Task.FromResult(new TransactionResult { Status = TransactionResultStatus.Mined, Bloom = ByteString.CopyFrom(logEvent.GetBloom().Data), Logs = { new LogEvent { Address = SampleAddress.AddressList[0], Name = logEvent.Name } } })); return(mockService.Object); }); context.Services.AddTransient(provider => { var mockService = new Mock <ISmartContractAddressService>(); var consensusHash = ConsensusSmartContractAddressNameProvider.Name; mockService.Setup(o => o.GetAddressByContractName(It.Is <Hash>(hash => hash != consensusHash))) .Returns(SampleAddress.AddressList[0]); mockService.Setup(o => o.GetAddressByContractName(It.Is <Hash>(hash => hash == consensusHash))) .Returns(SampleAddress.AddressList[1]); return(mockService.Object); }); context.Services.AddTransient(provider => { var mockService = new Mock <IBlockExtraDataService>(); mockService.Setup(m => m.GetExtraDataFromBlockHeader("Consensus", It.Is <BlockHeader>(o => o != null))) .Returns(ByteString.CopyFrom(new AElfConsensusHeaderInformation { Behaviour = AElfConsensusBehaviour.UpdateValue, SenderPubkey = ByteString.CopyFromUtf8("real-pubkey"), Round = new Round() }.ToByteArray())); mockService.Setup(m => m.GetExtraDataFromBlockHeader("Consensus", It.Is <BlockHeader>(o => o == null))) .Returns(ByteString.CopyFrom(new AElfConsensusHeaderInformation { Behaviour = AElfConsensusBehaviour.Nothing, SenderPubkey = ByteString.CopyFromUtf8("real-pubkey"), Round = new Round() }.ToByteArray())); return(mockService.Object); }); context.Services.AddTransient(provider => { var mockService = new Mock <IConsensusService>(); mockService.Setup(m => m.GetConsensusExtraDataAsync(It.IsAny <ChainContext>())).Returns( Task.FromResult(ByteString.CopyFromUtf8("test").ToByteArray())); mockService.Setup(m => m.TriggerConsensusAsync(It.IsAny <ChainContext>())).Returns(Task.CompletedTask); return(mockService.Object); }); context.Services.AddTransient(provider => { var mockService = new Mock <ITransactionReadOnlyExecutionService>(); mockService.Setup(m => m.ExecuteAsync(It.IsAny <ChainContext>(), It.Is <Transaction>(tx => tx.MethodName == "GetCurrentMinerList"), It.IsAny <Timestamp>())) .Returns(Task.FromResult(new TransactionTrace { ExecutionStatus = ExecutionStatus.Executed, ReturnValue = ByteString.CopyFrom(new MinerList { Pubkeys = { ByteString.CopyFromUtf8("bp1"), ByteString.CopyFromUtf8("bp2"), ByteString.CopyFromUtf8("bp3") } }.ToByteArray()) })); return(mockService.Object); }); context.Services.AddTransient(provider => { var encryptDic = new Dictionary <string, byte[]> { { "bp1", Hash.FromString("encrypt info").Value.ToByteArray() } }; var decryptDic = new Dictionary <string, byte[]> { { "bp2", Hash.FromString("decrypt info").Value.ToByteArray() } }; var inValuesDic = new Dictionary <string, Hash> { { "bp3", Hash.FromString("in values") } }; var mockService = new Mock <ISecretSharingService>(); mockService.Setup(m => m.GetEncryptedPieces(It.IsAny <long>())) .Returns(encryptDic); mockService.Setup(m => m.GetDecryptedPieces(It.IsAny <long>())) .Returns(decryptDic); mockService.Setup(m => m.GetRevealedInValues(It.IsAny <long>())) .Returns(inValuesDic); return(mockService.Object); }); }
public async Task UpdateAsyncTest() { IServiceCollection services = new ServiceCollection(); services.AddAuthorizationExtension(); services.AddScoped <ISystemResourceStore <SystemResource> >(sp => { var mockResourceStore = new Mock <ISystemResourceStore <SystemResource> >(); mockResourceStore.Setup(s => s.UpdateAsync(It.IsAny <SystemResource>(), It.IsAny <CancellationToken>())) .Returns((SystemResource resource, CancellationToken _) => Task.FromResult(resource)); SystemResource[] resources = new SystemResource[] { new SystemResource() { Id = "/Account/Index", Name = "Index", ResourceType = ResourceType.Api, PermissionId = "permission0" }, new SystemResource() { Id = "/Account/Create", Name = "Create", ResourceType = ResourceType.Api, PermissionId = "permission1" }, }; mockResourceStore.Setup(s => s.FindByIdAsync(It.IsIn("/Account/Index", "/Account/Create", "null"), It.IsAny <CancellationToken>())) .Returns((string id, CancellationToken _) => Task.FromResult(resources.FirstOrDefault(r => r.Id == id))); return(mockResourceStore.Object); }); services.AddScoped <ISystemPermissionStore <SystemPermission> >(sp => new Mock <ISystemPermissionStore <SystemPermission> >().Object); var mockPermissionMonitor = new Mock <IPermissionMonitor>(); services.AddScoped <IPermissionMonitor>(sp => { mockPermissionMonitor.Setup(p => p.OnResourceChangedAsync(It.IsAny <string>())); return(mockPermissionMonitor.Object); }); IServiceProvider serviceProvider = services.BuildServiceProvider(); using IServiceScope serviceScope = serviceProvider.CreateScope(); ISystemResourceService <SystemResource> systemResourceService = serviceScope.ServiceProvider.GetRequiredService <ISystemResourceService <SystemResource> >(); await systemResourceService.UpdateAsync(new SystemResource() { Id = "/Account/Index", Name = "首页", ResourceType = ResourceType.Api, PermissionId = "permission0" }, CancellationToken.None); mockPermissionMonitor.Verify(p => p.OnResourceChangedAsync("/Account/Index"), Times.Never(), "未改动相关属性,触发调用了OnResourceChangedAsync(\"/Account/Index\")"); await systemResourceService.UpdateAsync(new SystemResource() { Id = "/Account/Create", Name = "首页", ResourceType = ResourceType.Api, PermissionId = "permission3" }, CancellationToken.None); mockPermissionMonitor.Verify(p => p.OnResourceChangedAsync("/Account/Create"), Times.AtLeastOnce(), "改动相关属性,未触发调用了OnResourceChangedAsync(\"/Account/Create\")"); Task task = systemResourceService.UpdateAsync(new SystemResource() { Id = "null", Name = "首页", ResourceType = ResourceType.Api, PermissionId = "permission1" }, CancellationToken.None); await ShouldThrowAsyncExtensions.ShouldThrowAsync <Exception>(task); }