public AsyncChainEndToEndTests(TestFixture fixture)
        {
            _fixture    = fixture;
            _resolver   = new RandomNameResolver();
            _hostConfig = new JobHostConfiguration()
            {
                NameResolver = _resolver,
                TypeLocator  = new FakeTypeLocator(typeof(AsyncChainEndToEndTests))
            };

            _defaultExceptionHandler = new TestExceptionHandler();
            _hostConfig.AddService <IWebJobsExceptionHandler>(_defaultExceptionHandler);
            _hostConfig.Queues.MaxPollingInterval = TimeSpan.FromSeconds(2);

            _storageAccount  = fixture.StorageAccount;
            _timeoutJobDelay = TimeSpan.FromMinutes(5);

            ILoggerFactory loggerFactory = new LoggerFactory();

            loggerFactory.AddProvider(_loggerProvider);
            _hostConfig.LoggerFactory        = loggerFactory;
            _hostConfig.Aggregator.IsEnabled = false; // makes validation easier

            CloudQueueClient queueClient = _storageAccount.CreateCloudQueueClient();
            string           queueName   = _resolver.ResolveInString(TestQueueName);

            _testQueue = queueClient.GetQueueReference(queueName);
            if (!_testQueue.CreateIfNotExistsAsync().Result)
            {
                _testQueue.ClearAsync().Wait();
            }
        }
