protected EndToEndTestFixture(string rootPath, string testId)
        {
            FixtureId = testId;
            string connectionString            = AmbientConnectionStringProvider.Instance.GetConnectionString(ConnectionStringNames.Storage);
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);

            QueueClient = storageAccount.CreateCloudQueueClient();
            BlobClient  = storageAccount.CreateCloudBlobClient();
            TableClient = storageAccount.CreateCloudTableClient();

            CreateTestStorageEntities();
            TraceWriter = new TestTraceWriter(TraceLevel.Verbose);

            ApiHubTestHelper.SetDefaultConnectionFactory();

            ScriptHostConfiguration config = new ScriptHostConfiguration()
            {
                RootScriptPath  = rootPath,
                TraceWriter     = TraceWriter,
                FileLoggingMode = FileLoggingMode.Always
            };

            // Clear the timer logs first, since one of the tests will
            // be checking them
            TestHelpers.ClearFunctionLogs("TimerTrigger");
            Host = ScriptHost.Create(config);
            Host.Start();
        }
            public TestFixture()
            {
                ScriptHostConfiguration config = new ScriptHostConfiguration();

                config.HostConfig.HostId = ID;
                Host = ScriptHost.Create(config);
            }
        protected EndToEndTestFixture(string rootPath, string testId)
        {
            _settingsManager = ScriptSettingsManager.Instance;
            FixtureId        = testId;
            string connectionString            = AmbientConnectionStringProvider.Instance.GetConnectionString(ConnectionStringNames.Storage);
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);

            QueueClient = storageAccount.CreateCloudQueueClient();
            BlobClient  = storageAccount.CreateCloudBlobClient();
            TableClient = storageAccount.CreateCloudTableClient();

            CreateTestStorageEntities();
            TraceWriter = new TestTraceWriter(TraceLevel.Verbose);

            ApiHubTestHelper.SetDefaultConnectionFactory();

            ScriptHostConfiguration config = new ScriptHostConfiguration()
            {
                RootScriptPath  = rootPath,
                TraceWriter     = TraceWriter,
                FileLoggingMode = FileLoggingMode.Always
            };

            RequestConfiguration = new HttpConfiguration();
            RequestConfiguration.Formatters.Add(new PlaintextMediaTypeFormatter());

            ScriptHostEnvironmentMock = new Mock <IScriptHostEnvironment>();

            // Reset the timer logs first, since one of the tests will
            // be checking them
            TestHelpers.ClearFunctionLogs("TimerTrigger");
            Host = ScriptHost.Create(ScriptHostEnvironmentMock.Object, config, _settingsManager);
            Host.Start();
        }
Example #4
0
        static void Main(string[] args)
        {
            // Configure the full path to the functions directory
            string functionsPath = Path.Combine(Environment.CurrentDirectory, "Functions");

            ScriptSettingsManager settings = ScriptSettingsManager.Instance;

            {
            };


            // When deployed as a WebJob, the WebJobs infrastructure handles
            // watching for script changes and restarting the host, so we
            // need to disable ScriptHost's inbuilt file watching.
            ScriptHostConfiguration config = new ScriptHostConfiguration()
            {
                RootScriptPath      = functionsPath,
                FileWatchingEnabled = false,
                RootLogPath         = functionsPath
            };

            // start the ScriptHost
            ScriptHost scriptHost = ScriptHost.Create(settings, config);



            scriptHost.RunAndBlock();
        }
        protected EndToEndTestFixture(string rootPath, string testId)
        {
            _testId = testId;
            string connectionString            = AmbientConnectionStringProvider.Instance.GetConnectionString(ConnectionStringNames.Storage);
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);

            QueueClient = storageAccount.CreateCloudQueueClient();
            BlobClient  = storageAccount.CreateCloudBlobClient();
            TableClient = storageAccount.CreateCloudTableClient();

            CreateTestStorageEntities();
            TraceWriter = new TestTraceWriter(TraceLevel.Verbose);

            ScriptHostConfiguration config = new ScriptHostConfiguration()
            {
                RootScriptPath     = rootPath,
                TraceWriter        = TraceWriter,
                FileLoggingEnabled = true
            };

            ApiHubTestHelper.SetDefaultConnectionFactory();

            Host = ScriptHost.Create(config);
            Host.Start();
        }
