private void RebuildSchemaFirstTime(TestDbMeta meta) { var dbFactory = _dbFactoryProvider.Create(); dbFactory.Configure(meta.ToStronglyTypedConnectionString()); using var database = (UmbracoDatabase)dbFactory.CreateDatabase(); database.LogCommands = true; using NPoco.ITransaction transaction = database.GetTransaction(); var options = new TestOptionsMonitor <InstallDefaultDataSettings>(new InstallDefaultDataSettings { InstallData = InstallDefaultDataOption.All }); var schemaCreator = new DatabaseSchemaCreator( database, _loggerFactory.CreateLogger <DatabaseSchemaCreator>(), _loggerFactory, new UmbracoVersion(), Mock.Of <IEventAggregator>(), options); schemaCreator.InitializeDatabaseSchema(); transaction.Complete(); _cachedDatabaseInitCommands = database.Commands .Where(x => !x.Text.StartsWith("SELECT ", StringComparison.OrdinalIgnoreCase)) .ToArray(); }
public void Returns_ConfiguredServices() { var services = new List <ConfigurationServiceInstance> { new ConfigurationServiceInstance { ServiceId = "fruitService", Host = "fruitball", Port = 443, IsSecure = true }, new ConfigurationServiceInstance { ServiceId = "fruitService", Host = "fruitballer", Port = 8081 }, new ConfigurationServiceInstance { ServiceId = "fruitService", Host = "fruitballerz", Port = 8082 }, new ConfigurationServiceInstance { ServiceId = "vegetableService", Host = "vegemite", Port = 443, IsSecure = true }, new ConfigurationServiceInstance { ServiceId = "vegetableService", Host = "carrot", Port = 8081 }, new ConfigurationServiceInstance { ServiceId = "vegetableService", Host = "beet", Port = 8082 }, }; var serviceOptions = new TestOptionsMonitor <List <ConfigurationServiceInstance> >(services); var provider = new ConfigurationServiceInstanceProvider(serviceOptions); Assert.Equal(3, provider.GetInstances("fruitService").Count); Assert.Equal(3, provider.GetInstances("vegetableService").Count); Assert.Equal(2, provider.Services.Count); }
public void ProviderReloadWillReloadProperly() { string testFlagName = nameof(testFlagName); var originalFlag = new FeatureFlag(testFlagName, false); var featureFlagOptions = new FeatureFlagOption() { { testFlagName, originalFlag } }; string otherTestFlagName = nameof(otherTestFlagName); var otherFlag = new FeatureFlag(otherTestFlagName, false); var otherFeatureFlagOptions = new FeatureFlagOption() { { testFlagName, otherFlag } }; var optionsMonitor = new TestOptionsMonitor(featureFlagOptions); var provider = new ConfigurationFeatureFlagProvider(optionsMonitor); var originalFlags = provider.GetFlags(); optionsMonitor.Set(otherFeatureFlagOptions); var otherFlags = provider.GetFlags(); Assert.Single(originalFlags); Assert.NotNull(originalFlags.FirstOrDefault()); Assert.Equal(testFlagName, originalFlags.FirstOrDefault().Name); Assert.Single(otherFlags); Assert.NotNull(otherFlags.FirstOrDefault()); Assert.Equal(otherTestFlagName, otherFlags.FirstOrDefault().Name); }
public DiagnosticLoggerTests() { _environment.SetEnvironmentVariable(EnvironmentSettingNames.AzureWebsiteOwnerName, $"{_subscriptionId}+westuswebspace"); _environment.SetEnvironmentVariable(EnvironmentSettingNames.AzureWebsiteHostName, _websiteHostName); _environment.SetEnvironmentVariable(EnvironmentSettingNames.RegionName, _regionName); _environment.SetEnvironmentVariable(EnvironmentSettingNames.AzureWebsiteInstanceId, _roleInstance); _mockEventGenerator = new Mock <IEventGenerator>(MockBehavior.Strict); var appServiceOptions = new AppServiceOptions { AppName = "TestApp", SlotName = "Production", SubscriptionId = "abc123", RuntimeSiteName = "TestApp_Runtime" }; _appServiceOptionsWrapper = new TestOptionsMonitor <AppServiceOptions>(appServiceOptions); _category = LogCategories.CreateFunctionCategory(_functionName); var loggerProvider = new TestLoggerProvider(); var loggerFactory = new LoggerFactory(); loggerFactory.AddProvider(loggerProvider); _hostNameProvider = new HostNameProvider(_environment); _logger = new AzureMonitorDiagnosticLogger(_category, _hostInstanceId, _mockEventGenerator.Object, _environment, new LoggerExternalScopeProvider(), _hostNameProvider, _appServiceOptionsWrapper); }
public async Task DoesNotPublishExecutionActivityInStandbyMode() { var activity = new ContainerFunctionExecutionActivity(DateTime.MinValue, "func-1", ExecutionStage.InProgress, "trigger-1", false); var environment = new TestEnvironment(); environment.SetEnvironmentVariable(EnvironmentSettingNames.AzureWebsitePlaceholderMode, "1"); environment.SetEnvironmentVariable(EnvironmentSettingNames.ContainerName, "Container-Name"); var meshClient = new Mock <IMeshServiceClient>(); var standbyOptions = new TestOptionsMonitor <StandbyOptions>(new StandbyOptions { InStandbyMode = true }); using (var publisher = new LinuxContainerActivityPublisher(standbyOptions, meshClient.Object, environment, NullLogger <LinuxContainerActivityPublisher> .Instance, FlushIntervalMs)) { await publisher.StartAsync(CancellationToken.None); publisher.PublishFunctionExecutionActivity(activity); await Task.Delay(DelayIntervalMs); await publisher.StopAsync(CancellationToken.None); meshClient.Verify(c => c.PublishContainerActivity(It.IsAny <IEnumerable <ContainerFunctionExecutionActivity> >()), Times.Never); } }
public void InitializingPublisherThrowsExceptionForNonLinuxConsumptionApps() { var environment = new TestEnvironment(); environment.SetEnvironmentVariable(EnvironmentSettingNames.AzureWebsitePlaceholderMode, "1"); environment.SetEnvironmentVariable(EnvironmentSettingNames.ContainerName, string.Empty); var meshClient = new Mock <IMeshServiceClient>(); var standbyOptions = new TestOptionsMonitor <StandbyOptions>(new StandbyOptions { InStandbyMode = false }); var failsWithExpectedException = false; try { using (var publisher = new LinuxContainerActivityPublisher(standbyOptions, meshClient.Object, environment, NullLogger <LinuxContainerActivityPublisher> .Instance, FlushIntervalMs)) { } } catch (Exception e) { failsWithExpectedException = e is NotSupportedException && string.Equals(e.Message, $"{nameof(LinuxContainerActivityPublisher)} is available in Linux consumption environment only"); } Assert.True(failsWithExpectedException); }
public async Task PublishesFunctionExecutionActivity() { var activity = new ContainerFunctionExecutionActivity(DateTime.MinValue, "func-1", ExecutionStage.InProgress, "trigger-1", false); var environment = new TestEnvironment(); environment.SetEnvironmentVariable(EnvironmentSettingNames.ContainerName, "Container-Name"); var meshClient = new Mock <IMeshServiceClient>(); meshClient.Setup(c => c.PublishContainerActivity( It.IsAny <IEnumerable <ContainerFunctionExecutionActivity> >())).Returns(Task.FromResult(true)); var standbyOptions = new TestOptionsMonitor <StandbyOptions>(new StandbyOptions { InStandbyMode = false }); using (var publisher = new LinuxContainerActivityPublisher(standbyOptions, meshClient.Object, environment, NullLogger <LinuxContainerActivityPublisher> .Instance, FlushIntervalMs)) { await publisher.StartAsync(CancellationToken.None); publisher.PublishFunctionExecutionActivity(activity); await Task.Delay(DelayIntervalMs); await publisher.StopAsync(CancellationToken.None); meshClient.Verify( c => c.PublishContainerActivity( It.Is <IEnumerable <ContainerFunctionExecutionActivity> >(e => MatchesFunctionActivities(e, activity))), Times.Once); } }
public void GetInstances_ShouldBeAbleToHandleEndpointsFromMultipleNamespaces() { // arrange var mockHttpMessageHandler = new MockHttpMessageHandler(); mockHttpMessageHandler.Expect(HttpMethod.Get, "/api/v1/endpoints?fieldSelector=metadata.name%3Dendpoint") .Respond( HttpStatusCode.OK, new StringContent("{\"apiVersion\":\"v1\",\"items\":[{\"apiVersion\":\"v1\",\"kind\":\"Endpoints\",\"metadata\":{\"name\":\"endpoint\",\"namespace\":\"test\"},\"subsets\":[{\"addresses\":[{\"ip\":\"ip1\", \"targetRef\": {\"uid\":\"uid1\"}}],\"ports\":[{\"name\":\"http\",\"port\":80,\"protocol\":\"TCP\"}]}]},{\"apiVersion\":\"v1\",\"kind\":\"Endpoints\",\"metadata\":{\"name\":\"endpoint\",\"namespace\":\"test2\"},\"subsets\":[{\"addresses\":[{\"ip\":\"ip2\",\"targetRef\": {\"uid\":\"uid2\"}}],\"ports\":[{\"name\":\"http\",\"port\":80,\"protocol\":\"TCP\"}]}]}],\"kind\":\"List\",\"metadata\":{\"resourceVersion\":\"\",\"selfLink\":\"\"}}")); mockHttpMessageHandler.When(HttpMethod.Get, "/api/v1/namespaces/test/services") .WithQueryString("fieldSelector=metadata.name%3Dendpoint") .Respond( HttpStatusCode.OK, new StringContent( "{\"apiVersion\":\"v1\",\"items\":[{\"apiVersion\":\"v1\",\"kind\":\"Service\",\"metadata\":{\"labels\":{\"l\":\"v\"},\"name\":\"endpoint\",\"namespace\":\"test\",\"uid\":\"uids1\"}}],\"kind\":\"List\",\"metadata\":{\"resourceVersion\":\"\",\"selfLink\":\"\"}}")); mockHttpMessageHandler.When(HttpMethod.Get, "/api/v1/namespaces/test2/services") .WithQueryString("fieldSelector=metadata.name%3Dendpoint") .Respond( HttpStatusCode.OK, new StringContent( "{\"apiVersion\":\"v1\",\"items\":[{\"apiVersion\":\"v1\",\"kind\":\"Service\",\"metadata\":{\"labels\":{\"l\":\"v\"},\"name\":\"endpoint\",\"namespace\":\"test2\",\"uid\":\"uids2\"}}],\"kind\":\"List\",\"metadata\":{\"resourceVersion\":\"\",\"selfLink\":\"\"}}")); using var client = new k8s.Kubernetes( config: new KubernetesClientConfiguration { Host = "http://localhost" }, httpClient: mockHttpMessageHandler.ToHttpClient()); var options = new TestOptionsMonitor <KubernetesDiscoveryOptions>(new KubernetesDiscoveryOptions() { AllNamespaces = true }); IDiscoveryClient discoveryClient = new KubernetesDiscoveryClient( new DefaultIsServicePortSecureResolver(options.CurrentValue), client, options); // act var genericInstances = discoveryClient.GetInstances("endpoint"); var instances = genericInstances.Select(s => (KubernetesServiceInstance)s).ToList(); // assert Assert.NotNull(instances); Assert.Equal(actual: instances.Count, expected: 2); Assert.Equal( actual: instances.Count(s => s.Host.Equals("ip1") && !s.IsSecure), expected: 1); Assert.Equal( actual: instances.Count(s => s.Host.Equals("ip2") && !s.IsSecure), expected: 1); Assert.Equal( actual: instances.Count(s => s.InstanceId.Equals("uid1")), expected: 1); Assert.Equal( actual: instances.Count(s => s.InstanceId.Equals("uid2")), expected: 1); }
public LoginShould() { IOptionsMonitor <JwtConfig> om = new TestOptionsMonitor( new JwtConfig() { Secret = "ijurkbdlhmklqacwqzdxmkkhvqowlyqa" } ); _userRepository = new UserRepositoryMock(); _authService = new AuthService(_userRepository.Object, om); }
public void GetInstances_ThrowsOnNull() { var k8SDiscoveryOptions = new TestOptionsMonitor <KubernetesDiscoveryOptions>(new KubernetesDiscoveryOptions()); using var client = new k8s.Kubernetes(new KubernetesClientConfiguration { Host = "http://localhost" }); var testK8SDiscoveryClient = new KubernetesDiscoveryClient( new DefaultIsServicePortSecureResolver(k8SDiscoveryOptions.CurrentValue), client, k8SDiscoveryOptions); Assert.Throws <ArgumentNullException>(() => testK8SDiscoveryClient.GetInstances(null)); }
private ScriptApplicationHostOptionsSetup CreateSetupWithConfiguration(bool inStandbyMode) { var builder = new ConfigurationBuilder(); var configuration = builder.Build(); var standbyOptions = new TestOptionsMonitor <StandbyOptions>(new StandbyOptions { InStandbyMode = inStandbyMode }); var mockCache = new Mock <IOptionsMonitorCache <ScriptApplicationHostOptions> >(); return(new ScriptApplicationHostOptionsSetup(configuration, standbyOptions, mockCache.Object)); }
public void EnabledPropertyWorksBothWays() { // arrange var mockHttpMessageHandler = new MockHttpMessageHandler(); mockHttpMessageHandler .When(HttpMethod.Get, "/api/v1/namespaces/test/services") .Respond( HttpStatusCode.OK, new StringContent( "{\"apiVersion\":\"v1\",\"items\":[{\"apiVersion\":\"v1\",\"kind\":\"Service\",\"metadata\":" + "{\"labels\":{\"label1\":\"value1\"},\"name\":\"endpoint1\",\"namespace\":\"test\",\"uid\":" + "\"uids1\"}},{\"apiVersion\":\"v1\",\"kind\":\"Service\",\"metadata\":{\"labels\":{\"label2\":" + "\"value2\"},\"name\":\"endpoint2\",\"namespace\":\"test\",\"uid\":\"uids2\"}}]," + "\"kind\":\"List\",\"metadata\"" + ":{\"resourceVersion\":\"\",\"selfLink\":\"\"}}")); using var client = new k8s.Kubernetes( config: new KubernetesClientConfiguration { Host = "http://localhost" }, httpClient: mockHttpMessageHandler.ToHttpClient()); var k8sOptions = new KubernetesDiscoveryOptions() { Enabled = false, Namespace = "test" }; var options = new TestOptionsMonitor <KubernetesDiscoveryOptions>(k8sOptions); var discoveryClient = new KubernetesDiscoveryClient( new DefaultIsServicePortSecureResolver(options.CurrentValue), client, options); // act var services = discoveryClient.Services; // assert Assert.NotNull(services); Assert.Empty(services); // turn it on k8sOptions.Enabled = true; // act services = discoveryClient.Services; // assert Assert.NotNull(services); Assert.Equal(actual: services.Count, expected: 2); Assert.True(services.Contains("endpoint1")); Assert.True(services.Contains("endpoint2")); }
public void ConsoleLoggerOptions_TimeStampFormat_IsReloaded() { // Arrange var monitor = new TestOptionsMonitor(new ConsoleLoggerOptions() { FormatterName = "NonExistentFormatter" }); var loggerProvider = new ConsoleLoggerProvider(monitor, ConsoleLoggerTest.GetFormatters()); var logger = (ConsoleLogger)loggerProvider.CreateLogger("Name"); // Act & Assert Assert.Equal("NonExistentFormatter", logger.Options.FormatterName); Assert.Equal(ConsoleFormatterNames.Simple, logger.Formatter.Name); }
public void Constructor_Initializes_Correctly() { var mockHttpMessageHandler = new MockHttpMessageHandler(); using var client = new k8s.Kubernetes(new KubernetesClientConfiguration { Host = "http://localhost" }, mockHttpMessageHandler.ToHttpClient()); const string expectedDesc = "Steeltoe provided Kubernetes native service discovery client"; var k8SDiscoveryOptions = new TestOptionsMonitor <KubernetesDiscoveryOptions>(new KubernetesDiscoveryOptions()); var testK8SDiscoveryClient = new KubernetesDiscoveryClient( new DefaultIsServicePortSecureResolver(k8SDiscoveryOptions.CurrentValue), client, k8SDiscoveryOptions); Assert.Equal(expectedDesc, testK8SDiscoveryClient.Description); }
private void ConfiguredOptions(ScriptApplicationHostOptions options, bool inStandbyMode, IEnvironment environment = null, bool blobExists = false) { var builder = new ConfigurationBuilder(); var configuration = builder.Build(); var standbyOptions = new TestOptionsMonitor <StandbyOptions>(new StandbyOptions { InStandbyMode = inStandbyMode }); var mockServiceProvider = new Mock <IServiceProvider>(); var mockEnvironment = environment ?? new TestEnvironment(); var setup = new TestScriptApplicationHostOptionsSetup(configuration, standbyOptions, mockServiceProvider.Object, mockEnvironment) { BlobExistsReturnValue = blobExists }; setup.Configure(options); }
public void ReceivesUpdatesTo_ConfiguredServices() { var services = new List <ConfigurationServiceInstance> { new ConfigurationServiceInstance { ServiceId = "fruitService", Host = "fruitball", Port = 443, IsSecure = true }, }; var serviceOptions = new TestOptionsMonitor <List <ConfigurationServiceInstance> >(services); var provider = new ConfigurationServiceInstanceProvider(serviceOptions); Assert.Single(provider.GetInstances("fruitService")); Assert.Equal("fruitball", provider.GetInstances("fruitService").First().Host); services.First().Host = "updatedValue"; Assert.Equal("updatedValue", provider.GetInstances("fruitService").First().Host); }
private ScriptApplicationHostOptions CreateConfiguredOptions(bool inStandbyMode, IEnvironment environment = null) { var builder = new ConfigurationBuilder(); var configuration = builder.Build(); var standbyOptions = new TestOptionsMonitor <StandbyOptions>(new StandbyOptions { InStandbyMode = inStandbyMode }); var mockCache = new Mock <IOptionsMonitorCache <ScriptApplicationHostOptions> >(); var mockServiceProvider = new Mock <IServiceProvider>(); var mockEnvironment = environment ?? new TestEnvironment(); var setup = new ScriptApplicationHostOptionsSetup(configuration, standbyOptions, mockCache.Object, mockServiceProvider.Object, mockEnvironment); var options = new ScriptApplicationHostOptions(); setup.Configure(options); return(options); }
public void GetServices_ShouldReturnOnlyMatchingServicesWhenLabelsAreAppliedToTheClient() { // arrange var mockHttpMessageHandler = new MockHttpMessageHandler(); mockHttpMessageHandler.When(HttpMethod.Get, "/api/v1/namespaces/test/services") .WithQueryString("labelSelector=label%3Dvalue") .Respond( HttpStatusCode.OK, new StringContent( "{\"apiVersion\":\"v1\",\"items\":[{\"apiVersion\":\"v1\",\"kind\":\"Service\",\"metadata\":" + "{\"labels\":{\"label1\":\"value1\"},\"name\":\"endpoint1\",\"namespace\":\"test\",\"uid\":" + "\"uids1\"}},{\"apiVersion\":\"v1\",\"kind\":\"Service\",\"metadata\":{\"labels\":{\"label2\":" + "\"value2\"},\"name\":\"endpoint2\",\"namespace\":\"test\",\"uid\":\"uids2\"}}]," + "\"kind\":\"List\",\"metadata\"" + ":{\"resourceVersion\":\"\",\"selfLink\":\"\"}}")); using var client = new k8s.Kubernetes( config: new KubernetesClientConfiguration { Host = "http://localhost" }, httpClient: mockHttpMessageHandler.ToHttpClient()); var options = new TestOptionsMonitor <KubernetesDiscoveryOptions>(new KubernetesDiscoveryOptions() { Namespace = "test" }); var discoveryClient = new KubernetesDiscoveryClient( new DefaultIsServicePortSecureResolver(options.CurrentValue), client, options); // act var services = discoveryClient.GetServices(new Dictionary <string, string> { { "label", "value" } }); // assert Assert.NotNull(services); Assert.Equal(actual: services.Count, expected: 2); Assert.True(services.Contains("endpoint1")); Assert.True(services.Contains("endpoint2")); }
public async Task ResolveServiceInstance_ResolvesAndIncrementsServiceIndex() { // arrange var services = new List <ConfigurationServiceInstance> { new ConfigurationServiceInstance { ServiceId = "fruitservice", Host = "fruitball", Port = 8000, IsSecure = true }, new ConfigurationServiceInstance { ServiceId = "fruitservice", Host = "fruitballer", Port = 8001 }, new ConfigurationServiceInstance { ServiceId = "fruitservice", Host = "fruitballerz", Port = 8002 }, new ConfigurationServiceInstance { ServiceId = "vegetableservice", Host = "vegemite", Port = 8010, IsSecure = true }, new ConfigurationServiceInstance { ServiceId = "vegetableservice", Host = "carrot", Port = 8011 }, new ConfigurationServiceInstance { ServiceId = "vegetableservice", Host = "beet", Port = 8012 }, }; var serviceOptions = new TestOptionsMonitor <List <ConfigurationServiceInstance> >(services); var provider = new ConfigurationServiceInstanceProvider(serviceOptions); var loadBalancer = new RoundRobinLoadBalancer(provider); // act Assert.Throws <KeyNotFoundException>(() => loadBalancer.NextIndexForService[loadBalancer.IndexKeyPrefix + "fruitService"]); Assert.Throws <KeyNotFoundException>(() => loadBalancer.NextIndexForService[loadBalancer.IndexKeyPrefix + "vegetableService"]); var fruitResult = await loadBalancer.ResolveServiceInstanceAsync(new Uri("https://fruitservice/api")); await loadBalancer.ResolveServiceInstanceAsync(new Uri("https://vegetableservice/api")); var vegResult = await loadBalancer.ResolveServiceInstanceAsync(new Uri("https://vegetableservice/api")); // assert Assert.Equal(1, loadBalancer.NextIndexForService[loadBalancer.IndexKeyPrefix + "fruitservice"]); Assert.Equal(8000, fruitResult.Port); Assert.Equal(2, loadBalancer.NextIndexForService[loadBalancer.IndexKeyPrefix + "vegetableservice"]); Assert.Equal(8011, vegResult.Port); }
public LinuxContainerMetricsPublisherTests() { var handlerMock = new Mock <HttpMessageHandler>(MockBehavior.Strict); handlerMock.Protected().Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()) .Callback <HttpRequestMessage, CancellationToken>((request, token) => ValidateRequest(request)) .ReturnsAsync(new HttpResponseMessage { StatusCode = HttpStatusCode.OK }); _httpClient = new HttpClient(handlerMock.Object); var mockEnvironment = new Mock <IEnvironment>(MockBehavior.Strict); mockEnvironment.Setup(p => p.GetEnvironmentVariable(EnvironmentSettingNames.ContainerName)).Returns(_containerName); mockEnvironment.Setup(p => p.GetEnvironmentVariable(EnvironmentSettingNames.LinuxNodeIpAddress)).Returns(_testIpAddress); mockEnvironment.Setup(p => p.GetEnvironmentVariable(EnvironmentSettingNames.AzureWebsiteHostName)).Returns(_testHostName); mockEnvironment.Setup(p => p.GetEnvironmentVariable(EnvironmentSettingNames.WebSiteHomeStampName)).Returns(_testStampName); mockEnvironment.Setup(p => p.GetEnvironmentVariable(EnvironmentSettingNames.WebSiteStampDeploymentId)).Returns(_testTenant); var websiteAuthEncryptionKey = TestHelpers.GenerateKeyBytes(); var websiteAuthEncryptionStringKey = TestHelpers.GenerateKeyHexString(websiteAuthEncryptionKey); Environment.SetEnvironmentVariable(EnvironmentSettingNames.WebSiteAuthEncryptionKey, websiteAuthEncryptionStringKey); _testLoggerProvider = new TestLoggerProvider(); var loggerFactory = new LoggerFactory(); loggerFactory.AddProvider(_testLoggerProvider); ILogger <LinuxContainerMetricsPublisher> logger = loggerFactory.CreateLogger <LinuxContainerMetricsPublisher>(); var hostNameProvider = new HostNameProvider(mockEnvironment.Object); var standbyOptions = new TestOptionsMonitor <StandbyOptions>(new StandbyOptions { InStandbyMode = true }); _metricsPublisher = new LinuxContainerMetricsPublisher(mockEnvironment.Object, standbyOptions, logger, hostNameProvider, _httpClient); _testLoggerProvider.ClearAllLogMessages(); }
public async Task PublishesUniqueFunctionExecutionActivitiesOnly() { // activity1 and activity2 are duplicates. so only activity2 will be published var activity1 = new ContainerFunctionExecutionActivity(DateTime.MinValue, "func-1", ExecutionStage.InProgress, "trigger-1", false); var activity2 = new ContainerFunctionExecutionActivity(DateTime.MaxValue, "func-1", ExecutionStage.InProgress, "trigger-1", false); var activity3 = new ContainerFunctionExecutionActivity(DateTime.MaxValue, "func-1", ExecutionStage.Finished, "trigger-1", true); var activity4 = new ContainerFunctionExecutionActivity(DateTime.MaxValue, "func-1", ExecutionStage.Finished, "trigger-1", false); var environment = new TestEnvironment(); environment.SetEnvironmentVariable(EnvironmentSettingNames.ContainerName, "Container-Name"); var meshClient = new Mock <IMeshServiceClient>(); var standbyOptions = new TestOptionsMonitor <StandbyOptions>(new StandbyOptions { InStandbyMode = false }); using (var publisher = new LinuxContainerActivityPublisher(standbyOptions, meshClient.Object, environment, NullLogger <LinuxContainerActivityPublisher> .Instance, FlushIntervalMs)) { await publisher.StartAsync(CancellationToken.None); publisher.PublishFunctionExecutionActivity(activity1); publisher.PublishFunctionExecutionActivity(activity2); publisher.PublishFunctionExecutionActivity(activity3); publisher.PublishFunctionExecutionActivity(activity4); await Task.Delay(DelayIntervalMs); await publisher.StopAsync(CancellationToken.None); meshClient.Verify( c => c.PublishContainerActivity( It.Is <IEnumerable <ContainerFunctionExecutionActivity> >(e => MatchesFunctionActivities(e, activity2, activity3, activity4))), Times.Once); } }
public async Task ResolveServiceInstance_ResolvesAndIncrementsServiceIndex_WithDistributedCache() { // arrange var services = new List <ConfigurationServiceInstance> { new ConfigurationServiceInstance { ServiceId = "fruitservice", Host = "fruitball", Port = 8000, IsSecure = true }, new ConfigurationServiceInstance { ServiceId = "fruitservice", Host = "fruitballer", Port = 8001 }, new ConfigurationServiceInstance { ServiceId = "fruitservice", Host = "fruitballerz", Port = 8002 }, new ConfigurationServiceInstance { ServiceId = "vegetableservice", Host = "vegemite", Port = 8010, IsSecure = true }, new ConfigurationServiceInstance { ServiceId = "vegetableservice", Host = "carrot", Port = 8011 }, new ConfigurationServiceInstance { ServiceId = "vegetableservice", Host = "beet", Port = 8012 }, }; var serviceOptions = new TestOptionsMonitor <List <ConfigurationServiceInstance> >(services); var provider = new ConfigurationServiceInstanceProvider(serviceOptions); var loadBalancer = new RoundRobinLoadBalancer(provider, GetCache()); // act var fruitResult = await loadBalancer.ResolveServiceInstanceAsync(new Uri("https://fruitservice/api")); await loadBalancer.ResolveServiceInstanceAsync(new Uri("https://vegetableservice/api")); var vegResult = await loadBalancer.ResolveServiceInstanceAsync(new Uri("https://vegetableservice/api")); // assert Assert.Equal(8000, fruitResult.Port); Assert.Equal(8011, vegResult.Port); }
public async Task PublishesSpecializationCompleteEvent() { var activity = new ContainerFunctionExecutionActivity(DateTime.MinValue, "func-1", ExecutionStage.InProgress, "trigger-1", false); var environment = new TestEnvironment(); environment.SetEnvironmentVariable(EnvironmentSettingNames.ContainerName, "Container-Name"); var meshClient = new Mock <IMeshServiceClient>(MockBehavior.Strict); meshClient.Setup(c => c.NotifyHealthEvent(ContainerHealthEventType.Informational, It.IsAny <Type>(), LinuxContainerActivityPublisher.SpecializationCompleteEvent)).Returns(Task.FromResult(true)); var standbyOptions = new TestOptionsMonitor <StandbyOptions>(new StandbyOptions { InStandbyMode = false }); using (var publisher = new LinuxContainerActivityPublisher(standbyOptions, meshClient.Object, environment, NullLogger <LinuxContainerActivityPublisher> .Instance, 1000, InitialFlushIntervalMs)) { await publisher.StartAsync(CancellationToken.None); publisher.PublishFunctionExecutionActivity(activity); await Task.Delay(100); await publisher.StopAsync(CancellationToken.None); meshClient.Verify(c => c.NotifyHealthEvent(ContainerHealthEventType.Informational, It.IsAny <Type>(), LinuxContainerActivityPublisher.SpecializationCompleteEvent), Times.Once); // Since test is waiting for 100ms and Flush interval is 1000ms, there will be no PublishContainerActivity meshClient.Verify( c => c.PublishContainerActivity( It.Is <IEnumerable <ContainerFunctionExecutionActivity> >(e => MatchesFunctionActivities(e, activity))), Times.Never); } }
public LinuxContainerEventGeneratorTests() { _events = new List <string>(); Action <string> writer = (s) => { _events.Add(s); }; var mockEnvironment = new Mock <IEnvironment>(MockBehavior.Strict); mockEnvironment.Setup(p => p.GetEnvironmentVariable(EnvironmentSettingNames.ContainerName)).Returns(_containerName); mockEnvironment.Setup(p => p.GetEnvironmentVariable(EnvironmentSettingNames.WebSiteHomeStampName)).Returns(_stampName); mockEnvironment.Setup(p => p.GetEnvironmentVariable(EnvironmentSettingNames.WebSiteStampDeploymentId)).Returns(_tenantId); mockEnvironment.Setup(p => p.GetEnvironmentVariable(EnvironmentSettingNames.LinuxNodeIpAddress)).Returns(_testNodeAddress); var standbyOptions = new TestOptionsMonitor <StandbyOptions>(new StandbyOptions { InStandbyMode = true }); var handlerMock = new Mock <HttpMessageHandler>(MockBehavior.Strict); var httpClient = new HttpClient(handlerMock.Object); _generator = new LinuxContainerEventGenerator(mockEnvironment.Object, writer); }
public async Task GenesisWithEmptyParametersTimeShouldReject() { // Arrange IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(); ChainConstants chainConstants = testServiceProvider.GetService <ChainConstants>(); IOptionsMonitor <MiscellaneousParameters> miscellaneousParameterOptions = testServiceProvider.GetService <IOptionsMonitor <MiscellaneousParameters> >(); IOptionsMonitor <GweiValues> gweiValueOptions = testServiceProvider.GetService <IOptionsMonitor <GweiValues> >(); IOptionsMonitor <InitialValues> initialValueOptions = testServiceProvider.GetService <IOptionsMonitor <InitialValues> >(); IOptionsMonitor <TimeParameters> timeParameterOptions = testServiceProvider.GetService <IOptionsMonitor <TimeParameters> >(); IOptionsMonitor <StateListLengths> stateListLengthOptions = testServiceProvider.GetService <IOptionsMonitor <StateListLengths> >(); IOptionsMonitor <RewardsAndPenalties> rewardsAndPenaltiesOptions = testServiceProvider.GetService <IOptionsMonitor <RewardsAndPenalties> >(); IOptionsMonitor <MaxOperationsPerBlock> maxOperationsPerBlockOptions = testServiceProvider.GetService <IOptionsMonitor <MaxOperationsPerBlock> >(); IOptionsMonitor <ForkChoiceConfiguration> forkChoiceConfigurationOptions = testServiceProvider.GetService <IOptionsMonitor <ForkChoiceConfiguration> >(); IOptionsMonitor <SignatureDomains> signatureDomainOptions = testServiceProvider.GetService <IOptionsMonitor <SignatureDomains> >(); IOptionsMonitor <InMemoryConfiguration> inMemoryConfigurationOptions = testServiceProvider.GetService <IOptionsMonitor <InMemoryConfiguration> >(); miscellaneousParameterOptions.CurrentValue.MinimumGenesisActiveValidatorCount = 2; LoggerFactory loggerFactory = new LoggerFactory(new[] { new ConsoleLoggerProvider(TestOptionsMonitor.Create(new ConsoleLoggerOptions())) }); ICryptographyService cryptographyService = testServiceProvider.GetService <ICryptographyService>(); BeaconChainUtility beaconChainUtility = new BeaconChainUtility( loggerFactory.CreateLogger <BeaconChainUtility>(), chainConstants, miscellaneousParameterOptions, initialValueOptions, gweiValueOptions, timeParameterOptions, cryptographyService); BeaconStateAccessor beaconStateAccessor = new BeaconStateAccessor(chainConstants, miscellaneousParameterOptions, timeParameterOptions, stateListLengthOptions, signatureDomainOptions, cryptographyService, beaconChainUtility); BeaconStateMutator beaconStateMutator = new BeaconStateMutator(chainConstants, timeParameterOptions, stateListLengthOptions, rewardsAndPenaltiesOptions, beaconChainUtility, beaconStateAccessor); BeaconStateTransition beaconStateTransition = new BeaconStateTransition( loggerFactory.CreateLogger <BeaconStateTransition>(), chainConstants, gweiValueOptions, timeParameterOptions, stateListLengthOptions, rewardsAndPenaltiesOptions, maxOperationsPerBlockOptions, signatureDomainOptions, cryptographyService, beaconChainUtility, beaconStateAccessor, beaconStateMutator); SimpleLatestMessageDrivenGreedyHeaviestObservedSubtree simpleLmdGhost = new SimpleLatestMessageDrivenGreedyHeaviestObservedSubtree( loggerFactory.CreateLogger <SimpleLatestMessageDrivenGreedyHeaviestObservedSubtree>(), chainConstants, beaconChainUtility, beaconStateAccessor); MemoryStore store = new MemoryStore(loggerFactory.CreateLogger <MemoryStore>(), inMemoryConfigurationOptions, new DataDirectory("data"), Substitute.For <IFileSystem>(), simpleLmdGhost, new StoreAccessor()); ForkChoice forkChoice = new ForkChoice(loggerFactory.CreateLogger <ForkChoice>(), chainConstants, miscellaneousParameterOptions, timeParameterOptions, maxOperationsPerBlockOptions, forkChoiceConfigurationOptions, signatureDomainOptions, cryptographyService, beaconChainUtility, beaconStateAccessor, beaconStateTransition); GenesisChainStart genesisChainStart = new GenesisChainStart(loggerFactory.CreateLogger <GenesisChainStart>(), chainConstants, miscellaneousParameterOptions, gweiValueOptions, initialValueOptions, timeParameterOptions, stateListLengthOptions, cryptographyService, store, beaconStateAccessor, beaconStateTransition, forkChoice); // Act Bytes32 eth1BlockHash = Bytes32.Zero; ulong eth1Timestamp = 106185600uL; // 1973-05-14 Deposit[] deposits = Array.Empty <Deposit>(); bool success = await genesisChainStart.TryGenesisAsync(eth1BlockHash, eth1Timestamp, deposits); // Assert success.ShouldBeFalse(); }
public Mocks(Options options = null) { OptionsMonitor = new TestOptionsMonitor <Options>(options ?? new Options()); }