Exemple #2
0
        public async Task DynamicConcurrency_Queues()
        {
            // Reinitialize the name resolver to avoid conflicts
            _resolver = new RandomNameResolver();
            DynamicConcurrencyTestJob.InvocationCount = 0;

            IHost host = new HostBuilder()
                         .ConfigureDefaultTestHost <DynamicConcurrencyTestJob>(b =>
            {
                b.AddAzureStorageQueues();

                b.Services.AddOptions <ConcurrencyOptions>().Configure(options =>
                {
                    options.DynamicConcurrencyEnabled = true;
                });
            })
                         .ConfigureServices(services =>
            {
                services.AddSingleton <INameResolver>(_resolver);
            })
                         .ConfigureLogging((context, b) =>
            {
                b.SetMinimumLevel(LogLevel.Debug);
            })
                         .Build();

            MethodInfo methodInfo         = typeof(DynamicConcurrencyTestJob).GetMethod("ProcessMessage", BindingFlags.Public | BindingFlags.Static);
            string     functionId         = $"{methodInfo.DeclaringType.FullName}.{methodInfo.Name}";
            var        concurrencyManager = host.Services.GetServices <ConcurrencyManager>().SingleOrDefault();
            var        concurrencyStatus  = concurrencyManager.GetStatus(functionId);

            Assert.AreEqual(1, concurrencyStatus.CurrentConcurrency);

            // write a bunch of queue messages
            int    numMessages = 300;
            string queueName   = _resolver.ResolveInString(DynamicConcurrencyQueueName);

            await WriteQueueMessages(queueName, numMessages);

            // start the host
            await host.StartAsync();

            // wait for all messages to be processed
            await TestHelpers.Await(() =>
            {
                return(DynamicConcurrencyTestJob.InvocationCount >= numMessages);
            });

            await host.StopAsync();

            // ensure we've dynamically increased concurrency
            concurrencyStatus = concurrencyManager.GetStatus(functionId);
            Assert.GreaterOrEqual(concurrencyStatus.CurrentConcurrency, 5);

            // check a few of the concurrency logs
            var concurrencyLogs             = host.GetTestLoggerProvider().GetAllLogMessages().Where(p => p.Category == LogCategories.Concurrency).Select(p => p.FormattedMessage).ToList();
            int concurrencyIncreaseLogCount = concurrencyLogs.Count(p => p.Contains("ProcessMessage Increasing concurrency"));

            Assert.GreaterOrEqual(concurrencyIncreaseLogCount, 3);
        }
        private async Task AsyncChainEndToEndInternal()
        {
            _resolver = new RandomNameResolver();

            JobHostConfiguration hostConfiguration = new JobHostConfiguration()
            {
                NameResolver = _resolver,
                TypeLocator  = new FakeTypeLocator(typeof(AsyncChainEndToEndTests))
            };

            _storageAccount = CloudStorageAccount.Parse(hostConfiguration.StorageConnectionString);

            JobHost host = new JobHost(hostConfiguration);

            await host.StartAsync();

            await host.CallAsync(typeof(AsyncChainEndToEndTests).GetMethod("WriteStartDataMessageToQueue"));

            _functionCompletedEvent.WaitOne();

            // Stop async waits for the function to complete
            await host.StopAsync();

            await host.CallAsync(typeof(AsyncChainEndToEndTests).GetMethod("ReadResultBlob"));

            Assert.Equal("async works", _finalBlobContent);
        }
        /// <summary>
        /// There is a function that takes > 10 minutes and listens to a queue.
        /// </summary>
        /// <remarks>Ignored because it takes a long time. Can be enabled on demand</remarks>
        // Uncomment the Fact attribute to run
        //[Fact(Timeout = 20 * 60 * 1000)]
        public void QueueMessageLeaseRenew()
        {
            _messageFoundAgain = false;

            RandomNameResolver nameResolver = new RandomNameResolver();

            JobHostConfiguration hostConfig = new JobHostConfiguration()
            {
                NameResolver = nameResolver,
                TypeLocator  = new FakeTypeLocator(typeof(LeaseExpirationTests))
            };

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(hostConfig.StorageConnectionString);
            CloudQueueClient    queueClient    = storageAccount.CreateCloudQueueClient();
            CloudQueue          queue          = queueClient.GetQueueReference(nameResolver.ResolveInString(TestQueueName));

            try
            {
                queue.CreateIfNotExists();
                queue.AddMessage(new CloudQueueMessage("Test"));

                _tokenSource = new CancellationTokenSource();
                JobHost host = new JobHost(hostConfig);

                _tokenSource.Token.Register(host.Stop);
                host.RunAndBlock();

                Assert.False(_messageFoundAgain);
            }
            finally
            {
                queue.DeleteIfExists();
            }
        }
        private void ServiceBusEndToEndInternal()
        {
            // Reinitialize the name resolver to avoid naming conflicts
            _nameResolver = new RandomNameResolver();

            JobHostConfiguration config = new JobHostConfiguration()
            {
                NameResolver = _nameResolver,
                TypeLocator  = new FakeTypeLocator(this.GetType())
            };

            _namespaceManager = NamespaceManager.CreateFromConnectionString(config.ServiceBusConnectionString);

            CreateStartMessage(config.ServiceBusConnectionString);

            JobHost host = new JobHost(config);

            _topicSubscriptionCalled1 = new ManualResetEvent(initialState: false);
            _topicSubscriptionCalled2 = new ManualResetEvent(initialState: false);

            host.Start();

            bool signaled = WaitHandle.WaitAll(
                new WaitHandle[] { _topicSubscriptionCalled1, _topicSubscriptionCalled2 },
                2 * 60 * 1000);

            // Wait for the host to terminate
            host.Stop();

            Assert.True(signaled);

            Assert.Equal("E2E-SBQueue2SBQueue-SBQueue2SBTopic-topic-1", _resultMessage1);
            Assert.Equal("E2E-SBQueue2SBQueue-SBQueue2SBTopic-topic-2", _resultMessage2);
        }
        public IHost ConfigureHost(LogLevel logLevel)
        {
            _resolver = new RandomNameResolver();

            IHost host = new HostBuilder()
                         .ConfigureDefaultTestHost <HttpDependencyCollectionTests>(b =>
            {
                b.AddAzureStorage();
            })
                         .ConfigureServices(services =>
            {
                services.AddSingleton <INameResolver>(_resolver);
                services.Configure <FunctionResultAggregatorOptions>(o =>
                {
                    o.IsEnabled = false;
                });
            })
                         .ConfigureLogging(b =>
            {
                b.SetMinimumLevel(logLevel);
                b.AddApplicationInsightsWebJobs(o => o.InstrumentationKey = _mockApplicationInsightsKey);
            })
                         .Build();

            TelemetryConfiguration telemteryConfiguration = host.Services.GetService <TelemetryConfiguration>();

            telemteryConfiguration.TelemetryChannel = _channel;

            StorageAccountProvider provider       = host.Services.GetService <StorageAccountProvider>();
            CloudStorageAccount    storageAccount = provider.GetHost().SdkObject;

            _blobClient  = storageAccount.CreateCloudBlobClient();
            _queueClient = storageAccount.CreateCloudQueueClient();

            _inputContainerName   = _resolver.ResolveInString(InputContainerNamePattern);
            _outputContainerName  = _resolver.ResolveInString(OutputContainerNamePattern);
            _triggerContainerName = _resolver.ResolveInString(TriggerContainerNamePattern);
            _outputQueueName      = _resolver.ResolveInString(OutputQueueNamePattern);
            _triggerQueueName     = _resolver.ResolveInString(TriggerQueueNamePattern);

            CloudBlobContainer inContainer      = _blobClient.GetContainerReference(_inputContainerName);
            CloudBlobContainer outContainer     = _blobClient.GetContainerReference(_outputContainerName);
            CloudBlobContainer triggerContainer = _blobClient.GetContainerReference(_triggerContainerName);
            CloudQueue         outputQueue      = _queueClient.GetQueueReference(_outputQueueName);

            _triggerQueue = _queueClient.GetQueueReference(_triggerQueueName);

            inContainer.CreateIfNotExistsAsync().Wait();
            outContainer.CreateIfNotExistsAsync().Wait();
            triggerContainer.CreateIfNotExistsAsync().Wait();
            outputQueue.CreateIfNotExistsAsync().Wait();
            _triggerQueue.CreateIfNotExistsAsync().Wait();

            CloudBlockBlob inBlob = inContainer.GetBlockBlobReference("in");

            inBlob.UploadTextAsync("TestData").Wait();

            return(host);
        }