Example #6
0
        public void Create_InvalidFunctionNames_DoesNotCreateFunctionAndLogsFailure(string functionName)
        {
            string rootPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
            string invalidFunctionNamePath = Path.Combine(rootPath, functionName);

            try
            {
                Directory.CreateDirectory(invalidFunctionNamePath);

                JObject config = new JObject();
                config["id"] = ID;

                File.WriteAllText(Path.Combine(rootPath, ScriptConstants.HostMetadataFileName), config.ToString());
                File.WriteAllText(Path.Combine(invalidFunctionNamePath, ScriptConstants.FunctionMetadataFileName), string.Empty);

                ScriptHostConfiguration scriptConfig = new ScriptHostConfiguration()
                {
                    RootScriptPath = rootPath
                };

                var scriptHost = ScriptHost.Create(_settingsManager, scriptConfig);

                Assert.Equal(1, scriptHost.FunctionErrors.Count);
                Assert.Equal(functionName, scriptHost.FunctionErrors.First().Key);
                Assert.Equal($"'{functionName}' is not a valid function name.", scriptHost.FunctionErrors.First().Value.First());
            }
            finally
            {
                if (Directory.Exists(rootPath))
                {
                    Directory.Delete(rootPath, true);
                }
            }
        }
Example #7
0
        private static MethodInfo GenerateMethod(BindingMetadata trigger)
        {
            string           rootPath = Path.Combine(Environment.CurrentDirectory, @"TestScripts\Node");
            FunctionMetadata metadata = new FunctionMetadata();

            metadata.Name       = "Test";
            metadata.ScriptFile = Path.Combine(rootPath, @"Common\test.js");
            metadata.Bindings.Add(trigger);

            List <FunctionMetadata> metadatas = new List <FunctionMetadata>();

            metadatas.Add(metadata);

            ScriptHostConfiguration scriptConfig = new ScriptHostConfiguration()
            {
                RootScriptPath = rootPath
            };
            ScriptHost host = ScriptHost.Create(scriptConfig);

            FunctionDescriptorProvider[] descriptorProviders = new FunctionDescriptorProvider[]
            {
                new NodeFunctionDescriptorProvider(host, scriptConfig)
            };

            var  functionDescriptors = host.ReadFunctions(metadatas, descriptorProviders);
            Type t = FunctionGenerator.Generate("TestScriptHost", "Host.Functions", functionDescriptors);

            MethodInfo method = t.GetMethods(BindingFlags.Public | BindingFlags.Static).First();

            return(method);
        }
Example #8
0
            public TestFixture()
            {
                ScriptHostConfiguration config = new ScriptHostConfiguration();

                config.HostConfig.HostId = ID;
                _settingsManager         = ScriptSettingsManager.Instance;
                Host = ScriptHost.Create(_settingsManager, config);
            }
            public TestFixture()
            {
                ScriptHostConfiguration config = new ScriptHostConfiguration();

                config.HostConfig.HostId = ID;
                var environment = new Mock <IScriptHostEnvironment>();

                Host = ScriptHost.Create(environment.Object, config);
            }
        public FunctionDescriptorProviderTests()
        {
            string rootPath = Path.Combine(Environment.CurrentDirectory, @"TestScripts\Node");
            ScriptHostConfiguration config = new ScriptHostConfiguration
            {
                RootScriptPath = rootPath
            };

            _host     = ScriptHost.Create(config);
            _provider = new TestDescriptorProvider(_host, config);
        }
        private static ScriptHostInfo GetScriptHostInfo()
        {
            string rootPath = Path.Combine(Environment.CurrentDirectory, @"TestScripts\PowerShell");
            ScriptHostConfiguration scriptConfig = new ScriptHostConfiguration()
            {
                RootScriptPath = rootPath
            };
            var host = ScriptHost.Create(SettingsManager, scriptConfig);

            return(new ScriptHostInfo(host, scriptConfig, rootPath));
        }
        private static ScriptHostInfo GetScriptHostInfo()
        {
            var    environment  = new Mock <IScriptHostEnvironment>();
            var    eventManager = new Mock <IScriptEventManager>();
            string rootPath     = Path.Combine(Environment.CurrentDirectory, @"TestScripts\PowerShell");
            ScriptHostConfiguration scriptConfig = new ScriptHostConfiguration()
            {
                RootScriptPath = rootPath
            };
            var host = ScriptHost.Create(environment.Object, eventManager.Object, scriptConfig, SettingsManager);

            return(new ScriptHostInfo(host, scriptConfig, rootPath));
        }
        protected EndToEndTestFixture(string rootPath)
        {
            CreateTestStorageEntities();
            TraceWriter = new TestTraceWriter(TraceLevel.Verbose);

            ScriptHostConfiguration config = new ScriptHostConfiguration()
            {
                RootScriptPath = rootPath,
                TraceWriter    = TraceWriter
            };

            Host = ScriptHost.Create(config);
            Host.Start();
        }
