Пример #1
0
        public async Task ExecuteAsync_WithoutHistoryOption_AvoidsAddingCommandsExecutedFromScriptToCommandHistory()
        {
            string commands = @"set header name value1 value2";

            if (!File.Exists(_pathToScript))
            {
                File.WriteAllText(_pathToScript, commands);
            }

            string parseResultSections = "run " + _pathToScript;

            ArrangeInputs(parseResultSections: parseResultSections,
                          out MockedShellState _,
                          out HttpState httpState,
                          out ICoreParseResult parseResult);

            IShellState      shellState       = GetShellState(commands, httpState);
            MockedFileSystem mockedFileSystem = new MockedFileSystem();

            mockedFileSystem.AddFile(_pathToScript, commands);
            RunCommand runCommand = new RunCommand(mockedFileSystem);

            await runCommand.ExecuteAsync(shellState, httpState, parseResult, CancellationToken.None);

            string previousCommand = shellState.CommandHistory.GetPreviousCommand();

            Assert.True(string.IsNullOrEmpty(previousCommand));
        }
Пример #2
0
        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);
        }
Пример #3
0
        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]);
        }
Пример #4
0
        private static HttpState SetupHttpState(string preferencesFileContent = null)
        {
            UserProfileDirectoryProvider userProfileDirectoryProvider = new UserProfileDirectoryProvider();
            IFileSystem fileSystem;

            if (preferencesFileContent != null)
            {
                fileSystem = new MockedFileSystem();
            }
            else
            {
                fileSystem = new FileSystemStub();
            }
            UserFolderPreferences preferences = new UserFolderPreferences(fileSystem, userProfileDirectoryProvider, null);

            if (preferencesFileContent != null)
            {
                ((MockedFileSystem)fileSystem).AddFile(preferences.PreferencesFilePath, preferencesFileContent);
            }

            HttpClient client = new HttpClient();
            HttpState  state  = new HttpState(fileSystem, preferences, client);

            return(state);
        }
        public void WritePreferences_ChangeNonDefaultToDefault_RemovesDefaultValue()
        {
            string originalValue = "BoldMagenta";
            string defaultValue  = "Red";
            IDictionary <string, string> defaultPreferences = new Dictionary <string, string> {
                { WellKnownPreference.ProtocolColor, defaultValue }
            };

            MockedFileSystem fileSystem = new MockedFileSystem();
            IUserProfileDirectoryProvider userProfileDirectoryProvider = new UserProfileDirectoryProvider();
            UserFolderPreferences         preferences = new UserFolderPreferences(fileSystem, userProfileDirectoryProvider, defaultPreferences);

            // Create a file with a non-default value, read it from the file system and
            // validate that it was read correctly
            fileSystem.AddFile(preferences.PreferencesFilePath, $"{WellKnownPreference.ProtocolColor}={originalValue}");

            Assert.Equal(originalValue, preferences.CurrentPreferences[WellKnownPreference.ProtocolColor]);

            // Now change it to the default value, write it back to the file system and
            // validate that it was removed from the file
            bool succeeded = preferences.SetValue(WellKnownPreference.ProtocolColor, defaultPreferences[WellKnownPreference.ProtocolColor]);

            Assert.True(succeeded);
            Assert.Equal(string.Empty, fileSystem.ReadFile(preferences.PreferencesFilePath));
        }
        private void SetupPreferences(out UserFolderPreferences preferences, out MockedFileSystem fileSystem)
        {
            fileSystem = new MockedFileSystem();
            IUserProfileDirectoryProvider userProfileDirectoryProvider = new UserProfileDirectoryProvider();

            preferences = new UserFolderPreferences(fileSystem, userProfileDirectoryProvider, TestDefaultPreferences.GetDefaultPreferences());
        }
Пример #7
0
        private static void Arrange(string commandText, out HttpState httpState, out MockedShellState shellState, out ICoreParseResult parseResult, out PrefCommand command, out UserFolderPreferences preferences)
        {
            IFileSystem fileSystem = new MockedFileSystem();
            IUserProfileDirectoryProvider userProfileDirectoryProvider = new UserProfileDirectoryProvider();

            preferences = new UserFolderPreferences(fileSystem, userProfileDirectoryProvider, TestDefaultPreferences.GetDefaultPreferences());
            HttpClient httpClient = new HttpClient();

            httpState   = new HttpState(fileSystem, preferences, httpClient);
            shellState  = new MockedShellState();
            parseResult = CoreParseResultHelper.Create(commandText);
            command     = new PrefCommand(preferences);
        }
Пример #8
0
        public async Task ExecuteAsync_RootWithSwaggerSuffixAndOverride_DoesNotFixBase()
        {
            string rootAddress            = "https://*****:*****@"{
  ""openapi"": ""3.0.0"",
  ""info"": {
    ""title"": ""OpenAPI v3 Spec"",
    ""version"": ""v1""
  },
  ""paths"": {
    ""/WeatherForecast"": {
    }
  }
}";

            MockedFileSystem             fileSystem = new MockedFileSystem();
            UserProfileDirectoryProvider userProfileDirectoryProvider = new UserProfileDirectoryProvider();
            IPreferences preferences = new UserFolderPreferences(fileSystem,
                                                                 userProfileDirectoryProvider,
                                                                 new Dictionary <string, string> {
                { WellKnownPreference.ConnectCommandSkipRootFix, "true" }
            });

            ArrangeInputsWithOptional(commandText: $"connect {rootAddress}",
                                      baseAddress: null,
                                      path: null,
                                      urlsWithResponse: new Dictionary <string, string>()
            {
                { expectedSwaggerAddress, swaggerContent }
            },
                                      out MockedShellState shellState,
                                      out HttpState httpState,
                                      out ICoreParseResult parseResult,
                                      ref fileSystem,
                                      ref preferences);

            ConnectCommand connectCommand = new ConnectCommand(preferences, new NullTelemetry());

            await connectCommand.ExecuteAsync(shellState, httpState, parseResult, CancellationToken.None);

            Assert.Contains(string.Format(Resources.Strings.ConnectCommand_Status_Base, expectedBaseAddress), shellState.Output, StringComparer.Ordinal);
            Assert.Contains(string.Format(Resources.Strings.ConnectCommand_Status_Swagger, expectedSwaggerAddress), shellState.Output, StringComparer.Ordinal);
        }
