private async Task IndexBindings(Type testType, bool includeDefaultUri = true) { // Just start the host -- this should fail if function indexing fails. ExplicitTypeLocator locator = new ExplicitTypeLocator(testType); var resolver = new TestNameResolver(); if (includeDefaultUri) { resolver.Values.Add(MobileAppsExtensionConfigProvider.AzureWebJobsMobileAppUriName, "https://default"); } IHost host = new HostBuilder() .ConfigureWebJobs(builder => { builder.AddMobileApps(); }) .ConfigureServices(services => { services.AddSingleton <INameResolver>(resolver); services.AddSingleton <ITypeLocator>(locator); }) .ConfigureLogging(logging => { logging.ClearProviders(); logging.AddProvider(_loggerProvider); }) .Build(); await host.StartAsync(); await host.StopAsync(); }
public async Task ValidParametersWithAppSettings_Succeed(ParameterInfo parameter) { var nameResolver = new TestNameResolver(); nameResolver.Values["aDatabase"] = "myDatabase"; nameResolver.Values["aCollection"] = "myCollection"; var config = new ConfigurationBuilder() .AddInMemoryCollection(new Dictionary <string, string> { { "ConnectionStrings:CosmosDBConnectionString", "AccountEndpoint=https://fromSettings;AccountKey=c29tZV9rZXk=;" } }) .Build(); CosmosDBTriggerAttributeBindingProvider provider = new CosmosDBTriggerAttributeBindingProvider(config, nameResolver, _options, CreateExtensionConfigProvider(_options), _loggerFactory); CosmosDBTriggerBinding binding = (CosmosDBTriggerBinding)await provider.TryCreateAsync(new TriggerBindingProviderContext(parameter, CancellationToken.None)); Assert.Equal(typeof(IReadOnlyList <Document>), binding.TriggerValueType); Assert.Equal(new Uri("https://fromSettings"), binding.DocumentCollectionLocation.Uri); Assert.Equal(new Uri("https://fromSettings"), binding.LeaseCollectionLocation.Uri); Assert.Equal("myDatabase", binding.DocumentCollectionLocation.DatabaseName); Assert.Equal("myCollection", binding.DocumentCollectionLocation.CollectionName); Assert.Equal("myDatabase", binding.LeaseCollectionLocation.DatabaseName); Assert.Equal("leases", binding.LeaseCollectionLocation.CollectionName); }
public void Create_ConstantSchedule_CreatesExpectedSchedule() { TimerTriggerAttribute attribute = new TimerTriggerAttribute("00:00:15"); INameResolver nameResolver = new TestNameResolver(); ConstantSchedule schedule = (ConstantSchedule)TimerSchedule.Create(attribute, nameResolver, _logger); Assert.False(attribute.UseMonitor); var log = _loggerProvider.GetAllLogMessages().Single(); Assert.Equal("UseMonitor changed to false based on schedule frequency.", log.FormattedMessage); Assert.Equal(LogLevel.Debug, log.Level); DateTime now = new DateTime(2015, 5, 22, 9, 45, 00); DateTime nextOccurrence = schedule.GetNextOccurrence(now); Assert.Equal(new TimeSpan(0, 0, 15), nextOccurrence - now); // For schedules occuring on an interval greater than a minute, we expect // UseMonitor to be defaulted to true _loggerProvider.ClearAllLogMessages(); attribute = new TimerTriggerAttribute("01:00:00"); schedule = (ConstantSchedule)TimerSchedule.Create(attribute, nameResolver, _logger); Assert.True(attribute.UseMonitor); Assert.Empty(_loggerProvider.GetAllLogMessages()); // verify that if UseMonitor is set explicitly, it is not overridden attribute = new TimerTriggerAttribute("01:00:00"); attribute.UseMonitor = false; schedule = (ConstantSchedule)TimerSchedule.Create(attribute, nameResolver, _logger); Assert.False(attribute.UseMonitor); Assert.Empty(_loggerProvider.GetAllLogMessages()); }
private MobileAppsConfiguration InitializeConfig(string configApiKey, Uri configMobileAppUri) { var config = new MobileAppsConfiguration { ApiKey = configApiKey, MobileAppUri = configMobileAppUri }; var nameResolver = new TestNameResolver(); nameResolver.Values[MobileAppsConfiguration.AzureWebJobsMobileAppApiKeyName] = "Default"; nameResolver.Values[MobileAppsConfiguration.AzureWebJobsMobileAppUriName] = "https://default"; nameResolver.Values["Attribute"] = "ResolvedAttribute"; var jobHostConfig = new JobHostConfiguration(); jobHostConfig.NameResolver = nameResolver; var context = new ExtensionConfigContext { Config = jobHostConfig }; config.Initialize(context); return(config); }
public void Binding_UsesNameResolver() { ParameterInfo parameter = GetType().GetMethod("TestMethod", BindingFlags.Static | BindingFlags.NonPublic).GetParameters().First(); SendGridAttribute attribute = new SendGridAttribute { To = "%param1%", From = "%param2%", Subject = "%param3%", Text = "%param4%" }; SendGridConfiguration config = new SendGridConfiguration { ApiKey = "12345" }; Dictionary <string, Type> contract = new Dictionary <string, Type>(); BindingProviderContext context = new BindingProviderContext(parameter, contract, CancellationToken.None); var nameResolver = new TestNameResolver(); nameResolver.Values.Add("param1", "*****@*****.**"); nameResolver.Values.Add("param2", "*****@*****.**"); nameResolver.Values.Add("param3", "Value3"); nameResolver.Values.Add("param4", "Value4"); SendGridBinding binding = new SendGridBinding(parameter, attribute, config, nameResolver, context); Dictionary <string, object> bindingData = new Dictionary <string, object>(); SendGridMessage message = binding.CreateDefaultMessage(bindingData); Assert.Equal("*****@*****.**", message.To.Single().Address); Assert.Equal("*****@*****.**", message.From.Address); Assert.Equal("Value3", message.Subject); Assert.Equal("Value4", message.Text); }
private void RunTest(string testName, IMobileServiceClientFactory factory, TraceWriter testTrace, object argument = null) { Type testType = typeof(MobileTableEndToEndFunctions); ExplicitTypeLocator locator = new ExplicitTypeLocator(testType); JobHostConfiguration config = new JobHostConfiguration { TypeLocator = locator, }; config.Tracing.Tracers.Add(testTrace); var arguments = new Dictionary <string, object>(); arguments.Add("triggerData", argument); var mobileAppsConfig = new MobileAppsConfiguration { MobileAppUri = new Uri("https://someuri"), ApiKey = "api_key", ClientFactory = factory }; var resolver = new TestNameResolver(); config.NameResolver = resolver; config.UseMobileApps(mobileAppsConfig); JobHost host = new JobHost(config); host.Start(); host.Call(testType.GetMethod(testName), arguments); host.Stop(); }
public void Create_ConstantSchedule_CreatesExpectedSchedule() { TimerTriggerAttribute attribute = new TimerTriggerAttribute("00:00:15"); INameResolver nameResolver = new TestNameResolver(); ConstantSchedule schedule = (ConstantSchedule)TimerSchedule.Create(attribute, nameResolver); Assert.False(attribute.UseMonitor); DateTime now = new DateTime(2015, 5, 22, 9, 45, 00); DateTime nextOccurrence = schedule.GetNextOccurrence(now); Assert.Equal(new TimeSpan(0, 0, 15), nextOccurrence - now); // For schedules occuring on an interval greater than a minute, we expect // UseMonitor to be defaulted to true attribute = new TimerTriggerAttribute("01:00:00"); schedule = (ConstantSchedule)TimerSchedule.Create(attribute, nameResolver); Assert.True(attribute.UseMonitor); // verify that if UseMonitor is set explicitly, it is not overridden attribute = new TimerTriggerAttribute("01:00:00"); attribute.UseMonitor = false; schedule = (ConstantSchedule)TimerSchedule.Create(attribute, nameResolver); Assert.False(attribute.UseMonitor); }
private async Task IndexBindings(Type testType, bool includeDefaultUri = true) { // Just start the jobhost -- this should fail if function indexing fails. ExplicitTypeLocator locator = new ExplicitTypeLocator(testType); var nameResolver = new TestNameResolver(); if (includeDefaultUri) { nameResolver.Values.Add(MobileAppsConfiguration.AzureWebJobsMobileAppUriName, "https://default"); } JobHostConfiguration config = new JobHostConfiguration { NameResolver = nameResolver, TypeLocator = locator, }; config.UseMobileApps(); JobHost host = new JobHost(config); await host.StartAsync(); await host.StopAsync(); }
public DaprTestBase(ITestOutputHelper output, IDictionary <string, string> environmentVariables) { this.logProvider = new TestLogProvider(output); this.typeLocator = new TestFunctionTypeLocator(); this.nameResolver = new TestNameResolver(); foreach (var kvPair in DefaultEnvironmentVariables) { if (!environmentVariables.ContainsKey(kvPair.Key)) { environmentVariables[kvPair.Key] = kvPair.Value; } } foreach (var kvPair in environmentVariables) { this.nameResolver.AddSetting(kvPair.Key, kvPair.Value); } this.functionsHost = new HostBuilder() .ConfigureLogging(loggingBuilder => loggingBuilder.AddProvider(this.logProvider)) .ConfigureWebJobs(webJobsBuilder => webJobsBuilder.AddDapr()) .ConfigureServices( collection => { collection.AddSingleton <INameResolver>(this.nameResolver); collection.AddSingleton <ITypeLocator>(this.typeLocator); }) .Build(); this.daprRuntime = new DaprRuntimeEmulator(DaprPort); }
public async Task ValidLeaseHostOptions_Succeed(ParameterInfo parameter) { var nameResolver = new TestNameResolver(); nameResolver.Values["dynamicLeasePrefix"] = "someLeasePrefix"; var config = new ConfigurationBuilder() .AddInMemoryCollection(new Dictionary <string, string> { // Verify we load from connection strings first { "ConnectionStrings:CosmosDBConnectionString", "AccountEndpoint=https://fromSettings;AccountKey=c29tZV9rZXk=;" }, { "CosmosDBConnectionString", "will not work" }, { "ConnectionStrings:LeaseConnectionString", "AccountEndpoint=https://overridden;AccountKey=c29tZV9rZXk=;" }, { "LeaseConnectionString", "will not work" } }) .Build(); CosmosDBTriggerAttributeBindingProvider provider = new CosmosDBTriggerAttributeBindingProvider(config, nameResolver, _options, CreateExtensionConfigProvider(_options), _loggerFactory); CosmosDBTriggerBinding binding = (CosmosDBTriggerBinding)await provider.TryCreateAsync(new TriggerBindingProviderContext(parameter, CancellationToken.None)); // This test uses the default for ConnectionStringSetting, but overrides LeaseConnectionStringSetting Assert.Equal(typeof(IReadOnlyList <Document>), binding.TriggerValueType); Assert.Equal(new Uri("https://fromEnvironment"), binding.DocumentCollectionLocation.Uri); Assert.Equal(new Uri("https://overridden"), binding.LeaseCollectionLocation.Uri); Assert.Equal("someLeasePrefix", binding.ChangeFeedProcessorOptions.LeasePrefix); Assert.Null(binding.ChangeFeedProcessorOptions.MaxItemCount); Assert.False(binding.ChangeFeedProcessorOptions.StartFromBeginning); }
private async Task RunTestAsync(string testName, ISendGridClientFactory factory, object argument = null, string configApiKey = null, bool includeDefaultApiKey = true) { Type testType = typeof(SendGridEndToEndFunctions); var locator = new ExplicitTypeLocator(testType); ILoggerFactory loggerFactory = new LoggerFactory(); loggerFactory.AddProvider(_loggerProvider); var arguments = new Dictionary <string, object>(); arguments.Add("triggerData", argument); var resolver = new TestNameResolver(); IHost host = new HostBuilder() .ConfigureWebJobs(builder => { builder.AddSendGrid(o => { if (configApiKey != null) { o.ApiKey = configApiKey; } o.ToAddress = new EmailAddress("*****@*****.**"); o.FromAddress = new EmailAddress("*****@*****.**"); }); }) .ConfigureServices(services => { services.AddSingleton <ISendGridClientFactory>(factory); services.AddSingleton <INameResolver>(resolver); services.AddSingleton <ITypeLocator>(locator); }) .ConfigureLogging(logging => { logging.ClearProviders(); logging.AddProvider(_loggerProvider); }) .ConfigureAppConfiguration(c => { c.Sources.Clear(); var collection = new Dictionary <string, string> { { "MyKey1", AttributeApiKey1 }, { "MyKey2", AttributeApiKey2 } }; if (includeDefaultApiKey) { collection.Add(SendGridExtensionConfigProvider.AzureWebJobsSendGridApiKeyName, DefaultApiKey); } c.AddInMemoryCollection(collection); }) .Build(); await host.GetJobHost().CallAsync(testType.GetMethod(testName), arguments); }
private async Task RunTestAsync(Type testType, string testName, ICosmosDBServiceFactory factory, object argument = null, string configConnectionString = ConfigConnStr, bool includeDefaultConnectionString = true) { ExplicitTypeLocator locator = new ExplicitTypeLocator(testType); var arguments = new Dictionary <string, object> { { "triggerData", argument } }; var resolver = new TestNameResolver(); resolver.Values.Add("Database", "ResolvedDatabase"); resolver.Values.Add("Collection", "ResolvedCollection"); resolver.Values.Add("Query", "ResolvedQuery"); IHost host = new HostBuilder() .ConfigureWebJobs(builder => { builder.AddAzureStorage() .AddCosmosDB(); }) .ConfigureAppConfiguration(c => { c.Sources.Clear(); if (includeDefaultConnectionString) { c.AddInMemoryCollection(new Dictionary <string, string> { { $"ConnectionStrings:{Constants.DefaultConnectionStringName}", DefaultConnStr }, { ConnectionStringNames.Storage, "UseDevelopmentStorage=true" }, { "MyConnectionString", AttributeConnStr } }); } }) .ConfigureServices(services => { services.AddSingleton <ICosmosDBServiceFactory>(factory); services.AddSingleton <INameResolver>(resolver); services.AddSingleton <ITypeLocator>(locator); if (configConnectionString != null) { services.Configure <CosmosDBOptions>(o => o.ConnectionString = configConnectionString); } }) .ConfigureLogging(logging => { logging.ClearProviders(); logging.AddProvider(_loggerProvider); }) .Build(); await host.StartAsync(); await host.GetJobHost().CallAsync(testType.GetMethod(testName), arguments); await host.StopAsync(); }
public static JobHost GetJobHost( ILoggerProvider loggerProvider, string testName, bool enableExtendedSessions, string eventGridKeySettingName = null, INameResolver nameResolver = null, string eventGridTopicEndpoint = null, int?eventGridRetryCount = null, TimeSpan?eventGridRetryInterval = null, int[] eventGridRetryHttpStatus = null, bool logReplayEvents = true, Uri notificationUrl = null, HttpMessageHandler eventGridNotificationHandler = null, TimeSpan?maxQueuePollingInterval = null, string[] eventGridPublishEventTypes = null, bool autoFetchLargeMessages = true) { var durableTaskOptions = new DurableTaskOptions { HubName = GetTaskHubNameFromTestName(testName, enableExtendedSessions), TraceInputsAndOutputs = true, EventGridKeySettingName = eventGridKeySettingName, EventGridTopicEndpoint = eventGridTopicEndpoint, ExtendedSessionsEnabled = enableExtendedSessions, MaxConcurrentOrchestratorFunctions = 200, MaxConcurrentActivityFunctions = 200, LogReplayEvents = logReplayEvents, NotificationUrl = notificationUrl, NotificationHandler = eventGridNotificationHandler, EventGridPublishEventTypes = eventGridPublishEventTypes, FetchLargeMessagesAutomatically = autoFetchLargeMessages, }; if (eventGridRetryCount.HasValue) { durableTaskOptions.EventGridPublishRetryCount = eventGridRetryCount.Value; } if (eventGridRetryInterval.HasValue) { durableTaskOptions.EventGridPublishRetryInterval = eventGridRetryInterval.Value; } if (eventGridRetryHttpStatus != null) { durableTaskOptions.EventGridPublishRetryHttpStatus = eventGridRetryHttpStatus; } if (maxQueuePollingInterval != null) { durableTaskOptions.MaxQueuePollingInterval = maxQueuePollingInterval.Value; } var optionsWrapper = new OptionsWrapper <DurableTaskOptions>(durableTaskOptions); var testNameResolver = new TestNameResolver(nameResolver); return(PlatformSpecificHelpers.CreateJobHost(optionsWrapper, loggerProvider, testNameResolver)); }
public SingletonManagerTests() { _mockAccountProvider = new Mock <IStorageAccountProvider>(MockBehavior.Strict); _mockBlobDirectory = new Mock <IStorageBlobDirectory>(MockBehavior.Strict); _mockSecondaryBlobDirectory = new Mock <IStorageBlobDirectory>(MockBehavior.Strict); _mockStorageAccount = new Mock <IStorageAccount>(MockBehavior.Strict); _mockStorageAccount.SetupGet(a => a.Type).Returns(StorageAccountType.GeneralPurpose); _mockSecondaryStorageAccount = new Mock <IStorageAccount>(MockBehavior.Strict); _mockSecondaryStorageAccount.SetupGet(a => a.Type).Returns(StorageAccountType.GeneralPurpose); Mock <IStorageBlobClient> mockBlobClient = new Mock <IStorageBlobClient>(MockBehavior.Strict); Mock <IStorageBlobClient> mockSecondaryBlobClient = new Mock <IStorageBlobClient>(MockBehavior.Strict); Mock <IStorageBlobContainer> mockBlobContainer = new Mock <IStorageBlobContainer>(MockBehavior.Strict); mockBlobContainer.Setup(p => p.GetDirectoryReference(HostDirectoryNames.SingletonLocks)).Returns(_mockBlobDirectory.Object); mockBlobClient.Setup(p => p.GetContainerReference(HostContainerNames.Hosts)).Returns(mockBlobContainer.Object); Mock <IStorageBlobContainer> mockSecondaryBlobContainer = new Mock <IStorageBlobContainer>(MockBehavior.Strict); mockSecondaryBlobContainer.Setup(p => p.GetDirectoryReference(HostDirectoryNames.SingletonLocks)).Returns(_mockSecondaryBlobDirectory.Object); mockSecondaryBlobClient.Setup(p => p.GetContainerReference(HostContainerNames.Hosts)).Returns(mockSecondaryBlobContainer.Object); _mockStorageAccount.Setup(p => p.CreateBlobClient(null)).Returns(mockBlobClient.Object); _mockSecondaryStorageAccount.Setup(p => p.CreateBlobClient(null)).Returns(mockSecondaryBlobClient.Object); _mockAccountProvider.Setup(p => p.TryGetAccountAsync(ConnectionStringNames.Storage, It.IsAny <CancellationToken>())) .ReturnsAsync(_mockStorageAccount.Object); _mockAccountProvider.Setup(p => p.TryGetAccountAsync(Secondary, It.IsAny <CancellationToken>())) .ReturnsAsync(_mockSecondaryStorageAccount.Object); _mockExceptionDispatcher = new Mock <IWebJobsExceptionHandler>(MockBehavior.Strict); _mockStorageBlob = new Mock <IStorageBlockBlob>(MockBehavior.Strict); _mockBlobMetadata = new Dictionary <string, string>(); _mockBlobDirectory.Setup(p => p.GetBlockBlobReference(TestLockId)).Returns(_mockStorageBlob.Object); _singletonConfig = new SingletonConfiguration(); // use reflection to bypass the normal validations (so tests can run fast) TestHelpers.SetField(_singletonConfig, "_lockAcquisitionPollingInterval", TimeSpan.FromMilliseconds(25)); TestHelpers.SetField(_singletonConfig, "_lockPeriod", TimeSpan.FromMilliseconds(500)); _singletonConfig.LockAcquisitionTimeout = TimeSpan.FromMilliseconds(200); _nameResolver = new TestNameResolver(); ILoggerFactory loggerFactory = new LoggerFactory(); // We want to see all logs, so set the default level to Trace. LogCategoryFilter filter = new LogCategoryFilter { DefaultLevel = Extensions.Logging.LogLevel.Trace }; _loggerProvider = new TestLoggerProvider(filter.Filter); loggerFactory.AddProvider(_loggerProvider); var logger = loggerFactory?.CreateLogger(LogCategories.Singleton); _core = new BlobLeaseDistributedLockManager.DedicatedStorage(_mockAccountProvider.Object, logger); _singletonManager = new SingletonManager(_core, _singletonConfig, _mockExceptionDispatcher.Object, loggerFactory, new FixedHostIdProvider(TestHostId), _nameResolver); _singletonManager.MinimumLeaseRenewalInterval = TimeSpan.FromMilliseconds(250); }
private async Task RunTestAsync(string testName, IMobileServiceClientFactory factory, object argument = null, Uri configUri = null, string configKey = null, bool includeDefaultKey = true, bool includeDefaultUri = true, Type testType = null) { testType = testType ?? typeof(MobileTableEndToEndFunctions); ExplicitTypeLocator locator = new ExplicitTypeLocator(testType); var arguments = new Dictionary <string, object>(); arguments.Add("triggerData", argument); var resolver = new TestNameResolver(); resolver.Values.Add("MyUri", AttributeUri); resolver.Values.Add("MyKey", AttributeKey); if (includeDefaultUri) { resolver.Values.Add(MobileAppsExtensionConfigProvider.AzureWebJobsMobileAppUriName, DefaultUri); } if (includeDefaultKey) { resolver.Values.Add(MobileAppsExtensionConfigProvider.AzureWebJobsMobileAppApiKeyName, DefaultKey); } IHost host = new HostBuilder() .ConfigureWebJobs(builder => { builder.AddAzureStorage() .AddMobileApps(o => { o.MobileAppUri = configUri; o.ApiKey = configKey; }); }) .ConfigureServices(services => { services.AddSingleton <IMobileServiceClientFactory>(factory); services.AddSingleton <INameResolver>(resolver); services.AddSingleton <ITypeLocator>(locator); }) .ConfigureLogging(logging => { logging.ClearProviders(); logging.AddProvider(_loggerProvider); }) .Build(); await host.StartAsync(); await host.GetJobHost().CallAsync(testType.GetMethod(testName), arguments); await host.StopAsync(); }
public async Task ValidCosmosDBTriggerBindigsMultiMasterParameters_Succeed(ParameterInfo parameter) { var nameResolver = new TestNameResolver(); nameResolver.Values["regions"] = "East US, North Europe,"; CosmosDBTriggerAttributeBindingProvider provider = new CosmosDBTriggerAttributeBindingProvider(_emptyConfig, nameResolver, _options, CreateExtensionConfigProvider(_options), _loggerFactory); CosmosDBTriggerBinding binding = (CosmosDBTriggerBinding)await provider.TryCreateAsync(new TriggerBindingProviderContext(parameter, CancellationToken.None)); Assert.False(binding.DocumentCollectionLocation.ConnectionPolicy.UseMultipleWriteLocations); Assert.True(binding.LeaseCollectionLocation.ConnectionPolicy.UseMultipleWriteLocations); }
private CosmosDBExtensionConfigProvider InitializeExtensionConfigProvider(string defaultConnStr, string optionsConnStr = null) { var options = CosmosDBTestUtility.InitializeOptions(defaultConnStr, optionsConnStr); var factory = new DefaultCosmosDBServiceFactory(); var nameResolver = new TestNameResolver(); var configProvider = new CosmosDBExtensionConfigProvider(options, factory, _emptyConfig, nameResolver, NullLoggerFactory.Instance); var context = TestHelpers.CreateExtensionConfigContext(nameResolver); configProvider.Initialize(context); return(configProvider); }
public async Task ValidParametersWithEnvironment_Succeed(ParameterInfo parameter) { var nameResolver = new TestNameResolver(); nameResolver.Values[CosmosDBConfiguration.AzureWebJobsCosmosDBConnectionStringName] = "AccountEndpoint=https://fromEnvironment;AccountKey=someKey;"; nameResolver.Values["CosmosDBConnectionString"] = "AccountEndpoint=https://fromSettings;AccountKey=someKey;"; CosmosDBTriggerAttributeBindingProvider provider = new CosmosDBTriggerAttributeBindingProvider(nameResolver, CreateConfiguration()); CosmosDBTriggerBinding binding = (CosmosDBTriggerBinding)await provider.TryCreateAsync(new TriggerBindingProviderContext(parameter, CancellationToken.None)); Assert.Equal(typeof(IReadOnlyList <Document>), binding.TriggerValueType); Assert.Equal(binding.DocumentCollectionLocation.Uri, new Uri("https://fromEnvironment")); }
private async Task RunTestAsync(string testName, ISendGridClientFactory factory, object argument = null, string configApiKey = null, bool includeDefaultApiKey = true) { Type testType = typeof(SendGridEndToEndFunctions); ExplicitTypeLocator locator = new ExplicitTypeLocator(testType); JobHostConfiguration config = new JobHostConfiguration { TypeLocator = locator, }; ILoggerFactory loggerFactory = new LoggerFactory(); loggerFactory.AddProvider(_loggerProvider); config.LoggerFactory = loggerFactory; var arguments = new Dictionary <string, object>(); arguments.Add("triggerData", argument); var sendGridConfig = new SendGridConfiguration { ApiKey = configApiKey, ClientFactory = factory, ToAddress = new EmailAddress("*****@*****.**"), FromAddress = new EmailAddress("*****@*****.**") }; var resolver = new TestNameResolver(); resolver.Values.Add("MyKey1", AttributeApiKey1); resolver.Values.Add("MyKey2", AttributeApiKey2); if (includeDefaultApiKey) { resolver.Values.Add(SendGridConfiguration.AzureWebJobsSendGridApiKeyName, DefaultApiKey); } config.NameResolver = resolver; config.UseSendGrid(sendGridConfig); JobHost host = new JobHost(config); await host.StartAsync(); await host.CallAsync(testType.GetMethod(testName), arguments); await host.StopAsync(); }
public void Create_CustomSchedule_CreatesExpectedSchedule() { TimerTriggerAttribute attribute = new TimerTriggerAttribute(typeof(CustomSchedule)); INameResolver nameResolver = new TestNameResolver(); CustomSchedule schedule = (CustomSchedule)TimerSchedule.Create(attribute, nameResolver); Assert.NotNull(schedule); Assert.True(attribute.UseMonitor); // verify that if UseMonitor is set explicitly, it is not overridden attribute = new TimerTriggerAttribute(typeof(CustomSchedule)); attribute.UseMonitor = false; schedule = (CustomSchedule)TimerSchedule.Create(attribute, nameResolver); Assert.False(attribute.UseMonitor); }
public void Create_UsesNameResolver() { TimerTriggerAttribute attribute = new TimerTriggerAttribute("%test_schedule%"); TestNameResolver nameResolver = new TestNameResolver(); nameResolver.Values.Add("test_schedule", "*/15 * * * * *"); CronSchedule schedule = (CronSchedule)TimerSchedule.Create(attribute, nameResolver); Assert.False(attribute.UseMonitor); DateTime now = new DateTime(2015, 5, 22, 9, 45, 00); DateTime nextOccurrence = schedule.GetNextOccurrence(now); Assert.Equal(new TimeSpan(0, 0, 15), nextOccurrence - now); }
private async Task RunTestAsync(string testName, IMobileServiceClientFactory factory, TraceWriter testTrace, object argument = null, Uri configUri = null, string configKey = null, bool includeDefaultKey = true, bool includeDefaultUri = true) { Type testType = typeof(MobileTableEndToEndFunctions); ExplicitTypeLocator locator = new ExplicitTypeLocator(testType); JobHostConfiguration config = new JobHostConfiguration { TypeLocator = locator, }; config.Tracing.Tracers.Add(testTrace); var arguments = new Dictionary <string, object>(); arguments.Add("triggerData", argument); var mobileAppsConfig = new MobileAppsConfiguration { MobileAppUri = configUri, ApiKey = configKey, ClientFactory = factory }; var resolver = new TestNameResolver(); resolver.Values.Add("MyUri", AttributeUri); resolver.Values.Add("MyKey", AttributeKey); if (includeDefaultUri) { resolver.Values.Add(MobileAppsConfiguration.AzureWebJobsMobileAppUriName, DefaultUri); } if (includeDefaultKey) { resolver.Values.Add(MobileAppsConfiguration.AzureWebJobsMobileAppApiKeyName, DefaultKey); } config.NameResolver = resolver; config.UseMobileApps(mobileAppsConfig); JobHost host = new JobHost(config); await host.StartAsync(); await host.CallAsync(testType.GetMethod(testName), arguments); await host.StopAsync(); }
public async Task ValidChangeFeedOptions_Succeed(ParameterInfo parameter) { var nameResolver = new TestNameResolver(); nameResolver.Values[CosmosDBExtensionConfigProvider.AzureWebJobsCosmosDBConnectionStringName] = "AccountEndpoint=https://fromEnvironment;AccountKey=someKey;"; nameResolver.Values["CosmosDBConnectionString"] = "AccountEndpoint=https://fromSettings;AccountKey=someKey;"; CosmosDBTriggerAttributeBindingProvider provider = new CosmosDBTriggerAttributeBindingProvider(nameResolver, _options, CreateExtensionConfigProvider(_options), _loggerFactory); CosmosDBTriggerBinding binding = (CosmosDBTriggerBinding)await provider.TryCreateAsync(new TriggerBindingProviderContext(parameter, CancellationToken.None)); Assert.Equal(typeof(IReadOnlyList <Document>), binding.TriggerValueType); Assert.Equal(new Uri("https://fromSettings"), binding.DocumentCollectionLocation.Uri); Assert.Equal(10, binding.ChangeFeedOptions.MaxItemCount); Assert.True(binding.ChangeFeedOptions.StartFromBeginning); }
public async Task ValidCosmosDBTriggerBindigsPreferredLocationsParameters_Succeed(ParameterInfo parameter) { var nameResolver = new TestNameResolver(); nameResolver.Values["regions"] = "East US, North Europe,"; CosmosDBTriggerAttributeBindingProvider provider = new CosmosDBTriggerAttributeBindingProvider(_emptyConfig, nameResolver, _options, CreateExtensionConfigProvider(_options), _loggerFactory); CosmosDBTriggerBinding binding = (CosmosDBTriggerBinding)await provider.TryCreateAsync(new TriggerBindingProviderContext(parameter, CancellationToken.None)); Assert.Equal(2, binding.DocumentCollectionLocation.ConnectionPolicy.PreferredLocations.Count); Assert.Equal(2, binding.LeaseCollectionLocation.ConnectionPolicy.PreferredLocations.Count); Assert.Equal("East US", binding.DocumentCollectionLocation.ConnectionPolicy.PreferredLocations[0]); Assert.Equal("North Europe", binding.DocumentCollectionLocation.ConnectionPolicy.PreferredLocations[1]); Assert.Equal("East US", binding.LeaseCollectionLocation.ConnectionPolicy.PreferredLocations[0]); Assert.Equal("North Europe", binding.LeaseCollectionLocation.ConnectionPolicy.PreferredLocations[1]); }
private static async Task RunTestAsync(string testName, object argument = null) { Type testType = typeof(VisionFunctions); var locator = new ExplicitTypeLocator(testType); ILoggerFactory loggerFactory = new LoggerFactory(); loggerFactory.AddProvider(_loggerProvider); ICognitiveServicesClient testCognitiveServicesClient = new TestCognitiveServicesClient(); var arguments = new Dictionary <string, object>(); var resolver = new TestNameResolver(); IHost host = new HostBuilder() .ConfigureWebJobs(builder => { builder.AddVisionDescribe(); }) .ConfigureServices(services => { services.AddSingleton <ICognitiveServicesClient>(testCognitiveServicesClient); services.AddSingleton <INameResolver>(resolver); services.AddSingleton <ITypeLocator>(locator); }) .ConfigureLogging(logging => { logging.ClearProviders(); logging.AddProvider(_loggerProvider); }) .ConfigureAppConfiguration(c => { c.Sources.Clear(); var collection = new Dictionary <string, string> { { "VisionKey", "1234XYZ" }, { "VisionUrl", "http://url" } }; c.AddInMemoryCollection(collection); }) .Build(); var method = testType.GetMethod(testName); await host.GetJobHost().CallAsync(method, arguments); }
public void CreateDefaultMessage_CreatesExpectedMessage() { ParameterInfo parameter = GetType().GetMethod("TestMethod", BindingFlags.Static | BindingFlags.NonPublic).GetParameters().First(); SendGridAttribute attribute = new SendGridAttribute { To = "{Param1}", Subject = "Test {Param2}", Text = "Test {Param3}" }; SendGridConfiguration config = new SendGridConfiguration { ApiKey = "12345", FromAddress = new MailAddress("*****@*****.**", "Test2"), ToAddress = "*****@*****.**" }; Dictionary <string, Type> contract = new Dictionary <string, Type>(); contract.Add("Param1", typeof(string)); contract.Add("Param2", typeof(string)); contract.Add("Param3", typeof(string)); BindingProviderContext context = new BindingProviderContext(parameter, contract, CancellationToken.None); var nameResolver = new TestNameResolver(); SendGridBinding binding = new SendGridBinding(parameter, attribute, config, nameResolver, context); Dictionary <string, object> bindingData = new Dictionary <string, object>(); bindingData.Add("Param1", "*****@*****.**"); bindingData.Add("Param2", "Value2"); bindingData.Add("Param3", "Value3"); SendGridMessage message = binding.CreateDefaultMessage(bindingData); Assert.Same(config.FromAddress, message.From); Assert.Equal("*****@*****.**", message.To.Single().Address); Assert.Equal("Test Value2", message.Subject); Assert.Equal("Test Value3", message.Text); // If no To value specified, verify it is defaulted from config attribute = new SendGridAttribute { Subject = "Test {Param2}", Text = "Test {Param3}" }; binding = new SendGridBinding(parameter, attribute, config, nameResolver, context); message = binding.CreateDefaultMessage(bindingData); Assert.Equal("*****@*****.**", message.To.Single().Address); }
private CosmosDBExtensionConfigProvider InitializeExtensionConfigProvider(string defaultConnStr, string optionsConnStr = null) { var options = new OptionsWrapper <CosmosDBOptions>(new CosmosDBOptions { ConnectionString = optionsConnStr }); var factory = new DefaultCosmosDBServiceFactory(); var nameResolver = new TestNameResolver(); nameResolver.Values[CosmosDBExtensionConfigProvider.AzureWebJobsCosmosDBConnectionStringName] = defaultConnStr; var configProvider = new CosmosDBExtensionConfigProvider(options, factory, nameResolver, NullLoggerFactory.Instance); var context = TestHelpers.CreateExtensionConfigContext(nameResolver); configProvider.Initialize(context); return(configProvider); }
private void VerifyConstantSchedule(string expression, TimeSpan expectedInterval) { Assert.True(TimeSpan.TryParse(expression, out TimeSpan timeSpan)); Assert.Equal(timeSpan, expectedInterval); TimerTriggerAttribute attribute = new TimerTriggerAttribute(expression); INameResolver nameResolver = new TestNameResolver(); ConstantSchedule schedule = (ConstantSchedule)TimerSchedule.Create(attribute, nameResolver, _logger); DateTime now = new DateTime(2015, 5, 22, 9, 45, 00); var occurrences = schedule.GetNextOccurrences(5, now); for (int i = 0; i < 4; i++) { var delta = occurrences.ElementAt(i + 1) - occurrences.ElementAt(i); Assert.Equal(expectedInterval, delta); } }
private void RunTest(Type testType, string testName, INotificationHubClientServiceFactory factory, TraceWriter testTrace, object argument = null, string configConnectionString = ConfigConnStr, string configHubName = ConfigHubName, bool includeDefaultConnectionString = true, bool includeDefaultHubName = true) { ExplicitTypeLocator locator = new ExplicitTypeLocator(testType); JobHostConfiguration config = new JobHostConfiguration { TypeLocator = locator, }; config.Tracing.Tracers.Add(testTrace); var arguments = new Dictionary <string, object>(); arguments.Add("triggerData", argument); var notificationHubConfig = new NotificationHubsConfiguration() { ConnectionString = configConnectionString, HubName = configHubName, NotificationHubClientServiceFactory = factory }; var resolver = new TestNameResolver(); resolver.Values.Add("HubName", "ResolvedHubName"); resolver.Values.Add("MyConnectionString", AttributeConnStr); if (includeDefaultConnectionString) { resolver.Values.Add(NotificationHubsConfiguration.NotificationHubConnectionStringName, DefaultConnStr); } if (includeDefaultHubName) { resolver.Values.Add(NotificationHubsConfiguration.NotificationHubSettingName, DefaultHubName); } config.NameResolver = resolver; config.UseNotificationHubs(notificationHubConfig); JobHost host = new JobHost(config); host.Start(); host.Call(testType.GetMethod(testName), arguments); host.Stop(); }
private async Task RunTestAsync(Type testType, string testName, ICosmosDBServiceFactory factory, TraceWriter testTrace, object argument = null, string configConnectionString = ConfigConnStr, bool includeDefaultConnectionString = true) { ExplicitTypeLocator locator = new ExplicitTypeLocator(testType); JobHostConfiguration config = new JobHostConfiguration { TypeLocator = locator, }; config.Tracing.Tracers.Add(testTrace); var arguments = new Dictionary <string, object> { { "triggerData", argument } }; var cosmosDBConfig = new CosmosDBConfiguration() { ConnectionString = configConnectionString, CosmosDBServiceFactory = factory }; var resolver = new TestNameResolver(); resolver.Values.Add("Database", "ResolvedDatabase"); resolver.Values.Add("Collection", "ResolvedCollection"); resolver.Values.Add("MyConnectionString", AttributeConnStr); resolver.Values.Add("Query", "ResolvedQuery"); if (includeDefaultConnectionString) { resolver.Values.Add(CosmosDBConfiguration.AzureWebJobsCosmosDBConnectionStringName, DefaultConnStr); } config.NameResolver = resolver; config.UseCosmosDB(cosmosDBConfig); JobHost host = new JobHost(config); await host.StartAsync(); await host.CallAsync(testType.GetMethod(testName), arguments); await host.StopAsync(); }
public SingletonManagerTests() { _mockAccountProvider = new Mock<IStorageAccountProvider>(MockBehavior.Strict); _mockBlobDirectory = new Mock<IStorageBlobDirectory>(MockBehavior.Strict); _mockSecondaryBlobDirectory = new Mock<IStorageBlobDirectory>(MockBehavior.Strict); _mockStorageAccount = new Mock<IStorageAccount>(MockBehavior.Strict); _mockSecondaryStorageAccount = new Mock<IStorageAccount>(MockBehavior.Strict); Mock<IStorageBlobClient> mockBlobClient = new Mock<IStorageBlobClient>(MockBehavior.Strict); Mock<IStorageBlobClient> mockSecondaryBlobClient = new Mock<IStorageBlobClient>(MockBehavior.Strict); Mock<IStorageBlobContainer> mockBlobContainer = new Mock<IStorageBlobContainer>(MockBehavior.Strict); mockBlobContainer.Setup(p => p.GetDirectoryReference(HostDirectoryNames.SingletonLocks)).Returns(_mockBlobDirectory.Object); mockBlobClient.Setup(p => p.GetContainerReference(HostContainerNames.Hosts)).Returns(mockBlobContainer.Object); Mock<IStorageBlobContainer> mockSecondaryBlobContainer = new Mock<IStorageBlobContainer>(MockBehavior.Strict); mockSecondaryBlobContainer.Setup(p => p.GetDirectoryReference(HostDirectoryNames.SingletonLocks)).Returns(_mockSecondaryBlobDirectory.Object); mockSecondaryBlobClient.Setup(p => p.GetContainerReference(HostContainerNames.Hosts)).Returns(mockSecondaryBlobContainer.Object); _mockStorageAccount.Setup(p => p.CreateBlobClient(null)).Returns(mockBlobClient.Object); _mockSecondaryStorageAccount.Setup(p => p.CreateBlobClient(null)).Returns(mockSecondaryBlobClient.Object); _mockAccountProvider.Setup(p => p.GetAccountAsync(ConnectionStringNames.Storage, It.IsAny<CancellationToken>())) .ReturnsAsync(_mockStorageAccount.Object); _mockAccountProvider.Setup(p => p.GetAccountAsync(Secondary, It.IsAny<CancellationToken>())) .ReturnsAsync(_mockSecondaryStorageAccount.Object); _mockExceptionDispatcher = new Mock<IBackgroundExceptionDispatcher>(MockBehavior.Strict); _mockStorageBlob = new Mock<IStorageBlockBlob>(MockBehavior.Strict); _mockBlobMetadata = new Dictionary<string, string>(); _mockBlobDirectory.Setup(p => p.GetBlockBlobReference(TestLockId)).Returns(_mockStorageBlob.Object); _singletonConfig = new SingletonConfiguration(); // use reflection to bypass the normal validations (so tests can run fast) TestHelpers.SetField(_singletonConfig, "_lockAcquisitionPollingInterval", TimeSpan.FromMilliseconds(25)); TestHelpers.SetField(_singletonConfig, "_lockPeriod", TimeSpan.FromMilliseconds(500)); _singletonConfig.LockAcquisitionTimeout = TimeSpan.FromMilliseconds(200); _nameResolver = new TestNameResolver(); _singletonManager = new SingletonManager(_mockAccountProvider.Object, _mockExceptionDispatcher.Object, _singletonConfig, _trace, new FixedHostIdProvider(TestHostId), _nameResolver); _singletonManager.MinimumLeaseRenewalInterval = TimeSpan.FromMilliseconds(250); }