Example #14
0
            public ScriptHost Create(ScriptHostConfiguration config)
            {
                if (Throw)
                {
                    throw new Exception("Kaboom!");
                }

                var mockMetricsLogger = new Mock <IMetricsLogger>(MockBehavior.Strict);

                config.HostConfig.AddService <IMetricsLogger>(mockMetricsLogger.Object);
                mockMetricsLogger.Setup(p => p.LogEvent(It.IsAny <MetricEvent>()));

                return(ScriptHost.Create(config));
            }
Example #15
0
        public FunctionDescriptorProviderTests()
        {
            string rootPath = Path.Combine(Environment.CurrentDirectory, @"TestScripts\Node");
            ScriptHostConfiguration config = new ScriptHostConfiguration
            {
                RootScriptPath = rootPath
            };

            var environment = new Mock <IScriptHostEnvironment>();

            _settingsManager = ScriptSettingsManager.Instance;
            _host            = ScriptHost.Create(environment.Object, config, _settingsManager);
            _provider        = new TestDescriptorProvider(_host, config);
        }
        public ProxyFunctionDescriptorProviderTests()
        {
            string rootPath = Path.Combine(Environment.CurrentDirectory, @"TestScripts\Proxies");

            _config = new ScriptHostConfiguration
            {
                RootScriptPath = rootPath
            };

            var environment  = new Mock <IScriptHostEnvironment>();
            var eventManager = new Mock <IScriptEventManager>();

            _proxyClient        = GetMockProxyClient();
            _settingsManager    = ScriptSettingsManager.Instance;
            _host               = ScriptHost.Create(environment.Object, eventManager.Object, _config, _settingsManager, _proxyClient);
            _metadataCollection = _host.ReadProxyMetadata(_config, _settingsManager);
        }
Example #17
0
        public void Create_InvalidHostJson_ThrowsInformativeException()
        {
            string rootPath = Path.Combine(Environment.CurrentDirectory, @"TestScripts\Invalid");

            ScriptHostConfiguration scriptConfig = new ScriptHostConfiguration()
            {
                RootScriptPath = rootPath
            };

            var ex = Assert.Throws <FormatException>(() =>
            {
                ScriptHost.Create(_settingsManager, scriptConfig);
            });

            Assert.Equal(string.Format("Unable to parse {0} file.", ScriptConstants.HostMetadataFileName), ex.Message);
            Assert.Equal("Invalid property identifier character: ~. Path '', line 2, position 4.", ex.InnerException.Message);
        }
Example #18
0
            public ScriptHost Create(IScriptHostEnvironment environment, IScriptEventManager eventManager, ScriptSettingsManager settingsManager, ScriptHostConfiguration config, ILoggerFactoryBuilder loggerFactoryBuilder)
            {
                if (Throw)
                {
                    throw new Exception("Kaboom!");
                }

                var mockMetricsLogger = new Mock <IMetricsLogger>(MockBehavior.Strict);

                config.HostConfig.AddService <IMetricsLogger>(mockMetricsLogger.Object);
                mockMetricsLogger.Setup(p => p.BeginEvent(It.IsAny <string>(), It.IsAny <string>())).Returns(new object());
                mockMetricsLogger.Setup(p => p.EndEvent(It.IsAny <object>()));
                mockMetricsLogger.Setup(p => p.LogEvent(It.IsAny <string>(), It.IsAny <string>()));
                mockMetricsLogger.Setup(p => p.LogEvent(It.IsAny <MetricEvent>()));

                return(ScriptHost.Create(environment, eventManager, config, settingsManager, loggerFactoryBuilder));
            }
