public async Task ExecuteAsync_SetCommandNoValue_SetToDefault() { IFileSystem fileSystem = new MockedFileSystem(); IUserProfileDirectoryProvider userProfileDirectoryProvider = new UserProfileDirectoryProvider(); UserFolderPreferences preferences = new UserFolderPreferences(fileSystem, userProfileDirectoryProvider, TestDefaultPreferences.GetDefaultPreferences()); HttpClient httpClient = new HttpClient(); HttpState httpState = new HttpState(fileSystem, preferences, httpClient); MockedShellState shellState = new MockedShellState(); PrefCommand command = new PrefCommand(preferences); // First, set it to something other than the default and make sure that works. string firstCommandExpectedValue = "BoldMagenta"; string firstCommandText = $"pref set {WellKnownPreference.ProtocolColor} {firstCommandExpectedValue}"; ICoreParseResult firstParseResult = CoreParseResultHelper.Create(firstCommandText); await command.ExecuteAsync(shellState, httpState, firstParseResult, CancellationToken.None); Assert.Empty(shellState.Output); Assert.Equal(firstCommandExpectedValue, preferences.CurrentPreferences[WellKnownPreference.ProtocolColor]); // Then, set it to nothing and make sure it goes back to the default string secondCommandText = $"pref set {WellKnownPreference.ProtocolColor}"; ICoreParseResult secondParseResult = CoreParseResultHelper.Create(secondCommandText); await command.ExecuteAsync(shellState, httpState, secondParseResult, CancellationToken.None); Assert.Empty(shellState.Output); Assert.Equal(preferences.DefaultPreferences[WellKnownPreference.ProtocolColor], preferences.CurrentPreferences[WellKnownPreference.ProtocolColor]); }
protected void ArrangeInputs(string commandText, string baseAddress, string path, IDictionary <string, string> urlsWithResponse, out MockedShellState shellState, out HttpState httpState, out ICoreParseResult parseResult, out MockedFileSystem fileSystem, out IPreferences preferences, string header = "", bool readBodyFromFile = false, string fileContents = "", string contentType = "") { parseResult = CoreParseResultHelper.Create(commandText); shellState = new MockedShellState(); httpState = GetHttpState(out fileSystem, out preferences, baseAddress, header, path, urlsWithResponse, readBodyFromFile, fileContents, contentType); }
public static Task LeftArrow(ConsoleKeyInfo keyInfo, IShellState state, CancellationToken cancellationToken) { if (state.ConsoleManager.CaretPosition > 0) { if (!keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control)) { state.ConsoleManager.MoveCaret(-1); } else { string line = state.InputManager.GetCurrentBuffer(); ICoreParseResult parseResult = state.CommandDispatcher.Parser.Parse(line, state.ConsoleManager.CaretPosition); int targetSection = parseResult.SelectedSection - (parseResult.CaretPositionWithinSelectedSection > 0 ? 0 : 1); if (targetSection < 0) { targetSection = 0; } int desiredPosition = parseResult.SectionStartLookup[targetSection]; state.ConsoleManager.MoveCaret(desiredPosition - state.ConsoleManager.CaretPosition); } } return(Task.CompletedTask); }
public void Suggest(string commandText, params string[] expectedResults) { HttpState httpState = GetHttpState(out MockedFileSystem fileSystem, out _); ICoreParseResult parseResult = CreateCoreParseResult(commandText); IConsoleManager consoleManager = new LoggingConsoleManagerDecorator(new NullConsoleManager()); DefaultCommandDispatcher <HttpState> commandDispatcher = DefaultCommandDispatcher.Create((ss) => { }, httpState); commandDispatcher.AddCommand(new ClearCommand()); commandDispatcher.AddCommand(new ChangeDirectoryCommand()); commandDispatcher.AddCommand(new RunCommand(fileSystem)); IShellState shellState = new ShellState(commandDispatcher, consoleManager: consoleManager); HelpCommand helpCommand = new HelpCommand(); IEnumerable <string> result = helpCommand.Suggest(shellState, httpState, parseResult); Assert.NotNull(result); List <string> resultList = result.ToList(); Assert.Equal(expectedResults.Length, resultList.Count); for (int index = 0; index < expectedResults.Length; index++) { Assert.Contains(expectedResults[index], resultList, StringComparer.OrdinalIgnoreCase); } }
public static Task RightArrow(ConsoleKeyInfo keyInfo, IShellState state, CancellationToken cancellationToken) { string line = state.InputManager.GetCurrentBuffer(); if (state.ConsoleManager.CaretPosition < line.Length) { if (!keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control)) { state.ConsoleManager.MoveCaret(1); } else { ICoreParseResult parseResult = state.CommandDispatcher.Parser.Parse(line, state.ConsoleManager.CaretPosition); int targetSection = parseResult.SelectedSection + 1; if (targetSection >= parseResult.Sections.Count) { state.ConsoleManager.MoveCaret(line.Length - state.ConsoleManager.CaretPosition); } else { int desiredPosition = parseResult.SectionStartLookup[targetSection]; state.ConsoleManager.MoveCaret(desiredPosition - state.ConsoleManager.CaretPosition); } } } return(Task.CompletedTask); }
public void Parse_WithDoubleSpace_RemovesEmptySections(string commandText, int expectedSectionCount) { CoreParser parser = new CoreParser(); ICoreParseResult parseResult = parser.Parse(commandText, commandText.Length + 1); Assert.Equal(expectedSectionCount, parseResult.Sections.Count); }
public void Slice_WithVariousSliceLengths_CorrectCommandTextOutput(string commandText, int toRemove, string expectedCommandText) { CoreParser parser = new CoreParser(); ICoreParseResult parseResult = parser.Parse(commandText, commandText.Length); ICoreParseResult result = parseResult.Slice(toRemove); Assert.Equal(expectedCommandText, result.CommandText); }
public static bool ContainsAtLeast(this ICoreParseResult parseResult, int minimumLength, StringComparison stringComparison, params string[] sections) { if (parseResult.Sections.Count < minimumLength || parseResult.Sections.Count < sections.Length) { return(false); } return(CompareSections(parseResult.Sections, sections, stringComparison)); }
public void Slice_WithSelectedSection_SelectedSectionMoves(string commandText, int toRemove, int caretPosition, int expectedSelectedSection) { CoreParser parser = new CoreParser(); ICoreParseResult parseResult = parser.Parse(commandText, caretPosition); ICoreParseResult result = parseResult.Slice(toRemove); Assert.Equal(expectedSelectedSection, result.SelectedSection); }
public void Slice_WithZero_ReturnsThis() { CoreParser parser = new CoreParser(); string commandText = "set header content-type application/json"; ICoreParseResult parseResult = parser.Parse(commandText, commandText.Length); ICoreParseResult result = parseResult.Slice(0); Assert.Same(parseResult, result); }
public void Slice_WithCaretInSlicedRegion_CaretIsZero() { CoreParser parser = new CoreParser(); string commandText = "set header content-type application/json"; ICoreParseResult parseResult = parser.Parse(commandText, 5); ICoreParseResult result = parseResult.Slice(2); Assert.Equal(0, result.CaretPositionWithinCommandText); }
public static bool ContainsAtLeast(this ICoreParseResult parseResult, int minimumLength, StringComparison stringComparison, params string[] sections) { parseResult = parseResult ?? throw new ArgumentNullException(nameof(parseResult)); if (parseResult.Sections.Count < minimumLength || parseResult.Sections.Count < sections.Length) { return(false); } return(CompareSections(parseResult.Sections, sections, stringComparison)); }
public static ICoreParseResult Create(string commandText) { if (commandText == null) { throw new ArgumentNullException(nameof(commandText)); } CoreParser coreParser = new CoreParser(); ICoreParseResult parseResult = coreParser.Parse(commandText, commandText.Length); return(parseResult); }
public void CanHandle(string commandText, bool?expected) { HttpState httpState = GetHttpState(out _, out _); ICoreParseResult parseResult = CreateCoreParseResult(commandText); IShellState shellState = new MockedShellState(); HelpCommand helpCommand = new HelpCommand(); bool?result = helpCommand.CanHandle(shellState, httpState, parseResult); Assert.Equal(expected, result); }
protected async Task VerifyHeaders(string commandText, string baseAddress, string path, int expectedResponseLines, string expectedHeader) { MockedShellState shellState = new MockedShellState(); HttpState httpState = GetHttpState(baseAddress, path); ICoreParseResult parseResult = CoreParseResultHelper.Create(commandText); await _command.ExecuteAsync(shellState, httpState, parseResult, CancellationToken.None); Assert.Equal(expectedResponseLines, shellState.Output.Count); Assert.Equal(expectedHeader, shellState.Output[expectedResponseLines - 2]); }
private async Task <IDirectoryStructure> GetDirectoryStructure(string response, string parseResultSections, string baseAddress) { MockedShellState shellState = new MockedShellState(); IDictionary <string, string> urlsWithResponse = new Dictionary <string, string>(); urlsWithResponse.Add(baseAddress, response); HttpState httpState = GetHttpState(out _, out _, urlsWithResponse: urlsWithResponse); ICoreParseResult parseResult = CoreParseResultHelper.Create(parseResultSections); SetSwaggerCommand setSwaggerCommand = new SetSwaggerCommand(); await setSwaggerCommand.ExecuteAsync(shellState, httpState, parseResult, CancellationToken.None); return(httpState.Structure); }
protected async Task VerifyErrorMessage(string commandText, string baseAddress, string path, string expectedErrorMessage) { HttpState httpState = GetHttpState(baseAddress, path); expectedErrorMessage = expectedErrorMessage.SetColor(httpState.ErrorColor); MockedShellState shellState = new MockedShellState(); ICoreParseResult parseResult = CoreParseResultHelper.Create(commandText); await _command.ExecuteAsync(shellState, httpState, parseResult, CancellationToken.None); Assert.Equal(expectedErrorMessage, shellState.ErrorMessage); }
public async Task ExecuteAsync_CallsConsoleManagerClear() { HttpState httpState = GetHttpState(out _, out _); ICoreParseResult parseResult = CreateCoreParseResult("clear"); DefaultCommandDispatcher <HttpState> dispatcher = DefaultCommandDispatcher.Create((ss) => { }, httpState); LoggingConsoleManagerDecorator consoleManager = new LoggingConsoleManagerDecorator(new NullConsoleManager()); IShellState shellState = new ShellState(dispatcher, consoleManager: consoleManager); ClearCommand clearCommand = new ClearCommand(); await clearCommand.ExecuteAsync(shellState, httpState, parseResult, CancellationToken.None); Assert.True(consoleManager.WasClearCalled); }
public async Task ExecuteAsync_WithHttpStateBaseAddressSetToNull_WritesToConsoleManagerError() { MockedShellState shellState = new MockedShellState(); ICoreParseResult parseResult = CoreParseResultHelper.Create("ui"); HttpState httpState = GetHttpState(out _, out _); httpState.BaseAddress = null; Mock <IUriLauncher> mockLauncher = new Mock <IUriLauncher>(); UICommand uiCommand = new UICommand(mockLauncher.Object); await uiCommand.ExecuteAsync(shellState, httpState, parseResult, CancellationToken.None); VerifyErrorMessageWasWrittenToConsoleManagerError(shellState); }
public void Parse_WithQuotesButNoSpaces_DoesNotCombineSections() { // Arrange string commandText = "GET --response:headers \"file.txt\" --response:body \"file.txt\""; int caretPosition = commandText.Length + 1; CoreParser parser = new CoreParser(); int expectedSectionCount = 5; // Act ICoreParseResult parseResult = parser.Parse(commandText, caretPosition); // Assert Assert.Equal(expectedSectionCount, parseResult.Sections.Count); }
public void ParserTests_Basic() { string testString = "\"this is a test\" of \"Escape\\\\Sequences\\\"\""; CoreParser parser = new CoreParser(); ICoreParseResult result = parser.Parse(testString, 29); Assert.Equal(3, result.Sections.Count); Assert.Equal(2, result.SelectedSection); Assert.Equal(0, result.SectionStartLookup[0]); Assert.Equal(17, result.SectionStartLookup[1]); Assert.Equal(20, result.SectionStartLookup[2]); Assert.Equal(7, result.CaretPositionWithinSelectedSection); Assert.Equal(29, result.CaretPositionWithinCommandText); Assert.Equal(testString, result.CommandText); }
protected static void ArrangeInputs(string parseResultSections, out MockedShellState shellState, out HttpState httpState, out ICoreParseResult parseResult, string baseAddress = "", int caretPosition = -1, string responseContent = "") { parseResult = CoreParseResultHelper.Create(parseResultSections, caretPosition); shellState = new MockedShellState(); IDictionary <string, string> urlsWithResponse = new Dictionary <string, string>(); urlsWithResponse.Add(baseAddress, responseContent); httpState = GetHttpState(out _, out _, urlsWithResponse: urlsWithResponse); }
public void Slice_WithTooMany_ReturnsDefaultResult() { CoreParser parser = new CoreParser(); string commandText = "set header content-type application/json"; ICoreParseResult parseResult = parser.Parse(commandText, commandText.Length); ICoreParseResult result = parseResult.Slice(100); Assert.Equal(0, result.CaretPositionWithinCommandText); Assert.Equal(0, result.CaretPositionWithinSelectedSection); Assert.Equal(string.Empty, result.CommandText); Assert.Single(result.Sections); Assert.Contains(string.Empty, result.Sections); Assert.Equal(0, result.SelectedSection); Assert.Single(result.SectionStartLookup); Assert.Equal(0, result.SectionStartLookup.Single().Key); Assert.Equal(0, result.SectionStartLookup.Single().Value); }
public void PreviousSuggestion(IShellState shellState) { shellState = shellState ?? throw new ArgumentNullException(nameof(shellState)); string line = shellState.InputManager.GetCurrentBuffer(); ICoreParseResult parseResult = shellState.CommandDispatcher.Parser.Parse(line, shellState.ConsoleManager.CaretPosition); string currentSuggestion; //Check to see if we're continuing before querying for suggestions again if (_expected != null && string.Equals(_expected.CommandText, parseResult.CommandText, StringComparison.Ordinal) && _expected.SelectedSection == parseResult.SelectedSection && _expected.CaretPositionWithinSelectedSection == parseResult.CaretPositionWithinSelectedSection) { if (_suggestions == null || _suggestions.Count == 0) { return; } _currentSuggestion = (_currentSuggestion - 1 + _suggestions.Count) % _suggestions.Count; currentSuggestion = _suggestions[_currentSuggestion]; } else { _suggestions = shellState.CommandDispatcher.CollectSuggestions(shellState); _currentSuggestion = _suggestions.Count - 1; if (_suggestions == null || _suggestions.Count == 0) { return; } currentSuggestion = _suggestions[_suggestions.Count - 1]; } //We now have a suggestion, take the command text leading up to the section being suggested for, // concatenate that and the suggestion text, turn it in to keys, submit it to the input manager, // reset the caret, store the parse result of the new text as what's expected for a continuation string newText = parseResult.CommandText.Substring(0, parseResult.SectionStartLookup[parseResult.SelectedSection]) + currentSuggestion; _expected = shellState.CommandDispatcher.Parser.Parse(newText, newText.Length); shellState.InputManager.SetInput(shellState, newText); }
public async Task ExecuteAsync_WithNoParameterAndAbsolutePreference_VerifyLaunchUriAsyncWasCalledOnce() { string commandText = "ui"; ICoreParseResult parseResult = CoreParseResultHelper.Create(commandText); MockedShellState shellState = new MockedShellState(); MockedFileSystem fileSystem = new MockedFileSystem(); UserFolderPreferences preferences = new UserFolderPreferences(fileSystem, new UserProfileDirectoryProvider(), null); preferences.SetValue(WellKnownPreference.SwaggerUIEndpoint, "https://localhost:12345/mySwaggerPath"); HttpState httpState = new HttpState(fileSystem, preferences, new HttpClient()); httpState.BaseAddress = new Uri("https://localhost:44366", UriKind.Absolute); Mock <IUriLauncher> mockLauncher = new Mock <IUriLauncher>(); UICommand uiCommand = new UICommand(mockLauncher.Object, preferences); mockLauncher.Setup(s => s.LaunchUriAsync(It.IsAny <Uri>())) .Returns(Task.CompletedTask); await uiCommand.ExecuteAsync(shellState, httpState, parseResult, CancellationToken.None); mockLauncher.Verify(l => l.LaunchUriAsync(It.Is <Uri>(u => u.AbsoluteUri == "https://localhost:12345/mySwaggerPath")), Times.Once()); }
public async Task ExecuteAsync_WithEditorDoesNotExist_VerifyResponse() { // Arrange string editorPath = "FileThatDoesNotExist.exe"; string commandText = "POST https://localhost/"; MockedShellState shellState = new MockedShellState(); IFileSystem fileSystem = new MockedFileSystem(); IUserProfileDirectoryProvider userProfileDirectoryProvider = new UserProfileDirectoryProvider(); IPreferences preferences = new UserFolderPreferences(fileSystem, userProfileDirectoryProvider, null); ICoreParseResult parseResult = CoreParseResultHelper.Create(commandText); HttpClient httpClient = new HttpClient(); HttpState httpState = new HttpState(fileSystem, preferences, httpClient); PostCommand postCommand = new PostCommand(fileSystem, preferences); preferences.SetValue(WellKnownPreference.DefaultEditorCommand, editorPath); // Act await postCommand.ExecuteAsync(shellState, httpState, parseResult, CancellationToken.None); // Execute Assert.Empty(shellState.Output); Assert.Contains(string.Format(Strings.BaseHttpCommand_Error_DefaultEditorDoesNotExist, editorPath), shellState.ErrorMessage); }
private void ArrangeInputs(string commandText, out MockedShellState shellState, out HttpState httpState, out ICoreParseResult parseResult, out IPreferences preferences, string fileContents = null) { ArrangeInputs(commandText, baseAddress: null, path: null, urlsWithResponse: null, out shellState, out httpState, out parseResult, out _, out preferences, readBodyFromFile: fileContents is object, fileContents: fileContents); }
public static bool ContainsAtLeast(this ICoreParseResult parseResult, int minimumLength, params string[] sections) { return(ContainsAtLeast(parseResult, minimumLength, StringComparison.OrdinalIgnoreCase, sections)); }
private void Setup(string commandText, out MockedShellState mockedShellState, out HttpState httpState, out ICoreParseResult parseResult) { mockedShellState = new MockedShellState(); IFileSystem fileSystem = new RealFileSystem(); IUserProfileDirectoryProvider userProfileDirectoryProvider = new UserProfileDirectoryProvider(); IPreferences preferences = new UserFolderPreferences(fileSystem, userProfileDirectoryProvider, null); parseResult = CoreParseResultHelper.Create(commandText); HttpClient httpClient = new HttpClient(); httpState = new HttpState(preferences, httpClient); }
public static bool ContainsAtLeast(this ICoreParseResult parseResult, params string[] sections) { return(ContainsAtLeast(parseResult, minimumLength: sections.Length, sections)); }