public void 助詞によって引数の順番を切り替える() { // 副作用を有り。 var engine = new Engine(); string[] codes = { "「A」が「B」を「C」にテストする。" , "「A」が「C」に「B」をテストする。" , "「B」を「A」が「C」にテストする。" , "「B」を「C」に「A」がテストする。" , "「C」に「A」が「B」をテストする。" , "「C」に「B」を「A」がテストする。"}; engine.Global.SetVariable("テスト", new SuffixFunc<Func<object, object, object, object>>( (a, b, c) => ((string)a == "A" && (string)b == "B" && (string)c == "C"), "が", "を", "に")); foreach (var code in codes) { Assert.IsTrue((bool)engine.Execute(code, Statics.TestName)); } var defun = "以下の定義でAがBをCにテストする。" + " [A,B,C]を文字列連結する。" + "以上。"; engine.Execute(defun, Statics.TestName); foreach (var code in codes) { Assert.AreEqual("ABC", (string)engine.Execute(code, Statics.TestName)); } }
static void Main(string[] args) { var engine = new Engine(cfg => cfg.AllowClr()) .SetValue("print", new Action<object>(Console.WriteLine)) ; var filename = args.Length > 0 ? args[0] : ""; if (!String.IsNullOrEmpty(filename)) { if (!File.Exists(filename)) { Console.WriteLine("Could not find file: {0}", filename); } var script = File.ReadAllText(filename); var result = engine.GetValue(engine.Execute(script).GetCompletionValue()); return; } Assembly assembly = Assembly.GetExecutingAssembly(); FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location); string version = fvi.FileVersion; Console.WriteLine("Welcome to Jint ({0})", version); Console.WriteLine("Type 'exit' to leave, 'print()' to write on the console."); Console.WriteLine(); var defaultColor = Console.ForegroundColor; while (true) { Console.ForegroundColor = defaultColor; Console.Write("jint> "); var input = Console.ReadLine(); if (input == "exit") { return; } try { var result = engine.GetValue(engine.Execute(input).GetCompletionValue()); if (result.Type != Types.None && result.Type != Types.Null && result.Type != Types.Undefined) { var str = TypeConverter.ToString(engine.Json.Stringify(engine.Json, Arguments.From(result, Undefined.Instance, " "))); Console.WriteLine("=> {0}", str); } } catch (JavaScriptException je) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(je.ToString()); } catch (Exception e) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(e.Message); } } }
public void CanConvertEnumsToString() { var engine1 = new Engine(o => o.AddObjectConverter(new EnumsToStringConverter())) .SetValue("assert", new Action<bool>(Assert.True)); engine1.SetValue("p", new { Comparison = StringComparison.CurrentCulture }); engine1.Execute("assert(p.Comparison === 'CurrentCulture');"); engine1.Execute("var result = p.Comparison;"); Assert.Equal("CurrentCulture", (string)engine1.GetValue("result").ToObject()); }
public void ResultsInCorrectCountsWithPredicate() { // Given Engine engine = new Engine(); engine.CleanOutputPathOnExecute = false; CountModule a = new CountModule("A") { AdditionalOutputs = 1 }; CountModule b = new CountModule("B") { AdditionalOutputs = 2 }; CountModule c = new CountModule("C") { AdditionalOutputs = 3 }; engine.Pipelines.Add(a, new Branch(b).Where((x, y) => x.Content == "1"), c); // When engine.Execute(); // Then Assert.AreEqual(1, a.ExecuteCount); Assert.AreEqual(1, b.ExecuteCount); Assert.AreEqual(1, c.ExecuteCount); Assert.AreEqual(1, a.InputCount); Assert.AreEqual(1, b.InputCount); Assert.AreEqual(2, c.InputCount); Assert.AreEqual(2, a.OutputCount); Assert.AreEqual(3, b.OutputCount); Assert.AreEqual(8, c.OutputCount); }
public void ContentAndMetadataReturnsCorrectDocuments() { // Given List<string> content = new List<string>(); List<object> values = new List<object>(); Engine engine = new Engine(); engine.Trace.AddListener(new TestTraceListener()); Core.Modules.Documents documents = new Core.Modules.Documents( Tuple.Create("A", new Dictionary<string, object> { { "Foo", "a" } }.AsEnumerable()), Tuple.Create("B", new Dictionary<string, object> { { "Foo", "b" } }.AsEnumerable()), Tuple.Create("C", new Dictionary<string, object> { { "Foo", "c" } }.AsEnumerable())); Execute gatherData = new Execute((d, c) => { content.Add(d.Content); values.Add(d["Foo"]); return null; }); engine.Pipelines.Add(documents, gatherData); // When engine.Execute(); // Then Assert.AreEqual(3, content.Count); Assert.AreEqual(3, values.Count); CollectionAssert.AreEqual(new[] { "A", "B", "C" }, content); CollectionAssert.AreEqual(new[] { "a", "b", "c" }, values); }
public void OrderByOrdersInDescendingOrder() { // Given List<string> content = new List<string>(); Engine engine = new Engine(); engine.CleanOutputFolderOnExecute = false; engine.Trace.AddListener(new TestTraceListener()); CountModule count = new CountModule("A") { AdditionalOutputs = 4 }; CountModule count2 = new CountModule("A") { AdditionalOutputs = 2 }; Concat concat = new Concat(count2); OrderBy orderBy = new OrderBy((d, c) => d.Get<int>("A")).Descending(); Execute gatherData = new Execute((d, c) => { content.Add(d.Content); return null; }); engine.Pipelines.Add(count, concat, orderBy, gatherData); // When engine.Execute(); // Then Assert.AreEqual(8, content.Count); CollectionAssert.AreEqual(new[] { "5", "4", "3", "3", "2", "2", "1", "1" }, content); }
public void RunBumpersTest() { Engine<string> engine = new Engine<string>(new RuleCollection<string>()) { RunBumperRules = true }; var result = engine.Execute("blah"); Assert.IsNotNull(result); Assert.AreEqual(2, result.Count); }
public void OrderByOrdersDescendingThenByInDescendingOrder() { // Given List<string> content = new List<string>(); Engine engine = new Engine(); engine.Trace.AddListener(new TestTraceListener()); CountModule count = new CountModule("A") { AdditionalOutputs = 4 }; CountModule count2 = new CountModule("B") { AdditionalOutputs = 1 }; OrderBy orderBy = new OrderBy((d, c) => d.Get<int>("A")) .Descending() .ThenBy((d, c) => d.Get<int>("B")) .Descending(); Execute gatherData = new Execute((d, c) => { content.Add(d.Content); return null; }); engine.Pipelines.Add(count, count2, orderBy, gatherData); // When engine.Execute(); // Then Assert.AreEqual(10, content.Count); // (4+1) * (21+1) CollectionAssert.AreEqual(new[] { "510", "59", "48", "47", "36", "35", "24", "23", "12", "11" }, content); }
public void BranchResultsInCorrectCounts() { // Given Engine engine = new Engine(); CountModule a = new CountModule("A") { AdditionalOutputs = 1 }; CountModule b = new CountModule("B") { AdditionalOutputs = 2 }; CountModule c = new CountModule("C") { AdditionalOutputs = 3 }; engine.Pipelines.Add(a, new Branch(b), c); // When engine.Execute(); // Then Assert.AreEqual(1, a.ExecuteCount); Assert.AreEqual(1, b.ExecuteCount); Assert.AreEqual(1, c.ExecuteCount); Assert.AreEqual(1, a.InputCount); Assert.AreEqual(2, b.InputCount); Assert.AreEqual(2, c.InputCount); Assert.AreEqual(2, a.OutputCount); Assert.AreEqual(6, b.OutputCount); Assert.AreEqual(8, c.OutputCount); }
public void ShouldInterpretLiterals(object expected, string source) { var engine = new Engine(); var result = engine.Execute(source).GetCompletionValue().ToObject(); Assert.Equal(expected, result); }
public void WithPredicateResultsInCorrectCounts() { // Given Engine engine = new Engine(); engine.CleanOutputFolderOnExecute = false; engine.Trace.AddListener(new TestTraceListener()); CountModule a = new CountModule("A") { AdditionalOutputs = 1 }; CountModule b = new CountModule("B") { AdditionalOutputs = 2 }; CountModule c = new CountModule("C") { AdditionalOutputs = 3 }; engine.Pipelines.Add(a, new ConcatBranch(b).Where((x, y) => x.Content == "1"), c); // When engine.Execute(); // Then Assert.AreEqual(1, a.ExecuteCount); Assert.AreEqual(1, b.ExecuteCount); Assert.AreEqual(1, c.ExecuteCount); Assert.AreEqual(1, a.InputCount); Assert.AreEqual(1, b.InputCount); Assert.AreEqual(5, c.InputCount); Assert.AreEqual(2, a.OutputCount); Assert.AreEqual(3, b.OutputCount); Assert.AreEqual(20, c.OutputCount); }
public void ChildModulesAreExecuted() { // Given Engine engine = new Engine(); engine.CleanOutputPathOnExecute = false; CountModule a = new CountModule("A") { AdditionalOutputs = 1 }; CountModule b = new CountModule("B") { AdditionalOutputs = 2 }; CountModule c = new CountModule("C") { AdditionalOutputs = 3 }; engine.Pipelines.Add(a, new Core.Modules.Control.ModuleCollection(b, c)); // When engine.Execute(); // Then Assert.AreEqual(1, a.ExecuteCount); Assert.AreEqual(1, b.ExecuteCount); Assert.AreEqual(1, c.ExecuteCount); Assert.AreEqual(1, a.InputCount); Assert.AreEqual(2, b.InputCount); Assert.AreEqual(6, c.InputCount); Assert.AreEqual(2, a.OutputCount); Assert.AreEqual(6, b.OutputCount); Assert.AreEqual(24, c.OutputCount); }
public void MetadataReturnsCorrectDocuments() { // Given List<object> values = new List<object>(); Engine engine = new Engine(); engine.CleanOutputFolderOnExecute = false; engine.Trace.AddListener(new TestTraceListener()); Core.Modules.Control.Documents documents = new Core.Modules.Control.Documents( new Dictionary<string, object> { { "Foo", "a" } }, new Dictionary<string, object> { { "Foo", "b" } }, new Dictionary<string, object> { { "Foo", "c" } }); Execute gatherData = new Execute((d, c) => { values.Add(d["Foo"]); return null; }); engine.Pipelines.Add(documents, gatherData); // When engine.Execute(); // Then Assert.AreEqual(3, values.Count); CollectionAssert.AreEqual(new[] { "a", "b", "c" }, values); }
public void SetsDocumentsInMetadata() { // Given List<IList<string>> content = new List<IList<string>>(); Engine engine = new Engine(); engine.CleanOutputPathOnExecute = false; CountModule count = new CountModule("A") { AdditionalOutputs = 7 }; GroupBy groupBy = new GroupBy((d, c) => d.Get<int>("A")%3, count); OrderBy orderBy = new OrderBy((d, c) => d.Get<int>(Keys.GroupKey)); Execute gatherData = new Execute((d, c) => { content.Add(d.Get<IList<IDocument>>(Keys.GroupDocuments).Select(x => x.Content).ToList()); return null; }); engine.Pipelines.Add(groupBy, orderBy, gatherData); // When engine.Execute(); // Then Assert.AreEqual(3, content.Count); CollectionAssert.AreEquivalent(new[] {"3", "6"}, content[0]); CollectionAssert.AreEquivalent(new[] {"1", "4", "7"}, content[1]); CollectionAssert.AreEquivalent(new[] {"2", "5", "8"}, content[2]); }
public void GroupBySetsCorrectMetadata() { // Given List<int> groupKey = new List<int>(); Engine engine = new Engine(); engine.CleanOutputFolderOnExecute = false; engine.Trace.AddListener(new TestTraceListener()); CountModule count = new CountModule("A") { AdditionalOutputs = 7 }; GroupBy groupBy = new GroupBy((d, c) => d.Get<int>("A") % 3, count); Execute gatherData = new Execute((d, c) => { groupKey.Add(d.Get<int>(Keys.GroupKey)); return null; }); engine.Pipelines.Add(groupBy, gatherData); // When engine.Execute(); // Then CollectionAssert.AreEquivalent(new[] { 0, 1, 2 }, groupKey); }
public void PaginateSetsDocumentsInMetadata() { // Given List<IList<string>> content = new List<IList<string>>(); Engine engine = new Engine(); engine.Trace.AddListener(new TestTraceListener()); CountModule count = new CountModule("A") { AdditionalOutputs = 7 }; Paginate paginate = new Paginate(3, count); Execute gatherData = new Execute((d, c) => { content.Add(d.Get<IList<IDocument>>(Keys.PageDocuments).Select(x => x.Content).ToList()); return null; }); engine.Pipelines.Add(paginate, gatherData); // When engine.Execute(); // Then Assert.AreEqual(3, content.Count); CollectionAssert.AreEqual(new[] { "1", "2", "3" }, content[0]); CollectionAssert.AreEqual(new[] { "4", "5", "6" }, content[1]); CollectionAssert.AreEqual(new[] { "7", "8" }, content[2]); }
public void IfResultsInCorrectCounts() { // Given Engine engine = new Engine(); engine.Trace.AddListener(new TestTraceListener()); CountModule a = new CountModule("A") { AdditionalOutputs = 2 }; CountModule b = new CountModule("B") { AdditionalOutputs = 2 }; CountModule c = new CountModule("C") { AdditionalOutputs = 3 }; engine.Pipelines.Add(a, new If((x, y) => x.Content == "1", b), c); // When engine.Execute(); // Then Assert.AreEqual(1, a.ExecuteCount); Assert.AreEqual(1, b.ExecuteCount); Assert.AreEqual(1, c.ExecuteCount); Assert.AreEqual(1, a.InputCount); Assert.AreEqual(1, b.InputCount); Assert.AreEqual(5, c.InputCount); Assert.AreEqual(3, a.OutputCount); Assert.AreEqual(3, b.OutputCount); Assert.AreEqual(20, c.OutputCount); }
public void PaginateSetsCorrectMetadata() { // Given List<int> currentPage = new List<int>(); List<int> totalPages = new List<int>(); List<bool> hasNextPage = new List<bool>(); List<bool> hasPreviousPage = new List<bool>(); Engine engine = new Engine(); engine.Trace.AddListener(new TestTraceListener()); CountModule count = new CountModule("A") { AdditionalOutputs = 7 }; Paginate paginate = new Paginate(3, count); Execute gatherData = new Execute((d, c) => { currentPage.Add(d.Get<int>(Keys.CurrentPage)); totalPages.Add(d.Get<int>(Keys.TotalPages)); hasNextPage.Add(d.Get<bool>(Keys.HasNextPage)); hasPreviousPage.Add(d.Get<bool>(Keys.HasPreviousPage)); return null; }); engine.Pipelines.Add(paginate, gatherData); // When engine.Execute(); // Then CollectionAssert.AreEqual(new[] { 1, 2, 3 }, currentPage); CollectionAssert.AreEqual(new[] { 3, 3, 3 }, totalPages); CollectionAssert.AreEqual(new[] { true, true, false }, hasNextPage); CollectionAssert.AreEqual(new[] { false, true, true }, hasPreviousPage); }
public void Can_load_from_type() { var model = (ImmutableModel) _store.LoadModel(typeof (ImmutableModel)); var engine = new Engine<ImmutableModel>(model, _store, _config); engine.Execute(new AppendNumberCommand(53)); engine.Execute(new AppendNumberCommand(42)); engine.Close(); _store = new InMemoryStore(_config); _store.Init(); model = (ImmutableModel) _store.LoadModel(typeof (ImmutableModel)); //make sure state is valid after restore Assert.AreEqual(53 + 42, model.Numbers().Sum()); var ids = _store.GetJournalEntries().Select(je => (int) je.Id).ToArray(); Assert.AreEqual(Enumerable.Range(1,2),ids); }
protected void RunTestCode(string code, bool negative) { _lastError = null; //NOTE: The Date tests in test262 assume the local timezone is Pacific Standard Time var pacificTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"); var engine = new Engine(cfg => cfg.LocalTimeZone(pacificTimeZone)); // loading driver var driverFilename = Path.Combine(BasePath, "TestCases\\sta.js"); engine.Execute(File.ReadAllText(driverFilename)); if (negative) { try { engine.Execute(code); Assert.True(_lastError != null); Assert.False(true); } catch { // exception is expected } } else { try { engine.Execute(code); } catch (JavaScriptException j) { _lastError = TypeConverter.ToString(j.Error); } catch (Exception e) { _lastError = e.ToString(); } Assert.Null(_lastError); } }
public static void InitDb() { if (Db != null) Db.Close(); Db = Engine.LoadOrCreate<LaddersModel>(); if (Db.Execute(m => m.Players.Count == 0)) { SetupTestData(); } }
public void TestTraceListenerThrowsOnErrorOrWarning(TraceEventType traceEventType) { // Given Engine engine = new Engine(); engine.Trace.AddListener(new TestTraceListener()); engine.Pipelines.Add(new Trace(traceEventType.ToString()).EventType(traceEventType)); // When/Then Assert.Throws<Exception>(() => engine.Execute()); }
public void ShouldInterpretVariableDeclaration() { var engine = new Engine(); var result = engine .Execute("var foo = 'bar'; foo;") .GetCompletionValue() .ToObject(); Assert.Equal("bar", result); }
public void DoIt() { string text = "create class Employee (base = Person, table=employees)"; IEngine engine = new Engine(); LoggingService loggingService = new LoggingService(); engine.RegisterService<ILoggingService>(loggingService); CommandLoggingExecutor executor = new CommandLoggingExecutor(); engine.RegisterExecutor(executor); engine.Execute(text); Assert.AreEqual("create class Employee = (base = Person, table = employees, ) " + Environment.NewLine, loggingService.Output); }
public void 末尾再帰最適化が行われる() { // 副作用を有り。 var engine = new Engine(); var code = "以下の定義でAとBを加算する。" + " もし(A≦0)なら、Bである。" + " 他なら、(A-1)と(B+1)を加算する。" + "以上。" + "(1000*1000)と(1000*1000)を加算する。"; Assert.AreEqual(2 * 1000 * 1000, (int)engine.Execute(code, Statics.TestName)); }
public void グローバル変数は可変() { // 副作用を有り。 var engine = new Engine(); var code = "0を値とする。" + "以下の定義で増加する。" + " (値+1)を値に代入する。" + "以上。" + "増加する。増加する。値である。"; Assert.AreEqual(2, (int)engine.Execute(code, Statics.TestName)); }
public void ローカル変数によって上書きされない() { // 副作用有り var engine = new Engine(); var code = "1を値とする。" + "以下の定義で増加する。" + " 2を値とする。" + "以上。" + "値である。"; Assert.AreEqual(1, (int)engine.Execute(code, Statics.TestName)); }
/// <summary> /// Launches the engine. /// </summary> /// <param name="inputFilePaths">List of full input files to be processed.</param> /// <param name="recordReader">Instance that reads the record from the input files.</param> /// <param name="expression">Instance of the expression used to matched against the record.</param> public override void LaunchEngine(String[] inputFilePaths, IRecordReader recordReader, IRecordMatchExpression expression) { var recordWriter = CreateRecordWriter(); var engine = new Engine(); engine.FileOpened += this.FileOpenedHandler; engine.FileRead += this.FileReadHandler; engine.CheckForCancellation = this.CheckForCancellation; // Get the UI thread now because this method is guaranteed to be running on that thread (since this // method is called from a winform control handler method) this.mainTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext(); // Create a new cancellation source and token - the previous one may have been cancelled already. this.cancellationTokenSource = new CancellationTokenSource(); this.cancellationToken = this.cancellationTokenSource.Token; var task = Task.Factory.StartNew(() => { engine.Execute( inputFilePaths, this.uiLogManager, new FileReaderFactory(), recordReader, expression, recordWriter, this.statisticsManager, this.statisticsManager); }, this.cancellationToken); var finishedTask = task.ContinueWith((antecedent) => { if (antecedent.Exception != null) { this.uiLogManager.WriteMessagesToLogs("Job FAILED."); var ae = antecedent.Exception.Flatten(); Int32 count = 1; foreach (Exception e in ae.InnerExceptions) { this.uiLogManager.WriteMessagesToLogs(String.Format("EXCEPTION {0}: {1}", count++, e.Message)); this.uiLogManager.WriteMessagesToLogs("STACK: " + e.StackTrace); } } else if (this.cancellationToken.IsCancellationRequested) { this.uiLogManager.WriteMessagesToLogs("CANCELLED."); } recordWriter.Close(); this.uiLogManager.Close(); this.mainForm.JobFinished(); }, TaskScheduler.FromCurrentSynchronizationContext()); }
public IList<IEngineResult> Run(ExampleModel model) { Engine<ExampleModel> engine = new Engine<ExampleModel>( new List<IRule<ExampleModel>>() { new AddRule(), new DivisionRule(), new MultiplicationRule(), new SubtractRule() }); var retval = engine.Execute(model); return retval; }
public void ExecuteDoesNotThrowForNullResultWithDocumentConfig() { // Given Engine engine = new Engine(); engine.CleanOutputPathOnExecute = false; Execute execute = new Execute((d, c) => null); engine.Pipelines.Add(execute); // When engine.Execute(); // Then }
public void Initialize(Engine engine) { TypeScriptEnum typeScriptEnum = new(typeof(Easings.Functions)); string enums = ""; for (int index = 0; index < typeScriptEnum.Names.Length; index++) { enums = enums + typeScriptEnum.Names[index] + ": " + typeScriptEnum.Values[index] + ",\r\n"; } string enumDeclaration = "if (!Artemis.Core) {\r\n" + " Artemis.Core = {}\r\n" + "}\r\n" + "Artemis.Core.EasingsFunctions = {\r\n" + $" {enums.Trim()}\r\n" + "}"; engine.Execute(enumDeclaration); }
public void MethodCallCaching_MethodMissing5() { Engine.Execute(@" obj = Object.new class << obj def method_missing(*args) raise end end obj.f rescue nil module Kernel def f end end obj.f"); }
public void Initialize(SmugglerDatabaseOptions databaseOptions) { if (databaseOptions == null || string.IsNullOrEmpty(databaseOptions.TransformScript)) { return; } jint = new Engine(cfg => { cfg.AllowDebuggerStatement(false); cfg.MaxStatements(databaseOptions.MaxStepsForTransformScript); cfg.NullPropagation(); }); jint.Execute(string.Format(@" function Transform(docInner){{ return ({0}).apply(this, [docInner]); }};", databaseOptions.TransformScript)); }
public bool Execute(WorkFlowCommand command, Context context) { if (!CheckCondition(command, context)) { return(true); } var var = new Engine(); foreach (var variable in context.WorkFlow.Variables.Items) { //e.Parameters[variable.Name] = new Exception(variable.Value); var.SetValue(variable.Name, variable.GetAsObject()); } context.WorkFlow.Variables[command.Properties["Variable"].Value].Value = var.Execute(command.Properties["Formula"].ToString(context)).GetCompletionValue().ToString(); return(true); }
private static void Execute(Engine engine, string script) { try { engine.Execute(script); } catch (ArgumentException ex) { throw new ValidationException($"Failed to execute script with javascript syntax error: {ex.Message}", new ValidationError(ex.Message)); } catch (JavaScriptException ex) { throw new ValidationException($"Failed to execute script with javascript error: {ex.Message}", new ValidationError(ex.Message)); } catch (ParserException ex) { throw new ValidationException($"Failed to execute script with javascript error: {ex.Message}", new ValidationError(ex.Message)); } }
public void SameSourceThrowsException() { // Given Engine engine = new Engine(); CountModule a = new CountModule("A") { CloneSource = true }; CountModule b = new CountModule("B"); CountModule c = new CountModule("A") { CloneSource = true }; engine.Pipelines.Add("Count", a, new Concat(b, c)); // When, Then Assert.Throws <Exception>(() => engine.Execute()); }
public void CompletedMetadataIsPopulatedAfterRun() { // Given Engine engine = new Engine(); int c = 0; engine.Pipelines.Add("Pipeline", new Execute((x, ctx) => new[] { ctx.GetDocument(x, (string)null, new Dictionary <string, object> { { c.ToString(), c++ } }), ctx.GetDocument(x, (string)null, new Dictionary <string, object> { { c.ToString(), c++ } }) }), new Execute((x, ctx) => new[] { ctx.GetDocument(x, (string)null, new Dictionary <string, object> { { c.ToString(), c++ } }) })); // When engine.Execute(); // Then Assert.AreEqual(2, engine.Documents.FromPipeline("Pipeline").Count()); Assert.IsTrue(engine.Documents.FromPipeline("Pipeline").First().Metadata.ContainsKey("0")); Assert.AreEqual(0, engine.Documents.FromPipeline("Pipeline").First().Metadata["0"]); Assert.IsTrue(engine.Documents.FromPipeline("Pipeline").First().Metadata.ContainsKey("2")); Assert.AreEqual(2, engine.Documents.FromPipeline("Pipeline").First().Metadata["2"]); Assert.IsFalse(engine.Documents.FromPipeline("Pipeline").First().Metadata.ContainsKey("1")); Assert.IsFalse(engine.Documents.FromPipeline("Pipeline").First().Metadata.ContainsKey("3")); Assert.IsTrue(engine.Documents.FromPipeline("Pipeline").Skip(1).First().Metadata.ContainsKey("1")); Assert.AreEqual(1, engine.Documents.FromPipeline("Pipeline").Skip(1).First().Metadata["1"]); Assert.IsTrue(engine.Documents.FromPipeline("Pipeline").Skip(1).First().Metadata.ContainsKey("3")); Assert.AreEqual(3, engine.Documents.FromPipeline("Pipeline").Skip(1).First().Metadata["3"]); Assert.IsFalse(engine.Documents.FromPipeline("Pipeline").Skip(1).First().Metadata.ContainsKey("0")); Assert.IsFalse(engine.Documents.FromPipeline("Pipeline").Skip(1).First().Metadata.ContainsKey("2")); }
public override void Execute(string collection, ref JObject item, ref Dictionary <string, object> dataContext) { var settings = this.entityService.GetByName(collection); if (settings != null) { if (!string.IsNullOrEmpty(settings.PresaveScript)) { Dictionary <string, object> input = item.ToObject <Dictionary <string, object> >(); Engine engine = new Engine((x) => { x.AllowClr(typeof(JavascriptRestClient).Assembly); x.AllowClr(typeof(JavascriptRestClientRequest).Assembly); }); engine.SetValue("RAWCMSRestClient", Jint.Runtime.Interop.TypeReference.CreateTypeReference(engine, typeof(JavascriptRestClient))); engine.SetValue("RAWCMSRestClientRequest", Jint.Runtime.Interop.TypeReference.CreateTypeReference(engine, typeof(JavascriptRestClientRequest))); engine.SetValue("item", input); engine.Execute(settings.PresaveScript); item = JObject.FromObject(input); } } }
private void ValidateCustomFunctions(RavenJObject document) { var engine = new Engine(cfg => { cfg.AllowDebuggerStatement(); cfg.MaxStatements(1000); cfg.NullPropagation(); }); engine.Execute(string.Format(@" var customFunctions = function() {{ var exports = {{ }}; {0}; return exports; }}(); for(var customFunction in customFunctions) {{ this[customFunction] = customFunctions[customFunction]; }};", document.Value <string>("Functions"))); }
public void LoadLayoutFile() { // Given Engine engine = new Engine(); engine.InputFolder = @"TestFiles\Input\"; ReadFiles readFiles = new ReadFiles(@"Layout\Test.cshtml"); Razor razor = new Razor(); Meta meta = new Meta("Content", (x, y) => x.Content); engine.Pipelines.Add("Pipeline", readFiles, razor, meta); // When engine.Execute(); // Then Assert.AreEqual(1, engine.Documents.FromPipeline("Pipeline").Count()); Assert.AreEqual("LAYOUT\r\n\r\n<p>This is a test</p>", engine.Documents.FromPipeline("Pipeline").First().String("Content")); }
public void ScenarioTwo() { Engine engine = Engine.GetTestEngine(); Sku skuA = new Sku("A", 50); Sku skuB = new Sku("B", 30); Sku skuC = new Sku("C", 20); Dictionary <Sku, int> skuValues = new Dictionary <Sku, int>() { { skuA, 5 }, { skuB, 5 }, { skuC, 1 } }; int result = engine.Execute(skuValues); Assert.AreEqual(370, result); }
public void PythonInterop4() { if (!_driver.RunPython) { return; } // TODO: if (_driver.PartialTrust) { return; } var py = Runtime.GetEngine("python"); var scope = py.CreateScope(); py.Execute(@" def get_python_class(): class C(object): x = 123 def __str__(self): return 'this is C' return C() ", scope); Engine.Execute(@"self.c = get_python_class.call", scope); var s = Engine.Execute <MutableString>(@"c.to_str", scope); Assert(s.ToString() == @"this is C"); var i = Engine.Execute <int>(@"c.x", scope); Assert(i == 123); // TODO: test // c.y, where y is a delegate // c.p, where p is a Ruby Proc }
public void Test(Type kernelToRun) { try { Environment.CurrentDirectory = Path.GetDirectoryName(typeof(RunKernels).Assembly.Location); var xEngine = new Engine(); // Sets the time before an error is registered. For example if set to 60 then if a kernel runs for more than 60 seconds then // that kernel will be marked as a failure and terminated xEngine.AllowedSecondsInKernel = 1200; // If you want to test only specific platforms, add them to the list, like next line. By default, all platforms are run. xEngine.RunTargets.Add(RunTargetEnum.Bochs); //xEngine.StartBochsDebugGui = false; //xEngine.RunWithGDB = true; // If you're working on the compiler (or other lower parts), you can choose to run the compiler in process // one thing to keep in mind though, is that this only works with 1 kernel at a time! //xEngine.RunIL2CPUInProcess = true; xEngine.TraceAssembliesLevel = TraceAssemblies.User; xEngine.EnableStackCorruptionChecks = true; xEngine.StackCorruptionChecksLevel = StackCorruptionDetectionLevel.AllInstructions; // Select kernels to be tested by adding them to the engine xEngine.AddKernel(kernelToRun.Assembly.Location); xEngine.OutputHandler = new TestOutputHandler(); Assert.IsTrue(xEngine.Execute()); } catch (AssertionException) { throw; } catch (Exception E) { Console.WriteLine("Exception occurred: " + E.ToString()); Assert.Fail(); } }
static void Main(string[] args) { var xEngine = new Engine(); DefaultEngineConfiguration.Apply(xEngine); var xOutputXml = new OutputHandlerXml(); xEngine.OutputHandler = new MultiplexingOutputHandler( xOutputXml, new OutputHandlerFullConsole()); xEngine.Execute(); Console.WriteLine("Do you want to save test run details?"); Console.Write("Type yes, or nothing to just exit: "); var xResult = Console.ReadLine(); if (xResult != null && xResult.Trim().Equals("yes", StringComparison.OrdinalIgnoreCase)) { Console.Write("Path: "); xResult = Console.ReadLine(); try { xOutputXml.SaveToFile(xResult); } catch (Exception ex) { Console.WriteLine("Exception: " + ex.ToString()); } //var xSaveDialog = new SaveFileDialog(); //xSaveDialog.Filter = "XML documents|*.xml"; //if (xSaveDialog.ShowDialog() != DialogResult.OK) //{ // return; //} //xOutputXml.SaveToFile(xSaveDialog.FileName); } }
public override bool Compile(string code) { try { _jint = new Engine(cfg => cfg.AllowClr()); _jint = _jint.Execute(code); var isMainExists = (bool)_jint.Execute("typeof main === \"function\"").GetCompletionValue().ToObject(); Errors = new List <string>(); if (!isMainExists) { Errors = new List <string> { "`main(args)` function doesn't exist.", }; return(false); } _botInstance = code; return(true); } catch (ParserException ex) { Errors = new List <string> { ex.Message, }; } catch (JavaScriptException ex) { Errors = new List <string> { ex.Message, }; } catch (Exception) { throw; } return(false); }
public void BreakPointDoesNotTriggerBreakWhenStepping() { string script = @" 'first breakpoint'; 'dummy'; 'second breakpoint';"; var engine = new Engine(options => options .DebugMode() .InitialStepMode(StepMode.Into)); bool didStep = true; bool didBreak = true; engine.DebugHandler.BreakPoints.Set(new BreakPoint(2, 0)); engine.DebugHandler.BreakPoints.Set(new BreakPoint(4, 0)); engine.DebugHandler.Break += (sender, info) => { didBreak = true; // first breakpoint shouldn't cause us to get here, because we're stepping, // but when we reach the second, we're running: Assert.True(TestHelpers.ReachedLiteral(info, "second breakpoint")); return(StepMode.None); }; engine.DebugHandler.Step += (sender, info) => { didStep = true; if (TestHelpers.ReachedLiteral(info, "first breakpoint")) { // Run from here return(StepMode.None); } return(StepMode.Into); }; engine.Execute(script); Assert.True(didStep); Assert.True(didBreak); }
public void RubyHosting1C() { // Main singleton in a scope-unbound code doesn't define method_missing: AssertExceptionThrown <MemberAccessException>( () => Engine.Execute("class << self; remove_method(:method_missing); end") ); // Main singleton in a scope-bound code defines method_missing: Engine.Execute("class << self; remove_method(:method_missing); end", Engine.CreateScope()); var scope = Engine.CreateScope(); Engine.Execute("self.tmp = 1", scope); Assert(scope.ContainsVariable("tmp")); AssertExceptionThrown <MissingMethodException>(() => Engine.Execute("self.tmp = 1")); // method_missing on top-level scope is defined dynamically, not at compile time: var compiled = Engine.CreateScriptSourceFromString("some_variable").Compile(); scope = Engine.CreateScope(); scope.SetVariable("some_variable", 123); Assert(compiled.Execute <int>(scope) == 123); AssertExceptionThrown <MissingMethodException>(() => compiled.Execute()); scope.SetVariable("some_variable", "foo"); Assert(compiled.Execute <string>(scope) == "foo"); // we throw correct exceptions: scope = Engine.CreateScope(); scope.SetVariable("bar", 1); AssertExceptionThrown <MissingMethodException>(() => Engine.Execute("foo 1,2,3")); AssertExceptionThrown <MissingMethodException>(() => Engine.Execute("foo 1,2,3", scope)); AssertExceptionThrown <ArgumentException>(() => Engine.Execute("bar 1,2,3", scope)); AssertExceptionThrown <ArgumentException>(() => Engine.Execute("bar *[1,2,3]", scope)); AssertExceptionThrown <ArgumentException>(() => Engine.Execute("scope *[1,2,3]", scope)); Assert(Engine.Execute <int>("bar *[]", scope) == 1); }
public void ShouldConsiderConstraintsWhenCallingInvoke() { var engine = new Engine(options => { options.TimeoutInterval(TimeSpan.FromMilliseconds(100)); }); var myApi = new MyApi(); engine.SetValue("myApi", myApi); engine.Execute("myApi.addEventListener('DataReceived', (data) => { myApi.log(data) })"); var dataReceivedCallbacks = myApi.Callbacks.Where(kvp => kvp.Key == "DataReceived"); foreach (var callback in dataReceivedCallbacks) { engine.Invoke(callback.Value, "Data Received #1"); Thread.Sleep(101); engine.Invoke(callback.Value, "Data Received #2"); } }
public void ConstructorsCanBePassedToHost() { var engine = new Engine(); Func <JsValue, JsValue[], JsValue> ev = null; void addListener(Func <JsValue, JsValue[], JsValue> callback) { ev = callback; } engine.SetValue("addListener", new Action <Func <JsValue, JsValue[], JsValue> >(addListener)); engine.Execute(@"addListener(Boolean)"); Assert.Equal(true, ev(JsValue.Undefined, new JsValue[] { "test" })); Assert.Equal(true, ev(JsValue.Undefined, new JsValue[] { 5 })); Assert.Equal(false, ev(JsValue.Undefined, new JsValue[] { false })); Assert.Equal(false, ev(JsValue.Undefined, new JsValue[] { 0 })); Assert.Equal(false, ev(JsValue.Undefined, new JsValue[] { JsValue.Undefined })); }
/// <summary> /// Initializes engine in debugmode and executes script until debugger statement, /// before calling stepHandler for assertions. Also asserts that a break was triggered. /// </summary> /// <param name="script">Script that is basis for testing</param> /// <param name="breakHandler">Handler for assertions</param> public static void TestAtBreak(string script, Action <Engine, DebugInformation> breakHandler) { var engine = new Engine(options => options .DebugMode() .DebuggerStatementHandling(DebuggerStatementHandling.Script) ); bool didBreak = false; engine.DebugHandler.Break += (sender, info) => { didBreak = true; breakHandler(sender as Engine, info); return(StepMode.None); }; engine.Execute(script); Assert.True(didBreak, "Test script did not break (e.g. didn't reach debugger statement)"); }
public void AlternateIgnorePrefix() { // Given Engine engine = new Engine(); engine.RootFolder = TestContext.CurrentContext.TestDirectory; engine.InputFolder = @"TestFiles\Input\"; ReadFiles readFiles = new ReadFiles(@"AlternateIgnorePrefix\*.cshtml"); Razor razor = new Razor().IgnorePrefix("Ignore"); Meta meta = new Meta("Content", (x, y) => x.Content); engine.Pipelines.Add("Pipeline", readFiles, razor, meta); // When engine.Execute(); // Then Assert.AreEqual(1, engine.Documents.FromPipeline("Pipeline").Count()); Assert.AreEqual(@"<p>This is a test</p>", engine.Documents.FromPipeline("Pipeline").First().String("Content")); }
public void ShouldNotStepInIfRequiredToStepOut() { countBreak = 0; var engine = new Engine(options => options.DebugMode()); engine.Step += EngineStepOutWhenInsideFunction; engine.Execute(@"function func() // first step { ; // third step - now stepping out ; // it should not step here } func(); // second step ; // fourth step "); engine.Step -= EngineStepOutWhenInsideFunction; Assert.Equal(4, countBreak); }
public void CrossRuntime2() { Engine.Execute(@" C = IronRuby.create_engine.execute <<end class C def bar end end C end "); // can't define a method on a foreign class: AssertExceptionThrown <InvalidOperationException>(() => Engine.Execute("C.send(:define_method, :foo) {}")); // can't open a scope of a foreign class: AssertExceptionThrown <InvalidOperationException>(() => Engine.Execute("class C; end")); // alias operates in the runtime of the class within which scope it is used: Engine.Execute("C.send(:alias_method, :foo, :bar); C.new.foo"); }
public void RubyHosting4() { Runtime.Globals.SetVariable("foo_bar", 1); Engine.Execute(@" IronRuby.globals.x = 2 IronRuby.globals.z = IronRuby.globals.x + FooBar "); Assert(Runtime.Globals.GetVariable <int>("z") == 3); #if !CLR2 dynamic scope = Engine.CreateScope(); Engine.Execute(@"def foo; 1; end", scope); RubyMethod method = (RubyMethod)scope.foo; Assert(method.Name == "foo"); object value = scope.foo(); Assert((int)value == 1); #endif }
public void ShouldStepAllStatementsWithoutInvocationsIfStepOver() { countBreak = 0; var engine = new Engine(options => options.DebugMode()); stepMode = StepMode.Over; engine.Step += EngineStep; engine.Execute(@"var step1 = 1; // first step var step2 = 2; // second step if (step1 !== step2) // third step { // fourth step ; // fifth step }"); engine.Step -= EngineStep; Assert.Equal(5, countBreak); }
static JSInterop() { try { #if UNITY_EDITOR var files = Directory.GetFiles(JSConf.instance.JsprojPath, "*.js", SearchOption.AllDirectories); Array.ForEach(files, f => Engine.Execute(File.ReadAllText(f))); #endif Engine.SetValue(nameof(Debug.Log), new Action <UnityEngine.Object>(Debug.Log)); Engine.SetValue("AddComponent", new Action <GameObject, string>(AddComp)); Engine.SetValue(nameof(JSInteropComp), TypeReference.CreateTypeReference(Engine, typeof(JSInteropComp))); } catch (JavaScriptException exc) { Debug.LogError($"{exc},\n" + $"{nameof(exc.LineNumber)} = {exc.LineNumber}, \n" + $"{nameof(exc.Column)} = {exc.Column}), \n" + $"{nameof(exc.CallStack)} = {exc.CallStack} \n"); } }
public void OmittingCasesAndDefaultResultsInCorrectCounts() { // Given Engine engine = new Engine(); engine.Trace.AddListener(new TestTraceListener()); CountModule a = new CountModule("A") { AdditionalOutputs = 2 }; CountModule b = new CountModule("B"); engine.Pipelines.Add(a, new Switch((x, y) => x.Content), b); // When engine.Execute(); // Then Assert.AreEqual(3, b.InputCount); }
public MainViewModel() { RunScriptCommand = new Command(() => { if (SelectedScript is null) { return; } using (Profiler.Profile(SelectedScript.Name)) { var jint = new Engine(); jint.SetValue("context", this); jint.Execute(ScriptContent); } }); ScriptContent = SelectedScript.Content; }
public void CaseInsensitiveStringComparer() { // Given List <object> groupKey = new List <object>(); Engine engine = new Engine(); Execute meta = new Execute((d, c) => new IDocument[] { c.GetDocument(d, new MetadataItems { { "Tag", new[] { "A", "b" } } }), c.GetDocument(d, new MetadataItems { { "Tag", new[] { "B" } } }), c.GetDocument(d, new MetadataItems { { "Tag", "C" } }), c.GetDocument(d, new MetadataItems { { "Tag", new[] { "c" } } }), c.GetDocument(d, new MetadataItems { { "Tag", new[] { 1 } } }), c.GetDocument(d, new MetadataItems { { "Tag", "1" } }) }, false); GroupByMany groupByMany = new GroupByMany("Tag", meta).WithComparer(StringComparer.OrdinalIgnoreCase); Execute gatherData = new Execute((d, c) => { groupKey.Add(d.Get(Keys.GroupKey)); return(null); }, false); engine.Pipelines.Add(groupByMany, gatherData); // When engine.Execute(); // Then CollectionAssert.AreEquivalent(new object[] { "A", "b", "C", 1 }, groupKey); }
private void Execute() { var engine = new Engine(); var writer = new StringWriter(); engine.Out = writer; var code = txtProgram.Text; try { engine.Execute(code, tmpName); txtOut.ForeColor = Color.Black; txtOut.Text = writer.ToString(); } catch (CompilerException ex) { txtOut.ForeColor = Color.Red; txtOut.Text = "構文が間違っています。"; SelectLine(ex.Location.Line - 1); } catch (Exception ex) { txtOut.ForeColor = Color.Red; txtOut.Text = ex.Message; var regex = new Regex(@"行\s+(\d+)"); int lineNumber = 0; foreach (var line in ex.StackTrace.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)) { if (line.Contains(tmpName)) { var res = regex.Match(line); if (res.Success) { lineNumber = Int32.Parse(res.Groups[1].Value); break; } } } if (lineNumber > 0) { SelectLine(lineNumber - 1); } } }