public async Task Run_Command_LimitedToOneInstance_CommandIsRunOnCorrectInstance() { const int limitedToInstance = 2; GraphReplicaSet = new GraphReplicaSet(ReplicaSetName, GraphInstances, Logger, limitedToInstance); await GraphReplicaSet.Run(Command); int index = 0; foreach (var graph in GraphInstances) { var calls = Fake.GetCalls(graph).ToList(); TestOutputHelper.WriteLine($"Graph #{index}: Run() called x{calls.Count}."); ++index; } index = 0; foreach (var graph in GraphInstances) { A.CallTo(() => graph.Run(A <ICommand> ._)) .MustHaveHappened(index == limitedToInstance ? 1 : 0, Times.Exactly); ++index; } }
public void TestCreatingSettingsFromDictionary() { var dict = new Dictionary <string, object>() { { "nuix", new Dictionary <string, object>() { { "UseDongle", true }, { "Features", new List <string>() { "a", "b", "c" } } } } }; var entity = Entity.Create(("Connectors", dict)); var settings = new SCLSettings(entity); TestOutputHelper.WriteLine(settings.ToString()); var useDongleString = settings.Entity.TryGetNestedString("Connectors", "Nuix", "UseDongle"); useDongleString.HasValue.Should().BeTrue(); useDongleString.Value.Should().Be(true.ToString()); var useDongleBool = settings.Entity.TryGetNestedBool("Connectors", "Nuix", "UseDongle"); useDongleBool.Should().BeTrue(); }
public void Run_Query_EvenCallsAcrossReplicasTest() { const int iterationsPerGraphInstance = 5; const int numberOfIterations = NumberOfGraphInstances * iterationsPerGraphInstance; Parallel.For(0, numberOfIterations, async(iteration) => { await GraphReplicaSet.Run(Query); }); int index = 0; foreach (var graph in GraphInstances) { var calls = Fake.GetCalls(graph).ToList(); TestOutputHelper.WriteLine($"Graph #{index}: Run() called x{calls.Count}."); ++index; } foreach (var graph in GraphInstances) { A.CallTo(() => graph.Run(A <IQuery <int>[]> ._)) .MustHaveHappened(iterationsPerGraphInstance, Times.Exactly); } }
public async Task FindPackagesByIdTest() { string packageId = string.Format("TestV2FeedFindPackagesById.{0}", DateTime.UtcNow.Ticks); TestOutputHelper.WriteLine("Uploading package '{0}'", packageId); await _clientSdkHelper.UploadNewPackage(packageId, "1.0.0"); TestOutputHelper.WriteLine("Uploaded package '{0}'", packageId); await _clientSdkHelper.UploadNewPackage(packageId, "2.0.0"); // Wait for the packages to be available in V2 (due to async validation) await _clientSdkHelper.VerifyPackageExistsInV2Async(packageId, "1.0.0"); await _clientSdkHelper.VerifyPackageExistsInV2Async(packageId, "2.0.0"); string url = UrlHelper.V2FeedRootUrl + @"/FindPackagesById()?id='" + packageId + "'&$orderby=Version"; string[] expectedTexts = { @"<id>" + UrlHelper.V2FeedRootUrl + "Packages(Id='" + packageId + "',Version='1.0.0')</id>", @"<id>" + UrlHelper.V2FeedRootUrl + "Packages(Id='" + packageId + "',Version='2.0.0')</id>" }; var containsResponseText = await _odataHelper.ContainsResponseText(url, expectedTexts); Assert.True(containsResponseText); }
public async Task Can_subscribe_to_all_stream_from_start_before_messages_are_written() { string streamId1 = "stream-1"; string streamId2 = "stream-2"; var receiveMessages = new TaskCompletionSource <StreamMessage>(); List <StreamMessage> receivedMessages = new List <StreamMessage>(); using (store.SubscribeToAll( Position.None, (_, message, __) => { TestOutputHelper.WriteLine($"Received message {message.StreamId} {message.StreamVersion} {message.Position}"); receivedMessages.Add(message); if (message.StreamId == streamId1 && message.StreamVersion == 3) { receiveMessages.SetResult(message); } return(Task.CompletedTask); })) { await AppendMessages(store, streamId1, 3); await AppendMessages(store, streamId2, 3); await AppendMessages(store, streamId1, 1); await receiveMessages.Task.WithTimeout(5000); receivedMessages.Count.ShouldBe(7); } }
public void Fallback() { var aliceRequest = new SportsRequest() { Session = new AliceSessionModel(), Request = new AliceRequestModel <SportsIntents>() { Nlu = new AliceNluModel <SportsIntents>() { Intents = new SportsIntents() { }, }, OriginalUtterance = "тест" }, State = new AliceStateModel <SportsSessionState, object>() { Session = new SportsSessionState() { CurrentScene = SceneType.MainNews } } }; using var scope = _services.CreateScope(); var aliceService = scope.ServiceProvider.GetService <IAliceService>(); var aliceResponse = aliceService.ProcessRequest(aliceRequest); Assert.IsType <SportsResponse>(aliceResponse); var aliceGalleryResponse = aliceResponse as SportsResponse; Assert.NotNull(aliceGalleryResponse); TestOutputHelper.WriteLine($"Response text: {aliceGalleryResponse.Response.Text}"); }
public void Log(LogLevel logLevel, int eventId, object state, Exception exception, Func <object, Exception, string> formatter) { if (eventId == 6) { TestOutputHelper.WriteLine(formatter(state, exception)); } }
public async Task delete_performance(int count) { TestOutputHelper.WriteLine($"Appending {count} test events"); for (int i = 0; i < count; i++) { await Subject.Append(Stream, new EventData(i + 1, DateTime.UtcNow, new SomethingHappened { What = "Stuff" }, new Dictionary <string, string> { ["Hest"] = "Test" })); } TestOutputHelper.WriteLine($"Completed appending {count} test events"); TestOutputHelper.WriteLine($"Deleting all {count} test events from event stream"); var timer = Stopwatch.StartNew(); var events = await Subject.Delete(Stream); timer.Stop(); TestOutputHelper.WriteLine("Finished deleting all test events from event stream"); TestOutputHelper.WriteLine($" Total elapsed time: {timer.Elapsed}, ({timer.Elapsed.TotalSeconds:N2} seconds)"); var throughput = count / (decimal)timer.Elapsed.TotalSeconds; TestOutputHelper.WriteLine($" Throughput: {throughput:N0} events/s"); }
public async Task FindPackagesByIdTest() { // Temporary workaround for the SSL issue, which keeps the upload test from working with cloudapp.net sites if (UrlHelper.BaseUrl.Contains("nugettest.org") || UrlHelper.BaseUrl.Contains("nuget.org")) { string packageId = string.Format("TestV2FeedFindPackagesById.{0}", DateTime.UtcNow.Ticks); TestOutputHelper.WriteLine("Uploading package '{0}'", packageId); await _clientSdkHelper.UploadNewPackageAndVerify(packageId); TestOutputHelper.WriteLine("Uploaded package '{0}'", packageId); await _clientSdkHelper.UploadNewPackageAndVerify(packageId, "2.0.0"); string url = UrlHelper.V2FeedRootUrl + @"/FindPackagesById()?id='" + packageId + "'"; string[] expectedTexts = { @"<id>" + UrlHelper.V2FeedRootUrl + "Packages(Id='" + packageId + "',Version='1.0.0')</id>", @"<id>" + UrlHelper.V2FeedRootUrl + "Packages(Id='" + packageId + "',Version='2.0.0')</id>" }; var containsResponseText = await _odataHelper.ContainsResponseText(url, expectedTexts); Assert.True(containsResponseText); } }
private async Task SearchFeedAsync(string feedRootUrl, string title) { var requestUrl = feedRootUrl + @"Search()?$filter=IsLatestVersion&$skip=0&$top=25&searchTerm='web%20helpers'&targetFramework='net40'&includePrerelease=false"; TestOutputHelper.WriteLine("Request: GET " + requestUrl); var request = WebRequest.Create(requestUrl); var response = (HttpWebResponse)await request.GetResponseAsync(); TestOutputHelper.WriteLine("Response: HTTP " + response.StatusCode); string responseText; using (var sr = new StreamReader(response.GetResponseStream())) { responseText = await sr.ReadToEndAsync(); } var expectedUrl = feedRootUrl + "package/Microsoft.AspNet.WebHelpers/"; Assert.True(responseText.Contains(@"<title type=""text"">" + title + @"</title>") || responseText.Contains(@"<d:Title>" + title + @"</d:Title>"), "The expected package title '" + title + "' wasn't found in the feed. Feed contents: " + responseText); Assert.True(responseText.Contains(@"<content type=""application/zip"" src=""" + expectedUrl), "The expected package URL '" + expectedUrl + "' wasn't found in the feed. Feed contents: " + responseText); Assert.False(responseText.Contains(@"jquery"), "The feed contains non-matching package names. Feed contents: " + responseText); }
protected void Within(TimeSpan timeSpan, Func <AssertionFailure> actionContainingAssertions) { TimeSpan permitted = timeSpan; Stopwatch watch = Stopwatch.StartNew(); while (true) { var potentialFailure = actionContainingAssertions(); if (potentialFailure == null) { break; } if (watch.Elapsed > permitted) { TestOutputHelper.WriteLine("Failing assertion on: {0}", potentialFailure.Measure); potentialFailure.Actual.Should().Be(potentialFailure.Expected, $"for '{potentialFailure.Measure}', in scenario: {Scenario}"); throw new InvalidOperationException("Code should never reach here. Preceding assertion should fail."); } bool signaled = StatusChangedEvent.WaitOne(ShimTimeSpan); if (signaled) { // Following TraceableAction.CaptureCompletion() signalling the AutoResetEvent, // there can be race conditions between on the one hand exiting the bulkhead semaphore (and potentially another execution gaining it), // and the assertion being verified here about those same facts. // If that race is lost by the real-world state change, and the AutoResetEvent signal occurred very close to timeoutTime, // there might not be a second chance. // We therefore permit another shim time for the condition to come good. permitted += CohesionTimeLimit; } } }
public async void TestSingleLargeDocumentPerformance() { // Test the performance of writing and reading a single large, complex document. // // CosmosDb emulator setup // - 1000 RU/s collection. // - Rate limiting. // // Current performance // - Write: 0.5sec // - Read: 0.9sec var store = await StartNebula(dbAccess => new LargeDocumentStore(dbAccess)); var document = JsonConvert.DeserializeObject <LargeDocument>(File.ReadAllText("TestData/LargeDocument.json")); document.Id = Guid.NewGuid(); Stopwatch sw = new Stopwatch(); sw.Start(); await store.UpsertDocument(document); TestOutputHelper.WriteLine("Write={0}", sw.Elapsed); sw.Restart(); var result = await store.GetLargeDocument(document.Id); TestOutputHelper.WriteLine("Read={0}", sw.Elapsed); Assert.NotNull(result); }
public void WriteLine(string outputText, string expected) { var output = new TestOutputHelper(); var messageBus = new SpyMessageBus(); var test = Substitute.For <_ITest>(); test.UniqueID.Returns("test-id"); test.TestCase.UniqueID.Returns("case-id"); test.TestCase.TestMethod.UniqueID.Returns("method-id"); test.TestCase.TestMethod.TestClass.UniqueID.Returns("class-id"); test.TestCase.TestMethod.TestClass.TestCollection.UniqueID.Returns("coll-id"); test.TestCase.TestMethod.TestClass.TestCollection.TestAssembly.UniqueID.Returns("asm-id"); output.Initialize(messageBus, test); output.WriteLine(outputText); var message = Assert.Single(messageBus.Messages); var outputMessage = Assert.IsType <_TestOutput>(message); Assert.Equal("asm-id", outputMessage.AssemblyUniqueID); Assert.Equal(expected + Environment.NewLine, outputMessage.Output); Assert.Equal("case-id", outputMessage.TestCaseUniqueID); Assert.Equal("class-id", outputMessage.TestClassUniqueID); Assert.Equal("coll-id", outputMessage.TestCollectionUniqueID); Assert.Equal("method-id", outputMessage.TestMethodUniqueID); Assert.Equal("test-id", outputMessage.TestUniqueID); Assert.Equal(expected + Environment.NewLine, output.Output); }
/// <summary> /// Verifies if a set of packages in the feed have timestamps in a particular order. /// </summary> /// <param name="packageIds">An ordered list of package ids. Each package id in the list must have a timestamp in the feed earlier than all package ids after it.</param> /// <param name="timestampPropertyName">The timestamp property to test the ordering of. For example, "Created" or "LastEdited".</param> /// <param name="operationStartTimestamp">A timestamp that is before all of the timestamps expected to be found in the feed. This is used in a request to the feed.</param> private async Task CheckPackageTimestampsInOrder( IEnumerable <string> packageIds, string timestampPropertyName, DateTime operationStartTimestamp, string version) { var lastTimestamp = DateTime.MinValue; var lastPackageId = string.Empty; foreach (var packageId in packageIds) { TestOutputHelper.WriteLine($"Attempting to check order of package {packageId} {version} {timestampPropertyName} timestamp in feed."); var newTimestamp = await _odataHelper.GetTimestampOfPackageFromResponse( packageId, version, timestampPropertyName); Assert.True(newTimestamp.HasValue); Assert.True(newTimestamp.Value >= lastTimestamp, $"Package {packageId} was last modified after package {lastPackageId} but has an earlier {timestampPropertyName} timestamp ({newTimestamp} should be greater than {lastTimestamp})."); lastTimestamp = newTimestamp.Value; lastPackageId = packageId; } }
private async Task <HttpStatusCode> PushAsync( HttpClient client, string packagePath, Barrier barrier) { using (var package = File.OpenRead(packagePath)) using (var request = new HttpRequestMessage(HttpMethod.Put, UrlHelper.V2FeedPushSourceUrl)) { request.Content = new StreamContent(new BarrierStream(package, barrier)); request.Headers.Add("X-NuGet-ApiKey", EnvironmentSettings.TestAccountApiKey); using (var response = await client.SendAsync(request)) { if (response.StatusCode != HttpStatusCode.Created && response.StatusCode != HttpStatusCode.Conflict) { var content = await response.Content.ReadAsStringAsync(); TestOutputHelper.WriteLine($"HTTP {(int)response.StatusCode} {response.ReasonPhrase}{Environment.NewLine}{content}"); } return(response.StatusCode); } } }
public async Task Current_ShouldReceiveCurrent() { using var client = CreateClient(); var nonSubs = new List <CalledBase> { client.OnTrade.SubscribeCalled(), client.OnVolume.SubscribeCalled() }; var subscribe = client.OnCurrent.SubscribeCalled(c => { TestOutputHelper.WriteLine(c.ToString()); }); await client.StartAsync(); var sub = new CurrentSubscription("Bitfinex", "BTC", "USD"); _ = client.Subscribe(sub); await subscribe.AssertAtLeastOnceAsync(TimeSpan.FromMilliseconds(500)); nonSubs.ForEach(s => s.AssertNever()); _ = client.Unsubscribe(sub); }
public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter) { if (eventId.Id == 6) { TestOutputHelper.WriteLine(formatter(state, exception)); } }
public void TestPunHelper(string theme, PunCategory category) { var synSets = WordNetEngine.GetSynSets(theme).ToList(); var puns = PunHelper.GetPuns( category, theme, synSets, WordNetEngine, PronunciationEngine, SpellingEngine, PunStrategyFactory.AllFactories ) .ToList(); puns.Should().HaveCountGreaterThan(2); TestOutputHelper.WriteLine(puns.Count + " puns"); foreach (var(newPhrase, oldPhrase) in puns.Select(x => (x.NewPhrase, x.OldPhrase)) .Distinct()) { TestOutputHelper.WriteLine($"{newPhrase} ({oldPhrase})"); } }
public void TitleDoesNotContainPage() { var vm = new ReactivePageViewModel(TestOutputHelper); TestOutputHelper.WriteLine(vm.Title); Assert.Equal("Reactive", vm.Title); }
public void TitleIsSetToTypeName() { var vm = new ReactiveViewModelMock(TestOutputHelper); TestOutputHelper.WriteLine(vm.Title); Assert.Equal(nameof(ReactiveViewModelMock).Humanize(LetterCasing.Title), vm.Title); }
public async Task RunSCLFromFile(string path) { var scl = await File.ReadAllTextAsync(path); TestOutputHelper.WriteLine(scl); var sfs = StepFactoryStore.Create(); var stepResult = SCLParsing.TryParseStep(scl) .Bind(x => x.TryFreeze(TypeReference.Any.Instance, sfs)); if (stepResult.IsFailure) { throw new XunitException( string.Join( ", ", stepResult.Error.GetAllErrors() .Select(x => x.Message + " " + x.Location.AsString()) ) ); } var monad = new StateMonad( TestOutputHelper.BuildLogger(), SCLSettings.EmptySettings, sfs, ExternalContext.Default, new Dictionary <string, object>() ); var r = await stepResult.Value.Run <Unit>(monad, CancellationToken.None); r.ShouldBeSuccessful(); }
public async Task InitializeAsync() { var logger = new TestLogger(); try { // Restore the Analyzer packages that have been added to `for_analyzer_formatter/analyzer_project/analyzer_project.csproj` var exitCode = await DotNetHelper.PerformRestore(s_analyzerProjectFilePath, TestOutputHelper); Assert.Equal(0, exitCode); // Load the analyzer_project into a MSBuildWorkspace. var workspacePath = Path.Combine(TestProjectsPathHelper.GetProjectsDirectory(), s_analyzerProjectFilePath); MSBuildRegistrar.RegisterInstance(); var analyzerWorkspace = await MSBuildWorkspaceLoader.LoadAsync(workspacePath, WorkspaceType.Project, binaryLogPath : null, logWorkspaceWarnings : true, logger, CancellationToken.None); TestOutputHelper.WriteLine(logger.GetLog()); // From this project we can get valid AnalyzerReferences to add to our test project. _analyzerReferencesProject = analyzerWorkspace.CurrentSolution.Projects.Single(); } catch { TestOutputHelper.WriteLine(logger.GetLog()); throw; } }
private bool CheckPackageExistInCuratedFeed(string packageName, FeedType feedType) { string curatedFeedUrl = GetCuratedFeedUrl(feedType); var maxAttempts = 10; var interval = 30; bool applied = false; TestOutputHelper.WriteLine("Starting package verification checks ({0} attempts, interval {1} seconds).", maxAttempts, interval); for (int i = 0; i < maxAttempts && applied == false; i++) { TestOutputHelper.WriteLine("[verification attempt {0}]: Waiting {1} seconds before next check...", i, interval); if (i != 0) { Thread.Sleep(interval * 1000); } else { Thread.Sleep(5000); } if (_clientSdkHelper.CheckIfPackageExistsInSource(packageName, curatedFeedUrl)) { applied = true; } } return(applied); }
public async Task LockedPackageCannotBeModified() { // Arrange string version = "2.0.0"; var packageCreationHelper = new PackageCreationHelper(TestOutputHelper); var location = await packageCreationHelper.CreatePackage(LockedPackageId, version); // Act & Assert // 1. Try to upload package TestOutputHelper.WriteLine($"1. Trying to upload package '{LockedPackageId}', version '{version}' to locked package id."); var processResult = await _commandlineHelper.UploadPackageAsync(location, UrlHelper.V2FeedPushSourceUrl); Assert.True(processResult.ExitCode != 0, "Package push succeeded, although was expected to fail."); Assert.Contains("locked", processResult.StandardError); // 2. Try unlisting the locked package // Perform a sanity check that the package exists await _clientSdkHelper.VerifyPackageExistsInV2Async(LockedPackageId, LockedPackageVersion); TestOutputHelper.WriteLine($"5. Trying to unlist locked package '{LockedPackageId}', version '{LockedPackageVersion}'."); processResult = await _commandlineHelper.DeletePackageAsync(LockedPackageId, LockedPackageVersion, UrlHelper.V2FeedPushSourceUrl); Assert.True(processResult.ExitCode != 0, "Package delete succeeded, although was expected to fail."); Assert.Contains("locked", processResult.StandardError); }
private protected async Task <SourceText> AssertCodeChangedAsync( string testCode, string expectedCode, string editorConfig, Encoding?encoding = null, FixCategory fixCategory = FixCategory.Whitespace, IEnumerable <AnalyzerReference>?analyzerReferences = null, DiagnosticSeverity codeStyleSeverity = DiagnosticSeverity.Error, DiagnosticSeverity analyzerSeverity = DiagnosticSeverity.Error, string[]?diagnostics = null) { var(formattedText, _, logger) = await ApplyFormatterAsync(testCode, editorConfig, encoding, fixCategory, analyzerReferences, codeStyleSeverity, analyzerSeverity, diagnostics); try { Assert.Equal(expectedCode, formattedText.ToString()); } catch { TestOutputHelper?.WriteLine(logger.GetLog()); throw; } return(formattedText); }
private protected async Task <SourceText> AssertNoReportedFileChangesAsync( string code, string editorConfig, Encoding?encoding = null, FixCategory fixCategory = FixCategory.Whitespace, IEnumerable <AnalyzerReference>?analyzerReferences = null, DiagnosticSeverity codeStyleSeverity = DiagnosticSeverity.Error, DiagnosticSeverity analyzerSeverity = DiagnosticSeverity.Error, string[]?diagnostics = null) { var(formattedText, formattedFiles, logger) = await ApplyFormatterAsync(code, editorConfig, encoding, fixCategory, analyzerReferences, codeStyleSeverity, analyzerSeverity, diagnostics); try { // Ensure the code is unchanged Assert.Equal(code, formattedText.ToString()); // Ensure no non-fixable diagnostics were reported Assert.Empty(formattedFiles); } catch { TestOutputHelper?.WriteLine(logger.GetLog()); throw; } return(formattedText); }
public void DisableWaitsForInFlightQueriesTest() { const int replicaInstance = 0; var replicaSet = GraphClusterLowLevel.GetGraphReplicaSetLowLevel("published"); Parallel.For(0, 100, async(i, state) => { TestOutputHelper.WriteLine($"Iteration {i} on thread #{Thread.CurrentThread.ManagedThreadId}"); if (i == 5) { TestOutputHelper.WriteLine($"Disabling replica #{replicaInstance}. Iteration #{i}. Thread #{Thread.CurrentThread.ManagedThreadId}"); TestOutputHelper.WriteLine("----------------------------->>>-------------------------------"); replicaSet.Disable(replicaInstance); TestOutputHelper.WriteLine("-----------------------------<<<-------------------------------"); TestOutputHelper.WriteLine($"Disabled replica #{replicaInstance}. Iteration #{i}. Thread #{Thread.CurrentThread.ManagedThreadId}"); } else { await replicaSet.Run(Query); } }); Trace(replicaSet); Thread.Sleep(2000); // what can we check?, we can't assume all Run()'s before the disabled were started // and we can't assume Run()'s from later iteration's weren't started // int enabledInstanceCount = replicaSet.EnabledInstanceCount; // Assert.Equal(NumberOfReplicasConfiguredForPublishedSet, enabledInstanceCount); Assert.True(true); }
public void TitleIsSetToSanitizedName() { var vm = new ReactiveMockViewModel(TestOutputHelper); TestOutputHelper.WriteLine(vm.Title); Assert.Equal("Reactive Mock", vm.Title); }
public string Handle(QuerySomethingWithException query) { base.Handle <QuerySomethingWithException, string>(query); TestOutputHelper.WriteLine($"Query result: {query.Data}."); throw new TestQueryHandlerException("This is a triggered post-processing exception."); }
public Task <string> HandleAsync(QuerySomething query, CancellationToken cancellationToken = default(CancellationToken)) { base.HandleAsync <QuerySomething, string>(query); TestOutputHelper.WriteLine($"Query result: {query.Data}."); return(Task.FromResult(query.Data)); }