public void FluentNavigation_FollowingLinks_two_times() { string script = @" var requirements = self.FollowingLinks(""Microsoft.VSTS.Common.TestedBy-Reverse""); foreach(var req in requirements) { logger.Log(""Requirement #{0}"", req.Id); var testCases = req.FollowingLinks(""Microsoft.VSTS.Common.TestedBy-Forward""); double remaining = testCases.Sum(tc => tc.GetField(""Microsoft.VSTS.Scheduling.RemainingWork"", 0.0)); req[""Custom.RemainingWork""] = req.GetField(""Microsoft.VSTS.Scheduling.RemainingWork"", 0.0) + remaining; } "; IWorkItem startPoint; var repository = MakeRepository(out startPoint); var logger = new DebugEventLogger(); repository.Logger = logger; var tc2 = repository.GetWorkItem(22); var library = Substitute.For <IScriptLibrary>(); var engine = new CSharpScriptEngine(logger, true, library); engine.LoadAndRun("test", script, tc2, repository); Assert.AreEqual(42.0, startPoint["Custom.RemainingWork"]); }
public void InitTestScriptEngine() { var lgf = LoggerFactory.Create(f => { f.AddConsole(); }); _js_engine = new JavaScriptEngine(lgf.CreateLogger <JavaScriptEngine>(), Options.Create(new Interpreter.EngineSetting() { Timeout = 4 })); _python_engine = new PythonScriptEngine(lgf.CreateLogger <PythonScriptEngine>(), Options.Create(new Interpreter.EngineSetting() { Timeout = 4 })); _lua_engine = new LuaScriptEngine(lgf.CreateLogger <LuaScriptEngine>(), Options.Create(new Interpreter.EngineSetting() { Timeout = 4 })); _c_engine = new CScriptEngine(lgf.CreateLogger <CScriptEngine>(), Options.Create(new Interpreter.EngineSetting() { Timeout = 4 })); _sql_engine = new SQLEngine(lgf.CreateLogger <SQLEngine>(), Options.Create(new Interpreter.EngineSetting() { Timeout = 4 })); _csharp_engine = new CSharpScriptEngine(lgf.CreateLogger <CSharpScriptEngine>(), Options.Create(new Interpreter.EngineSetting() { Timeout = 4 })); }
public void Can_run_a_CSharp_script_interacting_with_a_verbose_object_model() { string script = @" self.Fields[""x""].Value = 33; return self.Fields[""z""].Value; "; var repository = Substitute.For <IWorkItemRepository>(); var workItem = Substitute.For <IWorkItem>(); var xField = Substitute.For <IFieldWrapper>(); var zField = Substitute.For <IFieldWrapper>(); workItem.Id.Returns(1); xField.OriginalValue.Returns(11); workItem.Fields["x"] = xField; workItem.Fields["z"] = zField; zField.Value.Returns(42); repository.GetWorkItem(1).Returns(workItem); var logger = Substitute.For <ILogEvents>(); var engine = new CSharpScriptEngine(repository, logger, Debugger.IsAttached); engine.LoadAndRun("test", script, workItem); Assert.AreEqual(33, xField.Value); object expected = 42; logger.Received().ResultsFromScriptRun("test", expected); }
public void Execute() { IScriptEngine scriptEngineProvider = new CSharpScriptEngine(); DynamicScript script = new DynamicScript(); script.Language = DynamicScriptLanguage.CSharp; script.Script = @" using System; public class Test { public int GetA(int a) { return a; } } "; script.ClassFullName = "Test"; script.FunctionName = "GetA"; script.Parameters = new object[] { 111 }; script.IsExecutionInSandbox = false; var result = scriptEngineProvider.Execute <int>(script); Assert.True(result.IsSuccess); Assert.Equal(111, result.Data); }
public void DeadCycile() { IScriptEngine scriptEngineProvider = new CSharpScriptEngine(); DynamicScript script = new DynamicScript(); script.Language = DynamicScriptLanguage.CSharp; script.Script = @" using System; public class Test { public int GetA(int a) { for(;;){} return a; } } "; script.ClassFullName = "Test"; script.FunctionName = "GetA"; script.Parameters = new object[] { 111 }; script.IsExecutionInSandbox = false; //因为有死循环,所以非信任脚本测试,测试是否会超时 script.ExecutionInSandboxMillisecondsTimeout = 1000; var result = scriptEngineProvider.Execute <int>(script); Assert.False(result.IsSuccess); Assert.Equal("execution timed out!", result.Message); }
private static async void TestScript() { // Code snippet: a class with one string-property. string codeContent = @" using System; public class ScriptedClass { public string HelloWorld { get; set; } public ScriptedClass() { HelloWorld = ""Hello Roslyn!""; } } new ScriptedClass().HelloWorld"; // Instanciate CSharpScriptEngine var engine = new CSharpScriptEngine(); // Execute code and return string property var scriptingState = await engine.ExecuteAsync(codeContent); // Print return value from CSharpScript Console.WriteLine("Returned from CSharpScript: {0}", scriptingState.ReturnValue); Console.WriteLine("Press any key to continue."); Console.ReadKey(); }
public void SearchPaths_BaseDirectory() { var engine = new CSharpScriptEngine(new MetadataReferenceProvider(new Dictionary <string, PortableExecutableReference> { { @"C:\dir\x.dll", (PortableExecutableReference)SystemCoreRef } })); engine.MetadataReferenceResolver = new VirtualizedFileReferenceResolver( existingFullPaths: new[] { @"C:\dir\x.dll" }, baseDirectory: @"C:\foo\bar" ); var session = engine.CreateSession(); var source = @" #r ""x.dll"" using System.Linq; var x = from a in new[] { 1,2,3 } select a + 1; "; var submission = session.CompileSubmission <object>(source, @"C:\dir\a.csx", isInteractive: false); submission.Execute(); }
public void TransitionStateCSharp_New_to_Done_succeeded_via_InProgress() { string script = @" self.TransitionToState(""Done"", ""script test""); "; var repository = new WorkItemRepositoryMock(); var logger = Substitute.For <ILogEvents>(); repository.Logger = logger; var workItem = new WorkItemMock(repository); var workItemType = new WorkItemTypeMock() { Name = "Task", DocumentContent = TestHelpers.LoadTextFromEmbeddedResource("task.xml") }; workItem.Id = 42; workItem.Type = workItemType; workItem.TypeName = workItemType.Name; ((FieldMock)workItem.Fields["State"]).OriginalValue = string.Empty; workItem.Fields["State"].Value = workItem.Fields["State"].OriginalValue; ((FieldMock)workItem.Fields["State"]).Status = Microsoft.TeamFoundation.WorkItemTracking.Client.FieldStatus.InvalidValueNotInOtherField; repository.SetWorkItems(new[] { workItem }); var engine = new CSharpScriptEngine(repository, logger, false); engine.LoadAndRun("test", script, workItem); Assert.AreEqual("Done", workItem.Fields["State"].Value); Assert.AreEqual(2, workItem.InternalSaveCount); }
public void FluentNavigation_CSharp_script_succeedes() { string script = @" var searchResult = self .WhereTypeIs(""Task"") .AtMost(2) .FollowingLinks(""*""); return searchResult; "; IWorkItem startPoint; var repository = MakeRepository(out startPoint); var logger = Substitute.For <ILogEvents>(); repository.Logger = logger; var engine = new CSharpScriptEngine(repository, logger, false); engine.LoadAndRun("test", script, startPoint); var expected = new FluentQuery(startPoint); expected.WorkItemType = "Task"; expected.Levels = 2; expected.LinkType = "*"; logger.Received().ResultsFromScriptRun("test", expected); }
/// <summary> /// initialize contextual attributes and setup the context streams /// </summary> /// <param name="commandEvaluationContext">context</param> public void Initialize(CommandEvaluationContext commandEvaluationContext) { this.CommandEvaluationContext = commandEvaluationContext; // TODO: activate after DotNetConsole is no more static - see remarks below /* * Out = new ConsoleTextWriterWrapper(System.Console.Out); * Err = new TextWriterWrapper(System.Console.Error); * In = System.Console.In; */ var scriptOptions = ScriptOptions.Default; var abl = Assembly.GetExecutingAssembly(); scriptOptions = scriptOptions.WithReferences(abl); var cSharpScriptEngine = new CSharpScriptEngine( commandEvaluationContext.CommandLineProcessor.Console, scriptOptions); Out = new ShellConsoleTextWriterWrapper( commandEvaluationContext, System.Console.Out, cSharpScriptEngine ) { IsMute = commandEvaluationContext.Out.IsMute }; commandEvaluationContext.CommandLineProcessor.Console.Out = Out; // are trully equals Err = commandEvaluationContext.CommandLineProcessor.Console.Err; In = commandEvaluationContext.CommandLineProcessor.Console.In; commandEvaluationContext.SetStreams(Out, In, Err); }
public void Catch_CSharp_rule_compile_error() { var good_script = new ScriptSourceElement() { Name = "good", Type = ScriptSourceElementType.Rule, SourceCode = @" logger.Log(""Test""); " }; var bad_script = new ScriptSourceElement() { Name = "bad", Type = ScriptSourceElementType.Rule, SourceCode = @" loger.Log(""Test""); " }; var logger = Substitute.For <ILogEvents>(); var library = Substitute.For <IScriptLibrary>(); var engine = new CSharpScriptEngine(logger, Debugger.IsAttached, library); engine.Load(new ScriptSourceElement[] { good_script, bad_script }); logger.Received().ScriptHasError("bad", 2, 1, "CS0103", "The name 'loger' does not exist in the current context"); }
public void ShouldNotMarkSubmissionsAsIncompleteWhenRunningScript( [Frozen] Mock <IScriptHostFactory> scriptHostFactory, [NoAutoProperties] CSharpScriptEngine engine, ScriptPackSession scriptPackSession) { // Arrange const string Code = "class test {"; var session = new SessionState <ScriptState> { Session = CSharpScript.Run("") }; scriptPackSession.State[CommonScriptEngine.SessionKey] = session; var refs = new AssemblyReferences(new[] { "System" }); engine.FileName = "test.csx"; // Act var result = engine.Execute( Code, new string[0], refs, Enumerable.Empty <string>(), scriptPackSession); // Assert result.IsCompleteSubmission.ShouldBeTrue(); result.CompileExceptionInfo.ShouldNotBeNull(); }
public void CompilationChain_SubmissionSlots() { var engine = new CSharpScriptEngine(); var session = engine.CreateSession(); session.Execute("using System;"); session.Execute("using static System.Environment;"); session.Execute("int x; x = 1;"); session.Execute("using static System.Math;"); session.Execute("int foo(int a) { return a + 1; } "); #if false Assert.True(session.executionState.submissions.Length >= 2, "Expected two submissions"); session.executionState.submissions.Aggregate(0, (i, sub) => { Assert.Equal(i < 2, sub != null); return(i + 1); }); #endif object result; // TODO (tomat): Version is a type and property, but we are not looking for a type, so can we disambiguate? ScriptingTestHelpers.AssertCompilationError(session, "Version", // (1,1): error CS0229: Ambiguity between 'System.Version' and 'System.Environment.Version' Diagnostic(ErrorCode.ERR_AmbigMember, "Version").WithArguments("System.Version", "System.Environment.Version") ); result = session.Execute("new System.Collections.Generic.List<Version>()"); Assert.True(result is List <Version>, "Expected List<Version>"); result = session.Execute("Environment.Version"); Assert.Equal(Environment.Version, result); result = session.Execute("foo(x)"); Assert.Equal(2, result); result = session.Execute("Sin(0)"); Assert.Equal(0.0, result); }
public void DownloadPackage() { IScriptEngine scriptEngineProvider = new CSharpScriptEngine(); DynamicScript script = new DynamicScript(); script.Language = DynamicScriptLanguage.CSharp; script.Script = @" using System; using Newtonsoft.Json; public class Test { public string GetA(int a) { return JsonConvert.SerializeObject(a); } } "; script.ClassFullName = "Test"; script.FunctionName = "GetA"; script.Parameters = new object[] { 111 }; script.IsExecutionInSandbox = false; var result = scriptEngineProvider.Execute <string>(script); Assert.True(result.IsSuccess); Assert.Equal("111", result.Data); }
public void Execute() { var proxy = new InfusionProxy(); proxy.Initialize(commandHandler, new NullSoundPlayer(), new LegacyApi.Injection.NullInjectionWindow()); var resolvedServerAddress = Dns.GetHostEntry(options.ServerAddress) .AddressList.First(a => a.AddressFamily == AddressFamily.InterNetwork); proxy.Start(new ProxyStartConfig() { ServerAddress = options.ServerAddress, ServerEndPoint = new IPEndPoint(resolvedServerAddress, options.Port), LocalProxyPort = (ushort)options.LocalPort, ProtocolVersion = options.ProtocolVersion, LoginEncryptionKey = LoginEncryptionKey.FromVersion(options.ProtocolVersion), Encryption = GetEncryptionSetup(options.Encryption), }); UO.CommandHandler.RegisterCommand(new Command("reload", () => Reload(), false, true, "Reloads an initial script file.")); csharpScriptEngine = new CSharpScriptEngine(console); scriptEngine = new ScriptEngine(csharpScriptEngine, new InjectionScriptEngine(UO.Injection, console)); console.Info($"\nConfigure your client to use 'localhost,{options.LocalPort}' as Ultima Online server address."); if (!string.IsNullOrEmpty(options.ScriptFileName)) { Load(options.ScriptFileName); } Console.ReadLine(); }
public void Library_SendMail_succeeds() { string script = @" string to = ""*****@*****.**""; string subject = ""Test from Rule""; string body = ""It worked!""; Library.SendMail(to, subject, body); "; var repository = Substitute.For <IWorkItemRepository>(); var workItem = Substitute.For <IWorkItem>(); workItem.Id.Returns(1); workItem.TypeName.Returns("Task"); repository.GetWorkItem(1).Returns(workItem); var logger = Substitute.For <ILogEvents>(); var library = Substitute.For <IScriptLibrary>(); var engine = new CSharpScriptEngine(logger, Debugger.IsAttached, library); engine.LoadAndRun("test", script, workItem, repository); string to = "*****@*****.**"; string subject = "Test from Rule"; string body = "It worked!"; library.Received().SendMail(to, subject, body); }
static void Main(string[] args) { var scriptEngine = new CSharpScriptEngine(); while (true) { Console.Write(">> "); var input = Console.ReadLine(); if (input == "exit") { break; } try { var result = scriptEngine.Execute(input); if (result != null) { Console.WriteLine(result); } } //CompilationErrorException catch (Exception ex) { Console.WriteLine(ex.Message); } } }
public void ShouldCompileWhenUsingClassesFromAPassedAssemblyInstance( [Frozen] Mock <IScriptHostFactory> scriptHostFactory, [Frozen] ScriptPackSession scriptPackSession) { // Arrange const string Code = "var x = new ScriptCs.Tests.TestMarkerClass();"; scriptHostFactory.Setup(f => f.CreateScriptHost(It.IsAny <IScriptPackManager>(), It.IsAny <string[]>())) .Returns <IScriptPackManager, string[]>((p, q) => new ScriptHost(p, new ScriptEnvironment(q))); var engine = new CSharpScriptEngine(scriptHostFactory.Object, new TestLogProvider()); var session = new SessionState <ScriptState> { Session = CSharpScript.Run("") }; scriptPackSession.State[CommonScriptEngine.SessionKey] = session; var refs = new AssemblyReferences(new[] { Assembly.GetExecutingAssembly() }, new[] { "System" }); // Act var result = engine.Execute(Code, new string[0], refs, Enumerable.Empty <string>(), scriptPackSession); // Assert result.CompileExceptionInfo.ShouldBeNull(); result.ExecuteExceptionInfo.ShouldBeNull(); }
public void ReferenceToInvalidType() { var badTypeBytes = TestResources.MetadataTests.Invalid.ClassLayout; var badTypeRef = MetadataReference.CreateFromImage(badTypeBytes.AsImmutableOrNull()); // TODO: enable this with our AssemblyLoader: ResolveEventHandler handler = (_, args) => { if (args.Name.StartsWith("b,", StringComparison.Ordinal)) { return(Assembly.Load(badTypeBytes)); } return(null); }; AppDomain.CurrentDomain.AssemblyResolve += handler; try { var engine = new CSharpScriptEngine(); var session = engine.CreateSession(); session.AddReference(badTypeRef); // we shouldn't throw while compiling: var submission = session.CompileSubmission <object>("new S1()"); // we should throw while executing: Assert.Throws <TypeLoadException>(() => submission.Execute()); } finally { AppDomain.CurrentDomain.AssemblyResolve -= handler; } }
public void ExecuteUntrastedCode() { IScriptEngine scriptEngineProvider = new CSharpScriptEngine(); DynamicScript script = new DynamicScript(); script.Language = DynamicScriptLanguage.CSharp; script.Script = @" using System; public class Test { public int GetC(int a) { int c = 0; for(; ; ) { c += 1; } return c; } } "; script.ClassFullName = "Test"; script.FunctionName = "GetC"; script.Parameters = new object[] { 1 }; script.IsExecutionInSandbox = true; //沙箱环境执行 script.ExecutionInSandboxMillisecondsTimeout = 100; //沙箱环境执行超时时间 var result = scriptEngineProvider.Execute <int>(script); Assert.False(result.IsSuccess); Assert.Equal("execution timed out!", result.Message); }
static void ExecuteCSharpRepl() { while (true) { var str = Console.ReadLine(); WriteLine(CSharpScriptEngine.Execute(str)); } }
public ShellConsoleTextWriterWrapper( CommandEvaluationContext commandEvaluationContext, TextWriter textWriter, CSharpScriptEngine cSharpScriptEngine = null ) : base(textWriter, cSharpScriptEngine) { CommandEvaluationContext = commandEvaluationContext; }
public void TestScriptArgs() { var script = Engine.AssetLoader.Get <CSharpScriptAsset>("Scripts/CustomMainArgsScript.cs"); const string objectPass = "******"; object result = CSharpScriptEngine.RunScript(script, objectPass).Result; Assert.True((int)result == objectPass.GetHashCode()); Engine.AssetLoader.Destroy("Scripts/CustomMainArgsScript.cs"); }
public Game(ItemManager itemManager) { _logger = LoggerProvider.GetLogger(); ItemManager = itemManager; ChatCommandManager = new ChatCommandManager(this); NetworkIdManager = new NetworkIdManager(); PlayerManager = new PlayerManager(this); ScriptEngine = new CSharpScriptEngine(); }
public void AssemblyResolution() { var engine = new CSharpScriptEngine(); var session = engine.CreateSession(); var instance = session.Execute("var x = new { a = 3 }; x"); var type = session.Execute("System.Type.GetType(x.GetType().AssemblyQualifiedName, true)"); Assert.Equal(instance.GetType(), type); }
public void CompilationChain_UsingRebinding_AddReference() { var engine = new CSharpScriptEngine(); var session = engine.CreateSession(); session.Execute(@"using System.Diagnostics;"); session.AddReference(typeof(Process).Assembly); session.Execute(@"Process.GetCurrentProcess()"); }
public Game() { _logger = LoggerProvider.GetLogger(); ItemManager = new ItemManager(); ChatCommandManager = new ChatCommandManager(this); NetworkIdManager = new NetworkIdManager(); PlayerManager = new PlayerManager(this); ScriptEngine = new CSharpScriptEngine(); RequestHandler = new NetworkHandler <ICoreRequest>(); ResponseHandler = new NetworkHandler <ICoreResponse>(); }
public void RepeatClassExecute() { IScriptEngine scriptEngineProvider = new CSharpScriptEngine(); DynamicScript script = new DynamicScript(); script.Language = DynamicScriptLanguage.CSharp; //先编译A执行A script.Script = @" using System; public class Test { public int GetA(int a) { return a; } } "; script.ClassFullName = "Test"; script.FunctionName = "GetA"; script.Parameters = new object[] { 111 }; var result1 = scriptEngineProvider.Execute <int>(script); //编译B执行B script.Script = @" using System; public class Test { public int GetB(int a) { return a; } } "; script.ClassFullName = "Test"; script.FunctionName = "GetB"; script.Parameters = new object[] { 99999999 }; var result2 = scriptEngineProvider.Execute <int>(script); //再执行A,这次是从B的脚本对应的Hash值去找Test类型,里面并没有A,所以报错没有找到方法A //也就是说,用B的脚本去调用A是错误的用法,即便类的名称是一样的,但其实不是一个类 script.ClassFullName = "Test"; script.FunctionName = "GetA"; script.Parameters = new object[] { 333 }; var result3 = scriptEngineProvider.Execute <int>(script); }
public void CompilationChain_UsingRebinding_Directive() { var engine = new CSharpScriptEngine(); var session = engine.CreateSession(); session.Execute(@"using System.Diagnostics;"); session.Execute(@" #r """ + typeof(Process).Assembly.Location + @""" Process.GetCurrentProcess()"); }
public void ReferenceArguments() { IScriptEngine scriptEngineProvider = new CSharpScriptEngine(); DynamicScript script = new DynamicScript(); script.Language = DynamicScriptLanguage.CSharp; script.Script = @" using System; using System.Collections.Generic; public class Test { public List<int> GetA(List<int> a) { a[0] = 3; return a; } } "; script.ClassFullName = "Test"; script.FunctionName = "GetA"; script.Parameters = new object[] { new List <int> { 1, 2 } }; var result = scriptEngineProvider.Execute <object>(script); DynamicScript script2 = new DynamicScript(); script2.Language = DynamicScriptLanguage.CSharp; script2.Script = @" using System; using System.Collections.Generic; public class Test { public List<int> GetA(List<int> a) { return a; } } "; script2.ClassFullName = "Test"; script2.FunctionName = "GetA"; script2.Parameters = script.Parameters; var result2 = scriptEngineProvider.Execute <List <int> >(script2); Assert.Equal(3, result2.Data[0]); Assert.Equal(3, (script.Parameters[0] as List <int>)[0]); }
public void Can_CSharp_use_Linq() { string script = @" int[] array = { 1, 3, 5, 7 }; return (int)array.Average(); "; var repository = Substitute.For<IWorkItemRepository>(); var workItem = Substitute.For<IWorkItem>(); repository.GetWorkItem(1).Returns(workItem); var logger = Substitute.For<ILogEvents>(); var engine = new CSharpScriptEngine(logger, Debugger.IsAttached); engine.LoadAndRun("test", script, workItem, repository); object expected = 4; logger.Received().ResultsFromScriptRun("test", expected); }
public void Can_run_a_CSharp_script_interacting_with_a_shorthand_object_model() { string script = @" self[""x""] = 33; return self[""z""]; "; var repository = Substitute.For<IWorkItemRepository>(); var workItem = Substitute.For<IWorkItem>(); workItem.Id.Returns(1); workItem["x"] = 11; workItem["z"].Returns(42); repository.GetWorkItem(1).Returns(workItem); var logger = Substitute.For<ILogEvents>(); var engine = new CSharpScriptEngine(logger, Debugger.IsAttached); engine.LoadAndRun("test", script, workItem, repository); Assert.AreEqual(33, workItem["x"]); object expected = 42; logger.Received().ResultsFromScriptRun("test", expected); }
public void ShouldCompileWhenUsingClassesFromAPassedAssemblyInstance( [Frozen] Mock<IScriptHostFactory> scriptHostFactory, [Frozen] ScriptPackSession scriptPackSession) { // Arrange const string Code = "var x = new ScriptCs.Tests.TestMarkerClass();"; scriptHostFactory.Setup(f => f.CreateScriptHost(It.IsAny<IScriptPackManager>(), It.IsAny<string[]>())) .Returns<IScriptPackManager, string[]>((p, q) => new ScriptHost(p, new ScriptEnvironment(q))); var engine = new CSharpScriptEngine(scriptHostFactory.Object, new TestLogProvider()); var session = new SessionState<ScriptState> { Session = CSharpScript.Run("") }; scriptPackSession.State[CommonScriptEngine.SessionKey] = session; var refs = new AssemblyReferences(new[] { Assembly.GetExecutingAssembly() }, new[] { "System" }); // Act var result = engine.Execute(Code, new string[0], refs, Enumerable.Empty<string>(), scriptPackSession); // Assert result.CompileExceptionInfo.ShouldBeNull(); result.ExecuteExceptionInfo.ShouldBeNull(); }
public void FluentNavigation_CSharp_script_succeedes() { string script = @" var searchResult = self .WhereTypeIs(""Task"") .AtMost(2) .FollowingLinks(""*""); return searchResult; "; IWorkItem startPoint; var repository = MakeRepository(out startPoint); var logger = Substitute.For<ILogEvents>(); repository.Logger = logger; var engine = new CSharpScriptEngine(repository, logger, false); engine.LoadAndRun("test", script, startPoint); var expected = new FluentQuery(startPoint); expected.WorkItemType = "Task"; expected.Levels = 2; expected.LinkType = "*"; logger.Received().ResultsFromScriptRun("test", expected); }
public void Can_run_a_CSharp_script_interacting_with_a_verbose_object_model() { string script = @" self.Fields[""x""].Value = 33; return self.Fields[""z""].Value; "; var repository = Substitute.For<IWorkItemRepository>(); var workItem = Substitute.For<IWorkItem>(); var xField = Substitute.For<IField>(); var zField = Substitute.For<IField>(); workItem.Id.Returns(1); xField.OriginalValue.Returns(11); workItem.Fields["x"] = xField; workItem.Fields["z"] = zField; zField.Value.Returns(42); repository.GetWorkItem(1).Returns(workItem); var logger = Substitute.For<ILogEvents>(); var engine = new CSharpScriptEngine(logger, Debugger.IsAttached); engine.LoadAndRun("test", script, workItem, repository); Assert.AreEqual(33, xField.Value); object expected = 42; logger.Received().ResultsFromScriptRun("test", expected); }
public void Can_run_a_CSharp_script_with_logging() { string script = @" logger.Log(""Test""); "; var repository = Substitute.For<IWorkItemRepository>(); var workItem = Substitute.For<IWorkItem>(); var logger = Substitute.For<ILogEvents>(); logger.ScriptLogger = Substitute.For<IRuleLogger>(); var engine = new CSharpScriptEngine(logger, Debugger.IsAttached); engine.LoadAndRun("test", script, workItem, repository); logger.ScriptLogger.Received().Log("Test"); }
public void Catch_CSharp_rule_compile_error() { string good_script = @" logger.Log(""Test""); "; string bad_script = @" loger.Log(""Test""); "; var logger = Substitute.For<ILogEvents>(); var engine = new CSharpScriptEngine(logger, Debugger.IsAttached); engine.Load("good", good_script); engine.Load("bad", bad_script); engine.LoadCompleted(); logger.Received().ScriptHasError("bad", 2, 1, "CS0103", "The name 'loger' does not exist in the current context"); }
public void Logger_overloads_work() { string script = @" logger.Log(""Hello, World from {1} #{0}!"", self.Id, self.TypeName); logger.Log(LogLevel.Warning, ""Unexpected work item state!""); "; var repository = Substitute.For<IWorkItemRepository>(); var workItem = Substitute.For<IWorkItem>(); workItem.Id.Returns(1); workItem.TypeName.Returns("Task"); repository.GetWorkItem(1).Returns(workItem); var logger = Substitute.For<ILogEvents>(); var engine = new CSharpScriptEngine(logger, Debugger.IsAttached); engine.LoadAndRun("test", script, workItem, repository); logger.Received().ScriptLogger.Log(LogLevel.Verbose, "test", "Hello, World from Task #1!"); logger.Received().ScriptLogger.Log(LogLevel.Warning, "test", "Unexpected work item state!"); }
public void TransitionStateCSharp_New_to_Done_succeeded_via_InProgress() { string script = @" self.TransitionToState(""Done"", ""script test""); "; var repository = new WorkItemRepositoryMock(); var logger = Substitute.For<ILogEvents>(); repository.Logger = logger; var workItem = new WorkItemMock(repository); var workItemType = new WorkItemTypeMock() { Name = "Task", DocumentContent = TestHelpers.LoadTextFromEmbeddedResource("task.xml") }; workItem.Id = 42; workItem.Type = workItemType; workItem.TypeName = workItemType.Name; ((FieldMock)workItem.Fields["State"]).OriginalValue = string.Empty; workItem.Fields["State"].Value = workItem.Fields["State"].OriginalValue; ((FieldMock)workItem.Fields["State"]).Status = Microsoft.TeamFoundation.WorkItemTracking.Client.FieldStatus.InvalidValueNotInOtherField; repository.SetWorkItems(new[] { workItem }); var engine = new CSharpScriptEngine(repository, logger, false); engine.LoadAndRun("test", script, workItem); Assert.AreEqual("Done", workItem.Fields["State"].Value); Assert.AreEqual(2, workItem.InternalSaveCount); }