public void IsEmptyFailTest() { new EnumerableAssertion <int>(FailureHandler.Object, new int[] { 1 }).IsEmpty(); FailureHandler.Verify(x => x.Fail(It.IsAny <string>()), Times.AtLeastOnce()); }
public void UseRequestDecompression() { var builderMock = new Mock <IApplicationBuilder>(MockBehavior.Strict); builderMock .Setup(o => o.New()) .Returns(builderMock.Object); builderMock .Setup(o => o.Use(It.IsNotNull <Func <RequestDelegate, RequestDelegate> >())) .Returns(builderMock.Object); builderMock .Setup(o => o.Build()) .Returns(c => Task.CompletedTask); RequestDecompressionBuilderExtensions.UseRequestDecompression(builderMock.Object); builderMock.Verify(o => o.Use(It.IsNotNull <Func <RequestDelegate, RequestDelegate> >()), Times.AtLeastOnce()); }
public void ThenSelectionModeShouldBeSetOnInputService() { InputService.VerifySet(s => s.SelectionMode = MainViewModel.SelectionMode, Times.AtLeastOnce()); }
public async Task GetById_NormalId_Sucess() { Guid id = new Guid(); var mockRepository = new Mock <ITripRepository>(); mockRepository.Setup(repository => repository.GetByIdAsync(It.IsAny <TripId>())); var mockUnit = new Mock <IUnitOfWork>(); TripService TripService = new TripService(mockUnit.Object, mockRepository.Object); TripsController controller = new TripsController(TripService); var result = await controller.GetGetById(id); mockRepository.Verify(repository => repository.GetByIdAsync(It.IsAny <TripId>()), Times.AtLeastOnce()); Assert.IsInstanceOfType(result, typeof(ActionResult <TripDto>)); }
public async Task HandleRevocationRequest_TokenIsSuccessfullyRevoked() { // Arrange var ticket = new AuthenticationTicket( new ClaimsPrincipal(), new AuthenticationProperties(), OpenIddictServerDefaults.AuthenticationScheme); ticket.SetInternalTokenId("3E228451-1555-46F7-A471-951EFBA23A56"); var format = new Mock <ISecureDataFormat <AuthenticationTicket> >(); format.Setup(mock => mock.Unprotect("SlAV32hkKG")) .Returns(ticket); var token = new OpenIddictToken(); var manager = CreateTokenManager(instance => { instance.Setup(mock => mock.FindByIdAsync("3E228451-1555-46F7-A471-951EFBA23A56", It.IsAny <CancellationToken>())) .ReturnsAsync(token); instance.Setup(mock => mock.GetIdAsync(token, It.IsAny <CancellationToken>())) .Returns(new ValueTask <string>("3E228451-1555-46F7-A471-951EFBA23A56")); }); var server = CreateAuthorizationServer(builder => { builder.Services.AddSingleton(manager); builder.Configure(options => options.RefreshTokenFormat = format.Object); }); var client = new OpenIdConnectClient(server.CreateClient()); // Act var response = await client.PostAsync(RevocationEndpoint, new OpenIdConnectRequest { Token = "SlAV32hkKG" }); // Assert Assert.Empty(response.GetParameters()); Mock.Get(manager).Verify(mock => mock.FindByIdAsync("3E228451-1555-46F7-A471-951EFBA23A56", It.IsAny <CancellationToken>()), Times.AtLeastOnce()); Mock.Get(manager).Verify(mock => mock.RevokeAsync(token, It.IsAny <CancellationToken>()), Times.Once()); }
public async Task Should_send_and_receive_plain_message() { IServiceLocator serviceLocator = new ServiceLocator(); byte[] messageData = Enumerable.Range(0, 255).Select(i => (byte)i).ToArray(); byte[] expectedMessageBytes = "00000000000000000807060504030201FF000000".HexToBytes().Concat(messageData).ToArray(); var inConnector = new Subject <byte[]>(); var mockTransport = new Mock <ITransport>(); mockTransport.Setup(connector => connector.Subscribe(It.IsAny <IObserver <byte[]> >())).Callback <IObserver <byte[]> >(observer => inConnector.Subscribe(observer)); var mockTransportFactory = new Mock <ITransportFactory>(); mockTransportFactory.Setup(manager => manager.CreateTransport(It.IsAny <TransportConfig>())).Returns(() => mockTransport.Object).Verifiable(); serviceLocator.RegisterInstance(mockTransportFactory.Object); serviceLocator.RegisterInstance(Mock.Of <TransportConfig>()); serviceLocator.RegisterInstance(TLRig.Default); serviceLocator.RegisterInstance <IMessageIdGenerator>(new TestMessageIdsGenerator()); serviceLocator.RegisterType <IHashServices, HashServices>(); serviceLocator.RegisterType <IEncryptionServices, EncryptionServices>(); serviceLocator.RegisterType <IMTProtoConnection, MTProtoConnection>(RegistrationType.Transient); using (var connection = serviceLocator.ResolveType <IMTProtoConnection>()) { await connection.Connect(); // Testing sending. var message = new PlainMessage(0x0102030405060708UL, messageData); connection.SendMessage(message); await Task.Delay(100); // Wait while internal sender processes the message. mockTransport.Verify(connector => connector.Send(expectedMessageBytes), Times.Once); // Testing receiving. mockTransport.Verify(connector => connector.Subscribe(It.IsAny <IObserver <byte[]> >()), Times.AtLeastOnce()); inConnector.OnNext(expectedMessageBytes); await Task.Delay(100); // Wait while internal receiver processes the message. IMessage actualMessage = await connection.InMessagesHistory.FirstAsync().ToTask(); actualMessage.MessageBytes.ShouldAllBeEquivalentTo(expectedMessageBytes); await connection.Disconnect(); } }
public void with_correct_searchRequest_saveRequest_successfully() { _sut.SaveRequest(_validSearchRequest); _distributedCacheMock.Verify(x => x.SetAsync(_existedReqestGuid.ToString(), It.IsAny <byte[]>(), It.IsAny <DistributedCacheEntryOptions>(), It.IsAny <CancellationToken>()), Times.AtLeastOnce()); }
public void Send_metrics_when_enabled() { var statsd = new Mock <IStatsd>(); var spans = SendSpan(tracerMetricsEnabled: true, statsd); Assert.True(spans.Count == 1, "Expected one span"); // for a single trace, these methods are called once with a value of "1" statsd.Verify( s => s.Add <Statsd.Counting, int>(TracerMetricNames.Queue.EnqueuedTraces, 1, 1, null), Times.Once()); statsd.Verify( s => s.Add <Statsd.Counting, int>(TracerMetricNames.Queue.EnqueuedSpans, 1, 1, null), Times.Once()); statsd.Verify( s => s.Add <Statsd.Counting, int>(TracerMetricNames.Queue.DequeuedTraces, 1, 1, null), Times.Once()); statsd.Verify( s => s.Add <Statsd.Counting, int>(TracerMetricNames.Queue.DequeuedSpans, 1, 1, null), Times.Once()); statsd.Verify( s => s.Add <Statsd.Counting, int>(TracerMetricNames.Api.Requests, 1, 1, null), Times.Once()); statsd.Verify( s => s.Add <Statsd.Counting, int>(TracerMetricNames.Api.Responses, 1, 1, "status:200"), Times.Once()); // these methods can be called multiple times with a "0" value (no more traces left) /* * statsd.Verify( * s => s.Add<Statsd.Gauge, int>(TracerMetricNames.Queue.DequeuedTraces, 0, 1, null), * Times.AtLeastOnce); * * statsd.Verify( * s => s.Add<Statsd.Gauge, int>(TracerMetricNames.Queue.DequeuedSpans, 0, 1, null), * Times.AtLeastOnce()); */ // these method can be called multiple times with a "1000" value (the max buffer size, constant) statsd.Verify( s => s.Add <Statsd.Gauge, int>(TracerMetricNames.Queue.MaxTraces, 1000, 1, null), Times.AtLeastOnce()); // these method can be called multiple times (send buffered commands) statsd.Verify( s => s.Send(), Times.AtLeastOnce()); // these method can be called multiple times (send heartbeat) statsd.Verify( s => s.Add <Statsd.Gauge, int>(TracerMetricNames.Health.Heartbeat, It.IsAny <int>(), 1, null), Times.AtLeastOnce()); // no other methods should be called on the IStatsd statsd.VerifyNoOtherCalls(); }
public void MockPlug_can_verify_call_via_VerifyAll() { MockPlug.Setup(new XUri("http://mock/foo")).ExpectCalls(Times.AtLeastOnce()); Assert.IsTrue(Plug.New("http://mock/foo").Get(new Result <DreamMessage>()).Wait().IsSuccessful); MockPlug.VerifyAll(); }
public void IntellisenseBox_GivenInvalidVariables_JsonObjectHasError_LogsTracking() { var _applicationTrackerMock = new Mock <IApplicationTracker>(); _applicationTrackerMock.Setup(controller => controller.TrackCustomEvent(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())); CustomContainer.Register(_applicationTrackerMock.Object); const string expectTooltipError = "Variable name \"[[obj!]]\" contains invalid character(s). Only use alphanumeric _ and - "; var textBoxTest = new IntellisenseTextBox { FilterType = enIntellisensePartType.JsonObject }; textBoxTest.Text = "\"[[obj!]]\""; var privateObj = new PrivateObject(textBoxTest); var results = privateObj.Invoke("LostFocusImpl"); Assert.IsTrue(textBoxTest.HasError); Assert.AreEqual(expectTooltipError, textBoxTest.ToolTip); _applicationTrackerMock.Verify(controller => controller.TrackCustomEvent(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>()), Times.AtLeastOnce()); }
public void CleanupCallsRunspaceProviderKillAndRemovesLocalDataForNeededRunspaces() { // Arrange const string userId = "UserID"; const string sessionId = "session-id-1"; const string runspaceId1 = "runspace-id-1"; const string runspaceId2 = "runspace-id-2"; var sessionTokenMock = new Mock <ISessionToken>(); sessionTokenMock.Setup(x => x.SessionId).Returns(sessionId); // Mock Runspaces Info var runspace1 = new Mock <IRunspaceInfo>(); runspace1.Setup(r => r.Id).Returns(runspaceId1); var runspace2 = new Mock <IRunspaceInfo>(); runspace2.Setup(r => r.Id).Returns(runspaceId2); // Mock RunspaceProvider var rsProvider = new Mock <IRunspaceProvider>(); rsProvider.Setup(p => p.Kill(It.IsAny <string>())); int callCount = 0; rsProvider.Setup(p => p.StartCreate()).Returns(() => { if (callCount == 0) { callCount = 1; return(runspace1.Object); } else { return(runspace2.Object); } }); rsProvider.Setup(p => p.List()).Returns(new [] { runspace1.Object, runspace2.Object }); rsProvider.Setup(p => p.Get(runspaceId1)).Returns(runspace1.Object); rsProvider.Setup(p => p.Get(runspaceId2)).Returns(runspace2.Object); // Mock RunsapcesStatsMonitor var runspacesStatsMonitor = new Mock <IRunspacesStatsMonitor>(); runspacesStatsMonitor.Setup(m => m.EvaluateRunspacesToRemove(IRunspacesStatsMonitor.RunspaceType.Runspace)).Returns(new[] { runspaceId1 }); runspacesStatsMonitor.Setup(m => m.Unregister(It.IsAny <string>())); _multiTenantRunspaceProvider = new MultiTenantRunspaceProvider( MockLoggerFactory(), rsProvider.Object, Int32.MaxValue, Int32.MaxValue, Int32.MaxValue, runspacesStatsMonitor.Object); _multiTenantRunspaceProvider.StartCreate(userId, sessionTokenMock.Object, null, false, null, null); _multiTenantRunspaceProvider.StartCreate(userId, sessionTokenMock.Object, null, false, null, null); // Act _multiTenantRunspaceProvider.Cleanup(); // Assert // Provider Kill is called rsProvider.Verify(mock => mock.Kill(It.IsAny <string>()), Times.AtLeastOnce()); // Stats Monitor Unregister is called runspacesStatsMonitor.Verify(mock => mock.Unregister(It.IsAny <string>()), Times.Exactly(2)); // Only Runspace2 is left var userRunspaces = _multiTenantRunspaceProvider.List(userId); Assert.AreEqual(1, userRunspaces.Count()); Assert.AreEqual(runspaceId2, userRunspaces.First().Id); }
public void IntellisenseTextBox_Text_NotLatinCharacter_ShowMessageBox_TextMadeEmpty() { //------------Setup for test-------------------------- CustomContainer.DeRegister <IPopupController>(); var mockPopupController = new Mock <IPopupController>(); mockPopupController.Setup(controller => controller.ShowInvalidCharacterMessage(It.IsAny <string>())); CustomContainer.Register(mockPopupController.Object); var intellisenseProvider = new Mock <IIntellisenseProvider>(); intellisenseProvider.Setup(a => a.HandlesResultInsertion).Returns(false); //------------Execute Test--------------------------- var textBox = new IntellisenseTextBox(); var checkHasUnicodeInText = textBox.CheckHasUnicodeInText("أَبْجَدِي"); //------------Assert Results------------------------- Assert.IsTrue(checkHasUnicodeInText); Assert.AreEqual("", textBox.Text); mockPopupController.Verify(controller => controller.ShowInvalidCharacterMessage(It.IsAny <string>()), Times.AtLeastOnce()); }
public void ThatBuildScriptDeploymentWorks() { Mock <IDatabaseService> databaseServiceMock = new Mock <IDatabaseService>(MockBehavior.Strict); Mock <IConfigurationService> configurationServiceMock = new Mock <IConfigurationService>(MockBehavior.Strict); Mock <IScriptService> scriptServiceMock = new Mock <IScriptService>(MockBehavior.Strict); Mock <IFileService> fileServiceMock = new Mock <IFileService>(MockBehavior.Strict); Mock <IScriptMessageFormatter> scriptMessageFormatterMock = new Mock <IScriptMessageFormatter>(MockBehavior.Strict); IDictionary <decimal, IScriptFile> availableScripts = this.GetScripts(); IDictionary <decimal, IChangeLog> changeLogs = this.GetChangeLogs(); string changeScript = "Change Script"; // FileService Setup fileServiceMock.Setup(file => file.CleanupPastRuns()).Verifiable(); fileServiceMock.Setup(file => file.GetScriptFiles()).Returns(availableScripts).Verifiable(); fileServiceMock.Setup(file => file.WriteChangeScript(It.Is <string>(s => s == changeScript))).Verifiable(); fileServiceMock.Setup(file => file.WriteUndoScript(It.Is <string>(s => s == changeScript))).Verifiable(); fileServiceMock.Setup(file => file.WriteScriptList(It.IsAny <Dictionary <decimal, IScriptFile> >())) .Verifiable(); // Database Service Setup databaseServiceMock.Setup(db => db.GetAppliedChanges()).Returns(changeLogs).Verifiable(); // Configuration Service Setup configurationServiceMock.Setup(config => config.LastChangeToApply).Returns(1000).Verifiable(); configurationServiceMock.Setup(config => config.OutputFile).Returns("File Location").Verifiable(); configurationServiceMock.Setup(config => config.UndoOutputFile).Returns("File Location").Verifiable(); configurationServiceMock.Setup(config => config.ScriptListFile) .Returns("ScriptListFileLocation") .Verifiable(); // Script Formatter setup scriptMessageFormatterMock.Setup(fm => fm.FormatCollection(It.IsAny <ICollection <decimal> >())) .Returns("String Formatted.") .Verifiable(); // Script Service Setup scriptServiceMock.Setup(script => script.BuildChangeScript(It.IsAny <IDictionary <decimal, IScriptFile> >())) .Returns(changeScript) .Verifiable(); scriptServiceMock.Setup(script => script.BuildUndoScript(It.IsAny <IDictionary <decimal, IScriptFile> >())) .Returns(changeScript) .Verifiable(); configurationServiceMock.Setup(c => c.DatabaseService).Returns(databaseServiceMock.Object); DeploymentService deploymentService = new DeploymentService( configurationServiceMock.Object, scriptServiceMock.Object, fileServiceMock.Object, scriptMessageFormatterMock.Object); deploymentService.BuildDeploymentScript(); // File Verifies fileServiceMock.Verify(file => file.CleanupPastRuns(), Times.Exactly(1)); fileServiceMock.Verify(file => file.GetScriptFiles(), Times.Exactly(1)); fileServiceMock.Verify( file => file.WriteChangeScript(It.Is <string>(s => s == changeScript)), Times.Exactly(1)); fileServiceMock.Verify( file => file.WriteUndoScript(It.Is <string>(s => s == changeScript)), Times.Exactly(1)); fileServiceMock.Verify( file => file.WriteScriptList(It.IsAny <Dictionary <decimal, IScriptFile> >()), Times.Exactly(1)); // Database Verifies databaseServiceMock.Verify(db => db.GetAppliedChanges(), Times.Exactly(1)); // Configuration Service Verifies configurationServiceMock.Verify(config => config.LastChangeToApply, Times.AtLeastOnce()); configurationServiceMock.Verify(config => config.OutputFile, Times.AtLeastOnce()); configurationServiceMock.Verify(config => config.UndoOutputFile, Times.AtLeastOnce()); configurationServiceMock.Verify(config => config.ScriptListFile, Times.AtLeastOnce()); // Script Formamter Verifies. scriptMessageFormatterMock.Verify( fm => fm.FormatCollection(It.IsAny <ICollection <decimal> >()), Times.AtLeastOnce()); // Script Service Verifies scriptServiceMock.Verify( script => script.BuildChangeScript(It.IsAny <IDictionary <decimal, IScriptFile> >()), Times.Exactly(1)); scriptServiceMock.Verify( script => script.BuildUndoScript(It.IsAny <IDictionary <decimal, IScriptFile> >()), Times.Exactly(1)); }
public void ShouldHavePublished(List <DomainEvent> domainEvents) { EventBus.Verify(x => x.Publish(domainEvents, CancellationToken.None), Times.AtLeastOnce()); }
public async Task CallsResponseFactoryWithConfig() { var context = TestHttpContextBuilder.CreateForPath($"/{clients[0].ClientId}/{nameof(SimpleConfig)}") .WithClaims() .TestContext; var config = new ConfigInstance <SimpleConfig>(new SimpleConfig { IntProperty = 43 }, new ConfigurationIdentity(clients[0], new Version(1, 0))); configurationService.Setup(r => r.GetAsync(typeof(SimpleConfig), It.Is <ConfigurationIdentity>(arg => arg.Client.ClientId == clients[0].ClientId))).ReturnsAsync(config); responseFactory.Setup(r => r.BuildJsonResponse(context, config.Configuration)) .Returns(Task.FromResult(true)); await target.Handle(context, options); responseFactory.Verify(r => r.BuildJsonResponse(context, config.Configuration), Times.AtLeastOnce()); }
public void Test_AbsorbHit_NoDamage() { _mockSettings.Setup(u => u.GetSetting <string>("Hostile")).Returns("blah Blah Blah!!!"); var shipToTest = new Ship(FactionName.Klingon, "TestShip", _mockSector.Object, _mockMap.Object, _mockMap.Object.Game); Shields.For(shipToTest).Energy = 100; //this is syntactic sugar for: ship.Subsystems.Single(s => s.Type == SubsystemType.Shields); Assert.AreEqual(100, Shields.For(shipToTest).Energy); _mockWrite.Setup(w => w.Line(It.IsAny <string>())); _mockMap.Object.Write = _mockWrite.Object; _mockSector.Setup(s => s.X).Returns(-2); _mockSector.Setup(s => s.Y).Returns(-3); var attacker = new Ship(FactionName.Klingon, "The attacking Ship", _mockSector.Object, _mockMap.Object, _mockMap.Object.Game); shipToTest.AbsorbHitFrom(attacker, 50); Assert.AreEqual(50, Shields.For(shipToTest).Energy); //Verifications of Output to User _mockSector.Verify(s => s.X, Times.Exactly(1)); _mockSector.Verify(s => s.Y, Times.Exactly(1)); _mockWrite.Verify(w => w.Line(It.IsAny <string>()), Times.Exactly(2)); _mockWrite.Verify(w => w.Line("Your Ship has been hit by The attacking Ship at sector [-2,-3]."), Times.AtLeastOnce()); _mockWrite.Verify(w => w.Line("No Damage."), Times.Once()); }
public void BehaviourWhenProcessorThrowsOnStart() { var exCount = 0; var mockPro1 = new Mock <IPollProcessor>(); mockPro1.Setup(x => x.Start()).Throws(new InvalidOperationException()); var mockPro2 = new Mock <IPollProcessor>(); try { var host = new PollingHost(new[] { mockPro1.Object, mockPro2.Object }); host.Start(); } catch (InvalidOperationException) { ++exCount; } mockPro1.Verify(x => x.Start(), Times.Once()); mockPro2.Verify(x => x.Start(), Times.Never()); mockPro2.Verify(x => x.Stop(), Times.AtLeast(2)); mockPro1.Verify(x => x.Stop(), Times.AtLeast(2)); AssemblyLoggerProvider.MockLogger.Verify(x => x.Error(It.IsAny <string>(), It.IsAny <Exception>()), Times.AtLeastOnce()); Assert.AreEqual(1, exCount); }
private void RunSolverToAbortDownload( AbstractEnhancedSolver solver, ContentChangeType localContent = ContentChangeType.NONE, ContentChangeType remoteContent = ContentChangeType.NONE) { var stream = new Mock <MemoryStream>(); stream.SetupAllProperties(); stream.Setup(f => f.CanWrite).Returns(true); // required for System.Security.Cryptography.CryptoStream this.localFileLength = 0; stream.Setup(f => f.Write(It.IsAny <byte[]>(), It.IsAny <int>(), It.IsAny <int>())).Callback((byte[] buffer, int offset, int count) => { if (this.localFileLength > 0) { foreach (Transmission transmission in this.transmissionManager.ActiveTransmissions) { transmission.Abort(); } } this.localFileLength += count; }); stream.Setup(f => f.Length).Returns(() => { return(this.localFileLength); }); this.cacheFile.Setup(f => f.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)).Returns(() => { this.cacheFile.Setup(f => f.Exists).Returns(true); return(stream.Object); }); var remoteDocument = MockOfIDocumentUtil.CreateRemoteDocumentMock(null, this.objectId, this.objectName, this.parentId, this.fileContent.Length, this.fileContent, this.changeToken); remoteDocument.Setup(f => f.LastModificationDate).Returns((DateTime?)this.creationDate); Assert.Throws <AbortException>(() => solver.Solve(this.localFile.Object, remoteDocument.Object, localContent, remoteContent)); this.cacheFile.Verify(f => f.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None), Times.Once()); this.cacheFile.VerifySet(f => f.Uuid = It.Is <Guid?>(uuid => uuid != null && !uuid.Equals(Guid.Empty)), Times.Never()); this.cacheFile.Verify(f => f.MoveTo(this.localPath), Times.Never()); this.localFile.VerifySet(d => d.LastWriteTimeUtc = It.Is <DateTime>(date => date.Equals(this.creationDate)), Times.Never()); this.transmissionStorage.Verify(f => f.GetObjectByRemoteObjectId(It.IsAny <string>()), Times.Once()); this.transmissionStorage.Verify(f => f.SaveObject(It.IsAny <IFileTransmissionObject>()), Times.AtLeastOnce()); this.transmissionStorage.Verify(f => f.RemoveObjectByRemoteObjectId(It.IsAny <string>()), Times.Never()); this.storage.Verify(f => f.SaveMappedObject(It.IsAny <IMappedObject>()), Times.Never()); }
public void with_correct_data_and_key_saveRequest_successfully() { _sut.SaveRequest("data", "key"); _distributedCacheMock.Verify(x => x.SetAsync("key", It.IsAny <byte[]>(), It.IsAny <DistributedCacheEntryOptions>(), It.IsAny <CancellationToken>()), Times.AtLeastOnce()); }
private void RunSolverToContinueDownload( AbstractEnhancedSolver solver, ContentChangeType localContent = ContentChangeType.NONE, ContentChangeType remoteContent = ContentChangeType.NONE) { Mock <MemoryStream> stream = new Mock <MemoryStream>(); stream.SetupAllProperties(); stream.Setup(f => f.CanWrite).Returns(true); // required for System.Security.Cryptography.CryptoStream stream.Setup(f => f.Write(It.IsAny <byte[]>(), It.IsAny <int>(), It.IsAny <int>())).Callback((byte[] buffer, int offset, int count) => this.localFileLength += count); stream.Setup(f => f.Length).Returns(() => { return(this.localFileLength); }); long lengthRead = 0; stream.Setup(f => f.Seek(It.IsAny <long>(), It.IsAny <SeekOrigin>())).Callback((long offset, SeekOrigin loc) => lengthRead = offset); stream.Setup(f => f.Read(It.IsAny <byte[]>(), It.IsAny <int>(), It.IsAny <int>())).Returns((byte[] buffer, int offset, int count) => { if (lengthRead >= this.localFileLength) { return(0); } int countRead = count; if (countRead > (this.localFileLength - lengthRead)) { countRead = (int)(this.localFileLength - lengthRead); } Array.Copy(this.fileContent, lengthRead, buffer, offset, countRead); lengthRead += countRead; stream.Object.Position = lengthRead; return(countRead); }); this.cacheFile.Setup(f => f.Open(It.IsAny <FileMode>(), It.IsAny <FileAccess>(), It.IsAny <FileShare>())).Returns(stream.Object); this.cacheFile.Setup(f => f.Length).Returns(() => { return(this.localFileLength); }); var remoteDocument = MockOfIDocumentUtil.CreateRemoteDocumentMock(null, this.objectId, this.objectName, this.parentId, this.fileContent.Length, this.fileContent, this.changeToken); remoteDocument.Setup(f => f.LastModificationDate).Returns((DateTime?)this.creationDate); solver.Solve(this.localFile.Object, remoteDocument.Object, localContent, remoteContent); Assert.That(this.localFileLength, Is.EqualTo(this.fileContent.Length)); stream.Verify(f => f.Seek(0, SeekOrigin.Begin), Times.Once()); this.cacheFile.Verify(f => f.Open(It.IsAny <FileMode>(), It.IsAny <FileAccess>(), It.IsAny <FileShare>()), Times.Exactly(3)); // first open in SetupToAbortThePreviousDownload, second open to validate checksum, third open to download this.localFile.VerifySet(d => d.LastWriteTimeUtc = It.Is <DateTime>(date => date.Equals(this.creationDate)), Times.Once()); this.storage.VerifySavedMappedObject(MappedObjectType.File, this.objectId, this.objectName, this.parentId, this.changeToken, true, this.creationDate, this.creationDate, this.fileHash, this.fileContent.Length); this.transmissionStorage.Verify(f => f.GetObjectByRemoteObjectId(this.objectId), Times.Exactly(2)); this.transmissionStorage.Verify(f => f.SaveObject(It.IsAny <IFileTransmissionObject>()), Times.AtLeastOnce()); this.transmissionStorage.Verify(f => f.RemoveObjectByRemoteObjectId(this.objectId), Times.Once()); }
public async Task Post_NormalParameters_Sucess() { CreatingTripDto creatingTripDto = new CreatingTripDto("asdsds", "asfdsa", "dcxvxc", new int[] { 1, 2, 3, 4, 5 }); TripDto tripDto = TripMapper.toDTO(creatingTripDto); Trip trip = TripMapper.toDomain(tripDto); var mockRepository = new Mock <ITripRepository>(); mockRepository.Setup(repository => repository.AddAsync(It.IsAny <Trip>())).Returns(Task.FromResult(trip)); var mockUnit = new Mock <IUnitOfWork>(); TripService TripService = new TripService(mockUnit.Object, mockRepository.Object); TripsController controller = new TripsController(TripService); var result = await controller.Create(creatingTripDto); mockRepository.Verify(repository => repository.AddAsync(It.IsAny <Trip>()), Times.AtLeastOnce()); mockUnit.Verify(unit => unit.CommitAsync(), Times.AtLeastOnce()); Assert.IsInstanceOfType(result, typeof(ActionResult <TripDto>)); }
private void RunSolverToChangeLocalCacheBeforeContinue( AbstractEnhancedSolver solver, ContentChangeType localContent = ContentChangeType.NONE, ContentChangeType remoteContent = ContentChangeType.NONE) { this.SetupToChangeLocalCache(); Mock <IDocument> remoteObject = MockOfIDocumentUtil.CreateRemoteDocumentMock(null, this.objectId, this.objectName, this.parentId, this.fileContent.Length, this.fileContent, this.changeToken); remoteObject.Setup(f => f.LastModificationDate).Returns((DateTime?)this.creationDate); solver.Solve(this.localFile.Object, remoteObject.Object, localContent, remoteContent); Assert.That(this.localFileLength, Is.EqualTo(this.fileContent.Length)); this.cacheFile.Verify(f => f.Open(It.IsAny <FileMode>(), It.IsAny <FileAccess>(), It.IsAny <FileShare>()), Times.Exactly(3)); // first open in SetupToAbortThePreviousDownload, second open to validate checksum, third open to download this.cacheFile.Verify(f => f.Delete(), Times.Once()); this.localFile.VerifySet(d => d.LastWriteTimeUtc = It.Is <DateTime>(date => date.Equals(this.creationDate)), Times.Once()); this.storage.VerifySavedMappedObject(MappedObjectType.File, this.objectId, this.objectName, this.parentId, this.changeToken, true, this.creationDate, this.creationDate, this.fileHash, this.fileContent.Length); this.transmissionStorage.Verify(f => f.GetObjectByRemoteObjectId(this.objectId), Times.Exactly(2)); this.transmissionStorage.Verify(f => f.SaveObject(It.IsAny <IFileTransmissionObject>()), Times.AtLeastOnce()); this.transmissionStorage.Verify(f => f.RemoveObjectByRemoteObjectId(this.objectId), Times.Once()); }
public void Verify2() { mock.Verify(foo => foo.DoSomething("ping"), Times.AtLeastOnce()); }
private void RunSolverToDeleteLocalCacheBeforeContinue( AbstractEnhancedSolver solver, ContentChangeType localContent = ContentChangeType.NONE, ContentChangeType remoteContent = ContentChangeType.NONE) { this.cacheFile.Setup(f => f.Exists).Returns(false); Mock <MemoryStream> stream = new Mock <MemoryStream>(); stream.SetupAllProperties(); stream.Setup(f => f.CanWrite).Returns(true); // required for System.Security.Cryptography.CryptoStream this.localFileLength = 0; stream.Setup(f => f.Write(It.IsAny <byte[]>(), It.IsAny <int>(), It.IsAny <int>())).Callback((byte[] buffer, int offset, int count) => this.localFileLength += count); this.cacheFile.Setup(f => f.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)).Returns(() => { this.cacheFile.Setup(f => f.Exists).Returns(true); return(stream.Object); }); Mock <IDocument> remoteObject = MockOfIDocumentUtil.CreateRemoteDocumentMock(null, this.objectId, this.objectName, this.parentId, this.fileContent.Length, this.fileContent, this.changeToken); remoteObject.Setup(f => f.LastModificationDate).Returns((DateTime?)this.creationDate); solver.Solve(this.localFile.Object, remoteObject.Object, localContent, remoteContent); Assert.That(this.localFileLength, Is.EqualTo(this.fileContent.Length)); this.cacheFile.Verify(f => f.Open(It.IsAny <FileMode>(), It.IsAny <FileAccess>(), It.IsAny <FileShare>()), Times.Exactly(2)); // first open in SetupToAbortThePreviousDownload, second open to download this.localFile.VerifySet(d => d.LastWriteTimeUtc = It.Is <DateTime>(date => date.Equals(this.creationDate)), Times.Once()); this.storage.VerifySavedMappedObject(MappedObjectType.File, this.objectId, this.objectName, this.parentId, this.changeToken, true, this.creationDate, this.creationDate, this.fileHash, this.fileContent.Length); this.transmissionStorage.Verify(f => f.GetObjectByRemoteObjectId(this.objectId), Times.Exactly(2)); this.transmissionStorage.Verify(f => f.SaveObject(It.IsAny <IFileTransmissionObject>()), Times.AtLeastOnce()); this.transmissionStorage.Verify(f => f.RemoveObjectByRemoteObjectId(this.objectId), Times.Once()); }
public void Execute_PreventsSQLInjection() { _subject.Execute(_user); _dbCommand.Verify(c => c.Parameters.Add(It.IsAny <IDbDataParameter>()), Times.AtLeastOnce()); }
public async Task CallsResponseFactoryWithConfig_WhenUserHasReadClaim() { var claimValue = "ClientOne"; clients[0].ReadClaim = claimValue; var readClaim = GetReadClaim(claimValue); var context = TestHttpContextBuilder.CreateForPath($"/{clients[0].ClientId}/{nameof(SimpleConfig)}") .WithClaims(readClaim) .TestContext; await target.Handle(context, options); responseFactory.Verify(r => r.BuildJsonResponse(context, It.IsAny <object>()), Times.AtLeastOnce()); }
public async Task CallsResponseFactoryWithTags() { var context = TestHttpContextBuilder.CreateForPath($"/") .WithClaims() .TestContext; var expectedTags = new[] { tagOne, tagTwo }; await target.Handle(context, options); responseFactory.Verify(r => r.BuildJsonResponse(context, It.Is <IEnumerable <Tag> >(o => TagsMatch(o, expectedTags))), Times.AtLeastOnce()); }
public async Task CallsResponseFactoryWithConfig_WhenAllowAnomymous() { var context = TestHttpContextBuilder.CreateForPath($"/{clients[0].ClientId}/{nameof(SimpleConfig)}") .TestContext; options.AllowAnomynousAccess = true; await target.Handle(context, options); responseFactory.Verify(r => r.BuildJsonResponse(context, It.IsAny <object>()), Times.AtLeastOnce()); }
public void TestCustomRedMetricsTagsWavefrontSpan() { string operationName = "dummyOp"; var pointTags = PointTags(operationName, new Dictionary <string, string> { { "tenant", "tenant1" }, { "env", "Staging" }, { Tags.SpanKind.Key, Tags.SpanKindServer } }); var wfSenderMock = new Mock <IWavefrontSender>(MockBehavior.Strict); Expression <Action <IWavefrontSender> > sendSpan = sender => sender.SendSpan(operationName, IsAny <long>(), IsAny <long>(), "source", IsAny <Guid>(), IsAny <Guid>(), new List <Guid>(), new List <Guid>(), IsAny <IList <KeyValuePair <string, string> > >(), new List <SpanLog>()); Expression <Action <IWavefrontSender> > sendInvocationCount = sender => sender.SendMetric( "tracing.derived.myApplication.myService.dummyOp.invocation.count", 1.0, IsAny <long>(), "source", Is <IDictionary <string, string> >(dict => ContainsPointTags(dict, pointTags) && !dict.ContainsKey("customId"))); Expression <Action <IWavefrontSender> > sendTotalMillis = sender => sender.SendMetric( "tracing.derived.myApplication.myService.dummyOp.total_time.millis.count", IsAny <double>(), IsAny <long>(), "source", Is <IDictionary <string, string> >(dict => ContainsPointTags(dict, pointTags) && !dict.ContainsKey("customId"))); Expression <Action <IWavefrontSender> > sendDurationMicros = sender => sender.SendDistribution( "tracing.derived.myApplication.myService.dummyOp.duration.micros", IsAny <IList <KeyValuePair <double, int> > >(), new HashSet <HistogramGranularity> { HistogramGranularity.Minute }, IsAny <long>(), "source", Is <IDictionary <string, string> >(dict => ContainsPointTags(dict, pointTags) && !dict.ContainsKey("customId"))); Expression <Action <IWavefrontSender> > sendHeartbeat = sender => sender.SendMetric( "~component.heartbeat", 1.0, IsAny <long>(), "source", IsAny <IDictionary <string, string> >()); wfSenderMock.Setup(sendSpan); wfSenderMock.Setup(sendInvocationCount); wfSenderMock.Setup(sendTotalMillis); wfSenderMock.Setup(sendDurationMicros); wfSenderMock.Setup(sendHeartbeat); WavefrontSpanReporter spanReporter = new WavefrontSpanReporter.Builder() .WithSource("source").Build(wfSenderMock.Object); WavefrontTracer tracer = new WavefrontTracer.Builder(spanReporter, BuildApplicationTags()).SetReportFrequency(TimeSpan.FromMilliseconds(50)) .RedMetricsCustomTagKeys(new HashSet <string> { "tenant", "env" }).Build(); tracer.BuildSpan(operationName).WithTag("tenant", "tenant1").WithTag("env", "Staging") .WithTag("customId", "abc123").WithTag(Tags.SpanKind, Tags.SpanKindServer) .StartActive(true).Dispose(); Console.WriteLine("Sleeping for 1 second zzzzz ....."); Thread.Sleep(1000); Console.WriteLine("Resuming execution ....."); wfSenderMock.Verify(sendSpan, Times.Once()); wfSenderMock.Verify(sendInvocationCount, Times.AtLeastOnce()); wfSenderMock.Verify(sendTotalMillis, Times.AtLeastOnce()); /* * TODO: update WavefrontHistogramOptions.Builder to allow a clock to be passed in * so that we can advance minute bin and update the below call to Times.AtLeastOnce() */ wfSenderMock.Verify(sendDurationMicros, Times.AtMost(int.MaxValue)); wfSenderMock.Verify(sendHeartbeat, Times.AtMost(int.MaxValue)); }
public void DoesNotContainFailTest() { CollectionAssertion.DoesNotContain(4, 5, 1, 6); FailureHandler.Verify(x => x.Fail(It.IsAny <string>()), Times.AtLeastOnce()); }