private void AndCreateNewBranchShouldHaveBeenCalled() { var captureNewBranch = new CaptureMatch <string>(newBranch => NewBranch = newBranch); DarcRemotes[TargetRepo] .Verify(r => r.CreateNewBranchAsync(TargetRepo, TargetBranch, Capture.With(captureNewBranch))); }
public async Task HandleAsync_ShouldReturnTrueAndNotLog_WhenNoErrorsFailedEncode() { // Arrange var payload = new FlipPayload() { OperationContext = testOpCtx, FactoryId = "424242", OutputContainer = "https://someaccount.blob.core.windows.net/somecontainer" }; var flipEncodeCompleteData = new FlipEncodingCompleteData() { EncodingId = "444", EncodingStatus = "777", OriginalFilename = "bbb.mp4", EventName = "flip", ServiceName = "flip", VideoId = "999", VideoPayload = payload, }; var appInsightsUri = new Uri("https://www.appinsights.com"); var eventToPublish = new EventGridEvent() { Id = Guid.NewGuid().ToString(), Data = JObject.FromObject(flipEncodeCompleteData), EventTime = DateTime.Now, EventType = ExternalEventTypes.FlipEncodingComplete, Subject = $"/EncodeCompleted/sagaid", DataVersion = "1.0", }; var expectedEventToPublishCaptureMatch = new CaptureMatch <EventGridEvent>(x => { // Assert values in the object passed to the publisher: x.EventType.ShouldBe(CustomEventTypes.ResponseFailure); }); // Arrange Mocks Mock.Get(_eventGridPublisher).Setup(x => x.PublishEventToTopic(Capture.With(expectedEventToPublishCaptureMatch))) .ReturnsAsync(true); Mock.Get(_logger) .Setup(x => x.LogEventObject( out appInsightsUri, LogEventIds.EncodeCompleteFailure, It.IsAny <object>())); Mock.Get(_flipService) .Setup(x => x.GetEncodeInfo(It.IsAny <FlipEncodingCompleteData>())) .Returns(new Telestream.Cloud.Flip.Model.Encoding { ErrorClass = "ErrorClass", ErrorMessage = "ErrorMessage" }); // Act var handleAsyncResult = await _handler.HandleAsync(eventToPublish).ConfigureAwait(false); // Assert handleAsyncResult.ShouldBe(true, "handleAsync should always return false"); }
public async Task HandleAsync_ShouldPublishFailureEvent_WhenChangeTierThrows() { // Arrange var blobUri = "https://gridwichasset00sasb.com/container1/la_macarena.mp4"; var appInsightsUri = new Uri("https://www.appinsights.com"); var context = TestHelpers.CreateGUIDContext(); var changeBlobTierData = new RequestBlobTierChangeDTO { AccessTier = BlobAccessTier.Archive, BlobUri = blobUri, RehydratePriority = BlobRehydratePriority.High, OperationContext = context.ClientRequestIdAsJObject }; var testEvent = new EventGridEvent { EventType = CustomEventTypes.RequestBlobTierChange, EventTime = DateTime.UtcNow, DataVersion = "1.0", Data = JObject.FromObject(changeBlobTierData) }; // Arrange Mocks var expectedEventToPublishCaptureMatch = new CaptureMatch <EventGridEvent>(x => { // Assert values in the object passed to the publisher: x.EventTime.ShouldBeInRange(testEvent.EventTime, testEvent.EventTime.AddMinutes(1)); x.Data.ShouldBeOfType(typeof(ResponseFailureDTO)); var data = (ResponseFailureDTO)x.Data; data.ShouldNotBeNull(); }); Mock.Get(_eventGridPublisher) .Setup(x => x.PublishEventToTopic(Capture.With(expectedEventToPublishCaptureMatch))) .ReturnsAsync(true); Mock.Get(_storageService) .Setup(x => x.ChangeBlobTierAsync(new Uri(blobUri), changeBlobTierData.AccessTier, changeBlobTierData.RehydratePriority, It.IsAny <StorageClientProviderContext>())) .ThrowsAsync(new InvalidOperationException()); Mock.Get(_logger) .Setup(x => x.LogExceptionObject( out appInsightsUri, LogEventIds.GridwichUnhandledException, It.IsAny <Exception>(), It.IsAny <object>())); // Act var handleAsyncResult = await _handler.HandleAsync(testEvent).ConfigureAwait(true); // Assert handleAsyncResult.ShouldBe(false); Mock.Get(_logger).Verify(x => x.LogExceptionObject(out appInsightsUri, LogEventIds.GridwichUnhandledException, It.IsAny <Exception>(), It.IsAny <object>()), Times.Once); }
public void CanRunCaptureCallback() { var capturedValue = string.Empty; var captureMatch = new CaptureMatch<string>(s => capturedValue = s); var mock = new Mock<IFoo>(); mock.Setup(x => x.DoSomething(Capture.With(captureMatch))); mock.Object.DoSomething("Hello!"); Assert.Equal("Hello!", capturedValue); }
public void CanRunCaptureCallback() { var capturedValue = string.Empty; var captureMatch = new CaptureMatch <string>(s => capturedValue = s); var mock = new Mock <IFoo>(); mock.Setup(x => x.DoSomething(Capture.With(captureMatch))); mock.Object.DoSomething("Hello!"); Assert.Equal("Hello!", capturedValue); }
public async Task HandleAsync_ShouldAcknowledgeEvent_WhenHandlingRequestorEvent() { // Arrange var blobUri = new Uri(_expectedInboxUrl); JObject operationContext = JObject.Parse("{}"); var topicEndpointUri = new Uri("https://www.topichost.com"); var testEvent = new EventGridEvent { EventTime = DateTime.UtcNow, EventType = CustomEventTypes.RequestBlobCopy, DataVersion = "1.0", Data = JsonConvert.SerializeObject(new RequestBlobMetadataCreateDTO { BlobUri = blobUri, OperationContext = JObject.FromObject(operationContext) }) }; // Arrange Mocks Mock.Get(_settingsProvider) .Setup(x => x.GetAppSettingsValue(Publishing.TopicOutboundEndpointSettingName)) .Returns(topicEndpointUri.ToString()); Mock.Get(_storageService) .Setup(x => x.GetBlobMetadataAsync(blobUri, It.IsAny <StorageClientProviderContext>())) .ReturnsAsync(new JObject() { }); var expectedEventToPublishCaptureMatch = new CaptureMatch <EventGridEvent>(x => { // Assert values in the object passed to the publisher: x.EventType.ShouldBe("gridwich.acknowledge"); x.EventTime.ShouldBeInRange(testEvent.EventTime, testEvent.EventTime.AddMinutes(1)); }); Mock.Get(_eventGridPublisher) .Setup(x => x.PublishEventToTopic(Capture.With(expectedEventToPublishCaptureMatch))) .ReturnsAsync(true); // Act var handleAsyncResult = await _handler.HandleAsync(testEvent).ConfigureAwait(true); // Assert Mock.Get(_logger).Verify(x => x.LogEventObject(LogEventIds.StartingAcknowledgement, It.IsAny <object>()), Times.Once, "It should log that it is starting the acknowledgement"); Mock.Get(_logger).Verify(x => x.LogEventObject(LogEventIds.FinishedAcknowledgement, It.IsAny <object>()), Times.Once, "It should log that it finished the acknowledgement"); }
public async Task HandleAsync_ShouldErrorOnBadInput() { // Arrange const string blobSasUrl = null; var topicEndpointUri = new Uri("https://www.topichost.com"); var appInsightsUri = new Uri("https://www.appinsights.com"); var testEvent = new EventGridEvent { EventTime = DateTime.UtcNow, EventType = CustomEventTypes.RequestBlobSasUrlCreate, DataVersion = "1.0", Data = JsonConvert.SerializeObject(new { foo = "bar" }) }; // Arrange Mocks Mock.Get(_settingsProvider) .Setup(x => x.GetAppSettingsValue(Publishing.TopicOutboundEndpointSettingName)) .Returns(topicEndpointUri.ToString()); Mock.Get(_storageService) .Setup(x => x.GetSasUrlForBlob(It.IsAny <Uri>(), It.IsAny <TimeSpan>(), It.IsAny <StorageClientProviderContext>())) .Returns(blobSasUrl); Mock.Get(_logger) .Setup(x => x.LogExceptionObject( out appInsightsUri, LogEventIds.GridwichUnhandledException, It.IsAny <Exception>(), It.IsAny <object>())); var expectedEventToPublishCaptureMatch = new CaptureMatch <EventGridEvent>(x => { // Assert values in the object passed to the publisher: x.EventType.ShouldBe(CustomEventTypes.ResponseBlobSasUrlSuccess); x.EventTime.ShouldBeInRange(testEvent.EventTime, testEvent.EventTime.AddMinutes(1)); x.Data.ShouldBeOfType(typeof(ResponseBlobSasUrlSuccessDTO)); var data = (ResponseBlobSasUrlSuccessDTO)x.Data; // TODO: make test pass with this assertion. // data.SasUrl.ToString().ShouldBe(BLOB_SAS_URL); }); Mock.Get(_eventGridPublisher) .Setup(x => x.PublishEventToTopic(Capture.With(expectedEventToPublishCaptureMatch))) .ReturnsAsync(true); // Act var handleAsyncResult = await _handler.HandleAsync(testEvent).ConfigureAwait(true); // Assert handleAsyncResult.ShouldBe(false, "handleAsync should return false"); }
public async Task when_subscribing_to_noninitialized_shell_then_can_wait_event_and_completion() { object zombie = true; uint cookie = 1; IVsShellPropertyEvents callback = null; var shell = new Mock <IVsShell>(); shell.Setup(x => x.GetProperty(ZombieProperty, out zombie)).Returns(VSConstants.S_OK); var capture = new CaptureMatch <IVsShellPropertyEvents>(s => callback = s); shell.Setup(x => x.AdviseShellPropertyChanges(Capture.With(capture), out cookie)) .Returns(VSConstants.S_OK); #pragma warning disable VSSDK005 // Avoid instantiating JoinableTaskContext var observable = new ShellInitializedObservable(new JoinableLazy <IVsShell>(() => shell.Object, taskFactory: new JoinableTaskContext().Factory)); #pragma warning restore VSSDK005 // Avoid instantiating JoinableTaskContext // Callback should have been provided at this point. Assert.NotNull(callback); var completed = false; ShellInitialized data = null; using (observable.Subscribe(e => data = e, () => completed = true)) { Assert.False(completed, "Observable shouldn't have completed yet."); Assert.Null(data); callback.OnShellPropertyChange(ZombieProperty, false); SpinWait.SpinUntil(() => completed, 5000); Assert.True(completed, "Observable should have completed already."); Assert.NotNull(data); shell.Verify(x => x.UnadviseShellPropertyChanges(cookie)); // Subsequent subscription should get one and complete right away. ShellInitialized ev = default; observable.Subscribe(e => ev = e); Assert.Same(data, ev); } }
public async Task HandleAsync_ShouldReturnTrueAndNotLog_WhenNoErrors() { // Arrange const string BLOB_URL = "https://some.com/path/to/a/blob.mp4"; const string BLOB_SAS_URL = "https://sas-url-for-your-blob.com"; var topicEndpointUri = new Uri("https://www.topichost.com"); var testEvent = new EventGridEvent { EventTime = DateTime.UtcNow, EventType = CustomEventTypes.RequestBlobSasUrlCreate, DataVersion = "1.0", Data = JsonConvert.SerializeObject(new RequestBlobSasUrlCreateDTO { BlobUri = new Uri(BLOB_URL), SecToLive = 10 }) }; // Arrange Mocks Mock.Get(_settingsProvider) .Setup(x => x.GetAppSettingsValue(Publishing.TopicOutboundEndpointSettingName)) .Returns(topicEndpointUri.ToString()); Mock.Get(_storageService) .Setup(x => x.GetSasUrlForBlob(It.IsAny <Uri>(), It.IsAny <TimeSpan>(), It.IsAny <StorageClientProviderContext>())) .Returns(BLOB_SAS_URL); var expectedEventToPublishCaptureMatch = new CaptureMatch <EventGridEvent>(x => { // Assert values in the object passed to the publisher: x.EventType.ShouldBe(CustomEventTypes.ResponseBlobSasUrlSuccess); x.EventTime.ShouldBeInRange(testEvent.EventTime, testEvent.EventTime.AddMinutes(1)); x.Data.ShouldBeOfType(typeof(ResponseBlobSasUrlSuccessDTO)); var data = (ResponseBlobSasUrlSuccessDTO)x.Data; // TODO: make test pass with this assertion. // data.SasUrl.ToString().ShouldBe(BLOB_SAS_URL); }); Mock.Get(_eventGridPublisher) .Setup(x => x.PublishEventToTopic(Capture.With(expectedEventToPublishCaptureMatch))) .ReturnsAsync(true); // Act var handleAsyncResult = await _handler.HandleAsync(testEvent).ConfigureAwait(true); // Assert handleAsyncResult.ShouldBe(true, "handleAsync should always return true"); }
public async Task when_subscribing_to_noninitialized_shell_then_can_wait_event_and_completion() { object zombie = true; uint cookie = 1; IVsShellPropertyEvents callback = null; var shell = new Mock <IVsShell>(); shell.Setup(x => x.GetProperty(ZombieProperty, out zombie)).Returns(VSConstants.S_OK); var capture = new CaptureMatch <IVsShellPropertyEvents>(s => callback = s); shell.Setup(x => x.AdviseShellPropertyChanges(Capture.With(capture), out cookie)) .Returns(VSConstants.S_OK); var observable = new ShellInitializedObservable(shell.Object); // Callback should have been provided at this point. Assert.NotNull(callback); var completed = false; ShellInitialized data = null; observable.Subscribe(e => data = e, () => completed = true); Assert.False(completed, "Observable shouldn't have completed yet."); Assert.Null(data); callback.OnShellPropertyChange(ZombieProperty, false); SpinWait.SpinUntil(() => completed, 5000); Assert.True(completed, "Observable should have completed already."); Assert.NotNull(data); shell.Verify(x => x.UnadviseShellPropertyChanges(cookie)); // Subsequent subscription should get one and complete right away. var ev = await observable; Assert.Same(data, ev); }
public async Task HandleAsync_ShouldPublishFailureEvent_WhenAccessTierIsInvalid() { // Arrange var accessTier = BlobAccessTier.Lookup("Invalid"); var blobUri = "https://gridwichasset00sasb.com/container1/la_macarena.mp4"; var appInsightsUri = new Uri("https://www.appinsights.com"); var changeBlobTierData = new RequestBlobTierChangeDTO { AccessTier = accessTier, BlobUri = blobUri, RehydratePriority = BlobRehydratePriority.High }; var testEvent = new EventGridEvent { EventType = CustomEventTypes.RequestBlobTierChange, EventTime = DateTime.UtcNow, DataVersion = "1.0", Data = JObject.FromObject(changeBlobTierData) }; var expectedEventToPublishCaptureMatch = new CaptureMatch <EventGridEvent>(x => { // Assert values in the object passed to the publisher: x.EventTime.ShouldBeInRange(testEvent.EventTime, testEvent.EventTime.AddMinutes(1)); x.Data.ShouldBeOfType(typeof(ResponseFailureDTO)); var data = (ResponseFailureDTO)x.Data; data.ShouldNotBeNull(); }); Mock.Get(_eventGridPublisher) .Setup(x => x.PublishEventToTopic(Capture.With(expectedEventToPublishCaptureMatch))) .ReturnsAsync(true); Mock.Get(_logger) .Setup(x => x.LogExceptionObject( out appInsightsUri, LogEventIds.GridwichUnhandledException, It.IsAny <Exception>(), It.IsAny <object>())); // Act var handleAsyncResult = await _handler.HandleAsync(testEvent).ConfigureAwait(true); // Assert handleAsyncResult.ShouldBe(false); }
public async Task when_subscribing_to_noninitialized_shell_then_can_wait_event_and_completion() { object zombie = true; uint cookie = 1; IVsShellPropertyEvents callback = null; var shell = new Mock<IVsShell>(); shell.Setup(x => x.GetProperty(ZombieProperty, out zombie)).Returns(VSConstants.S_OK); var capture = new CaptureMatch<IVsShellPropertyEvents>(s => callback = s); shell.Setup(x => x.AdviseShellPropertyChanges(Capture.With(capture), out cookie)) .Returns(VSConstants.S_OK); var observable = new ShellInitializedObservable(shell.Object); // Callback should have been provided at this point. Assert.NotNull(callback); var completed = false; ShellInitialized data = null; observable.Subscribe(e => data = e, () => completed = true); Assert.False(completed, "Observable shouldn't have completed yet."); Assert.Null(data); callback.OnShellPropertyChange(ZombieProperty, false); SpinWait.SpinUntil(() => completed, 5000); Assert.True(completed, "Observable should have completed already."); Assert.NotNull(data); shell.Verify(x => x.UnadviseShellPropertyChanges(cookie)); // Subsequent subscription should get one and complete right away. var ev = await observable; Assert.Same(data, ev); }
public async Task Create_WithoutReleaseId() { var subject = new Subject { Id = Guid.NewGuid() }; var request = new PermalinkCreateViewModel { Query = { SubjectId = subject.Id } }; var release = new Release { Id = Guid.NewGuid() }; var tableResult = new TableBuilderResultViewModel { SubjectMeta = new ResultSubjectMetaViewModel() }; var blobStorageService = new Mock <IBlobStorageService>(MockBehavior.Strict); var releaseRepository = new Mock <IReleaseRepository>(MockBehavior.Strict); var subjectRepository = new Mock <ISubjectRepository>(MockBehavior.Strict); var tableBuilderService = new Mock <ITableBuilderService>(MockBehavior.Strict); // Permalink id is assigned on creation and used as the blob path // Capture it so we can compare it with the view model result string blobPath = string.Empty; var blobPathCapture = new CaptureMatch <string>(callback => blobPath = callback); blobStorageService.Setup(s => s.UploadAsJson( Permalinks, Capture.With(blobPathCapture), It.Is <Permalink>(p => p.Configuration.Equals(request.Configuration) && p.FullTable.IsDeepEqualTo(new PermalinkTableBuilderResult(tableResult)) && p.Query.Equals(request.Query)), It.IsAny <JsonSerializerSettings>())) .Returns(Task.CompletedTask); releaseRepository .Setup(s => s.GetLatestPublishedRelease(_publicationId)) .Returns(release); subjectRepository .Setup(s => s.Get(subject.Id)) .ReturnsAsync(subject); subjectRepository .Setup(s => s.GetPublicationIdForSubject(subject.Id)) .ReturnsAsync(_publicationId); subjectRepository .Setup(s => s.IsSubjectForLatestPublishedRelease(subject.Id)) .ReturnsAsync(true); tableBuilderService .Setup(s => s.Query(release.Id, request.Query, CancellationToken.None)) .ReturnsAsync(tableResult); var service = BuildService(blobStorageService: blobStorageService.Object, releaseRepository: releaseRepository.Object, subjectRepository: subjectRepository.Object, tableBuilderService: tableBuilderService.Object); var result = (await service.Create(request)).AssertRight(); MockUtils.VerifyAllMocks( blobStorageService, releaseRepository, subjectRepository, tableBuilderService); Assert.Equal(Guid.Parse(blobPath), result.Id); Assert.InRange(DateTime.UtcNow.Subtract(result.Created).Milliseconds, 0, 1500); Assert.False(result.Invalidated); }