public async Task DefaultAddressBinderBindsToHttpPort5000() { var logger = new MockLogger(); var addresses = new ServerAddressesFeature(); var services = new ServiceCollection(); services.AddLogging(); var options = new KestrelServerOptions() { ApplicationServices = services.BuildServiceProvider() }; var endpoints = new List <ListenOptions>(); var addressBindContext = TestContextFactory.CreateAddressBindContext( addresses, options, logger, listenOptions => { endpoints.Add(listenOptions); return(Task.CompletedTask); }); await AddressBinder.BindAsync(options.ListenOptions, addressBindContext, CancellationToken.None); Assert.Contains(endpoints, e => e.IPEndPoint.Port == 5000 && !e.IsTls); }
public TestInput(KestrelTrace log = null, ITimeoutControl timeoutControl = null) { _memoryPool = PinnedBlockMemoryPoolFactory.Create(); var options = new PipeOptions(pool: _memoryPool, readerScheduler: PipeScheduler.Inline, writerScheduler: PipeScheduler.Inline, useSynchronizationContext: false); var pair = DuplexPipe.CreateConnectionPair(options, options); Transport = pair.Transport; Application = pair.Application; var connectionFeatures = new FeatureCollection(); connectionFeatures.Set(Mock.Of <IConnectionLifetimeFeature>()); Http1ConnectionContext = TestContextFactory.CreateHttpConnectionContext( serviceContext: new TestServiceContext { Log = log ?? new KestrelTrace(NullLoggerFactory.Instance) }, connectionContext: Mock.Of <ConnectionContext>(), transport: Transport, timeoutControl: timeoutControl ?? Mock.Of <ITimeoutControl>(), memoryPool: _memoryPool, connectionFeatures: connectionFeatures); Http1Connection = new Http1Connection(Http1ConnectionContext); Http1Connection.HttpResponseControl = Mock.Of <IHttpResponseControl>(); Http1Connection.Reset(); }
public void LogsInformationWhenKestrelAddressesAreOverridden() { var logger = new TestApplicationErrorLogger(); var overriddenAddress = "http://localhost:5000"; var addresses = new ServerAddressesFeature(); addresses.InternalCollection.Add(overriddenAddress); var options = new KestrelServerOptions(); options.ListenAnyIP(8080); var addressBindContext = TestContextFactory.CreateAddressBindContext( addresses, options, logger, endpoint => Task.CompletedTask); addressBindContext.ServerAddressesFeature.PreferHostingUrls = true; var bindTask = AddressBinder.BindAsync(options.ListenOptions, addressBindContext, CancellationToken.None); Assert.True(bindTask.IsCompletedSuccessfully); var log = Assert.Single(logger.Messages); Assert.Equal(LogLevel.Information, log.LogLevel); Assert.Equal(CoreStrings.FormatOverridingWithPreferHostingUrls(nameof(addressBindContext.ServerAddressesFeature.PreferHostingUrls), overriddenAddress), log.Message); }
public override void Initialize(TestContext context, MethodInfo methodInfo, object[] testMethodArguments, ITestOutputHelper testOutputHelper) { base.Initialize(context, methodInfo, testMethodArguments, testOutputHelper); _pipelineFactory = PinnedBlockMemoryPoolFactory.Create(); var options = new PipeOptions(_pipelineFactory, readerScheduler: PipeScheduler.Inline, writerScheduler: PipeScheduler.Inline, useSynchronizationContext: false); var pair = DuplexPipe.CreateConnectionPair(options, options); _transport = pair.Transport; _application = pair.Application; var connectionFeatures = new FeatureCollection(); connectionFeatures.Set(Mock.Of <IConnectionLifetimeFeature>()); _serviceContext = new TestServiceContext(LoggerFactory) { Scheduler = PipeScheduler.Inline }; _timeoutControl = new Mock <ITimeoutControl>(); _http1ConnectionContext = TestContextFactory.CreateHttpConnectionContext( serviceContext: _serviceContext, connectionContext: Mock.Of <ConnectionContext>(), transport: pair.Transport, timeoutControl: _timeoutControl.Object, memoryPool: _pipelineFactory, connectionFeatures: connectionFeatures); _http1Connection = new TestHttp1Connection(_http1ConnectionContext); }
public virtual void GlobalSetup() { _memoryPool = SlabMemoryPoolFactory.Create(); _httpFrame = new Http2Frame(); var options = new PipeOptions(_memoryPool, readerScheduler: PipeScheduler.Inline, writerScheduler: PipeScheduler.Inline, useSynchronizationContext: false); _connectionPair = DuplexPipe.CreateConnectionPair(options, options); _httpRequestHeaders = new HttpRequestHeaders(); _httpRequestHeaders.HeaderMethod = new StringValues("GET"); _httpRequestHeaders.HeaderPath = new StringValues("/"); _httpRequestHeaders.HeaderScheme = new StringValues("http"); _httpRequestHeaders.HeaderAuthority = new StringValues("localhost:80"); _headersBuffer = new byte[1024 * 16]; _hpackEncoder = new HPackEncoder(); var serviceContext = TestContextFactory.CreateServiceContext( serverOptions: new KestrelServerOptions(), dateHeaderValueManager: new DateHeaderValueManager(), systemClock: new MockSystemClock(), log: new MockTrace()); serviceContext.DateHeaderValueManager.OnHeartbeat(default);
public StartLineTests() { MemoryPool = PinnedBlockMemoryPoolFactory.Create(); var options = new PipeOptions(MemoryPool, readerScheduler: PipeScheduler.Inline, writerScheduler: PipeScheduler.Inline, useSynchronizationContext: false); var pair = DuplexPipe.CreateConnectionPair(options, options); Transport = pair.Transport; var serviceContext = TestContextFactory.CreateServiceContext( serverOptions: new KestrelServerOptions(), httpParser: new HttpParser <Http1ParsingHandler>()); var connectionContext = TestContextFactory.CreateHttpConnectionContext( serviceContext: serviceContext, connectionContext: Mock.Of <ConnectionContext>(), transport: Transport, timeoutControl: new TimeoutControl(timeoutHandler: null), memoryPool: MemoryPool, connectionFeatures: new FeatureCollection()); Http1Connection = new Http1Connection(connectionContext); Parser = new HttpParser <Http1ParsingHandler>(showErrorDetails: true); ParsingHandler = new Http1ParsingHandler(Http1Connection); }
public HttpProtocolFeatureCollection() { var memoryPool = SlabMemoryPoolFactory.Create(); var options = new PipeOptions(memoryPool, readerScheduler: PipeScheduler.Inline, writerScheduler: PipeScheduler.Inline, useSynchronizationContext: false); var pair = DuplexPipe.CreateConnectionPair(options, options); var serviceContext = TestContextFactory.CreateServiceContext( serverOptions: new KestrelServerOptions(), httpParser: new HttpParser <Http1ParsingHandler>(), dateHeaderValueManager: new DateHeaderValueManager(), log: new MockTrace()); var connectionContext = TestContextFactory.CreateHttpConnectionContext( serviceContext: serviceContext, connectionContext: null, transport: pair.Transport, memoryPool: memoryPool, connectionFeatures: new FeatureCollection()); var http1Connection = new Http1Connection(connectionContext); http1Connection.Reset(); _collection = http1Connection; }
public async Task WriteDataRateTimeoutAbortsConnection() { var mockConnectionContext = new Mock <ConnectionContext>(); var httpConnectionContext = TestContextFactory.CreateHttpConnectionContext( serviceContext: new TestServiceContext(), connectionContext: mockConnectionContext.Object, connectionFeatures: new FeatureCollection(), transport: new DuplexPipe(Mock.Of <PipeReader>(), Mock.Of <PipeWriter>())); var httpConnection = new HttpConnection(httpConnectionContext); var aborted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var http1Connection = new Http1Connection(httpConnectionContext); httpConnection.Initialize(http1Connection); http1Connection.Reset(); http1Connection.RequestAborted.Register(() => { aborted.SetResult(); }); httpConnection.OnTimeout(TimeoutReason.WriteDataRate); mockConnectionContext .Verify(c => c.Abort(It.Is <ConnectionAbortedException>(ex => ex.Message == CoreStrings.ConnectionTimedBecauseResponseMininumDataRateNotSatisfied)), Times.Once); await aborted.Task.DefaultTimeout(); }
private TestHttp1Connection MakeHttp1Connection() { var options = new PipeOptions(_memoryPool, useSynchronizationContext: false); var pair = DuplexPipe.CreateConnectionPair(options, options); _pair = pair; var serviceContext = TestContextFactory.CreateServiceContext( serverOptions: new KestrelServerOptions(), httpParser: new HttpParser <Http1ParsingHandler>(), dateHeaderValueManager: new DateHeaderValueManager()); var connectionContext = TestContextFactory.CreateHttpConnectionContext( serviceContext: serviceContext, connectionContext: null, transport: pair.Transport, timeoutControl: new TimeoutControl(timeoutHandler: null), memoryPool: _memoryPool, connectionFeatures: new FeatureCollection()); var http1Connection = new TestHttp1Connection(connectionContext); http1Connection.Reset(); http1Connection.InitializeBodyControl(MessageBody.ZeroContentLengthKeepAlive); serviceContext.DateHeaderValueManager.OnHeartbeat(DateTimeOffset.UtcNow); return(http1Connection); }
public void GlobalSetup() { _memoryPool = PinnedBlockMemoryPoolFactory.Create(); var options = new PipeOptions(_memoryPool, readerScheduler: PipeScheduler.Inline, writerScheduler: PipeScheduler.Inline, useSynchronizationContext: false); _pipe = new Pipe(options); var serviceContext = TestContextFactory.CreateServiceContext( serverOptions: new KestrelServerOptions(), httpParser: new HttpParser <Http1ParsingHandler>(), dateHeaderValueManager: new DateHeaderValueManager()); _frameWriter = new Http2FrameWriter( new NullPipeWriter(), connectionContext: null, http2Connection: null, maxStreamsPerConnection: 1, timeoutControl: null, minResponseDataRate: null, "TestConnectionId", _memoryPool, serviceContext); _responseHeaders = new HttpResponseHeaders(); var headers = (IHeaderDictionary)_responseHeaders; headers.ContentType = "application/json"; headers.ContentLength = 1024; }
public void GlobalSetup() { _memoryPool = SlabMemoryPoolFactory.Create(); var options = new PipeOptions(_memoryPool, readerScheduler: PipeScheduler.Inline, writerScheduler: PipeScheduler.Inline, useSynchronizationContext: false); _pipe = new Pipe(options); var serviceContext = TestContextFactory.CreateServiceContext( serverOptions: new KestrelServerOptions(), httpParser: new HttpParser <Http1ParsingHandler>(), dateHeaderValueManager: new DateHeaderValueManager(), log: new MockTrace()); _frameWriter = new Http2FrameWriter( new NullPipeWriter(), connectionContext: null, http2Connection: null, new OutputFlowControl(new SingleAwaitableProvider(), initialWindowSize: int.MaxValue), timeoutControl: null, minResponseDataRate: null, "TestConnectionId", _memoryPool, serviceContext); _responseHeaders = new HttpResponseHeaders(); _responseHeaders.HeaderContentType = "application/json"; _responseHeaders.HeaderContentLength = "1024"; }
public void Setup() { _memoryPool = PinnedBlockMemoryPoolFactory.Create(); var options = new PipeOptions(_memoryPool, readerScheduler: PipeScheduler.Inline, writerScheduler: PipeScheduler.Inline, useSynchronizationContext: false); var pair = DuplexPipe.CreateConnectionPair(options, options); var serviceContext = TestContextFactory.CreateServiceContext( serverOptions: new KestrelServerOptions(), httpParser: new HttpParser <Http1ParsingHandler>(), dateHeaderValueManager: new DateHeaderValueManager(), log: new MockTrace()); var connectionContext = TestContextFactory.CreateHttpConnectionContext( serviceContext: serviceContext, connectionContext: null, transport: pair.Transport, memoryPool: _memoryPool, connectionFeatures: new FeatureCollection(), timeoutControl: new TimeoutControl(timeoutHandler: null)); var http1Connection = new Http1Connection(connectionContext); http1Connection.Reset(); Http1Connection = http1Connection; Pipe = new Pipe(new PipeOptions(_memoryPool)); }
public void SetUp() { testContext = TestContextFactory.Get(opts => opts .UseEntryAssembly(typeof(WindsorRegistrationOptionsTestCase).Assembly) .RegisterTagHelpers(typeof(OverrideTagHelper).Assembly) .RegisterControllers(typeof(OverrideController).Assembly) .RegisterTagHelpers(typeof(OverrideViewComponent).Assembly)); }
public static void RunTests(KontrolRegistry registry, ITestReporter reporter, TestContextFactory contextFactory) { foreach (IKontrolModule module in registry.modules.Values) { RunTests(module, reporter, contextFactory); } }
public override void SetUp() { testContext = TestContextFactory.Get(opts => opts .UseEntryAssembly(typeof(WindsorRegistrationOptionsTestCase).Assembly) .RegisterTagHelpers(Component.For <OverrideTagHelper>().LifestyleScoped().Named("tag-helpers")) .RegisterControllers(Component.For <OverrideController>().LifestyleScoped().Named("controllers")) .RegisterViewComponents(Component.For <OverrideViewComponent>().LifestyleScoped().Named("view-components"))); }
public Http3HttpProtocolFeatureCollectionTests() { var streamContext = TestContextFactory.CreateHttp3StreamContext(transport: DuplexPipe.CreateConnectionPair(new PipeOptions(), new PipeOptions()).Application); var http3Stream = new TestHttp3Stream(streamContext); http3Stream.Reset(); _http3Collection = http3Stream; }
public TestContextFixture() { SourcePath = Path.Combine(Directory.GetCurrentDirectory(), SOURCE_DIRECTORY); CompilationUnitFactory = new TestCompilationUnitFactory(); DataProvider = new TestDataProvider(Path.Combine(SourcePath, COMPILER_TESTS_FILE_NAME)); TestContextFactory = new TestContextFactory(SourcePath, DataProvider); FileComparer = new IgnoredCharactersStringComparer("\r\n"); }
public void Setup() { var memoryPool = PinnedBlockMemoryPoolFactory.Create(); var options = new PipeOptions(memoryPool, readerScheduler: PipeScheduler.Inline, writerScheduler: PipeScheduler.Inline, useSynchronizationContext: false); var pair = DuplexPipe.CreateConnectionPair(options, options); var serviceContext = TestContextFactory.CreateServiceContext( serverOptions: new KestrelServerOptions(), httpParser: new HttpParser <Http1ParsingHandler>(), dateHeaderValueManager: _dateHeaderValueManager, log: new MockTrace()); var connectionContext = TestContextFactory.CreateHttpConnectionContext( serviceContext: serviceContext, connectionContext: null, transport: pair.Transport, memoryPool: memoryPool, connectionFeatures: new FeatureCollection()); var http1Connection = new Http1Connection(connectionContext); http1Connection.Reset(); serviceContext.DateHeaderValueManager.OnHeartbeat(DateTimeOffset.UtcNow); _responseHeadersDirect = (HttpResponseHeaders)http1Connection.ResponseHeaders; var context = new DefaultHttpContext(http1Connection); _response = context.Response; switch (Type) { case BenchmarkTypes.ContentLengthNumeric: SetContentLengthNumeric(1); GetContentLengthNumeric(1); break; case BenchmarkTypes.ContentLengthString: SetContentLengthString(1); GetContentLengthString(1); break; case BenchmarkTypes.Plaintext: SetPlaintext(1); GetPlaintext(1); break; case BenchmarkTypes.Common: SetCommon(1); GetCommon(1); break; case BenchmarkTypes.Unknown: SetUnknown(1); GetUnknown(1); break; } }
public static TestResult RunTest(IKontrolModule module, IKontrolFunction testFunction, TestContextFactory contextFactory) { TestRunnerContext testContext = contextFactory(); try { testContext.ResetTimeout(); object testReturn = testFunction.Invoke(testContext); switch (testReturn) { case bool booleanResult when !booleanResult: return(new TestResult(module.Name + "::" + testFunction.Name, testContext.AssertionsCount, "Returned false", testContext.Messages)); case IAnyOption option when !option.Defined: return(new TestResult(module.Name + "::" + testFunction.Name, testContext.AssertionsCount, "Returned None", testContext.Messages)); case IAnyResult result when !result.Success: return(new TestResult(module.Name + "::" + testFunction.Name, testContext.AssertionsCount, $"Returned Err({result.ErrorString})", testContext.Messages)); case IAnyFuture future: ContextHolder.CurrentContext.Value = testContext; for (int i = 0; i < 100; i++) { testContext.IncrYield(); testContext.ResetTimeout(); IAnyFutureResult result = future.Poll(); if (result.IsReady) { return(new TestResult(module.Name + "::" + testFunction.Name, testContext.AssertionsCount, testContext.Messages)); } } return(new TestResult(module.Name + "::" + testFunction.Name, testContext.AssertionsCount, "Future did not become ready", testContext.Messages)); default: return(new TestResult(module.Name + "::" + testFunction.Name, testContext.AssertionsCount, testContext.Messages)); } } catch (AssertException e) { return(new TestResult(module.Name + "::" + testFunction.Name, testContext.AssertionsCount, e.Message, testContext.Messages)); } catch (Exception e) { Console.Error.WriteLine(e); return(new TestResult(module.Name + "::" + testFunction.Name, testContext.AssertionsCount, e, testContext.Messages)); } finally { ContextHolder.CurrentContext.Value = null; } }
public Http2HttpProtocolFeatureCollectionTests() { var context = TestContextFactory.CreateHttp2StreamContext( serviceContext: new TestServiceContext(), timeoutControl: Mock.Of <ITimeoutControl>()); var http2Stream = new TestHttp2Stream(context); http2Stream.Reset(); _http2Collection = http2Stream; }
// Create test data and pass repositories to access it in callback private void RunTest(Action <RepositoryEnq> test = null , Action <RepositoryEnq, RepositoryEnq> testMulti = null) { using var factory = new TestContextFactory(_data); using var context = factory.GetContext(); var repo = new RepositoryEnq(context); test?.Invoke(repo); testMulti?.Invoke(repo, new RepositoryEnq(context)); }
private async Task RunTestAsync(Func <RepositoryEnq, Task> test = null , Func <RepositoryEnq, RepositoryEnq, Task> testMulti = null) { using var factory = new TestContextFactory(_data); await using var context = factory.GetContext(); RepositoryEnq repo = new RepositoryEnq(context); await(test?.Invoke(repo) ?? Task.CompletedTask); await(testMulti?.Invoke(repo, new RepositoryEnq(context)) ?? Task.CompletedTask); }
public Http3HttpProtocolFeatureCollectionTests() { var connectionFeatures = new TestConnectionFeatures().FeatureCollection; var streamContext = TestContextFactory.CreateHttp3StreamContext( transport: DuplexPipe.CreateConnectionPair(new PipeOptions(), new PipeOptions()).Application, connectionFeatures: connectionFeatures); var http3Stream = new TestHttp3Stream(); http3Stream.Initialize(streamContext); _http3Collection = http3Stream; }
public Http1HttpProtocolFeatureCollectionTests() { var context = TestContextFactory.CreateHttpConnectionContext( connectionContext: Mock.Of <ConnectionContext>(), serviceContext: new TestServiceContext(), transport: Mock.Of <IDuplexPipe>(), connectionFeatures: new FeatureCollection(), timeoutControl: Mock.Of <ITimeoutControl>()); _httpConnectionContext = context; _http1Connection = new TestHttp1Connection(context); _http1Connection.Reset(); _collection = _http1Connection; }
public void TestInit() { this._contextFactory = new TestContextFactory(_connection); var node = new Uri(ConfigurationManager.AppSettings["Search-Uri"]); var settings = new ConnectionSettings(node); settings.ThrowExceptions(alwaysThrow: true); settings.PrettyJson(true); settings.DisableDirectStreaming(); var client = new ElasticClient(settings); this._service = new SearchService(client, _contextFactory); }
public static void RunTests(IKontrolModule module, ITestReporter reporter, TestContextFactory contextFactory) { if (!module.TestFunctions.Any()) { return; } reporter.BeginModule(module.Name); foreach (IKontrolFunction testFunction in module.TestFunctions) { reporter.Report(RunTest(module, testFunction, contextFactory)); } reporter.EndModule(module.Name); }
public async Task WrapsAddressInUseExceptionAsIOException() { var addresses = new ServerAddressesFeature(); addresses.InternalCollection.Add("http://localhost:5000"); var options = new KestrelServerOptions(); var addressBindContext = TestContextFactory.CreateAddressBindContext( addresses, options, NullLogger.Instance, endpoint => throw new AddressInUseException("already in use")); await Assert.ThrowsAsync <IOException>(() => AddressBinder.BindAsync(options.ListenOptions, addressBindContext, CancellationToken.None)); }
public static WebTransportStream CreateStream(WebTransportStreamType type, Memory <byte>?memory = null) { var features = new FeatureCollection(); features.Set <IStreamIdFeature>(new StreamId(streamCounter++)); features.Set <IStreamDirectionFeature>(new DefaultStreamDirectionFeature(type != WebTransportStreamType.Output, type != WebTransportStreamType.Input)); features.Set(Mock.Of <IConnectionItemsFeature>()); features.Set(Mock.Of <IProtocolErrorCodeFeature>()); var writer = new HttpResponsePipeWriter(new StreamWriterControl(memory)); writer.StartAcceptingWrites(); var transport = new DuplexPipe(new StreamReader(memory), writer); return(new WebTransportStream(TestContextFactory.CreateHttp3StreamContext("id", null, new TestServiceContext(), features, null, null, null, transport), type)); }
private LibuvOuputProcessor CreateOutputProducer(PipeOptions pipeOptions, CancellationTokenSource cts = null) { var pair = DuplexPipe.CreateConnectionPair(pipeOptions, pipeOptions); var logger = new TestApplicationErrorLogger(); var serviceContext = new TestServiceContext { Log = new TestKestrelTrace(logger), Scheduler = PipeScheduler.Inline }; var transportContext = new TestLibuvTransportContext { Log = new LibuvTrace(logger) }; var socket = new MockSocket(_mockLibuv, _libuvThread.Loop.ThreadId, transportContext.Log); var consumer = new LibuvOutputConsumer(pair.Application.Input, _libuvThread, socket, "0", transportContext.Log); var connectionFeatures = new FeatureCollection(); connectionFeatures.Set(Mock.Of <IConnectionLifetimeFeature>()); var connectionContext = TestContextFactory.CreateHttpConnectionContext( serviceContext: serviceContext, connectionContext: Mock.Of <ConnectionContext>(), transport: pair.Transport, memoryPool: _memoryPool, connectionFeatures: connectionFeatures, timeoutControl: Mock.Of <ITimeoutControl>()); var http1Connection = new Http1Connection(connectionContext); if (cts != null) { http1Connection.RequestAborted.Register(cts.Cancel); } var outputTask = WriteOutputAsync(consumer, pair.Application.Input, http1Connection); var processor = new LibuvOuputProcessor { ProcessingTask = outputTask, OutputProducer = (Http1OutputProducer)http1Connection.Output, PipeWriter = pair.Transport.Output, }; return(processor); }
public async Task StartAsync(CancellationToken cancellationToken) { _logger.LogInformation("App Start at: {time}", DateTimeOffset.Now); var contextFactory = new TestContextFactory { Configuration = _configuration }; await using (var dbContext = contextFactory.CreateDbContext(Array.Empty <string>())) { var db = dbContext.Database; await db.MigrateAsync(cancellationToken : cancellationToken); } _appLifetime.StopApplication(); }