Exemple #7
0
        public ServiceBusEndToEndTests()
        {
            _serviceBusConfig          = new ServiceBusConfiguration();
            _nameResolver              = new RandomNameResolver();
            _secondaryConnectionString = AmbientConnectionStringProvider.Instance.GetConnectionString("ServiceBusSecondary");

            _loggerFactory.AddProvider(_loggerProvider);
        }
Exemple #8
0
 public ServiceBusEndToEndTests()
 {
     _serviceBusConfig          = new ServiceBusConfiguration();
     _nameResolver              = new RandomNameResolver();
     _namespaceManager          = NamespaceManager.CreateFromConnectionString(_serviceBusConfig.ConnectionString);
     _secondaryConnectionString = AmbientConnectionStringProvider.Instance.GetConnectionString("ServiceBusSecondary");
     _secondaryNamespaceManager = NamespaceManager.CreateFromConnectionString(_secondaryConnectionString);
 }
        public AsyncChainEndToEndTests(TestFixture fixture)
        {
            _resolver   = new RandomNameResolver();
            _hostConfig = new JobHostConfiguration()
            {
                NameResolver = _resolver,
                TypeLocator  = new FakeTypeLocator(typeof(AsyncChainEndToEndTests))
            };

            _storageAccount = fixture.StorageAccount;
        }
