public OutputChainBuffer(Sandbox sb, OutputChainBuffer prev, OutputChainBuffer targetOrigin) { _prevItem = prev; if (prev != null) { prev._nextItem = this; _caps = prev is OutputChainArticleBuffer && prev.Caps == Capitalization.First ? Capitalization.None : prev._caps; } _buffer = targetOrigin._buffer; sandbox = sb; }
public void RunTests(IEnumerable<TestCase> tests, IRunContext runContext, IFrameworkHandle frameworkHandle) { this.frameworkHandle = frameworkHandle; var testLogger = new TestLogger(frameworkHandle); testLogger.SendMainMessage("Execution started"); foreach (var group in tests.GroupBy(t => t.Source)) { testLogger.SendInformationalMessage(String.Format("Running selected: '{0}'", group.Key)); try { using (var sandbox = new Sandbox<Executor>(group.Key)) { var assemblyDirectory = new DirectoryInfo(Path.GetDirectoryName(group.Key)); Directory.SetCurrentDirectory(assemblyDirectory.FullName); sandbox.Content.Execute(this, group.Select(t => t.FullyQualifiedName).ToArray()); } } catch (Exception ex) { testLogger.SendErrorMessage(ex, String.Format("Exception found while executing tests in group '{0}'", group.Key)); // just go on with the next } } testLogger.SendMainMessage("Execution finished"); }
public override void Init(Sandbox.Common.ObjectBuilders.MyObjectBuilder_CubeBlock objectBuilder, Sandbox.Game.Entities.MyCubeGrid cubeGrid) { base.Init(objectBuilder, cubeGrid); m_oxygenFarmDefinition = BlockDefinition as MyOxygenFarmDefinition; IsWorkingChanged += OnIsWorkingChanged; NeedsUpdate = MyEntityUpdateEnum.EACH_10TH_FRAME | MyEntityUpdateEnum.EACH_100TH_FRAME; InitializeConveyorEndpoint(); PowerReceiver = new MyPowerReceiver( MyConsumerGroupEnum.Factory, false, m_oxygenFarmDefinition.OperationalPowerConsumption, ComputeRequiredPower); PowerReceiver.IsPoweredChanged += PowerReceiver_IsPoweredChanged; PowerReceiver.Update(); GameLogic = new MySolarGameLogicComponent(); m_solarComponent = GameLogic as MySolarGameLogicComponent; m_solarComponent.Initialize(m_oxygenFarmDefinition.PanelOrientation, m_oxygenFarmDefinition.IsTwoSided, m_oxygenFarmDefinition.PanelOffset, this); AddDebugRenderComponent(new Components.MyDebugRenderComponentSolarPanel(this)); }
public override IEnumerator<RantAction> Run(Sandbox sb) { if (sb.Objects[Name] == null) throw new RantRuntimeException(sb.Pattern, _name, $"The subroutine '{Name}' does not exist."); var sub = (RADefineSubroutine)sb.Objects[Name].Value; if (sub.Parameters.Keys.Count != Arguments.Count) throw new RantRuntimeException(sb.Pattern, _name, "Argument mismatch on subroutine call."); var action = sub.Body; var args = new Dictionary<string, RantAction>(); var parameters = sub.Parameters.Keys.ToArray(); for (var i = 0; i < Arguments.Count; i++) { if (sub.Parameters[parameters[i]] == SubroutineParameterType.Greedy) { sb.AddOutputWriter(); yield return Arguments[i]; var output = sb.Return(); args[parameters[i]] = new RAText(_name, output.Main); } else args[parameters[i]] = Arguments[i]; } sb.SubroutineArgs.Push(args); yield return action; sb.SubroutineArgs.Pop(); yield break; }
public OutputWriter(Sandbox sb) { sandbox = sb; mainChain = chains[MainChannelName] = new OutputChain(sb, MainChannelName); chainStack.Push(mainChain); activeChains.Add(mainChain); }
public IEnumerator<RichActionBase> Execute(Sandbox sb) { List<object> args = new List<object>(); for (var i = 0; i < _argCount; i++) args.Add(new RantObject(sb.ScriptObjectStack.Pop())); args.Add(That); args.Reverse(); IEnumerator<RantAction> iterator = null; while (true) { try { if(iterator == null) iterator = _function.Invoke(sb, args.ToArray()); if (!iterator.MoveNext()) break; } // attach token to it and throw it up catch (RantRuntimeException e) { e.SetToken(Range); throw e; } yield return iterator.Current as RichActionBase; } }
public void DiscoverTests(IEnumerable<string> sources, IDiscoveryContext discoveryContext, IMessageLogger logger, ITestCaseDiscoverySink discoverySink) { testLogger = new TestLogger(logger); testLogger.SendMainMessage("Discovery started"); foreach (var source in sources) { testLogger.SendDebugMessage(String.Format("Processing: '{0}'", source)); try { using (var sandbox = new Sandbox<Discoverer>(source)) { if (sandbox.Content != null) { sandbox.Content .DiscoverTests() .Select(name => name.ToTestCase(source)) .ForEach(discoverySink.SendTestCase); } } } catch (Exception ex) { testLogger.SendErrorMessage(ex, String.Format("Exception found while discovering tests in source '{0}'", source)); // just go on with the next } } testLogger.SendMainMessage("Discovery finished"); }
protected internal override TestResult RunImpl(ITestCommand rootTestCommand, Model.Tree.TestStep parentTestStep, TestExecutionOptions options, IProgressMonitor progressMonitor) { using (progressMonitor.BeginTask("Running tests.", rootTestCommand.TestCount)) { // Note: We do not check options.SkipTestExecution here because we want to build up // the tree of data-driven test steps. So we actually check it later on in the // PatternTestExecutor. This is different from framework adapters // at this time (because they do not generally support dynamically generated data-driven tests). Sandbox sandbox = new Sandbox(); EventHandler canceledHandler = delegate { sandbox.Abort(TestOutcome.Canceled, "The user canceled the test run."); }; try { progressMonitor.Canceled += canceledHandler; TestAssemblyExecutionParameters.Reset(); PatternTestExecutor executor = new PatternTestExecutor(options, progressMonitor, formatter, converter, environmentManager); // Inlined to minimize stack depth. var action = executor.CreateActionToRunTest(rootTestCommand, parentTestStep, sandbox, null); action.Run(); return action.Result; } finally { progressMonitor.Canceled -= canceledHandler; sandbox.Dispose(); } } }
public override IEnumerator<RantAction> Run(Sandbox sb) { if (Items == null || ItemsChanged) { List<RichActionBase> tempItems = new List<RichActionBase>(); for (var i = 0; i < _items.Count; i++) { var item = _items[i]; if (item is RichActionBase) { yield return item; var val = sb.ScriptObjectStack.Pop(); if (val is RichList && _concatSyntax) tempItems.AddRange((val as RichList).Items); else tempItems.Add(Util.ConvertToAction(item.Range, val)); } else tempItems.Add(item); } Items = tempItems; ItemsChanged = false; } yield break; }
public OutputChain(Sandbox sb, string name) { sandbox = sb; _first = new OutputChainBuffer(sb, null); _last = _first; Name = name; }
public override IEnumerator<RantAction> Run(Sandbox sb) { var iterator = _function.Invoke(sb, new object[] { }); while (iterator.MoveNext()) yield return iterator.Current; yield break; }
public override IEnumerator<RantAction> Run(Sandbox sb) { foreach (RichActionBase action in Group.Actions) yield return action; if (sb.ScriptObjectStack.Any()) { var obj = sb.ScriptObjectStack.Pop(); if (obj is RichList) { var list = (obj as RichList); // don't make a block from a list with zero items if (list.Items.Count == 0) yield break; List<RantAction> actions = new List<RantAction>(); foreach (RichActionBase action in list.Items) { yield return action; var item = sb.ScriptObjectStack.Pop(); if (item is RichPatternString) actions.Add((item as RichPatternString).Pattern.Action); else actions.Add(new RAText(action.Range, item.ToString())); } yield return new RABlock(list.Range, actions.ToArray()); } else if (obj is RichPatternString) yield return (obj as RichPatternString).Pattern.Action; else if (obj is bool) sb.Print((bool)obj ? "true" : "false"); else if(!(obj is RantObject && (obj as RantObject).Type == RantObjectType.Undefined)) sb.Print(obj); } yield break; }
public override IEnumerator<RantAction> Run(Sandbox sb) { yield return _expr; var expr = sb.ScriptObjectStack.Pop(); if (!(expr is REAList) && !(expr is REAObject)) throw new RantRuntimeException(sb.Pattern, Range, "Provided expression is not a list or object."); if (expr is REAList) { yield return expr as REAList; var list = sb.ScriptObjectStack.Pop() as REAList; var items = (list as REAList).Items; for (var i = 0; i < items.Count; i++) { sb.Objects.EnterScope(); sb.Objects[_indexName] = new ObjectModel.RantObject(i); yield return _body; sb.Objects.ExitScope(); } yield break; } else if (expr is REAObject) { var items = (expr as REAObject).Values.Keys.ToList(); foreach (string key in items) { sb.Objects.EnterScope(); sb.Objects[_indexName] = new ObjectModel.RantObject(key); yield return _body; sb.Objects.ExitScope(); } yield break; } }
public void RunTests(IEnumerable<string> sources, IRunContext runContext, IFrameworkHandle frameworkHandle) { this.frameworkHandle = frameworkHandle; var testLogger = new TestLogger(frameworkHandle); testLogger.SendMainMessage("Execution started"); foreach (var source in sources) { try { using (var sandbox = new Sandbox<Executor>(source)) { testLogger.SendInformationalMessage(String.Format("Running: '{0}'", source)); var assemblyDirectory = new DirectoryInfo(Path.GetDirectoryName(source)); Directory.SetCurrentDirectory(assemblyDirectory.FullName); sandbox.Content.Execute(this); } } catch (Exception ex) { testLogger.SendErrorMessage(ex, String.Format("Exception found while executing tests in source '{0}'", source)); // just go on with the next } } testLogger.SendMainMessage("Execution finished"); }
public static IEnumerable<TestCase> Discover(IEnumerable<string> sources, ITestCaseDiscoverySink discoverySink) { List<TestCase> result = new List<TestCase>(); // System.Diagnostics.Debugger.Launch(); var specList = new List<dynamic>(); foreach (var source in sources) { using (var sandbox = new Sandbox<Discover>(source)) { List<DefinitionSource> discoveredDefinitions = new List<DefinitionSource>(); try { discoveredDefinitions = sandbox.Content.DiscoverSpecsFromCurrentAssembly(); } catch (Exception a) { Console.WriteLine(a.Message); } discoveredDefinitions .Select(x => AddToSink(source, x, discoverySink)) .ToList() .ForEach(x => result.Add(x)); } } return result; }
public override IEnumerator<RantAction> Run(Sandbox sb) { var stackSize = sb.ScriptObjectStack.Count; yield return RightSide; if (stackSize >= sb.ScriptObjectStack.Count) throw new RantRuntimeException(sb.Pattern, Range, "Invalid right side of invert operator."); yield break; }
public override IEnumerator<RantAction> Run(Sandbox sb) { sb.Objects.EnterScope(); foreach (RantExpressionAction action in _actions) yield return action; sb.Objects.ExitScope(); yield break; }
public override IEnumerator<RantAction> Run(Sandbox sb) { if (LeftSide == null || RightSide == null) throw new RantRuntimeException(sb.Pattern, Origin, "Missing part of infix operation."); yield return RightSide; yield return LeftSide; yield break; }
public override IEnumerator<RantAction> Run(Sandbox sb) { if (!Actions.Any()) yield break; foreach (RichActionBase action in Actions) yield return action; yield break; }
protected override void Init(Sandbox.Common.ObjectBuilders.Definitions.MyObjectBuilder_DefinitionBase builder) { base.Init(builder); var ob = builder as MyObjectBuilder_CurveDefinition; Curve = new Curve(); foreach (var point in ob.Points) Curve.Keys.Add(new CurveKey(point.Time, point.Value)); }
public override object GetValue(Sandbox sb) { var rightVal = sb.ScriptObjectStack.Pop(); if (!(rightVal is bool)) throw new RantRuntimeException(sb.Pattern, Range, "Right side of invert operator must be a boolean value."); bool rightBool = (bool)rightVal; return !rightBool; }
public override object GetValue(Sandbox sb) { var leftVal = sb.ScriptObjectStack.Pop(); var rightVal = sb.ScriptObjectStack.Pop(); if (leftVal is double && rightVal is double) return (_orEqual ? (double)leftVal >= (double)rightVal : (double)leftVal > (double)rightVal); throw new RantRuntimeException(sb.Pattern, Range, "Invalid " + (leftVal is double ? "right hand" : "left hand") + " side of comparison operator."); }
public override object GetValue(Sandbox sb) { if (RichardFunctions.HasObject(Name)) return RichardFunctions.GetObject(Name); if (sb.Objects[Name] == null) return new RantObject(RantObjectType.Undefined); var obj = sb.Objects[Name]; if (obj.Type == RantObjectType.No) return obj; return obj.Value; }
public void AddChildWithMatrix(Sandbox.ModAPI.IMyEntity child, ref Matrix childLocalMatrix, bool insertIntoSceneIfNeeded = true) { child.Hierarchy.Parent = this; Children.Add(child.Hierarchy); child.WorldMatrix = (MatrixD)childLocalMatrix * Entity.PositionComp.WorldMatrix; if (Entity.InScene && !child.InScene && insertIntoSceneIfNeeded) child.OnAddedToScene(this); }
public override object GetValue(Sandbox sb) { var leftVal = sb.ScriptObjectStack.Pop(); var rightVal = sb.ScriptObjectStack.Pop(); if (!(leftVal is bool)) throw new RantRuntimeException(sb.Pattern, Range, "Invalid left hand side of boolean OR operator."); if (!(rightVal is bool)) throw new RantRuntimeException(sb.Pattern, Range, "Invalid right hand side of boolean OR operator."); return (bool)leftVal || (bool)rightVal; }
private bool TransferItemsTo(Sandbox.ModAPI.Interfaces.IMyInventory dst, int sourceItemIndex, int? targetItemIndex, VRage.MyFixedPoint? amount,bool useConveyor) { MyInventory dstInventory = dst as MyInventory; if (dstInventory != null) { if (sourceItemIndex < 0 || sourceItemIndex >= this.m_items.Count || (useConveyor == true && IsConnected(dstInventory) == false)) { return false; } Transfer(this as MyInventory, dstInventory, this.GetItems()[sourceItemIndex].ItemId, targetItemIndex.HasValue ? targetItemIndex.Value : -1, amount); return true; } return false; }
public void RunTests(IEnumerable<TestCase> tests, IRunContext runContext, IFrameworkHandle frameworkHandle) { this.frameworkHandle = frameworkHandle; foreach (var group in tests.GroupBy(t => t.Source)) { frameworkHandle.SendMessage(TestMessageLevel.Informational, "Running selected: " + group.Key); using (var sandbox = new Sandbox<Executor>(group.Key)) { sandbox.Content.Execute(this, group.Select(t => t.FullyQualifiedName).ToArray()); } } }
public override IEnumerator<RantAction> Run(Sandbox sb) { object func = _function; if ( func is RichVariable || func is RichFunctionCall || func is RichGroup || func is RichObjectProperty) { var count = sb.ScriptObjectStack.Count; yield return (func as RichActionBase); if (count >= sb.ScriptObjectStack.Count) throw new RantRuntimeException(sb.Pattern, Range, "Invalid function call target."); func = sb.ScriptObjectStack.Pop(); } if (func is RichFunction) { var expectedCount = (func as RichFunction).ArgCount; if (expectedCount != _argValues.Length) throw new RantRuntimeException(sb.Pattern, Range, $"Function expected {expectedCount} arguments, got {_argValues.Length}."); foreach (RichActionBase argAction in _argValues) yield return argAction; var iterator = (func as RichFunction).Execute(sb); while (iterator.MoveNext()) yield return iterator.Current; yield break; } else if (func is RichPatternString) { if (_argValues.Length > 0) throw new RantRuntimeException(sb.Pattern, base.Range, "Unexpected arguments for pattern string."); yield return (func as RichPatternString).Execute(sb); yield break; } else if (func is RichNativeFunction) { var expectedCount = (func as RichNativeFunction).ArgCount; if (expectedCount != _argValues.Length) throw new RantRuntimeException(sb.Pattern, Range, $"Native function expected {expectedCount} arguments, got {_argValues.Length}."); foreach (RichActionBase argAction in _argValues) yield return argAction; // we have to set this for reasons (func as RichNativeFunction).Range = this.Range; var iterator = (func as RichNativeFunction).Execute(sb); while (iterator.MoveNext()) yield return iterator.Current; yield break; } throw new RantRuntimeException(sb.Pattern, base.Range, "Cannot execute " + Util.ScriptingObjectType(func) + " as function."); }
public override IEnumerator<RantAction> Run(Sandbox sb) { yield return _expression; var result = sb.ScriptObjectStack.Pop(); if (!(result is bool)) throw new RantRuntimeException(sb.Pattern, Range, "Expected boolean value in if statement."); sb.Objects.EnterScope(); if ((bool)result) yield return _body; else if (_elseBody != null) yield return _elseBody; sb.Objects.ExitScope(); yield break; }
public override object GetValue(Sandbox sb) { if (LeftSide == null || RightSide == null) throw new RantRuntimeException(sb.Pattern, Origin, "Both sides of infix operation must be defined."); var leftValue = sb.ScriptObjectStack.Pop(); var rightValue = sb.ScriptObjectStack.Pop(); if (!(leftValue is double)) throw new RantRuntimeException(sb.Pattern, Origin, "Left side of infix operation must be a number."); if (!(rightValue is double)) throw new RantRuntimeException(sb.Pattern, Origin, "Right side of infix operation must be a number."); if (this is RichDivisionOperator && (double)rightValue == 0) throw new RantRuntimeException(sb.Pattern, Origin, "Cannot divide by zero."); return Operation((double)leftValue, (double)rightValue); }
private Type[] GetKnownTypes() { if (CompiledAssembly == null) { throw new Exception("Assembly is not compiled yet"); } var assemblies = _cSharpProject.MetadataReferences.Select(i => { if (i is PortableExecutableReference g) { return(Sandbox.LoadByFullFilename(g.FilePath).WrappedAssembly); } throw new NotSupportedException(i.GetType().FullName); }).ToList(); assemblies.Add(CompiledAssembly); return(CompileState.GetAllTypes(assemblies)); }
private void LogData_NewEntry(object sender, DataLogOutput.LogEntryEventArgs e) { if (this.InvokeRequired) { return; } bool pause = e.Entry.Type == LogMessageType.Error && this.buttonPauseOnError.Checked && Sandbox.State == SandboxState.Playing && !Sandbox.IsChangingState; if (pause) { System.Media.SystemSounds.Hand.Play(); Sandbox.Pause(); } }
public async Task CheckProcessTreeTimoutOnReportQueueStarvationAndStuckRootProcessAsync() { var processInfo = CreateProcessInfoWithSandboxConnection(Operation.Block()); processInfo.ReportQueueProcessTimeoutForTests = TimeSpan.FromMilliseconds(10); // Set the last enqueue time to now s_connection.MinReportQueueEnqueueTime = Sandbox.GetMachAbsoluteTime(); using (var process = CreateAndStartSandboxedProcess(processInfo, measureTime: true)) { // Post nothing to the report queue, and the process tree must be timed out after ReportQueueProcessTimeout // has been reached, including the stuck root process var result = await process.GetResultAsync(); XAssert.IsTrue(result.Killed, "Expected process to have been killed"); XAssert.IsFalse(result.TimedOut, "Didn't expect process to have timed out"); } }
public void ShouldExecuteHookAndReportFailureOnException(string hookType) { var expression = Hooks[hookType]; _mockHookRegistry.Setup(registry => registry.MethodFor(MethodName)) .Returns(mockHookMethodInfo.Object); _mockHookRegistry.Setup(expression).Returns(_hookMethods).Verifiable(); reflectionWrapper.Setup(x => x.Invoke(mockHookMethodInfo.Object, mockInstance.Object, new object[] { })) .Throws(new Exception("foo")) .Verifiable(); var sandbox = new Sandbox(_mockAssemblyLoader.Object, _mockHookRegistry.Object, activatorWrapper.Object, reflectionWrapper.Object); var executionResult = sandbox.ExecuteHooks(hookType, _mockStrategy.Object, _applicableTags, new ExecutionContext()); Assert.False(executionResult.Success); Assert.AreEqual("foo", executionResult.ExceptionMessage); }
AvailableDatasets MapToAvailable(Sandbox sandbox) { var availableDatasets = sandbox.Study .StudyDatasets .Select(sd => new AvailableDatasetItem() { DatasetId = sd.DatasetId, Name = sd.Dataset.Name, Classification = sd.Dataset.Classification, AddedToSandbox = sd.Dataset.SandboxDatasets.Where(sd => sd.SandboxId == sandbox.Id).Any() }); var result = new AvailableDatasets(availableDatasets); DatasetClassificationUtils.SetRestrictionProperties(result); return(result); }
public override object GetValue(Sandbox sb) { if (RichardFunctions.HasObject(Name)) { return(RichardFunctions.GetObject(Name)); } if (sb.Objects[Name] == null) { return(new RantObject(RantObjectType.Undefined)); } var obj = sb.Objects[Name]; if (obj.Type == RantObjectType.No) { return(obj); } return(obj.Value); }
public OutputChainBuffer(Sandbox sb, OutputChainBuffer prev) { _prevItem = prev; if (prev != null) { prev._nextItem = this; _caps = prev is OutputChainArticleBuffer && prev.Caps == Capitalization.First ? Capitalization.None : prev._caps; _numberFormatter.BinaryFormat = prev.NumberFormatter.BinaryFormat; _numberFormatter.BinaryFormatDigits = prev.NumberFormatter.BinaryFormatDigits; _numberFormatter.Endianness = prev.NumberFormatter.Endianness; _numberFormatter.NumberFormat = prev.NumberFormatter.NumberFormat; } _isTarget = true; _buffer = new StringBuilder(InitialCapacity); sandbox = sb; }
public void ShouldLoadClassInstanceManager() { var mockAssemblyLoader = new Mock <IAssemblyLoader>(); var mockInstanceManagerType = new Mock <Type>(); mockAssemblyLoader.Setup(loader => loader.ClassInstanceManagerType) .Returns(mockInstanceManagerType.Object); var activatorWrapper = new Mock <IActivatorWrapper>(); var mockInstanceManager = new Mock <object>(); activatorWrapper.Setup(x => x.CreateInstance(mockInstanceManagerType.Object)) .Returns(mockInstanceManager.Object) .Verifiable(); var mockTypeWrapper = new Mock <IReflectionWrapper>(); var sandbox = new Sandbox(mockAssemblyLoader.Object, null, activatorWrapper.Object, mockTypeWrapper.Object); activatorWrapper.VerifyAll(); }
static void AddDatasets(bool addDatasets, Study study, Sandbox sandbox) { if (addDatasets) { if (study.StudyDatasets != null) { sandbox.SandboxDatasets = new List <SandboxDataset>(); foreach (var curDs in study.StudyDatasets) { sandbox.SandboxDatasets.Add(new SandboxDataset() { DatasetId = curDs.DatasetId, Sandbox = sandbox, Added = DateTime.UtcNow, AddedBy = "seed" }); } } } }
public async Task SpringCloudConfigServer_WithHealthEnabled_ReturnsHealth() { // These settings match the default java config server var appsettings = @" { ""spring"": { ""application"": { ""name"": ""foo"" }, ""cloud"": { ""config"": { ""uri"": ""http://localhost:8888"", ""env"": ""development"", ""health"": { ""enabled"": true }, ""failfast"": ""true"" } } } }"; using var sandbox = new Sandbox(); var path = sandbox.CreateFile("appsettings.json", appsettings); var directory = Path.GetDirectoryName(path); var fileName = Path.GetFileName(path); var builder = new WebHostBuilder() .UseStartup <TestServerStartup>() .ConfigureAppConfiguration((context, config) => { config.SetBasePath(directory) .AddJsonFile(fileName) .AddConfigServer(context.HostingEnvironment); }); // Act and Assert (TestServer expects Spring Cloud Config server to be running) using var server = new TestServer(builder); using var client = server.CreateClient(); var result = await client.GetStringAsync("http://localhost/Home/Health"); // after switching to newer config server image, the health response has changed to // https://github.com/spring-cloud-samples/config-repo/Config resource 'file [/tmp/config-repo-4389533880216684481/application.yml' via location '' (document #0)" Assert.StartsWith("UP,https://github.com/spring-cloud-samples/config-repo/foo-development.properties,https://github.com/spring-cloud-samples/config-repo/foo.properties,https://github.com/spring-cloud-samples/config-repo/Config", result); }
public static string LiteralValue(this Sandbox sandbox) { switch (sandbox) { case Sandbox.AllowForms: return("allow-forms"); case Sandbox.AllowPointerLock: return("allow-pointer-lock"); case Sandbox.AllowPopups: return("allow-popups"); case Sandbox.AllowSameOrigin: return("allow-same-origin"); case Sandbox.AllowScripts: return("allow-scripts"); case Sandbox.AllowTopNavigation: return("allow-top-navigation"); default: throw new ArgumentException(); } }
public void AddConfigServer_IniAppSettingsConfiguresClient() { var appsettings = @" [spring:cloud:config] uri=https://foo.com:9999 enabled=false failFast=false label=myLabel name=myName username=myUsername password=myPassword "; using var sandbox = new Sandbox(); var path = sandbox.CreateFile("appsettings.json", appsettings); var directory = Path.GetDirectoryName(path); var fileName = Path.GetFileName(path); var configurationBuilder = new ConfigurationBuilder(); configurationBuilder.SetBasePath(directory); var csettings = new ConfigServerClientSettings(); configurationBuilder.AddIniFile(fileName); configurationBuilder.AddConfigServer(csettings); var config = configurationBuilder.Build(); var configServerProvider = config.Providers.OfType <ConfigServerConfigurationProvider>().SingleOrDefault(); Assert.NotNull(configServerProvider); var settings = configServerProvider.Settings; Assert.False(settings.Enabled); Assert.False(settings.FailFast); Assert.Equal("https://foo.com:9999", settings.Uri); Assert.Equal(ConfigServerClientSettings.DEFAULT_ENVIRONMENT, settings.Environment); Assert.Equal("myName", settings.Name); Assert.Equal("myLabel", settings.Label); Assert.Equal("myUsername", settings.Username); Assert.Equal("myPassword", settings.Password); }
public async Task CheckProcessTreeTimoutOnReportQueueStarvationAndStuckRootProcessAsync() { var processInfo = CreateProcessInfoWithSandboxConnection(Operation.Block()); // Set the last enqueue time to now s_connection.MinReportQueueEnqueueTime = Sandbox.GetMachAbsoluteTime(); var process = CreateAndStartSandboxedProcess(processInfo, measureTime: true); var taskCancelationSource = new CancellationTokenSource(); // Post nothing to the report queue, and the process tree must be timed out after ReportQueueProcessTimeout // has been reached, including the stuck root process ContinouslyPostAccessReports(process, taskCancelationSource.Token); var result = await process.GetResultAsync(); taskCancelationSource.Cancel(); XAssert.IsTrue(result.Killed, "Expected process to have been killed"); XAssert.IsFalse(result.TimedOut, "Didn't expect process to have timed out"); }
public void Create_multiple_process_in_limit_should_be_ok(int limitCount, int createCount, bool result) { // Arrange using (var compiler = new CSharpCompiler()) { var asm = compiler.Compile(Code); var info = new SandboxRunInfo { LimitProcessCount = limitCount, MemoryLimitMb = 40.0f, Path = asm.PathToAssembly, TimeLimitMs = 1000, }; var ior = Sandbox.BeginRun(info); using (var writer = new StreamWriter(ior.InputWriteStream)) { writer.Write(createCount); } var res = Sandbox.EndRun(ior.InstanceHandle); res.Succeed.Should().BeTrue(); if (result) { res.ExitCode.Should().Be(0); } else { res.ExitCode.Should().NotBe(0); } res.TimeMs.Should().BeLessThan(info.TimeLimitMs); res.MemoryMb.Should().BeLessThan(info.MemoryLimitMb); Console.WriteLine("Time: {0}ms", res.TimeMs); Console.WriteLine("Memory: {0}MB", res.MemoryMb); Console.WriteLine(info.Path); Thread.Sleep(10); } }
public void SuccessIsFalseOnSerializableExceptionThrown() { const string expectedMessage = "I am a custom serializable exception"; var reflectionWrapper = new ReflectionWrapper(); var assemblyLoader = new AssemblyLoader(new AssemblyWrapper(), new AssemblyLocater(new DirectoryWrapper(), new FileWrapper()).GetAllAssemblies(), reflectionWrapper); var sandbox = new Sandbox(assemblyLoader, new HookRegistry(assemblyLoader), new ActivatorWrapper(), reflectionWrapper); var stepMethods = sandbox.GetStepMethods(); var gaugeMethod = stepMethods.First(info => string.CompareOrdinal(info.Name, "IntegrationTestSample.StepImplementation.ThrowSerializableException") == 0); var executionResult = sandbox.ExecuteMethod(gaugeMethod); Assert.False(executionResult.Success); Assert.AreEqual(expectedMessage, executionResult.ExceptionMessage); StringAssert.Contains("IntegrationTestSample.StepImplementation.ThrowSerializableException", executionResult.StackTrace); }
static CloudResource CreateFailedVmResource(Sandbox sandbox, CloudResource sandboxResourceGroup, string studyName, string nameSuffix, string configString = null, string statusOfFailedResource = CloudResourceOperationState.FAILED, int tryCount = CloudResourceConstants.RESOURCE_MAX_TRY_COUNT, int maxTryCount = CloudResourceConstants.RESOURCE_MAX_TRY_COUNT, bool deleted = false, bool deleteSucceeded = false) { var vmResourceName = AzureResourceNameUtil.VirtualMachine(studyName, sandbox.Name, nameSuffix); var vmResource = CloudResourceFactory.CreateFailing(sandboxResourceGroup.Region, AzureResourceType.VirtualMachine, sandboxResourceGroup.ResourceName, vmResourceName, parentResource: sandboxResourceGroup, statusOfFailedResource: statusOfFailedResource, tryCount: tryCount, maxTryCount: maxTryCount, deleted: deleted, deleteSucceeded: deleteSucceeded); vmResource.SandboxId = sandbox.Id; vmResource.ConfigString = configString; return(vmResource); }
private void ExecutePendingActions() { var sandboxLoader = new SandboxLoader(_filesystem); while (!_isDisposed) { PendingAction action; while (_pendingActions.TryDequeue(out action)) { Execute(sandboxLoader, action); } // TODO: We should probably add a delay _currentSandbox = sandboxLoader.CreateSandbox(); Thread.Sleep(TimeSpan.FromMilliseconds(100)); } }
private void Update(Sandbox sandbox, FileInfo fileInfo) { using (ExcelPackage package = new ExcelPackage(fileInfo)) { ExcelWorkbook book = package.Workbook; ExcelWorksheet sheet = book.Worksheets[sheetName]; int rowNum = GetRowNumberFromSandBox(sandbox, sheet); sheet.Cells[rowNum, 1].Value = sandbox.SandboxNumber; sheet.Cells[rowNum, 2].Value = sandbox.Developer; sheet.Cells[rowNum, 3].Value = sandbox.DateLastDeployed; sheet.Cells[rowNum, 4].Value = sandbox.Status; sheet.Cells[rowNum, 5].Value = sandbox.UserStory; sheet.Cells[rowNum, 6].Value = sandbox.Deployable; Save(package); } }
public void CallingNextPhase_WithSeveralPhases_LastPhaseBegingDataAvailable_WillThrow() { var sandboxWithoutPhase = new Sandbox() { PhaseHistory = new List <SandboxPhaseHistory>() { new SandboxPhaseHistory() { Counter = 0, Phase = SandboxPhase.Open }, new SandboxPhaseHistory() { Counter = 1, Phase = SandboxPhase.DataAvailable } } }; Assert.Throws <Exception>(() => SandboxPhaseUtil.GetNextPhase(sandboxWithoutPhase)); }
public AssemblyUsage(string fullname) { Evidence e = new Evidence(); var ads = new AppDomainSetup { ApplicationBase = Path.GetDirectoryName(fullname) }; this.Sandbox = AppDomain.CreateDomain("test", e, ads, new PermissionSet(PermissionState.Unrestricted)); new Mapper(Sandbox); try { var assembly = Sandbox.Load(Path.GetFileNameWithoutExtension(fullname)); this.Assembly = assembly; } catch (Exception ex) { this.Assembly = Assembly.Load(File.ReadAllBytes(fullname)); } }
public void ShouldGetAllStepTexts() { var reflectionWrapper = new ReflectionWrapper(); var assemblyLoader = new AssemblyLoader(new AssemblyWrapper(), new AssemblyLocater(new DirectoryWrapper(), new FileWrapper()).GetAllAssemblies(), reflectionWrapper); var sandbox = new Sandbox(assemblyLoader, new HookRegistry(assemblyLoader), new ActivatorWrapper(), reflectionWrapper); var stepTexts = sandbox.GetAllStepTexts().ToList(); new List <string> { "Say <what> to <who>", "A context step which gets executed before every scenario", "Step that takes a table <table>", "Refactoring Say <what> to <who>", "Refactoring 1 Say <what> to <who>", "Refactoring A context step which gets executed before every scenario", "Refactoring Step that takes a table <table>" }.ForEach(s => Assert.Contains(s, stepTexts)); }
public override IEnumerator <RST> Run(Sandbox sb) { if (sb.Objects.ContainsKey(Name) && CheckIfSubroutineList(sb.Objects[Name])) { var subroutines = sb.Objects[Name].Value as List <RantObject>; if (subroutines.Any(s => (s.Value as RstDefineSubroutine).Parameters.Count == Parameters.Count)) { subroutines.RemoveAll(s => (s.Value as RstDefineSubroutine).Parameters.Count == Parameters.Count); } subroutines.Add(new RantObject(this)); } else { var list = new List <RantObject>(); list.Add(new RantObject(this)); sb.Objects[Name] = new RantObject(list); } yield break; }
public MainForm() { InitializeComponent(); //создаем песочницу sb = new Sandbox(); //создаем инструмент рсования tools = new Tools() { Sandbox = sb }; cbTool.SelectedIndex = 0; pnSandbox.Sandbox = sb; //запускаем моделирование физики в отдельном потоке ThreadPool.QueueUserWorkItem((_) => { var sw = new Stopwatch(); //цикл моделирования физики const float dt = 0.25f; while (true) { sw.Restart(); sb.Update((float)dt); physCounter++; var el = (int)sw.ElapsedMilliseconds; if (el < 20) { Thread.Sleep(20 - el);//ограничиваем FPS } } }); //запускаем таймер обновления интерфейса new System.Windows.Forms.Timer { Enabled = true, Interval = 15 }.Tick += delegate { UpdateCreator(); pnSandbox.Invalidate(); }; //запускаем таймер FPS new System.Windows.Forms.Timer { Enabled = true, Interval = 1000 }.Tick += CalcFPS; }
bool AllSandboxResourcesOkay(Sandbox sandbox) { if (sandbox.Resources == null) { throw new Exception("Missing include for Sandbox.Resources"); } foreach (var currentSandboxResource in CloudResourceUtil.GetSandboxControlledResources(sandbox.Resources)) { //If create operation failed if (!CloudResourceOperationUtil.HasSuccessfulCreateOperation(currentSandboxResource)) { return(false); } } return(true); }
public void Create_calc_should_return_success() { // arrange var calc = new JudgeInfo { Path = "calc.exe", MemoryLimitMb = 10.0f, TimeLimitMs = 100, Input = null }; // act var result = Sandbox.Judge(calc); // assert result.Succeed.Should().BeTrue(); result.ErrorCode.Should().Be(0); result.MemoryMb.Should().BeGreaterThan(0); }
public void should_broadcast_occupy_message_to_peers() { var evt = new ManualResetEvent(false); //var synService = Substitute.For<IMigrationNumberSync>(); //var publisher = Substitute.For<IEventPublisher>(); var synService = Substitute.For <IMigrationNumberSync>(); synService.WhenForAnyArgs(x => x.Occupy(new Migration())).Do(c => evt.Set()); //new MigrationNumberSyncService(publisher); var localPeer = new MigrationNumberSyncPeer(synService); localPeer.Start(521); try { // act Sandbox.Execute(() => { var remotePeer = new MigrationNumberSyncPeer(new MigrationNumberSyncService(new EventPublisher(), new CallbackChannelProvider())); remotePeer.Start(125); try { remotePeer.Channel.Occupy(new Migration { Number = "1", ProjectId = "2" }); } finally { remotePeer.Stop(); } }); // assert evt.WaitOne(400000, false); //publisher.Received().Publish(Arg.Is<OccupyEvent>(e => e.Number == "1" && e.ProjectId == "1")); synService.ReceivedWithAnyArgs().Occupy(Arg.Is <Migration>(m => m.Number == "1" && m.ProjectId == "2")); } finally { localPeer.Stop(); } }
public void ShouldReorderParameters() { const string newStepValue = "Refactoring Say <who> to <what>"; var reflectionWrapper = new ReflectionWrapper(); var activatorWrapper = new ActivatorWrapper(); var assemblyLoader = new AssemblyLoader(new AssemblyWrapper(), new AssemblyLocater(new DirectoryWrapper(), new FileWrapper()).GetAllAssemblies(), reflectionWrapper); var sandbox = new Sandbox(assemblyLoader, new HookRegistry(assemblyLoader), activatorWrapper, reflectionWrapper); var gaugeMethod = sandbox.GetStepMethods().First(info => info.Name == "IntegrationTestSample.RefactoringSample.RefactoringSaySomething-StringwhatStringwho"); var parameterPositions = new[] { new Tuple <int, int>(0, 1), new Tuple <int, int>(1, 0) }; sandbox.Refactor(gaugeMethod, parameterPositions, new List <string> { "who", "what" }, newStepValue); AssertStepAttributeWithTextExists(gaugeMethod.Name, newStepValue); AssertParametersExist(gaugeMethod.Name, new[] { "who", "what" }); }
public void ShouldAddParametersWithReservedKeywordName() { const string newStepValue = "Refactoring this is a test step <class>"; var reflectionWrapper = new ReflectionWrapper(); var activatorWrapper = new ActivatorWrapper(); var assemblyLoader = new AssemblyLoader(new AssemblyWrapper(), new AssemblyLocater(new DirectoryWrapper(), new FileWrapper()).GetAllAssemblies(), reflectionWrapper); var sandbox = new Sandbox(assemblyLoader, new HookRegistry(assemblyLoader), activatorWrapper, reflectionWrapper); var gaugeMethod = sandbox.GetStepMethods().First(info => info.Name == "IntegrationTestSample.RefactoringSample.RefactoringSampleTest"); var parameterPositions = new[] { new Tuple <int, int>(-1, 0) }; sandbox.Refactor(gaugeMethod, parameterPositions, new List <string> { "class" }, newStepValue); AssertStepAttributeWithTextExists(gaugeMethod.Name, newStepValue); AssertParametersExist(gaugeMethod.Name, new[] { "@class" }); }
static void Main(string[] args) { var uri = new Uri("http://localhost:3579"); using (var host = new NancyHost(uri)) { host.Start(); var guid = new Guid("e28b7426-c328-49fc-b3c2-e9f225b534e9"); var exam = new Exam("Title", guid, new List <BaseQuestion>()); Sandbox.AddExamToSandbox(exam); Console.WriteLine("Your application is running on " + uri); Console.WriteLine("Press any [Enter] to close the host."); Console.ReadLine(); } }
public async Task ShouldBuildCorrectMainScriptContentWithSingleScript() { IList <string> actualScripts = new List <string>(); IOptions options = new Options(); ISandboxConfigurationBuilder configurationBuilder = new SandboxConfigurationBuilder(new Options()); Action <string> createDirectory = path => { }; Action <string> deleteFiles = path => { }; Action <string> deleteDirectories = path => { }; Func <string, Task> startProcess = path => Task.CompletedTask; Func <string, byte[], CancellationToken, Task> writeAllBytes = (path, content, token) => Task.CompletedTask; Func <string, string, CancellationToken, Task> copyFiles = (source, destination, token) => Task.CompletedTask; Func <IList <string>, IPowershellTranslator, string, IOptions, Task <LiteralScript> > literalScriptFactory = async(scripts, translator, name, options) => { actualScripts = scripts; var literalScript = new LiteralScript(scripts, translator, name, writeAllBytes); await literalScript.Process(options); return(literalScript); }; var sandbox = new Sandbox(options, configurationBuilder, createDirectory, deleteFiles, deleteDirectories, startProcess, literalScriptFactory); await sandbox.Run( // Raw script that will be executed new LiteralScript(new List <string>() { @"Start-Process 'C:\windows\system32\notepad.exe'" }, new PowershellTranslator(null, () => 1000), "mockScriptName1.ps1", writeAllBytes)); IList <string> expected = new List <string>() { @"powershell.exe -ExecutionPolicy Bypass -File C:\Users\WDAGUtilityAccount\Desktop\Sandbox\mockScriptName1.ps1 3>&1 2>&1 > ""C:\Users\WDAGUtilityAccount\Desktop\Log_1000.txt""", }; IList <string> actual = actualScripts; Assert.Equal(expected, actual); }