Example #19
0
            public ScriptHost Create(ScriptSettingsManager settingsManager, ScriptHostConfiguration config)
            {
                if (Throw)
                {
                    throw new Exception("Kaboom!");
                }

                var mockMetricsLogger = new Mock <IMetricsLogger>(MockBehavior.Strict);

                config.HostConfig.AddService <IMetricsLogger>(mockMetricsLogger.Object);
                mockMetricsLogger.Setup(p => p.BeginEvent(It.IsAny <string>())).Returns(new object());
                mockMetricsLogger.Setup(p => p.EndEvent(It.IsAny <object>()));
                mockMetricsLogger.Setup(p => p.LogEvent(It.IsAny <string>()));
                mockMetricsLogger.Setup(p => p.LogEvent(It.IsAny <MetricEvent>()));

                return(ScriptHost.Create(settingsManager, config));
            }
        protected EndToEndTestFixture(string rootPath, string testId)
        {
            _settingsManager = ScriptSettingsManager.Instance;
            FixtureId        = testId;
            string connectionString            = AmbientConnectionStringProvider.Instance.GetConnectionString(ConnectionStringNames.Storage);
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);

            QueueClient = storageAccount.CreateCloudQueueClient();
            BlobClient  = storageAccount.CreateCloudBlobClient();
            TableClient = storageAccount.CreateCloudTableClient();

            CreateTestStorageEntities();
            TraceWriter = new TestTraceWriter(TraceLevel.Verbose);

            ApiHubTestHelper.SetDefaultConnectionFactory();

            ScriptHostConfiguration config = new ScriptHostConfiguration()
            {
                RootScriptPath  = rootPath,
                TraceWriter     = TraceWriter,
                FileLoggingMode = FileLoggingMode.Always
            };

            RequestConfiguration = new HttpConfiguration();
            RequestConfiguration.Formatters.Add(new PlaintextMediaTypeFormatter());

            EventManager = new ScriptEventManager();
            ScriptHostEnvironmentMock = new Mock <IScriptHostEnvironment>();

            // Reset the timer logs first, since one of the tests will
            // be checking them
            TestHelpers.ClearFunctionLogs("TimerTrigger");
            TestHelpers.ClearFunctionLogs("ListenerStartupException");

            InitializeConfig(config);
            Func <string, FunctionDescriptor> funcLookup = (name) => this.Host.GetFunctionOrNull(name);
            var fastLogger = new FunctionInstanceLogger(funcLookup, new MetricsLogger());

            config.HostConfig.AddService <IAsyncCollector <FunctionInstanceLogEntry> >(fastLogger);

            Host = ScriptHost.Create(ScriptHostEnvironmentMock.Object, EventManager, config, _settingsManager);
            Host.Start();
        }
Example #21
0
 static void Main(string[] args)
 {
     using (var host = new ScriptHost())
     {
         // create a javascript engine
         var engine = host.Create("javascript");                 // you can use the ChakraJS const here for IE9+'s fast engine
         // evaluate an expression
         Console.WriteLine(engine.Evaluate("2+2"));
         // add some code to the current script
         engine.AddCode("var i = 7;");
         // get the object for the script
         dynamic obj = engine.Script;
         // print var i
         Console.WriteLine(obj.i);
         // add an app object to the script
         engine.Globals.Add("app", new AppObject());
         // let the script call the app object
         engine.Run("app.writeLine('Hello World! ' + i);");
     }
 }