Пример #9
0
        protected static HttpState GetHttpState(out MockedFileSystem fileSystem,
                                                out IPreferences preferences,
                                                string baseAddress = "",
                                                string header      = "",
                                                string path        = "",
                                                IDictionary <string, string> urlsWithResponse = null,
                                                bool readFromFile   = false,
                                                string fileContents = "",
                                                string contentType  = "")
        {
            HttpResponseMessage responseMessage = new HttpResponseMessage();

            responseMessage.Content = new MockHttpContent(string.Empty);
            MockHttpMessageHandler messageHandler = new MockHttpMessageHandler(urlsWithResponse, header, readFromFile, fileContents, contentType);
            HttpClient             httpClient     = new HttpClient(messageHandler);

            fileSystem  = new MockedFileSystem();
            preferences = new NullPreferences();

            HttpState httpState = new HttpState(fileSystem, preferences, httpClient);

            if (!string.IsNullOrWhiteSpace(baseAddress))
            {
                httpState.BaseAddress = new Uri(baseAddress);
            }
            if (!string.IsNullOrWhiteSpace(path))
            {
                httpState.BaseAddress = new Uri(baseAddress);

                if (path != null)
                {
                    string[] pathParts = path.Split('/');

                    foreach (string pathPart in pathParts)
                    {
                        httpState.PathSections.Push(pathPart);
                    }
                }
            }

            return(httpState);
        }
Пример #10
0
        public void Suggest_WithSelectedSectionAtOneAndValidParseResultSection_ReturnsCompletionEntries()
        {
            string pathToScript        = Path.Combine(Directory.GetCurrentDirectory(), "InputFileForRunCommand.txt");
            string parseResultSections = "run " + pathToScript;

            ArrangeInputs(parseResultSections: parseResultSections,
                          out MockedShellState _,
                          out HttpState httpState,
                          out ICoreParseResult parseResult,
                          caretPosition: 7);

            IShellState      shellState       = GetShellState(string.Empty, httpState);
            MockedFileSystem mockedFileSystem = new MockedFileSystem();

            mockedFileSystem.AddFile(pathToScript, string.Empty);

            RunCommand           runCommand = new RunCommand(mockedFileSystem);
            IEnumerable <string> result     = runCommand.Suggest(shellState, httpState, parseResult);

            Assert.NotEmpty(result);
        }
Пример #11
0
        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());
        }
Пример #12
0
        protected static HttpState GetHttpState(out MockedFileSystem fileSystem,
                                                out IPreferences preferences,
                                                string baseAddress = "",
                                                string header      = "",
                                                string path        = "",
                                                IDictionary <string, string> urlsWithResponse = null,
                                                bool readFromFile   = false,
                                                string fileContents = "",
                                                string contentType  = "")
        {
            fileSystem  = new MockedFileSystem();
            preferences = new NullPreferences();

            return(GetHttpStateWithOptional(ref fileSystem,
                                            ref preferences,
                                            baseAddress,
                                            header,
                                            path,
                                            urlsWithResponse,
                                            readFromFile,
                                            fileContents,
                                            contentType));
        }
Пример #13
0
        public async Task ExecuteAsync_WithValidInput_ExecutesTheCommandsInTheScript()
        {
            string commands = @"set header name value1 value2";

            if (!File.Exists(_pathToScript))
            {
                File.WriteAllText(_pathToScript, commands);
            }

            string parseResultSections = "run " + _pathToScript;

            ArrangeInputs(parseResultSections: parseResultSections,
                          out MockedShellState _,
                          out HttpState httpState,
                          out ICoreParseResult parseResult);

            IShellState      shellState       = GetShellState(commands, httpState);
            MockedFileSystem mockedFileSystem = new MockedFileSystem();

            mockedFileSystem.AddFile(_pathToScript, commands);
            RunCommand runCommand = new RunCommand(mockedFileSystem);

            await runCommand.ExecuteAsync(shellState, httpState, parseResult, CancellationToken.None);

            Dictionary <string, IEnumerable <string> >   headers      = httpState.Headers;
            KeyValuePair <string, IEnumerable <string> > firstHeader  = headers.First();
            KeyValuePair <string, IEnumerable <string> > secondHeader = headers.ElementAt(1);

            Assert.Equal(2, httpState.Headers.Count);
            Assert.Equal("User-Agent", firstHeader.Key);
            Assert.Equal("HTTP-REPL", firstHeader.Value.First());

            Assert.Equal("name", secondHeader.Key);
            Assert.Equal("value1", secondHeader.Value.First());
            Assert.Equal("value2", secondHeader.Value.ElementAt(1));
        }
Пример #14
0
        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);
        }