public override void SetUp() { base.SetUp(); _executionState = new RedirectingToSubFunctionState( ExecutionStateContextMock, new RedirectingToSubFunctionStateParameters(SubFunction, PostBackCollection, "~/destination.wxe")); }
// Passes initial value overrides (presumably from ConfigurationSettings) public ConfigurationSettings( IExecutionState executionState, IConfiguration configuration, IEnumerable <KeyValuePair <string, object> > settings) : base(configuration) { _executionState = executionState ?? throw new ArgumentNullException(nameof(executionState)); _settings = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase); if (settings != null) { foreach (KeyValuePair <string, object> setting in settings) { this[setting.Key] = setting.Value; } } // Iterate over configuration and convert them, but only if we don't already have a setting for that key foreach (KeyValuePair <string, string> item in configuration.AsEnumerable()) { if (!_settings.ContainsKey(item.Key) && ScriptMetadataValue.TryGetScriptMetadataValue(item.Key, item.Value, executionState, out ScriptMetadataValue metadataValue)) { _settings[item.Key] = metadataValue; } } }
public static EmbedBuilder ToEmbed(this IExecutionState state, Action <EmbedBuilder>?pre = null) { var embed = new EmbedBuilder { Title = "Execution Finished", Color = Color.Purple, Footer = new EmbedFooterBuilder().WithText("A Cylon Project") }; embed.Description += $"{state.TotalLinesExecuted} lines executed. Next line: {state.ProgramCounter}"; pre?.Invoke(embed); var locals = state.Where(a => !a.Key.IsExternal).ToArray(); if (locals.Length > 0) { embed.AddField("Locals", string.Join("\n", locals.OrderBy(a => a.Key.Name).Select(a => $"`{a.Key}={a.Value.ToHumanString()}`"))); } var globals = state.Where(a => a.Key.IsExternal).ToArray(); if (globals.Length > 0) { embed.AddField("Globals", string.Join("\n", globals.OrderBy(a => a.Key.Name).Select(a => $"`{a.Key}={a.Value.ToHumanString()}`"))); } return(embed); }
public void ExecuteSubFunction_UsesEventTarget() { IExecutionState executionState = CreateExecutionStateForSupressRepost(true); using (MockRepository.Ordered()) { using (MockRepository.Unordered()) { _pageMock.Expect(mock => mock.GetPostBackCollection()).Return(PostBackCollection); _pageMock.Expect(mock => mock.SaveAllState()); } ExecutionStateContextMock.Expect(mock => mock.SetExecutionState(Arg <ExecutingSubFunctionWithoutPermaUrlState> .Is.NotNull)) .WhenCalled( invocation => { var nextState = CheckExecutionState((ExecutingSubFunctionWithoutPermaUrlState)invocation.Arguments[0]); Assert.That(nextState.Parameters.PostBackCollection.AllKeys, Is.EquivalentTo(new[] { "Key", c_senderUniqueID })); }); } MockRepository.ReplayAll(); executionState.ExecuteSubFunction(WxeContext); MockRepository.VerifyAll(); }
/// <summary> /// Creates a new set of metadata. /// </summary> /// <param name="executionState">The current execution state.</param> /// <param name="items">The initial set of items. If null, no underlying dictionary will be created.</param> public Metadata(IExecutionState executionState, IEnumerable <KeyValuePair <string, object> > items = null) { _ = executionState ?? throw new ArgumentNullException(nameof(executionState)); if (items != null) { Dictionary = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase); // If items is an IMetadata, use the raw enumerable so that we don't expand IMetadataValue and Config values if (items is IMetadata metadata) { items = metadata.GetRawEnumerable(); } // Iterate the items, checking for script values foreach (KeyValuePair <string, object> item in items) { if (ScriptMetadataValue.TryGetScriptMetadataValue(item.Key, item.Value, executionState, out ScriptMetadataValue metadataValue)) { Dictionary[item.Key] = metadataValue; } else { Dictionary[item.Key] = item.Value; } } } }
private static Failure?RunToDone(IExecutionState state, uint maxTestIters, int testIndex, int testCount, ref long overflowIters) { // Clear completion indicator state.Done = false; // Run for max allowed number of lines var err1 = state.Run(maxTestIters, TimeSpan.FromMilliseconds(600)); if (err1 != null) { return(new Failure(FailureType.Other, err1)); } // This test case didn't finish yet, run it some more with the overflow pool if (!state.Done) { var executed = state.TotalLinesExecuted; var err2 = state.Run((uint)overflowIters, TimeSpan.FromMilliseconds(600)); if (err2 != null) { return(new Failure(FailureType.Other, err2)); } // Shrink the overflow pool by however many ticks that just used overflowIters -= (uint)(state.TotalLinesExecuted - executed); //Once the overflow pool is empty too, fail if (overflowIters <= 0 || !state.Done) { return(new Failure(FailureType.RuntimeTooLong, $"Completed {testIndex}/{testCount} tests.")); } } return(null); }
public void ExecuteSubFunction_WithPermaUrl() { WxePermaUrlOptions permaUrlOptions = new WxePermaUrlOptions(); IExecutionState executionState = CreateExecutionStateForDoRepost(null, permaUrlOptions); using (MockRepository.Ordered()) { using (MockRepository.Unordered()) { _pageMock.Expect(mock => mock.GetPostBackCollection()).Return(PostBackCollection); _pageMock.Expect(mock => mock.SaveAllState()); } ExecutionStateContextMock.Expect(mock => mock.SetExecutionState(Arg <PreparingRedirectToSubFunctionState> .Is.NotNull)) .WhenCalled( invocation => { var nextState = CheckExecutionState((PreparingRedirectToSubFunctionState)invocation.Arguments[0]); Assert.That(nextState.Parameters.PostBackCollection, Is.Not.SameAs(PostBackCollection)); Assert.That( nextState.Parameters.PostBackCollection.AllKeys, Is.EquivalentTo(new[] { "Key", c_senderUniqueID, ControlHelper.PostEventSourceID, ControlHelper.PostEventArgumentID })); Assert.That(nextState.Parameters.SubFunction.ParentStep, Is.SameAs(_parentStep)); Assert.That(nextState.Parameters.PermaUrlOptions, Is.SameAs(permaUrlOptions)); }); } MockRepository.ReplayAll(); executionState.ExecuteSubFunction(WxeContext); MockRepository.VerifyAll(); }
private ScriptMetadataValue(string key, string originalPrefix, string script, IExecutionState executionState) { _key = key ?? throw new ArgumentNullException(nameof(key)); _originalPrefix = originalPrefix ?? throw new ArgumentNullException(nameof(originalPrefix)); _script = script ?? throw new ArgumentNullException(nameof(script)); _executionState = executionState ?? throw new ArgumentNullException(nameof(executionState)); }
public void ExecuteSubFunction_SuppressSender_IPostBackDataHandler() { Control senderMock = MockRepository.StrictMultiMock <Control> (typeof(IPostBackDataHandler)); senderMock.Stub(stub => stub.UniqueID).Return(c_senderUniqueID).Repeat.Any(); IExecutionState executionState = CreateExecutionStateForSupressRepost(senderMock); using (MockRepository.Ordered()) { using (MockRepository.Unordered()) { _pageMock.Expect(mock => mock.GetPostBackCollection()).Return(PostBackCollection); _pageMock.Expect(mock => mock.SaveAllState()); } ExecutionStateContextMock.Expect(mock => mock.SetExecutionState(Arg <ExecutingSubFunctionWithoutPermaUrlState> .Is.NotNull)) .WhenCalled( invocation => { var nextState = CheckExecutionState((ExecutingSubFunctionWithoutPermaUrlState)invocation.Arguments[0]); Assert.That(nextState.Parameters.PostBackCollection, Is.Not.SameAs(PostBackCollection)); Assert.That( nextState.Parameters.PostBackCollection.AllKeys, Is.EquivalentTo(new[] { "Key", ControlHelper.PostEventSourceID, ControlHelper.PostEventArgumentID })); }); } MockRepository.ReplayAll(); executionState.ExecuteSubFunction(WxeContext); MockRepository.VerifyAll(); }
public void ExecuteSubFunction_WithPermaUrl_WithParentPermaUrl_DoNotReturnToCaller_GoesToRedirectingToSubFunction () { WxeContext.QueryString.Add ("Key", "NewValue"); WxePermaUrlOptions permaUrlOptions = new WxePermaUrlOptions (true); IExecutionState executionState = CreateExecutionState (permaUrlOptions, WxeReturnOptions.Null); ExecutionStateContextMock.Expect (mock => mock.SetExecutionState (Arg<RedirectingToSubFunctionState>.Is.NotNull)) .WhenCalled ( invocation => { var nextState = CheckExecutionState ((RedirectingToSubFunctionState) invocation.Arguments[0]); Assert.That (nextState.Parameters.SubFunction.ReturnUrl, Is.EqualTo ("DefaultReturn.html")); string destinationUrl = UrlUtility.AddParameters ( "/session/sub.wxe", new NameValueCollection { { "Parameter1", "OtherValue" }, { WxeHandler.Parameters.WxeFunctionToken, SubFunction.FunctionToken }, { WxeHandler.Parameters.ReturnUrl, "/root.wxe?Key=NewValue" } }, Encoding.Default); Assert.That (nextState.Parameters.DestinationUrl, Is.EqualTo (destinationUrl)); }); MockRepository.ReplayAll(); executionState.ExecuteSubFunction (WxeContext); MockRepository.VerifyAll(); }
public void ExecuteSubFunction_SenderRequiresRegistrationForPostBack() { Control senderMock = MockRepository.StrictMultiMock <Control> (typeof(IPostBackDataHandler)); senderMock.Stub(stub => stub.UniqueID).Return(c_senderUniqueID).Repeat.Any(); PostBackCollection.Remove(c_senderUniqueID); IExecutionState executionState = CreateExecutionStateForDoRepost(senderMock, WxePermaUrlOptions.Null); using (MockRepository.Ordered()) { using (MockRepository.Unordered()) { _pageMock.Expect(mock => mock.GetPostBackCollection()).Return(PostBackCollection); } _pageMock.Expect(mock => mock.RegisterRequiresPostBack(senderMock)); _pageMock.Expect(mock => mock.SaveAllState()); ExecutionStateContextMock.Expect(mock => mock.SetExecutionState(Arg <ExecutingSubFunctionWithoutPermaUrlState> .Is.NotNull)) .WhenCalled(invocation => CheckExecutionState((ExecutingSubFunctionWithoutPermaUrlState)invocation.Arguments[0])); } MockRepository.ReplayAll(); executionState.ExecuteSubFunction(WxeContext); MockRepository.VerifyAll(); }
internal static void RenderExternalDocument( this IDocument document, IExecutionState context, TextWriter writer, bool prependLinkRoot, string configuration, string filePath, bool isCodeBlock, string overrideCodeLang = null, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int?callerLineNumber = null, [CallerMemberName] string callerMemberName = null ) { string GetCallerInfo() => $"{Path.GetFileName(callerFilePath)}:{callerLineNumber}:{callerMemberName}"; // If no path specified just skip if (string.IsNullOrWhiteSpace(filePath)) { context.Logger.LogDebug(document, $"{GetCallerInfo()}: Empty file path specified skipping."); return; } var normalizedFilePath = new NormalizedPath(filePath) switch { // If relative try find absolute path based on document path { IsRelative : true } relativePath => document.Source.ChangeFileName(relativePath) switch { { IsAbsolute : true } changedPath => changedPath, _ => relativePath },
public void ExecuteSubFunction_WithPermaUrl_ReturnToCaller_WithCallerUrlParameters_GoesToRedirectingToSubFunction () { WxePermaUrlOptions permaUrlOptions = new WxePermaUrlOptions(); IExecutionState executionState = CreateExecutionState (permaUrlOptions, new WxeReturnOptions (new NameValueCollection { { "Key", "Value" } })); ExecutionStateContextMock.Stub (stub => stub.CurrentFunction).Return (RootFunction).Repeat.Any(); ExecutionStateContextMock.Expect (mock => mock.SetExecutionState (Arg<RedirectingToSubFunctionState>.Is.NotNull)) .WhenCalled ( invocation => { var nextState = CheckExecutionState ((RedirectingToSubFunctionState) invocation.Arguments[0]); Assert.That ( nextState.Parameters.SubFunction.ReturnUrl, Is.EqualTo ("/session/root.wxe?Key=Value&WxeFunctionToken=" + WxeContext.FunctionToken)); Assert.That ( nextState.Parameters.DestinationUrl, Is.EqualTo ("/session/sub.wxe?Parameter1=OtherValue&WxeFunctionToken=" + SubFunction.FunctionToken)); }); MockRepository.ReplayAll(); executionState.ExecuteSubFunction (WxeContext); MockRepository.VerifyAll(); }
public void RollbackTransaction() { if (!IsInTransaction) { throw new ApplicationException("A transaction is not started!"); } _transactionalState.RollbackTransaction(); _currentState = _defaultState; }
public void BeginTransaction() { if (IsInTransaction) { throw new ApplicationException("A transaction is already started!"); } _transactionalState.BeginTransaction(); _currentState = _transactionalState; }
public static void CopyTo(this IExecutionState from, IExecutionState to, bool externalsOnly = false) { foreach (var(name, value) in from) { if (!name.IsExternal && externalsOnly) { continue; } to.Set(name, value); } }
public static SerializedState Serialize(this IExecutionState state, IReadOnlyDictionary <string, Value>?set = null) { var values = set?.ToDictionary(a => a.Key.ToLowerInvariant(), a => a.Value) ?? new(); foreach (var(k, v) in state) { values[k.Name.ToLowerInvariant()] = v; } return(new SerializedState(state.Code, values, state.ProgramCounter - 1)); }
public void IExecutionStateContext_GetAndSetExecutionState() { IExecutionStateContext executionStateContext = _pageStep; IExecutionState newExecutionState = MockRepository.GenerateStub <IExecutionState> (); Assert.That(executionStateContext.ExecutionState, Is.SameAs(NullExecutionState.Null)); executionStateContext.SetExecutionState(newExecutionState); Assert.That(executionStateContext.ExecutionState, Is.SameAs(newExecutionState)); }
public NameSorterProcess(String fileName, IExecutionState executionState) { FileName = fileName; NameDetailsLineBuilder = new NameDetailsLineBuilder(); NameSortProcess = new NameSortProcess(); Process = new NameSorterLinesProcess(NameDetailsLineBuilder); FileUtils = new NameSorterFileUtils(Process); ExecutionState = executionState; }
/// <summary> /// Testing constructor /// </summary> /// <param name="database"></param> /// <param name="factory"></param> /// <param name="defaultState"></param> /// <param name="transactionalState"></param> public DataSession(IDatabaseEngine database, ICommandFactory factory, IExecutionState defaultState, ITransactionalExecutionState transactionalState) { _database = database; _factory = factory; _defaultState = defaultState; _transactionalState = transactionalState; _currentState = _defaultState; _commands = new CommandCollection(this, _factory); _readerSources = new ReaderSourceCollection(this, _factory); }
public static bool TryGetScriptMetadataValue(string key, object value, IExecutionState executionState, out ScriptMetadataValue scriptMetadataValue) { scriptMetadataValue = default; if (value is string stringValue && IScriptHelper.TryGetScriptString(stringValue, out string script)) { scriptMetadataValue = new ScriptMetadataValue( key, stringValue.Substring(0, stringValue.Length - script.Length), script, executionState); return(true); } return(false); }
internal void SignalStarted(ICoroutineScheduler scheduler, IExecutionState executionState, Coroutine spawner) { lock (SyncRoot) { if (Status != CoroutineStatus.WaitingForStart) { throw new CoroutineException("Signalling start to non-stated coroutine"); } Scheduler = scheduler; ExecutionState = executionState; Spawner = spawner; Status = CoroutineStatus.Running; } }
public void ExecuteFunctionExternalByRedirect(PreProcessingSubFunctionStateParameters parameters, WxeReturnOptions returnOptions) { ArgumentUtility.CheckNotNull("parameters", parameters); ArgumentUtility.CheckNotNull("returnOptions", returnOptions); if (_executionState.IsExecuting) { throw new InvalidOperationException("Cannot execute function while another function executes."); } _wxeHandler = parameters.Page.WxeHandler; _executionState = new ExecuteByRedirect_PreProcessingSubFunctionState(this, parameters, returnOptions); Execute(); }
public static EmbedBuilder ToEmbed(this IExecutionState state, Action <EmbedBuilder>?pre = null) { var embed = new EmbedBuilder { Title = "Execution Finished", Color = Color.Purple, Footer = new EmbedFooterBuilder().WithText("A Cylon Project") }; embed.Description += $"{state.TotalLinesExecuted} lines executed. Next line: {state.ProgramCounter}"; pre?.Invoke(embed); BuildFieldsList(embed, "Locals", state.Where(a => !a.Key.IsExternal).ToArray()); BuildFieldsList(embed, "Globals", state.Where(a => a.Key.IsExternal).ToArray()); return(embed); }
public void SetUp() { _factoryMock = new DynamicMock(typeof(ICommandFactory)); _databaseMock = new DynamicMock(typeof(IDatabaseEngine)); _database = (IDatabaseEngine)_databaseMock.MockInstance; _factory = (ICommandFactory)_factoryMock.MockInstance; _autoCommitMock = new DynamicMock(typeof(IExecutionState)); _transactionalMock = new DynamicMock(typeof(ITransactionalExecutionState)); IExecutionState autoCommitState = (IExecutionState)_autoCommitMock.MockInstance; ITransactionalExecutionState transactionalState = (ITransactionalExecutionState)_transactionalMock.MockInstance; _session = new DataSession(_database, _factory, autoCommitState, transactionalState); }
// Passes initial value overrides (presumably from ConfigurationSettings) public ReadOnlyConfigurationSettings( IExecutionState executionState, IConfiguration configuration, IDictionary <string, object> valueOverrides) : base(configuration) { _ = executionState ?? throw new ArgumentNullException(nameof(executionState)); _valueOverrides = valueOverrides ?? new Dictionary <string, object>(); foreach (KeyValuePair <string, string> item in configuration.AsEnumerable()) { if (!_valueOverrides.ContainsKey(item.Key) && ScriptMetadataValue.TryGetScriptMetadataValue(item.Key, item.Value, executionState, out ScriptMetadataValue metadataValue)) { _valueOverrides[item.Key] = metadataValue; } } }
public void ExecuteSubFunction_WithPermaUrl_DoNotReturnToCaller_GoesToRedirectingToSubFunction () { IExecutionState executionState = CreateExecutionState (new WxePermaUrlOptions(), WxeReturnOptions.Null); ExecutionStateContextMock.Expect (mock => mock.SetExecutionState (Arg<RedirectingToSubFunctionState>.Is.NotNull)) .WhenCalled ( invocation => { var nextState = CheckExecutionState ((RedirectingToSubFunctionState) invocation.Arguments[0]); Assert.That (nextState.Parameters.SubFunction.ReturnUrl, Is.EqualTo ("DefaultReturn.html")); Assert.That ( nextState.Parameters.DestinationUrl, Is.EqualTo ("/session/sub.wxe?Parameter1=OtherValue&WxeFunctionToken=" + SubFunction.FunctionToken)); }); MockRepository.ReplayAll(); executionState.ExecuteSubFunction (WxeContext); MockRepository.VerifyAll(); }
public void ExecuteSubFunction_WithPermaUrl_GoesToExecutingSubFunction() { WxePermaUrlOptions permaUrlOptions = new WxePermaUrlOptions(); IExecutionState executionState = CreateExecutionState(permaUrlOptions); ExecutionStateContextMock.Expect(mock => mock.SetExecutionState(Arg <RedirectingToSubFunctionState> .Is.NotNull)) .WhenCalled( invocation => { var nextState = CheckExecutionState((RedirectingToSubFunctionState)invocation.Arguments[0]); Assert.That( nextState.Parameters.DestinationUrl, Is.EqualTo("/session/sub.wxe?Parameter1=OtherValue&WxeFunctionToken=" + WxeContext.FunctionToken)); Assert.That(nextState.Parameters.ResumeUrl, Is.EqualTo("/session/root.wxe?WxeFunctionToken=" + WxeContext.FunctionToken)); }); MockRepository.ReplayAll(); executionState.ExecuteSubFunction(WxeContext); MockRepository.VerifyAll(); }
public static bool TryGetScriptMetadataValue(string key, object value, IExecutionState executionState, out ScriptMetadataValue scriptMetadataValue) { scriptMetadataValue = default; if (value is string script) { script = script.TrimStart(); if (script.StartsWith("=>")) { script = script.Substring(2); if (!string.IsNullOrWhiteSpace(script)) { scriptMetadataValue = new ScriptMetadataValue( key, ((string)value).Substring(0, ((string)value).Length - script.Length), script, executionState); return(true); } } } return(false); }
public override Failure?CheckCase(IReadOnlyDictionary <string, Value> inputs, IReadOnlyDictionary <string, Value> expectedOutputs, IExecutionState state, SerializedState?debugState) { // Check that the machine state is exactly correct for every expected output foreach (var(key, expected) in expectedOutputs) { var actual = state.TryGet(new VariableName($":{key}")) ?? (Value)0; // Add bonus points averaged across all cases switch (expected.Type, actual.Type) {
public void CommitTransaction() { if (!IsInTransaction) { throw new ApplicationException("A transaction is not started!"); } _transactionalState.CommitTransaction(); _currentState = _defaultState; }
public IIntValue IntValue(IExecutionState executionState) { return new MockIntValue(this.value); }
public TypeNode BestType(IExecutionState executionState) { throw new Exception("The method or operation is not implemented."); }
public bool IsNull(IExecutionState executionState) { throw new Exception("The method or operation is not implemented."); }
public ITypeValue TypeValue(IExecutionState executionState) { throw new Exception("The method or operation is not implemented."); }