Example #22
0
        private static MethodInfo GenerateMethod(BindingMetadata trigger)
        {
            string           rootPath = Path.Combine(Environment.CurrentDirectory, @"TestScripts\Node");
            FunctionMetadata metadata = new FunctionMetadata();

            metadata.Name       = "Test";
            metadata.ScriptFile = Path.Combine(rootPath, @"Common\test.js");
            metadata.Bindings.Add(trigger);

            List <FunctionMetadata> functions = new List <FunctionMetadata>();

            functions.Add(metadata);

            var environment = new Mock <IScriptHostEnvironment>();

            ScriptHostConfiguration scriptConfig = new ScriptHostConfiguration()
            {
                RootScriptPath = rootPath
            };

            Collection <FunctionDescriptor> functionDescriptors = null;

            using (ScriptHost host = ScriptHost.Create(environment.Object, scriptConfig, SettingsManager))
            {
                FunctionDescriptorProvider[] descriptorProviders = new FunctionDescriptorProvider[]
                {
                    new NodeFunctionDescriptorProvider(host, scriptConfig)
                };

                functionDescriptors = host.GetFunctionDescriptors(functions, descriptorProviders);
            }

            Type t = FunctionGenerator.Generate("TestScriptHost", "Host.Functions", null, functionDescriptors);

            MethodInfo method = t.GetMethods(BindingFlags.Public | BindingFlags.Static).First();

            return(method);
        }
Example #23
0
 public ScriptHost Create(ScriptHostConfiguration config)
 {
     return(ScriptHost.Create(config));
 }
        public static void WarmUp(WebHostSettings settings)
        {
            var        traceWriter = new FileTraceWriter(Path.Combine(settings.LogPath, "Host"), TraceLevel.Info);
            ScriptHost host        = null;

            try
            {
                traceWriter.Info("Warm up started");

                string rootPath = settings.ScriptPath;
                if (Directory.Exists(rootPath))
                {
                    Directory.Delete(rootPath, true);
                }
                Directory.CreateDirectory(rootPath);

                string content = ReadResourceString("Functions.host.json");
                File.WriteAllText(Path.Combine(rootPath, "host.json"), content);

                // read in the C# function
                string functionPath = Path.Combine(rootPath, "Test-CSharp");
                Directory.CreateDirectory(functionPath);
                content = ReadResourceString("Functions.Test_CSharp.function.json");
                File.WriteAllText(Path.Combine(functionPath, "function.json"), content);
                content = ReadResourceString("Functions.Test_CSharp.run.csx");
                File.WriteAllText(Path.Combine(functionPath, "run.csx"), content);

                // read in the F# function
                functionPath = Path.Combine(rootPath, "Test-FSharp");
                Directory.CreateDirectory(functionPath);
                content = ReadResourceString("Functions.Test_FSharp.function.json");
                File.WriteAllText(Path.Combine(functionPath, "function.json"), content);
                content = ReadResourceString("Functions.Test_FSharp.run.fsx");
                File.WriteAllText(Path.Combine(functionPath, "run.fsx"), content);

                traceWriter.Info("Warm up functions deployed");

                ScriptHostConfiguration config = new ScriptHostConfiguration
                {
                    RootScriptPath      = rootPath,
                    FileLoggingMode     = FileLoggingMode.Never,
                    RootLogPath         = settings.LogPath,
                    TraceWriter         = traceWriter,
                    FileWatchingEnabled = false
                };
                config.HostConfig.StorageConnectionString   = null;
                config.HostConfig.DashboardConnectionString = null;

                host = ScriptHost.Create(config);
                traceWriter.Info(string.Format("Starting Host (Id={0})", host.ScriptConfig.HostConfig.HostId));

                host.Start();

                var arguments = new Dictionary <string, object>
                {
                    { "input", "{}" }
                };
                host.CallAsync("Test-CSharp", arguments).Wait();
                host.CallAsync("Test-FSharp", arguments).Wait();
                host.Stop();

                traceWriter.Info("Warm up succeeded");
            }
            catch (Exception ex)
            {
                traceWriter.Error(string.Format("Warm up failed: {0}", ex));
            }
            finally
            {
                host?.Dispose();
                traceWriter.Dispose();
            }
        }