Exemple #10
0
        public BlobTriggerEndToEndTests()
        {
            _nameResolver = new RandomNameResolver();

            var storageConnectionString = new JobHostConfiguration().StorageConnectionString;

            _storageAccount = CloudStorageAccount.Parse(storageConnectionString);
            CloudBlobClient blobClient = _storageAccount.CreateCloudBlobClient();

            _testContainer = blobClient.GetContainerReference(_nameResolver.ResolveInString(SingleTriggerContainerName));
            Assert.False(_testContainer.ExistsAsync().Result);
            _testContainer.CreateAsync().Wait();
        }
        public ServiceBusSessionsBusEndToEndTests()
        {
            var config = new ConfigurationBuilder()
                         .AddEnvironmentVariables()
                         .AddTestSettings()
                         .Build();

            _connectionString = config.GetConnectionStringOrSetting(ServiceBus.Constants.DefaultConnectionStringName);

            _nameResolver = new RandomNameResolver();

            Cleanup().GetAwaiter().GetResult();
        }
        public AsyncChainEndToEndTests(TestFixture fixture)
        {
            _resolver   = new RandomNameResolver();
            _hostConfig = new JobHostConfiguration()
            {
                NameResolver = _resolver,
                TypeLocator  = new FakeTypeLocator(typeof(AsyncChainEndToEndTests))
            };

            _hostConfig.Queues.MaxPollingInterval = TimeSpan.FromSeconds(2);

            _storageAccount = fixture.StorageAccount;
        }
        public async Task MaxDegreeOfParallelism_Queues(int batchSize, int maxExpectedParallelism)
        {
            _receivedMessages = 0;
            _currentSimultaneouslyRunningFunctions = 0;
            _maxSimultaneouslyRunningFunctions     = 0;
            _numberOfQueueMessages = batchSize * 3;

            RandomNameResolver nameResolver = new RandomNameResolver();
            IHost host = new HostBuilder()
                         .ConfigureDefaultTestHost <ParallelExecutionTests>(b =>
            {
                b.AddAzureStorage();
            })
                         .ConfigureServices(services =>
            {
                services.AddSingleton <INameResolver>(nameResolver);
                services.Configure <QueuesOptions>(o => o.BatchSize = batchSize);
            })
                         .Build();

            StorageAccount storageAccount = host.GetStorageAccount();

            _queueClient = storageAccount.CreateCloudQueueClient();
            CloudQueue queue = _queueClient.GetQueueReference(nameResolver.ResolveInString(TestQueueName));

            await queue.CreateIfNotExistsAsync();

            for (int i = 0; i < _numberOfQueueMessages; i++)
            {
                int sleepTimeInSeconds = i % 2 == 0 ? 5 : 1;
                await queue.AddMessageAsync(new CloudQueueMessage(sleepTimeInSeconds.ToString()));
            }

            using (_allMessagesProcessed = new ManualResetEvent(initialState: false))
                using (host)
                {
                    await host.StartAsync();

                    _allMessagesProcessed.WaitOne(TimeSpan.FromSeconds(90));
                    await host.StopAsync();
                }

            Assert.Equal(_numberOfQueueMessages, _receivedMessages);
            Assert.Equal(0, _currentSimultaneouslyRunningFunctions);

            // the actual value will vary sometimes based on the speed of the machine
            // running the test.
            int delta = _maxSimultaneouslyRunningFunctions - maxExpectedParallelism;

            Assert.True(delta == 0 || delta == 1, $"Expected delta of 0 or 1. Actual: {delta}.");
        }
        public void MaxDegreeOfParallelism_Queues(int batchSize)
        {
            _receivedMessages = 0;
            _currentSimultaneouslyRunningFunctions = 0;
            _maxSimultaneouslyRunningFunctions     = 0;

            int expectedMaxSimultaneouslyRunningFunctions = (int)Math.Floor(batchSize + 0.5 * batchSize);

            _numberOfQueueMessages = batchSize * 3;

            RandomNameResolver   nameResolver      = new RandomNameResolver();
            JobHostConfiguration hostConfiguration = new JobHostConfiguration()
            {
                NameResolver = nameResolver,
                TypeLocator  = new FakeTypeLocator(typeof(ParallelExecutionTests)),
            };

            hostConfiguration.Queues.BatchSize = batchSize;

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(hostConfiguration.StorageConnectionString);
            CloudQueueClient    queueClient    = storageAccount.CreateCloudQueueClient();
            CloudQueue          queue          = queueClient.GetQueueReference(nameResolver.ResolveInString(TestQueueName));

            queue.CreateIfNotExists();

            try
            {
                for (int i = 0; i < _numberOfQueueMessages; i++)
                {
                    int sleepTimeInSeconds = i % 2 == 0 ? 5 : 1;
                    queue.AddMessage(new CloudQueueMessage(sleepTimeInSeconds.ToString()));
                }

                using (_allMessagesProcessed = new ManualResetEvent(initialState: false))
                    using (JobHost host = new JobHost(hostConfiguration))
                    {
                        host.Start();
                        _allMessagesProcessed.WaitOne(TimeSpan.FromSeconds(90));
                        host.Stop();
                    }

                Assert.Equal(_numberOfQueueMessages, _receivedMessages);
                Assert.Equal(0, _currentSimultaneouslyRunningFunctions);
                Assert.Equal(expectedMaxSimultaneouslyRunningFunctions, _maxSimultaneouslyRunningFunctions);
            }
            finally
            {
                queue.DeleteIfExists();
            }
        }
        public ServiceBusEndToEndTests()
        {
            var config = new ConfigurationBuilder()
                         .AddEnvironmentVariables()
                         .Build();

            var configSection = Utility.GetExtensionConfigurationSection(config, "ServiceBus");

            _primaryConnectionString   = configSection.GetConnectionString("Primary");
            _secondaryConnectionString = configSection.GetConnectionString("Secondary");

            _nameResolver = new RandomNameResolver();

            Cleanup().GetAwaiter().GetResult();
        }
        public Task <JobHostContext> CreateAndLogHostStartedAsync(JobHost host, CancellationToken shutdownToken, CancellationToken cancellationToken)
        {
            INameResolver        nameResolver = new RandomNameResolver();
            JobHostConfiguration config       = new JobHostConfiguration
            {
                NameResolver = nameResolver,
                TypeLocator  = TypeLocator
            };

            return(JobHostContextFactory.CreateAndLogHostStartedAsync(
                       host, StorageAccountProvider, QueueConfiguration, TypeLocator, DefaultJobActivator.Instance, nameResolver,
                       ConsoleProvider, new JobHostConfiguration(), shutdownToken, cancellationToken, BackgroundExceptionDispatcher, HostIdProvider, FunctionExecutor,
                       FunctionIndexProvider, BindingProvider, HostInstanceLoggerProvider, FunctionInstanceLoggerProvider,
                       FunctionOutputLoggerProvider));
        }
        public ServiceBusEndToEndTests()
        {
            var config = new ConfigurationBuilder()
                         .AddEnvironmentVariables()
                         .AddTestSettings()
                         .Build();

            _eventWait = new ManualResetEvent(initialState: false);

            _primaryConnectionString   = config.GetConnectionStringOrSetting(ServiceBus.Constants.DefaultConnectionStringName);
            _secondaryConnectionString = config.GetConnectionStringOrSetting(SecondaryConnectionStringKey);

            _nameResolver = new RandomNameResolver();

            Cleanup().GetAwaiter().GetResult();
        }
