public ApplicationInsightsTestFixture(string scriptRoot, string testId) { _settingsManager = ScriptSettingsManager.Instance; HostSettings = new WebHostSettings { IsSelfHost = true, ScriptPath = Path.Combine(Environment.CurrentDirectory, scriptRoot), LogPath = Path.Combine(Path.GetTempPath(), @"Functions"), SecretsPath = Environment.CurrentDirectory, // not used LoggerFactoryBuilder = new TestLoggerFactoryBuilder(Channel), IsAuthDisabled = true }; WebApiConfig.Register(_config, _settingsManager, HostSettings); var resolver = _config.DependencyResolver; var hostConfig = resolver.GetService <WebHostResolver>().GetScriptHostConfiguration(HostSettings); _settingsManager.ApplicationInsightsInstrumentationKey = TestChannelLoggerFactoryBuilder.ApplicationInsightsKey; InitializeConfig(hostConfig); _httpServer = new HttpServer(_config); HttpClient = new HttpClient(_httpServer) { BaseAddress = new Uri("https://localhost/") }; TestHelpers.WaitForWebHost(HttpClient); }
public ControllerScenarioTestFixture() { _config = new HttpConfiguration(); _settingsManager = ScriptSettingsManager.Instance; HostSettings = new WebHostSettings { IsSelfHost = true, ScriptPath = Path.Combine(Environment.CurrentDirectory, @"..\..\..\..\..\sample"), LogPath = Path.Combine(Path.GetTempPath(), @"Functions"), SecretsPath = Path.Combine(Path.GetTempPath(), @"FunctionsTests\Secrets") }; var webHostBuilder = new WebHostBuilder() .UseStartup <Startup>() .ConfigureAppConfiguration(c => c.AddEnvironmentVariables()); ConfigureWebHostBuilder(webHostBuilder); HttpServer = new TestServer(webHostBuilder); HttpClient = HttpServer.CreateClient(); HttpClient.BaseAddress = new Uri("https://localhost/"); TestHelpers.WaitForWebHost(HttpClient); }
public TestFunctionHost(string appRoot) { _appRoot = appRoot; _hostSettings = new WebHostSettings { IsSelfHost = true, ScriptPath = _appRoot, LogPath = Path.Combine(Path.GetTempPath(), @"Functions"), SecretsPath = Environment.CurrentDirectory // not used }; _testServer = new TestServer( Microsoft.AspNetCore.WebHost.CreateDefaultBuilder() .UseStartup <Startup>() .ConfigureServices(services => { services.Replace(new ServiceDescriptor(typeof(WebHostSettings), _hostSettings)); services.Replace(new ServiceDescriptor(typeof(ILoggerProviderFactory), new TestLoggerProviderFactory(_loggerProvider, includeDefaultLoggerProviders: false))); services.Replace(new ServiceDescriptor(typeof(ISecretManager), new TestSecretManager())); })); HttpClient = new HttpClient(new UpdateContentLengthHandler(_testServer.CreateHandler())); HttpClient.BaseAddress = new Uri("https://localhost/"); }
public WebScriptHostManagerTests(WebScriptHostManagerTests.Fixture fixture) { _fixture = fixture; _settingsManager = ScriptSettingsManager.Instance; string functionTestDir = Path.Combine(_fixture.TestFunctionRoot, Guid.NewGuid().ToString()); Directory.CreateDirectory(functionTestDir); string logDir = Path.Combine(_fixture.TestLogsRoot, Guid.NewGuid().ToString()); string secretsDir = Path.Combine(_fixture.TestSecretsRoot, Guid.NewGuid().ToString()); _config = new ScriptHostConfiguration { RootLogPath = logDir, RootScriptPath = functionTestDir, FileLoggingMode = FileLoggingMode.Always, }; var secretsRepository = new FileSystemSecretsRepository(_secretsDirectory.Path); SecretManager secretManager = new SecretManager(_settingsManager, secretsRepository, NullTraceWriter.Instance, null); WebHostSettings webHostSettings = new WebHostSettings { SecretsPath = _secretsDirectory.Path }; var mockEventManager = new Mock <IScriptEventManager>(); _mockScriptHostFactory = new Mock <IScriptHostFactory>(); _hostManager = new WebScriptHostManager(_config, new TestSecretManagerFactory(secretManager), mockEventManager.Object, _settingsManager, webHostSettings, _mockScriptHostFactory.Object, new DefaultSecretsRepositoryFactory(), 2, 500); }
public TestFixture() { _config = new HttpConfiguration(); _config.Formatters.Add(new PlaintextMediaTypeFormatter()); _settingsManager = ScriptSettingsManager.Instance; HostSettings = new WebHostSettings { IsSelfHost = true, ScriptPath = Path.Combine(Environment.CurrentDirectory, @"..\..\..\..\sample"), LogPath = Path.Combine(Path.GetTempPath(), @"Functions"), SecretsPath = Path.Combine(Environment.CurrentDirectory, @"..\..\..\..\src\WebJobs.Script.WebHost\App_Data\Secrets") }; WebApiConfig.Register(_config, _settingsManager, HostSettings); HttpServer = new HttpServer(_config); this.HttpClient = new HttpClient(HttpServer); this.HttpClient.BaseAddress = new Uri("https://localhost/"); string connectionString = AmbientConnectionStringProvider.Instance.GetConnectionString("Storage"); CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString); BlobClient = storageAccount.CreateCloudBlobClient(); QueueClient = storageAccount.CreateCloudQueueClient(); TableClient = storageAccount.CreateCloudTableClient(); var table = TableClient.GetTableReference("samples"); table.CreateIfNotExists(); var batch = new TableBatchOperation(); batch.InsertOrReplace(new TestEntity { PartitionKey = "samples-python", RowKey = "1", Title = "Test Entity 1", Status = 0 }); batch.InsertOrReplace(new TestEntity { PartitionKey = "samples-python", RowKey = "2", Title = "Test Entity 2", Status = 0 }); batch.InsertOrReplace(new TestEntity { PartitionKey = "samples-python", RowKey = "3", Title = "Test Entity 3", Status = 1 }); batch.InsertOrReplace(new TestEntity { PartitionKey = "samples-python", RowKey = "4", Title = "Test Entity 4", Status = 0 }); batch.InsertOrReplace(new TestEntity { PartitionKey = "samples-python", RowKey = "5", Title = "Test Entity 5", Status = 0 }); batch.InsertOrReplace(new TestEntity { PartitionKey = "samples-python", RowKey = "6", Title = "Test Entity 6", Status = 0 }); batch.InsertOrReplace(new TestEntity { PartitionKey = "samples-python", RowKey = "7", Title = "Test Entity 7", Status = 0 }); table.ExecuteBatch(batch); connectionString = AmbientConnectionStringProvider.Instance.GetConnectionString(ConnectionStringNames.ServiceBus); NamespaceManager = NamespaceManager.CreateFromConnectionString(connectionString); WaitForHost(); }
private async Task <IWebHost> BuildWebHost(WebHostSettings hostSettings, Uri baseAddress, X509Certificate2 certificate) { IDictionary <string, string> settings = await GetConfigurationSettings(hostSettings.ScriptPath, baseAddress); UpdateEnvironmentVariables(settings); var defaultBuilder = Microsoft.AspNetCore.WebHost.CreateDefaultBuilder(Array.Empty <string>()); if (UseHttps) { defaultBuilder .UseKestrel(options => { options.Listen(IPAddress.Loopback, baseAddress.Port, listenOptins => { listenOptins.UseHttps(certificate); }); }); } var arguments = IConfigurationArguments.Select(pair => $"/workers:{pair.Key}={pair.Value}").ToArray(); return(defaultBuilder .UseSetting(WebHostDefaults.ApplicationKey, typeof(Startup).Assembly.GetName().Name) .UseUrls(baseAddress.ToString()) .ConfigureAppConfiguration(configBuilder => { configBuilder.AddEnvironmentVariables() .AddCommandLine(arguments); }) .ConfigureServices((context, services) => services.AddSingleton <IStartup>(new Startup(context, hostSettings, CorsOrigins))) .Build()); }
public AuthorizationLevelAttributeTests() { _actionContext = new HttpActionContext(); HttpControllerContext controllerContext = new HttpControllerContext(); _actionContext.ControllerContext = controllerContext; HttpConfiguration httpConfig = new HttpConfiguration(); controllerContext.Configuration = httpConfig; Mock <IDependencyResolver> mockDependencyResolver = new Mock <IDependencyResolver>(MockBehavior.Strict); httpConfig.DependencyResolver = mockDependencyResolver.Object; _mockSecretManager = new Mock <ISecretManager>(MockBehavior.Strict); _hostSecrets = new HostSecretsInfo { MasterKey = testMasterKeyValue, FunctionKeys = new Dictionary <string, string> { { "1", TestHostFunctionKeyValue1 }, { "2", TestHostFunctionKeyValue2 } } }; _mockSecretManager.Setup(p => p.GetHostSecretsAsync()).ReturnsAsync(_hostSecrets); _functionSecrets = new Dictionary <string, string> { { "1", TestFunctionKeyValue1 }, { "2", TestFunctionKeyValue2 } }; _mockSecretManager.Setup(p => p.GetFunctionSecretsAsync(It.IsAny <string>(), false)).ReturnsAsync(_functionSecrets); mockDependencyResolver.Setup(p => p.GetService(typeof(ISecretManager))).Returns(_mockSecretManager.Object); _webHostSettings = new WebHostSettings(); mockDependencyResolver.Setup(p => p.GetService(typeof(WebHostSettings))).Returns(_webHostSettings); }
public KeysController(WebHostSettings settings, ISecretManager secretManager, ILoggerFactory loggerFactory, IFileSystem fileSystem) { _settings = settings; _secretManager = secretManager; _logger = loggerFactory.CreateLogger(ScriptConstants.LogCategoryKeysController); _fileSystem = fileSystem; }
public WebScriptHostManagerTests(WebScriptHostManagerTests.Fixture fixture) { _fixture = fixture; _settingsManager = ScriptSettingsManager.Instance; string functionTestDir = Path.Combine(_fixture.TestFunctionRoot, Guid.NewGuid().ToString()); Directory.CreateDirectory(functionTestDir); string logDir = Path.Combine(_fixture.TestLogsRoot, Guid.NewGuid().ToString()); string secretsDir = Path.Combine(_fixture.TestSecretsRoot, Guid.NewGuid().ToString()); _config = new ScriptHostConfiguration { RootLogPath = logDir, RootScriptPath = functionTestDir, FileLoggingMode = FileLoggingMode.Always, }; var secretsRepository = new FileSystemSecretsRepository(_secretsDirectory.Path); SecretManager secretManager = new SecretManager(_settingsManager, secretsRepository, NullLogger.Instance); WebHostSettings webHostSettings = new WebHostSettings { SecretsPath = _secretsDirectory.Path }; var mockEventManager = new Mock <IScriptEventManager>(); _mockScriptHostFactory = new Mock <IScriptHostFactory>(); IWebJobsRouter router = fixture.CreateRouter(); _hostManager = new WebScriptHostManager(_config, new TestSecretManagerFactory(secretManager), mockEventManager.Object, _settingsManager, webHostSettings, router, NullLoggerFactory.Instance, secretsRepositoryFactory: new DefaultSecretsRepositoryFactory(), hostTimeoutSeconds: 2, hostPollingIntervalMilliseconds: 500, scriptHostFactory: _mockScriptHostFactory.Object); }
public WebScriptHostHandlerTests() { _settingsManager = ScriptSettingsManager.Instance; var eventManager = new Mock <IScriptEventManager>(); _managerMock = new Mock <WebScriptHostManager>(MockBehavior.Strict, new ScriptHostConfiguration(), new TestSecretManagerFactory(), eventManager.Object, _settingsManager, new WebHostSettings { SecretsPath = _secretsDirectory.Path }, null, null, null, 1, 50); _managerMock.SetupGet(p => p.Initialized).Returns(true); Mock <IDependencyResolver> mockResolver = new Mock <IDependencyResolver>(MockBehavior.Strict); mockResolver.Setup(p => p.GetService(typeof(WebScriptHostManager))).Returns(_managerMock.Object); _webHostSettings = new WebHostSettings(); mockResolver.Setup(p => p.GetService(typeof(WebHostSettings))).Returns(_webHostSettings); HttpConfiguration config = new HttpConfiguration(); config.DependencyResolver = mockResolver.Object; WebScriptHostHandler handler = new WebScriptHostHandler(config) { InnerHandler = new TestHandler() }; _invoker = new HttpMessageInvoker(handler); }
public InstanceManager(ScriptSettingsManager settingsManager, WebHostSettings webHostSettings, ILoggerFactory loggerFactory, HttpClient client) { _settingsManager = settingsManager; _webHostSettings = webHostSettings; _logger = loggerFactory.CreateLogger(nameof(InstanceManager)); _client = client; }
public AdminController(WebScriptHostManager scriptHostManager, WebHostSettings webHostSettings, TraceWriter traceWriter, ILoggerFactory loggerFactory) { _scriptHostManager = scriptHostManager; _webHostSettings = webHostSettings; _traceWriter = traceWriter.WithSource($"{ScriptConstants.TraceSourceHostAdmin}.Api"); _logger = loggerFactory?.CreateLogger(ScriptConstants.LogCategoryAdminController); }
public TestFixture() { HttpConfiguration config = new HttpConfiguration(); WebHostSettings settings = new WebHostSettings { IsSelfHost = true, ScriptPath = Path.Combine(Environment.CurrentDirectory, @"..\..\..\..\sample"), LogPath = Path.Combine(Path.GetTempPath(), @"Functions"), SecretsPath = Path.Combine(Environment.CurrentDirectory, @"..\..\..\..\src\WebJobs.Script.WebHost\App_Data\Secrets") }; WebApiConfig.Register(config, settings); HttpServer server = new HttpServer(config); this.HttpClient = new HttpClient(server); this.HttpClient.BaseAddress = new Uri("https://localhost/"); string connectionString = AmbientConnectionStringProvider.Instance.GetConnectionString("Storage"); CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString); BlobClient = storageAccount.CreateCloudBlobClient(); QueueClient = storageAccount.CreateCloudQueueClient(); WaitForHost(); }
public AuthorizationLevelAttributeTests() { HttpConfig = new HttpConfiguration(); _actionContext = CreateActionContext(typeof(TestController).GetMethod("Get"), HttpConfig); Mock <IDependencyResolver> mockDependencyResolver = new Mock <IDependencyResolver>(MockBehavior.Strict); HttpConfig.DependencyResolver = mockDependencyResolver.Object; MockSecretManager = new Mock <ISecretManager>(MockBehavior.Strict); _hostSecrets = new HostSecretsInfo { MasterKey = TestMasterKeyValue, FunctionKeys = new Dictionary <string, string> { { TestHostFunctionKeyName1, TestHostFunctionKeyValue1 }, { TestHostFunctionKeyName2, TestHostFunctionKeyValue2 } }, SystemKeys = new Dictionary <string, string> { { TestSystemKeyName1, TestSystemKeyValue1 }, { TestSystemKeyName2, TestSystemKeyValue2 } } }; MockSecretManager.Setup(p => p.GetHostSecretsAsync()).ReturnsAsync(_hostSecrets); _functionSecrets = new Dictionary <string, string> { { TestFunctionKeyName1, TestFunctionKeyValue1 }, { TestFunctionKeyName2, TestFunctionKeyValue2 } }; MockSecretManager.Setup(p => p.GetFunctionSecretsAsync(It.IsAny <string>(), false)).ReturnsAsync(_functionSecrets); mockDependencyResolver.Setup(p => p.GetService(typeof(ISecretManager))).Returns(MockSecretManager.Object); _webHostSettings = new WebHostSettings(); mockDependencyResolver.Setup(p => p.GetService(typeof(WebHostSettings))).Returns(_webHostSettings); }
public void GetScriptHostConfiguration_SetsHostId() { var environmentSettings = new Dictionary <string, string> { { EnvironmentSettingNames.AzureWebsiteName, "testsite" }, { EnvironmentSettingNames.AzureWebsiteSlotName, "production" }, }; using (var environment = new TestScopedEnvironmentVariable(environmentSettings)) { var settingsManager = new ScriptSettingsManager(); var secretManagerFactoryMock = new Mock <ISecretManagerFactory>(); var eventManagerMock = new Mock <IScriptEventManager>(); var resolver = new WebHostResolver(settingsManager, secretManagerFactoryMock.Object, eventManagerMock.Object); var settings = new WebHostSettings { ScriptPath = @"c:\some\path", LogPath = @"c:\log\path", SecretsPath = @"c:\secrets\path" }; ScriptHostConfiguration configuration = resolver.GetScriptHostConfiguration(settings); Assert.Equal("testsite", configuration.HostConfig.HostId); } }
public InstanceManager(ScriptSettingsManager settingsManager, WebHostSettings webHostSettings, ILoggerFactory loggerFactory, HttpClient client) { _settingsManager = settingsManager; _webHostSettings = webHostSettings; _logger = loggerFactory.CreateLogger(LogCategories.Startup); _client = client; }
public TestFixture() { HostSettings = new WebHostSettings { IsSelfHost = true, ScriptPath = Path.Combine(Environment.CurrentDirectory, @"..\..\..\TestScripts\Proxies"), LogPath = Path.Combine(Path.GetTempPath(), @"ProxyTests\Logs"), SecretsPath = Path.Combine(Path.GetTempPath(), @"ProxyTests\Secrets") }; _testServer = new TestServer( AspNetCore.WebHost.CreateDefaultBuilder() .UseStartup <Startup>() .ConfigureServices(services => { services.Replace(new ServiceDescriptor(typeof(WebHostSettings), HostSettings)); services.Replace(new ServiceDescriptor(typeof(ISecretManager), new TestSecretManager())); })); var scriptConfig = _testServer.Host.Services.GetService <WebHostResolver>().GetScriptHostConfiguration(HostSettings); HttpClient = _testServer.CreateClient(); HttpClient.BaseAddress = new Uri("https://localhost/"); TestHelpers.WaitForWebHost(HttpClient); }
private async Task <IWebHost> BuildWebHost(WebHostSettings hostSettings, WorkerRuntime workerRuntime, Uri baseAddress, X509Certificate2 certificate) { IDictionary <string, string> settings = await GetConfigurationSettings(hostSettings.ScriptPath, baseAddress); settings.AddRange(LanguageWorkerHelper.GetWorkerConfiguration(workerRuntime, LanguageWorkerSetting)); UpdateEnvironmentVariables(settings); var defaultBuilder = Microsoft.AspNetCore.WebHost.CreateDefaultBuilder(Array.Empty <string>()); if (UseHttps) { defaultBuilder .UseKestrel(options => { options.Listen(IPAddress.Loopback, baseAddress.Port, listenOptins => { listenOptins.UseHttps(certificate); }); }); } return(defaultBuilder .UseSetting(WebHostDefaults.ApplicationKey, typeof(Startup).Assembly.GetName().Name) .UseUrls(baseAddress.ToString()) .ConfigureAppConfiguration(configBuilder => { configBuilder.AddEnvironmentVariables(); }) .ConfigureServices((context, services) => services.AddSingleton <IStartup>(new Startup(context, hostSettings, CorsOrigins))) .Build()); }
public HostController(WebScriptHostManager scriptHostManager, WebHostSettings webHostSettings, ILoggerFactory loggerFactory, IAuthorizationService authorizationService) { _scriptHostManager = scriptHostManager; _webHostSettings = webHostSettings; _logger = loggerFactory.CreateLogger(ScriptConstants.LogCategoryHostController); _authorizationService = authorizationService; }
public Fixture() { EventGenerator = new TestSystemEventGenerator(); _settingsManager = ScriptSettingsManager.Instance; TestFunctionRoot = Path.Combine(TestHelpers.FunctionsTestDirectory, "Functions"); TestLogsRoot = Path.Combine(TestHelpers.FunctionsTestDirectory, "Logs"); TestSecretsRoot = Path.Combine(TestHelpers.FunctionsTestDirectory, "Secrets"); string testRoot = Path.Combine(TestFunctionRoot, Guid.NewGuid().ToString()); SecretsPath = Path.Combine(TestSecretsRoot, Guid.NewGuid().ToString()); Directory.CreateDirectory(SecretsPath); string logRoot = Path.Combine(TestLogsRoot, Guid.NewGuid().ToString(), @"Functions"); Directory.CreateDirectory(logRoot); FunctionsLogDir = Path.Combine(logRoot, @"Function"); Directory.CreateDirectory(FunctionsLogDir); // Add some secret files (both old and valid) File.WriteAllText(Path.Combine(SecretsPath, ScriptConstants.HostMetadataFileName), string.Empty); File.WriteAllText(Path.Combine(SecretsPath, "WebHookTrigger.json"), string.Empty); File.WriteAllText(Path.Combine(SecretsPath, "QueueTriggerToBlob.json"), string.Empty); File.WriteAllText(Path.Combine(SecretsPath, "Foo.json"), string.Empty); File.WriteAllText(Path.Combine(SecretsPath, "Bar.json"), string.Empty); File.WriteAllText(Path.Combine(SecretsPath, "Invalid.json"), string.Empty); // Add some old file directories CreateTestFunctionLogs(FunctionsLogDir, "Foo"); CreateTestFunctionLogs(FunctionsLogDir, "Bar"); CreateTestFunctionLogs(FunctionsLogDir, "Baz"); CreateTestFunctionLogs(FunctionsLogDir, "Invalid"); ScriptHostConfiguration config = new ScriptHostConfiguration { RootScriptPath = @"TestScripts\Node", RootLogPath = logRoot, FileLoggingMode = FileLoggingMode.Always }; ISecretsRepository repository = new FileSystemSecretsRepository(SecretsPath); ISecretManager secretManager = new SecretManager(_settingsManager, repository, NullLogger.Instance); WebHostSettings webHostSettings = new WebHostSettings(); webHostSettings.SecretsPath = SecretsPath; var hostConfig = config.HostConfig; var testEventGenerator = new TestSystemEventGenerator(); hostConfig.AddService <IEventGenerator>(EventGenerator); var mockEventManager = new Mock <IScriptEventManager>(); var mockRouter = CreateRouter(); var mockHostManager = new WebScriptHostManager(config, new TestSecretManagerFactory(secretManager), mockEventManager.Object, _settingsManager, webHostSettings, mockRouter, NullLoggerFactory.Instance, null); HostManager = mockHostManager; _initializationTask = EnsureInitialized(); }
public Startup(WebHostBuilderContext builderContext, WebHostSettings hostSettings, string corsOrigins) { _builderContext = builderContext; _hostSettings = hostSettings; if (!string.IsNullOrEmpty(corsOrigins)) { _corsOrigins = corsOrigins.Split(',', StringSplitOptions.RemoveEmptyEntries); } }
public async Task EmptyHost_StartsSuccessfully() { await _fixture.InitializationTask; string functionTestDir = Path.Combine(_fixture.TestFunctionRoot, Guid.NewGuid().ToString()); Directory.CreateDirectory(functionTestDir); // important for the repro that these directories no not exist string logDir = Path.Combine(_fixture.TestLogsRoot, Guid.NewGuid().ToString()); string secretsDir = Path.Combine(_fixture.TestSecretsRoot, Guid.NewGuid().ToString()); JObject hostConfig = new JObject { { "id", "123456" } }; File.WriteAllText(Path.Combine(functionTestDir, ScriptConstants.HostMetadataFileName), hostConfig.ToString()); ScriptHostConfiguration config = new ScriptHostConfiguration { RootScriptPath = functionTestDir, RootLogPath = logDir, FileLoggingMode = FileLoggingMode.Always }; string connectionString = AmbientConnectionStringProvider.Instance.GetConnectionString(ConnectionStringNames.Storage); ISecretsRepository repository = new BlobStorageSecretsRepository(secretsDir, connectionString, "EmptyHost_StartsSuccessfully"); ISecretManager secretManager = new SecretManager(_settingsManager, repository, null); WebHostSettings webHostSettings = new WebHostSettings(); webHostSettings.SecretsPath = _secretsDirectory.Path; var mockEventManager = new Mock <IScriptEventManager>(); IWebJobsRouter router = _fixture.CreateRouter(); ScriptHostManager hostManager = new WebScriptHostManager(config, new TestSecretManagerFactory(secretManager), mockEventManager.Object, _settingsManager, webHostSettings, router, NullLoggerFactory.Instance); Task runTask = Task.Run(() => hostManager.RunAndBlock()); await TestHelpers.Await(() => hostManager.State == ScriptHostState.Running, timeout : 10000); hostManager.Stop(); Assert.Equal(ScriptHostState.Default, hostManager.State); // give some time for the logs to be flushed fullly await Task.Delay(FileWriter.LogFlushIntervalMs * 3); string hostLogFilePath = Directory.EnumerateFiles(Path.Combine(logDir, "Host")).Single(); string hostLogs = File.ReadAllText(hostLogFilePath); Assert.Contains("Generating 0 job function(s)", hostLogs); Assert.Contains("No job functions found.", hostLogs); Assert.Contains("Job host started", hostLogs); Assert.Contains("Job host stopped", hostLogs); }
public StandbyModeTests() { _settingsManager = ScriptSettingsManager.Instance; var eventManagerMock = new Mock <IScriptEventManager>(); var routerMock = new Mock <IWebJobsRouter>(); _webHostResolver = new WebHostResolver(_settingsManager, new TestSecretManagerFactory(false), eventManagerMock.Object, WebHostSettings.CreateDefault(_settingsManager), routerMock.Object, new DefaultLoggerFactoryBuilder()); _traceWriter = new TestTraceWriter(TraceLevel.Info); WebScriptHostManager.ResetStandbyMode(); }
private async Task InitializeTestHost(string testDirName) { var httpConfig = new HttpConfiguration(); var testRootPath = Path.Combine(Path.GetTempPath(), testDirName); await FileUtility.DeleteDirectoryAsync(testRootPath, true); _loggerProvider = new TestLoggerProvider(); var loggerProviderFactory = new TestLoggerProviderFactory(_loggerProvider); _webHostSettings = new WebHostSettings { IsSelfHost = true, LogPath = Path.Combine(testRootPath, "Logs"), SecretsPath = Path.Combine(testRootPath, "Secrets"), ScriptPath = Path.Combine(testRootPath, "WWWRoot") }; if (_settingsManager.IsAppServiceEnvironment) { // if the test is mocking App Service environment, we need // to also set the HOME variable Environment.SetEnvironmentVariable(EnvironmentSettingNames.AzureWebsiteHomePath, testRootPath); } var loggerFactory = new LoggerFactory(); loggerFactory.AddProvider(_loggerProvider); var webHostBuilder = Program.CreateWebHostBuilder() .ConfigureServices(c => { c.AddSingleton(_webHostSettings) .AddSingleton <ILoggerProviderFactory>(loggerProviderFactory) .AddSingleton <ILoggerFactory>(loggerFactory); }); _httpServer = new TestServer(webHostBuilder); _httpClient = _httpServer.CreateClient(); _httpClient.BaseAddress = new Uri("https://localhost/"); TestHelpers.WaitForWebHost(_httpClient); var traces = _loggerProvider.GetAllLogMessages().ToArray(); Assert.NotNull(traces.Single(p => p.FormattedMessage.StartsWith("Starting Host (HostId=placeholder-host"))); Assert.NotNull(traces.Single(p => p.FormattedMessage.StartsWith("Host is in standby mode"))); var hostConfig = WebHostResolver.CreateScriptHostConfiguration(_webHostSettings, true); _expectedHostId = hostConfig.HostConfig.HostId; }
internal static void Initialize(ContainerBuilder builder, WebHostSettings settings) { ScriptHostConfiguration scriptHostConfig = new ScriptHostConfiguration() { RootScriptPath = settings.ScriptPath, RootLogPath = settings.LogPath, FileLoggingEnabled = true }; // If running on Azure Web App, derive the host ID from the site name string hostId = Environment.GetEnvironmentVariable("WEBSITE_SITE_NAME"); if (!String.IsNullOrEmpty(hostId)) { // Truncate to the max host name length if needed const int MaximumHostIdLength = 32; if (hostId.Length > MaximumHostIdLength) { hostId = hostId.Substring(0, MaximumHostIdLength); } // Trim any trailing - as they can cause problems with queue names hostId = hostId.TrimEnd('-'); scriptHostConfig.HostConfig.HostId = hostId.ToLowerInvariant(); } WebScriptHostManager scriptHostManager = new WebScriptHostManager(scriptHostConfig); builder.RegisterInstance <WebScriptHostManager>(scriptHostManager); SecretManager secretManager = new SecretManager(settings.SecretsPath); // Make sure that host secrets get created on startup if they don't exist secretManager.GetHostSecrets(); builder.RegisterInstance <SecretManager>(secretManager); WebHookReceiverManager webHookReceiverManager = new WebHookReceiverManager(secretManager); builder.RegisterInstance <WebHookReceiverManager>(webHookReceiverManager); if (!settings.IsSelfHost) { HostingEnvironment.QueueBackgroundWorkItem((ct) => scriptHostManager.RunAndBlock(ct)); } else { Task.Run(() => scriptHostManager.RunAndBlock()); } }
protected override void RegisterDependencies(ContainerBuilder builder, WebHostSettings settings) { TestFunctionKeys = new Dictionary <string, string> { { "key1", "1234" }, { "key2", "1234" } }; SecretManagerMock = BuildSecretManager(); builder.RegisterInstance <ISecretManager>(SecretManagerMock.Object); base.RegisterDependencies(builder, settings); }
public void CreateScriptHostConfiguration_StandbyMode_ReturnsExpectedConfiguration() { var settings = new WebHostSettings { IsSelfHost = true }; var config = WebHostResolver.CreateScriptHostConfiguration(settings, true); Assert.Equal(FileLoggingMode.DebugOnly, config.FileLoggingMode); Assert.Null(config.HostConfig.StorageConnectionString); Assert.Null(config.HostConfig.DashboardConnectionString); Assert.Equal(Path.Combine(Path.GetTempPath(), "Functions", "Standby"), config.RootScriptPath); }
public async Task MultipleHostRestarts() { string functionTestDir = Path.Combine(_fixture.TestFunctionRoot, Guid.NewGuid().ToString()); Directory.CreateDirectory(functionTestDir); string logDir = Path.Combine(_fixture.TestLogsRoot, Guid.NewGuid().ToString()); string secretsDir = Path.Combine(_fixture.TestSecretsRoot, Guid.NewGuid().ToString()); ScriptHostConfiguration config = new ScriptHostConfiguration { RootLogPath = logDir, RootScriptPath = functionTestDir, FileLoggingMode = FileLoggingMode.Always, }; ISecretsRepository repository = new FileSystemSecretsRepository(_secretsDirectory.Path); SecretManager secretManager = new SecretManager(_settingsManager, repository, NullTraceWriter.Instance, null); WebHostSettings webHostSettings = new WebHostSettings(); webHostSettings.SecretsPath = _secretsDirectory.Path; var mockEventManager = new Mock <IScriptEventManager>(); var factoryMock = new Mock <IScriptHostFactory>(); int count = 0; factoryMock.Setup(p => p.Create(It.IsAny <IScriptHostEnvironment>(), It.IsAny <IScriptEventManager>(), _settingsManager, config)).Callback(() => { count++; }).Throws(new Exception("Kaboom!")); ScriptHostManager hostManager = new WebScriptHostManager(config, new TestSecretManagerFactory(secretManager), mockEventManager.Object, _settingsManager, webHostSettings, factoryMock.Object); Task runTask = Task.Run(() => hostManager.RunAndBlock()); await TestHelpers.Await(() => { return(count > 3); }); hostManager.Stop(); Assert.Equal(ScriptHostState.Default, hostManager.State); // regression test: previously on multiple restarts we were recomposing // the writer on each restart, resulting in a nested chain of writers // increasing on each restart Assert.Equal(typeof(SystemTraceWriter), config.TraceWriter.GetType()); }
public KeysControllerTests() { _settingsManager = ScriptSettingsManager.Instance; _testFunctions = new Collection <FunctionDescriptor>(); _testFunctionErrors = new Dictionary <string, Collection <string> >(); string rootScriptPath = @"c:\test\functions"; var environment = new NullScriptHostEnvironment(); var eventManager = new Mock <IScriptEventManager>(); var mockRouter = new Mock <IWebJobsRouter>(); var settings = new WebHostSettings() { ScriptPath = rootScriptPath, SecretsPath = _secretsDirectory.Path }; _secretsManagerMock = new Mock <ISecretManager>(MockBehavior.Strict); var fileSystem = new Mock <IFileSystem>(); var fileBase = new Mock <FileBase>(); var dirBase = new Mock <DirectoryBase>(); fileSystem.SetupGet(f => f.File).Returns(fileBase.Object); fileBase.Setup(f => f.ReadAllText(Path.Combine(rootScriptPath, "TestFunction1", ScriptConstants.FunctionMetadataFileName))).Returns("{}"); fileBase.Setup(f => f.ReadAllText(Path.Combine(rootScriptPath, "TestFunction2", ScriptConstants.FunctionMetadataFileName))).Returns("{}"); fileBase.Setup(f => f.ReadAllText(Path.Combine(rootScriptPath, "DNE", ScriptConstants.FunctionMetadataFileName))).Throws(new DirectoryNotFoundException()); _testController = new KeysController(settings, _secretsManagerMock.Object, new LoggerFactory(), fileSystem.Object); var keys = new Dictionary <string, string> { { "key1", "secret1" } }; _secretsManagerMock.Setup(p => p.GetFunctionSecretsAsync("TestFunction1", false)).ReturnsAsync(keys); keys = new Dictionary <string, string> { { "key1", "secret1" } }; _secretsManagerMock.Setup(p => p.GetFunctionSecretsAsync("TestFunction2", false)).ReturnsAsync(keys); _secretsManagerMock.Setup(p => p.GetFunctionSecretsAsync("DNE", false)).ReturnsAsync((IDictionary <string, string>)null); SetHttpContext(); }
internal static void Initialize(ContainerBuilder builder, WebHostSettings settings) { ScriptHostConfiguration scriptHostConfig = new ScriptHostConfiguration() { RootScriptPath = settings.ScriptPath, RootLogPath = settings.LogPath, FileLoggingEnabled = true }; // If running on Azure Web App, derive the host ID from the site name string hostId = Environment.GetEnvironmentVariable("WEBSITE_SITE_NAME"); if (!String.IsNullOrEmpty(hostId)) { // Truncate to the max host name length if needed const int MaximumHostIdLength = 32; if (hostId.Length > MaximumHostIdLength) { hostId = hostId.Substring(0, MaximumHostIdLength); } // Trim any trailing - as they can cause problems with queue names hostId = hostId.TrimEnd('-'); scriptHostConfig.HostConfig.HostId = hostId.ToLowerInvariant(); } WebScriptHostManager scriptHostManager = new WebScriptHostManager(scriptHostConfig); builder.RegisterInstance<WebScriptHostManager>(scriptHostManager); SecretManager secretManager = new SecretManager(settings.SecretsPath); // Make sure that host secrets get created on startup if they don't exist secretManager.GetHostSecrets(); builder.RegisterInstance<SecretManager>(secretManager); WebHookReceiverManager webHookReceiverManager = new WebHookReceiverManager(secretManager); builder.RegisterInstance<WebHookReceiverManager>(webHookReceiverManager); if (!settings.IsSelfHost) { HostingEnvironment.QueueBackgroundWorkItem((ct) => scriptHostManager.RunAndBlock(ct)); } else { Task.Run(() => scriptHostManager.RunAndBlock()); } }
public AdminControllerTests() { testFunctions = new Collection <FunctionDescriptor>(); var config = new ScriptHostConfiguration(); hostMock = new Mock <ScriptHost>(MockBehavior.Strict, new object[] { config }); hostMock.Setup(p => p.Functions).Returns(testFunctions); ISecretManager secretManager = new SecretManager(); WebHostSettings settings = new WebHostSettings(); managerMock = new Mock <WebScriptHostManager>(MockBehavior.Strict, new object[] { config, secretManager, settings }); managerMock.SetupGet(p => p.Instance).Returns(hostMock.Object); testController = new AdminController(managerMock.Object); }