Exemple #18
0
            public async Task InitializeAsync(WebJobsTestEnvironment testEnvironment)
            {
                RandomNameResolver nameResolver = new RandomNameResolver();

                CacheMock = CreateMockFunctionDataCache();
                CacheMock
                .Setup(c => c.IsEnabled)
                .Returns(true);
                IFunctionDataCache cache = CacheMock.Object;

                Host = new HostBuilder()
                       .ConfigureDefaultTestHost <CacheableBlobsEndToEndTests>(b =>
                {
                    b.AddAzureStorageBlobs().AddAzureStorageQueues();
                    b.AddAzureStorageCoreServices();
                })
                       .ConfigureServices(services =>
                {
                    services.AddSingleton <INameResolver>(nameResolver)
                    .AddSingleton(cache);
                })
                       .Build();

                JobHost = Host.GetJobHost();

                BlobServiceClient = new BlobServiceClient(testEnvironment.PrimaryStorageAccountConnectionString);

                BlobContainer = BlobServiceClient.GetBlobContainerClient(nameResolver.ResolveInString(ContainerName));
                Assert.False(await BlobContainer.ExistsAsync());
                await BlobContainer.CreateAsync();

                OutputBlobContainer = BlobServiceClient.GetBlobContainerClient(nameResolver.ResolveInString(OutputContainerName));

                await Host.StartAsync();

                // Upload some test blobs
                BlockBlobClient blob = BlobContainer.GetBlockBlobClient(InputBlobName);
                await blob.UploadTextAsync(TestData);

                // Get information about the uploaded blob
                BlobProperties blobProperties = await blob.GetPropertiesAsync();

                string blobId      = blob.Uri.ToString();
                string blobVersion = blobProperties.ETag.ToString();

                _expectedBlobCacheKey = new FunctionDataCacheKey(blobId, blobVersion);
            }
        public async Task MaxDegreeOfParallelism_Queues(int batchSize, int maxExpectedParallelism)
        {
            _receivedMessages = 0;
            _currentSimultaneouslyRunningFunctions = 0;
            _maxSimultaneouslyRunningFunctions     = 0;
            _numberOfQueueMessages = batchSize * 3;

            RandomNameResolver   nameResolver      = new RandomNameResolver();
            JobHostConfiguration hostConfiguration = new JobHostConfiguration()
            {
                NameResolver = nameResolver,
                TypeLocator  = new FakeTypeLocator(typeof(ParallelExecutionTests)),
            };

            hostConfiguration.AddService <IWebJobsExceptionHandler>(new TestExceptionHandler());
            hostConfiguration.Queues.BatchSize = batchSize;

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(hostConfiguration.StorageConnectionString);

            _queueClient = storageAccount.CreateCloudQueueClient();
            CloudQueue queue = _queueClient.GetQueueReference(nameResolver.ResolveInString(TestQueueName));

            await queue.CreateIfNotExistsAsync();

            for (int i = 0; i < _numberOfQueueMessages; i++)
            {
                int sleepTimeInSeconds = i % 2 == 0 ? 5 : 1;
                await queue.AddMessageAsync(new CloudQueueMessage(sleepTimeInSeconds.ToString()));
            }

            using (_allMessagesProcessed = new ManualResetEvent(initialState: false))
                using (JobHost host = new JobHost(hostConfiguration))
                {
                    host.Start();
                    _allMessagesProcessed.WaitOne(TimeSpan.FromSeconds(90));
                    host.Stop();
                }

            Assert.Equal(_numberOfQueueMessages, _receivedMessages);
            Assert.Equal(0, _currentSimultaneouslyRunningFunctions);

            // the actual value will vary sometimes based on the speed of the machine
            // running the test.
            int delta = _maxSimultaneouslyRunningFunctions - maxExpectedParallelism;

            Assert.True(delta == 0 || delta == 1);
        }
Exemple #20
0
        public AsyncCancellationEndToEndTests()
        {
            _resolver = new RandomNameResolver();

            _hostConfiguration = new JobHostConfiguration()
            {
                NameResolver = _resolver,
                TypeLocator  = new FakeTypeLocator(typeof(AsyncCancellationEndToEndTests))
            };

            _storageAccount = CloudStorageAccount.Parse(_hostConfiguration.StorageConnectionString);

            _invokeInFunction  = () => { };
            _tokenCancelled    = false;
            _functionStarted   = new ManualResetEvent(initialState: false);
            _functionCompleted = new ManualResetEvent(initialState: false);
        }
        private async Task EndToEndTest(bool uploadBlobBeforeHostStart)
        {
            // Reinitialize the name resolver to avoid conflicts
            _resolver = new RandomNameResolver();

            IHost host = new HostBuilder()
                         .ConfigureDefaultTestHost <AzureStorageEndToEndTests>(b =>
            {
                b.AddAzureStorage();
            })
                         .ConfigureServices(services =>
            {
                services.AddSingleton <INameResolver>(_resolver);
            })
                         .Build();

            if (uploadBlobBeforeHostStart)
            {
                // The function will be triggered fast because the blob is already there
                await UploadTestObject();
            }

            // The jobs host is started
            JobHost jobHost = host.GetJobHost();

            _functionChainWaitHandle = new ManualResetEvent(initialState: false);

            await host.StartAsync();

            if (!uploadBlobBeforeHostStart)
            {
                await WaitForTestFunctionsToStart();
                await UploadTestObject();
            }

            var  waitTime = TimeSpan.FromSeconds(15);
            bool signaled = _functionChainWaitHandle.WaitOne(waitTime);

            // Stop the host and wait for it to finish
            await host.StopAsync();

            Assert.True(signaled, $"[{DateTime.UtcNow.ToString("HH:mm:ss.fff")}] Function chain did not complete in {waitTime}. Logs:{Environment.NewLine}{host.GetTestLoggerProvider().GetLogString()}");

            // Verify
            await VerifyTableResultsAsync();
        }
        public LeaseExpirationTests()
        {
            RandomNameResolver nameResolver = new RandomNameResolver();

            _config = new JobHostConfiguration()
            {
                NameResolver = nameResolver,
                TypeLocator  = new FakeTypeLocator(typeof(LeaseExpirationTests))
            };

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_config.StorageConnectionString);

            _queueClient = storageAccount.CreateCloudQueueClient();

            _queue = _queueClient.GetQueueReference(nameResolver.ResolveInString(TestQueueName));
            _queue.CreateIfNotExistsAsync().Wait();
        }
        public Task <JobHostContext> CreateAndLogHostStartedAsync(CancellationToken shutdownToken, CancellationToken cancellationToken)
        {
            ITypeLocator         typeLocator  = new DefaultTypeLocator(new StringWriter());
            INameResolver        nameResolver = new RandomNameResolver();
            JobHostConfiguration config       = new JobHostConfiguration
            {
                NameResolver = nameResolver,
                TypeLocator  = typeLocator
            };

            return(JobHostContextFactory.CreateAndLogHostStartedAsync(
                       StorageAccountProvider, config.Queues, typeLocator, DefaultJobActivator.Instance, nameResolver,
                       new NullConsoleProvider(), new JobHostConfiguration(), shutdownToken, cancellationToken,
                       new FixedHostIdProvider(Guid.NewGuid().ToString("N")),
                       null, new EmptyFunctionIndexProvider(),
                       null, new NullHostInstanceLoggerProvider(), new NullFunctionInstanceLoggerProvider(), new NullFunctionOutputLoggerProvider()));
        }
        public BlobTriggerEndToEndTests()
        {
            _nameResolver = new RandomNameResolver();

            // pull from a default host
            var host = new HostBuilder()
                       .ConfigureDefaultTestHost(b =>
            {
                b.AddAzureStorageBlobs().AddAzureStorageQueues();
            })
                       .Build();

            _blobServiceClient = new BlobServiceClient(TestEnvironment.PrimaryStorageAccountConnectionString);
            _testContainer     = _blobServiceClient.GetBlobContainerClient(_nameResolver.ResolveInString(SingleTriggerContainerName));
            Assert.False(_testContainer.ExistsAsync().Result);
            _testContainer.CreateAsync().Wait();
        }
Exemple #25
0
        public BlobTriggerEndToEndTests()
        {
            _timesProcessed = 0;

            _nameResolver      = new RandomNameResolver();
            _hostConfiguration = new JobHostConfiguration()
            {
                NameResolver = _nameResolver,
                TypeLocator  = new FakeTypeLocator(this.GetType()),
            };

            _storageAccount = CloudStorageAccount.Parse(_hostConfiguration.StorageConnectionString);
            CloudBlobClient blobClient = _storageAccount.CreateCloudBlobClient();

            _testContainer = blobClient.GetContainerReference(_nameResolver.ResolveInString(SingleTriggerContainerName));
            Assert.False(_testContainer.Exists());
            _testContainer.Create();
        }
        private async Task EndToEndTest(bool uploadBlobBeforeHostStart)
        {
            // Reinitialize the name resolver to avoid conflicts
            _resolver = new RandomNameResolver();

            JobHostConfiguration hostConfig = new JobHostConfiguration()
            {
                NameResolver = _resolver,
                TypeLocator  = new FakeTypeLocator(
                    this.GetType(),
                    typeof(BlobToCustomObjectBinder))
            };

            hostConfig.AddService <IWebJobsExceptionHandler>(new TestExceptionHandler());

            if (uploadBlobBeforeHostStart)
            {
                // The function will be triggered fast because the blob is already there
                await UploadTestObject();
            }

            // The jobs host is started
            JobHost host = new JobHost(hostConfig);

            _functionChainWaitHandle = new ManualResetEvent(initialState: false);

            host.Start();

            if (!uploadBlobBeforeHostStart)
            {
                await WaitForTestFunctionsToStart();
                await UploadTestObject();
            }

            bool signaled = _functionChainWaitHandle.WaitOne(15 * 1000);

            // Stop the host and wait for it to finish
            host.Stop();

            Assert.True(signaled);

            // Verify
            await VerifyTableResultsAsync();
        }
        private void EndToEndTestInternal(bool uploadBlobBeforeHostStart)
        {
            // Reinitialize the name resolver to avoid conflicts
            _resolver = new RandomNameResolver();

            JobHostConfiguration hostConfig = new JobHostConfiguration()
            {
                NameResolver = _resolver,
                TypeLocator  = new FakeTypeLocator(
                    this.GetType(),
                    typeof(BlobToCustomObjectBinder))
            };

            _storageAccount = CloudStorageAccount.Parse(hostConfig.StorageConnectionString);

            if (uploadBlobBeforeHostStart)
            {
                // The function will be triggered fast because the blob is already there
                UploadTestObject();
            }

            // The jobs host is started
            JobHost host = new JobHost(hostConfig);

            _functionChainWaitHandle = new ManualResetEvent(initialState: false);

            host.Start();

            if (!uploadBlobBeforeHostStart)
            {
                WaitForTestFunctionsToStart();
                UploadTestObject();
            }

            bool signaled = _functionChainWaitHandle.WaitOne(15 * 60 * 1000);

            // Stop the host and wait for it to finish
            host.Stop();

            Assert.True(signaled);

            // Verify
            VerifyTableResults();
        }
Exemple #28
0
        public ServiceBusSessionsBusEndToEndTests(ITestOutputHelper output)
        {
            outputLogger = output;

            var config = new ConfigurationBuilder()
                         .AddEnvironmentVariables()
                         .AddTestSettings()
                         .Build();

            // Add all test configuration to the environment as WebJobs requires a few of them to be in the environment
            foreach (var kv in config.AsEnumerable())
            {
                Environment.SetEnvironmentVariable(kv.Key, kv.Value);
            }
            _connectionString = config.GetConnectionStringOrSetting(ServiceBus.Constants.DefaultConnectionStringName);

            _nameResolver = new RandomNameResolver();

            Cleanup().GetAwaiter().GetResult();
        }
Exemple #29
0
        public BlobTriggerEndToEndTests()
        {
            _nameResolver = new RandomNameResolver();

            // pull from a default host
            var host = new HostBuilder()
                       .ConfigureDefaultTestHost(b =>
            {
                b.AddAzureStorageBlobs().AddAzureStorageQueues();
            })
                       .Build();
            var provider = host.Services.GetService <StorageAccountProvider>();

            _storageAccount = provider.GetHost();
            var blobClient = _storageAccount.CreateBlobServiceClient();

            _testContainer = blobClient.GetBlobContainerClient(_nameResolver.ResolveInString(SingleTriggerContainerName));
            Assert.False(_testContainer.ExistsAsync().Result);
            _testContainer.CreateAsync().Wait();
        }
        public IHost ConfigureHost()
        {
            _resolver = new RandomNameResolver();

            IHost host = new HostBuilder()
                         .ConfigureDefaultTestHost <ServiceBusRequestAndDependencyCollectionTests>(b =>
            {
                b.AddAzureStorage();
                b.AddServiceBus();
            })
                         .ConfigureLogging(b =>
            {
                b.SetMinimumLevel(LogLevel.Information);
                b.AddApplicationInsights(o => o.InstrumentationKey = _mockApplicationInsightsKey);
            })
                         .Build();

            TelemetryConfiguration telemteryConfiguration = host.Services.GetService <TelemetryConfiguration>();

            telemteryConfiguration.TelemetryChannel = _channel;

            return(host);
        }