Esempio n. 1
0
        public PackagingFixture(RemoteBehaviorGraph remoteGraph, CommandRunner runner)
        {
            _remoteGraph = remoteGraph;
            _runner = runner;

            this["SetUp"] = Embed<PackagingSetupFixture>("If the packaging setup is");
        }
Esempio n. 2
0
        public void try_command_runner()
        {
            var builder = new SchemaBuilder();
            builder.CreateTable(typeof(SchemaBuilderTests.MySpecialDocument), typeof(Guid));
            builder.DefineUpsert(typeof (SchemaBuilderTests.MySpecialDocument), typeof(Guid));

            var id = Guid.NewGuid();

            using (var runner = new CommandRunner(ConnectionSource.ConnectionString))
            {
                runner.Execute(builder.ToSql());
                /*
                runner.Execute("mt_upsert_myspecialdocument", command =>
                {
                    command.Parameters.Add("docId", NpgsqlDbType.Uuid).Value = id;
                    command.Parameters.Add("doc", NpgsqlDbType.Json).Value = "{\"id\":\"1\"}";
                });

                runner.Execute("mt_upsert_myspecialdocument", command =>
                {
                    command.Parameters.Add("docId", NpgsqlDbType.Uuid).Value = id;
                    command.Parameters.Add("doc", NpgsqlDbType.Json).Value = "{\"id\":\"2\"}";
                });
                 * */
                //runner.DescribeSchema();
                runner.SchemaFunctionNames().Each(x => Debug.WriteLine(x));
            }
        }
Esempio n. 3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ExecutionContext"/> class.
 /// </summary>
 /// <param name="io">The io.</param>
 /// <param name="command">The command.</param>
 /// <param name="runner">The runner.</param>
 /// <param name="arguments">The arguments.</param>
 public ExecutionContext(ConsoleUtility io, CommandResult command, CommandRunner runner, List<string> arguments)
 {
     IO = io;
     Command = command;
     Runner = runner;
     Arguments = arguments;
 }
Esempio n. 4
0
        private void Create(KeyRemapMode countKeyRemapMode, params string[] lines)
        {
            _textView = CreateTextView(lines);
            _vimTextBuffer = Vim.CreateVimTextBuffer(_textView.TextBuffer);
            _registerMap = Vim.RegisterMap;
            var vimBufferData = CreateVimBufferData(
                _vimTextBuffer,
                _textView);
            _commandUtil = CreateCommandUtil(vimBufferData);
            var incrementalSearch = new IncrementalSearch(
                vimBufferData,
                CommonOperationsFactory.GetCommonOperations(vimBufferData));
            var motionCapture = new MotionCapture(vimBufferData, incrementalSearch);

            _runnerRaw = new CommandRunner(
                _textView,
                _registerMap,
                motionCapture,
                vimBufferData.LocalSettings,
                _commandUtil,
                new StatusUtil(),
                VisualKind.Character,
                countKeyRemapMode);
            _runner = _runnerRaw;
        }
Esempio n. 5
0
 static void Main(string[] args)
 {
     var db = new CommandRunner("dvds");
       var salesOrder = new SalesOrder();
       salesOrder.Items.Add(new LineItem { SKU = "Ducky", Price = 12.00M, Name = "Little Duck Buddy" });
       var cmd = new Commands.Sales.SaveSalesOrder(db).Execute(salesOrder);
       Console.WriteLine(cmd);
       Console.Read();
 }
        public void Should_run_and_cleanup_disposable_command()
        {
            var command = Substitute.For<ICommand, IDisposable>();
            var runner = new CommandRunner(command);

            runner.RunCommand();

            command.Received().Execute();
            ((IDisposable)command).Received().Dispose();
        }
Esempio n. 7
0
        public HiLoSequence(CommandRunner runner, string entityName, HiloDef def)
        {
            _runner = runner;
            _entityName = entityName;

            CurrentHi = -1;
            CurrentLo = 1;
            MaxLo = def.MaxLo;
            Increment = def.Increment;
        }
Esempio n. 8
0
        public HiLoSequenceTests()
        {
            _container.GetInstance<DocumentCleaner>().CompletelyRemoveAll();

            var sql = SchemaBuilder.GetText("mt_hilo");

            _runner = _container.GetInstance<CommandRunner>();
            _runner.Execute(sql);

            theSequence = new HiLoSequence(_runner, "foo", new HiloDef());
        }
Esempio n. 9
0
        static void Main(string[] args)
        {
            var commandParser = new CommandParser();
            var command = commandParser.Parse();

            var moduleRunner = new ModuleRunner();
            moduleRunner.Execute(command);

            var commandRunner = new CommandRunner();
            commandRunner.Execute(command);
        }
        public void Given_Invalid_Command_Then_No_Robots_Returned()
        {
            // ARRANGE
            var command = "M E %£";

            // ACT
            var result = new CommandRunner().Run(command);

            // ASSERT
            Assert.AreEqual(0, result.Count);
        }
Esempio n. 11
0
        public static void CleanBasicDocuments()
        {
            var runner = new CommandRunner(new ConnectionSource());
                runner.Execute("DROP TABLE IF EXISTS {0} CASCADE;".ToFormat(SchemaBuilder.TableNameFor(typeof (User))));
                runner.Execute("DROP TABLE IF EXISTS {0} CASCADE;".ToFormat(SchemaBuilder.TableNameFor(typeof (Issue))));
                runner.Execute("DROP TABLE IF EXISTS {0} CASCADE;".ToFormat(SchemaBuilder.TableNameFor(typeof (Company))));
                runner.Execute("DROP TABLE IF EXISTS {0} CASCADE;".ToFormat(SchemaBuilder.TableNameFor(typeof (Target))));

                runner.Execute("DROP FUNCTION if exists {0}(docId UUID, doc JSON)".ToFormat(SchemaBuilder.UpsertNameFor(typeof(User))));
                runner.Execute("DROP FUNCTION if exists {0}(docId UUID, doc JSON)".ToFormat(SchemaBuilder.UpsertNameFor(typeof(Issue))));
                runner.Execute("DROP FUNCTION if exists {0}(docId UUID, doc JSON)".ToFormat(SchemaBuilder.UpsertNameFor(typeof(Company))));
                runner.Execute("DROP FUNCTION if exists {0}(docId UUID, doc JSON)".ToFormat(SchemaBuilder.UpsertNameFor(typeof(Target))));
        }
Esempio n. 12
0
        public void try_it_out()
        {
            var runner = new CommandRunner(new ConnectionSource());

            runner.Execute(conn =>
            {
                var table = conn.GetSchema("Tables");

                foreach (DataRow row in table.Rows)
                {
                    Debug.WriteLine("{0} / {1} / {2}", row[0], row[1], row[2]);
                }
            });
        }
Esempio n. 13
0
        public void RunnerTest(string commandLineArguments, ResultState expectedResultValidate, ResultState expectedResultRun, ParserNotation notation)
        {
            var configuration = new CommandConfiguration();
            configuration.CommandAssemblies.Add(Assembly.GetExecutingAssembly());
            var runner = new CommandRunner(new CommandParser(notation), new CommandLookup(configuration));
            var result1 = runner.Validate(commandLineArguments);
            var result2 = runner.Run(commandLineArguments);

            // Assert
            Assert.NotNull(result1);
            Assert.NotNull(result2);
            Assert.True(result1.State == expectedResultValidate);
            Assert.True(result2.State == expectedResultRun);
            Assert.NotNull(result1.CommandInfo);
        }
        public void Given_Valid_Input_For_One_Robot_Then_One_Robot_Returned_With_Correct_Position()
        {
            // ARRANGE
            var command = "5 5\n1 2 N\nLMLMLMLMM\n";

            // ACT
            var result = new CommandRunner().Run(command);

            // ASSERT
            Assert.AreEqual(1, result.Count);

            Assert.AreEqual(1, result[0].Position.XCoordinate);
            Assert.AreEqual(3, result[0].Position.YCoordinate);
            Assert.AreEqual(Orientation.North, result[0].Position.Orientation);
        }
Esempio n. 15
0
		static void Main(string[] args)
		{
			CommandRunner runner = new CommandRunner();
			
			WriteHeader();
			
			while(ContextFactory.ActiveContext.IsOpen)
			{
				runner.Reset();
				runner.ShowPrompt();
				runner.ParseInput();
				runner.Run();
				
				WriteBody();
			}
			
			WriteFooter();
		}
        public void builds_schema_objects_on_the_fly_as_needed()
        {
            _schema.StorageFor(typeof (User)).ShouldNotBeNull();
            _schema.StorageFor(typeof (Issue)).ShouldNotBeNull();
            _schema.StorageFor(typeof (Company)).ShouldNotBeNull();

            using (var runner = new CommandRunner(ConnectionSource.ConnectionString))
            {
                var tables = runner.SchemaTableNames();
                tables.ShouldContain(SchemaBuilder.TableNameFor(typeof(User)).ToLower());
                tables.ShouldContain(SchemaBuilder.TableNameFor(typeof(Issue)).ToLower());
                tables.ShouldContain(SchemaBuilder.TableNameFor(typeof(Company)).ToLower());

                var functions = runner.SchemaFunctionNames();
                functions.ShouldContain(SchemaBuilder.UpsertNameFor(typeof(User)).ToLower());
                functions.ShouldContain(SchemaBuilder.UpsertNameFor(typeof(Issue)).ToLower());
                functions.ShouldContain(SchemaBuilder.UpsertNameFor(typeof(Company)).ToLower());
            }
        }
        public void persist_a_single_document()
        {
            var user = new User {FirstName = "Magic", LastName = "Johnson"};

            theSession.Store(user);

            theSession.SaveChanges();

            var runner = new CommandRunner(new ConnectionSource());

            var json = runner.QueryScalar<string>("select data from mt_doc_user where id = '{0}'".ToFormat(user.Id));

            json.ShouldNotBeNull();

            var loadedUser = new JsonNetSerializer().FromJson<User>(json);

            user.ShouldNotBeSameAs(loadedUser);
            loadedUser.FirstName.ShouldBe(user.FirstName);
            loadedUser.LastName.ShouldBe(user.LastName);
        }
        public void Given_Valid_Input_For_Two_Robot_Then_Two_Robot_Returned_With_Correct_Positions()
        {
            // ARRANGE
            var command = "5 5\n1 2 N\nLMLMLMLMM\n3 3 E\nMMRMMRMRRM\n";

            // ACT
            var result = new CommandRunner().Run(command);

            // ASSERT
            Assert.AreEqual(2, result.Count);

            // First Robot..
            Assert.AreEqual(1, result[0].Position.XCoordinate);
            Assert.AreEqual(3, result[0].Position.YCoordinate);
            Assert.AreEqual(Orientation.North, result[0].Position.Orientation);

            // Second Robot..
            Assert.AreEqual(5, result[1].Position.XCoordinate);
            Assert.AreEqual(1, result[1].Position.YCoordinate);
            Assert.AreEqual(Orientation.East, result[1].Position.Orientation);
        }
Esempio n. 19
0
        private void Create2(
            ModeKind kind = ModeKind.VisualCharacter,
            params string[] lines)
        {
            _textView = CreateTextView(lines);
            _textBuffer = _textView.TextBuffer;
            var vimTextBuffer = Vim.CreateVimTextBuffer(_textBuffer);
            var vimBufferData = CreateVimBufferData(vimTextBuffer, _textView);
            var visualKind = VisualKind.OfModeKind(kind).Value;

            _selection = _textView.Selection;
            _factory = new MockRepository(MockBehavior.Strict);
            _tracker = _factory.Create<ISelectionTracker>();
            _tracker.Setup(x => x.Start());
            _tracker.Setup(x => x.UpdateSelection());
            _tracker.Setup(x => x.RecordCaretTrackingPoint(It.IsAny<ModeArgument>()));
            _tracker.SetupGet(x => x.IsRunning).Returns(true);
            _operations = _factory.Create<ICommonOperations>();
            _operations.SetupGet(x => x.TextView).Returns(_textView);
            _operations.Setup(x => x.MoveCaretToPoint(It.IsAny<SnapshotPoint>(), ViewFlags.Standard));
            _commandUtil = _factory.Create<ICommandUtil>();
            var motionUtil = new MotionUtil(vimBufferData, _operations.Object);
            var capture = new MotionCapture(vimBufferData, new IncrementalSearch(vimBufferData, _operations.Object));
            var runner = new CommandRunner(
                _textView,
                Vim.RegisterMap,
                capture,
                vimBufferData.LocalSettings,
                _commandUtil.Object,
                (new Mock<IStatusUtil>()).Object,
                VisualKind.Character,
                KeyRemapMode.Visual);
            _modeRaw = new VisualMode(vimBufferData, _operations.Object, motionUtil, visualKind, runner, capture, _tracker.Object);
            _mode = _modeRaw;
            _mode.OnEnter(ModeArgument.None);
        }
Esempio n. 20
0
        public void CreateCore(IMotionUtil motionUtil, params string[] lines)
        {
            _textView = CreateTextView(lines);
            _textView.Caret.MoveTo(new SnapshotPoint(_textView.TextSnapshot, 0));
            _unnamedRegister = Vim.RegisterMap.GetRegister(RegisterName.Unnamed);
            _factory = new MockRepository(MockBehavior.Strict);
            _incrementalSearch = MockObjectFactory.CreateIncrementalSearch(factory: _factory);
            _commandUtil = _factory.Create<ICommandUtil>();

            _globalSettings = Vim.GlobalSettings;

            var vimTextBuffer = Vim.CreateVimTextBuffer(_textView.TextBuffer);
            var vimBufferData = CreateVimBufferData(vimTextBuffer, _textView);
            var operations = CommonOperationsFactory.GetCommonOperations(vimBufferData);
            motionUtil = motionUtil ?? new MotionUtil(vimBufferData, operations);
            var lineChangeTracker = new LineChangeTracker(vimBufferData);

            var capture = new MotionCapture(vimBufferData, _incrementalSearch.Object);
            var runner = new CommandRunner(
                _textView,
                Vim.RegisterMap,
                capture,
                vimBufferData.LocalSettings,
                _commandUtil.Object,
                vimBufferData.StatusUtil,
                VisualKind.Character,
                KeyRemapMode.Normal);
            _modeRaw = new NormalMode(
                vimBufferData,
                operations,
                motionUtil,
                runner,
                capture);
            _mode = _modeRaw;
            _mode.OnEnter(ModeArgument.None);
        }
Esempio n. 21
0
    public async Task UrlsAsSnippetsLong()
    {
        await CommandRunner.RunCommand(Capture, "--urls-as-snippets", "url");

        await VerifyResult();
    }
Esempio n. 22
0
        public void CreateCore(IMotionUtil motionUtil, params string[] lines)
        {
            _textView = CreateTextView(lines);
            _textView.Caret.MoveTo(new SnapshotPoint(_textView.TextSnapshot, 0));
            _unnamedRegister = Vim.RegisterMap.GetRegister(RegisterName.Unnamed);
            _factory = new MockRepository(MockBehavior.Strict);
            _incrementalSearch = MockObjectFactory.CreateIncrementalSearch(factory: _factory);
            _commandUtil = _factory.Create<ICommandUtil>();
            _displayWindowBroker = _factory.Create<IDisplayWindowBroker>(MockBehavior.Strict);
            _displayWindowBroker.SetupGet(x => x.IsCompletionActive).Returns(false);
            _displayWindowBroker.SetupGet(x => x.IsSignatureHelpActive).Returns(false);
            _displayWindowBroker.SetupGet(x => x.IsSmartTagSessionActive).Returns(false);

            _globalSettings = Vim.GlobalSettings;

            var vimTextBuffer = Vim.CreateVimTextBuffer(_textView.TextBuffer);
            var vimBufferData = CreateVimBufferData(vimTextBuffer, _textView);
            var operations = CommonOperationsFactory.GetCommonOperations(vimBufferData);
            motionUtil = motionUtil ?? new MotionUtil(vimBufferData);

            var capture = new MotionCapture(vimBufferData, _incrementalSearch.Object);
            var runner = new CommandRunner(
                _textView,
                Vim.RegisterMap,
                capture,
                _commandUtil.Object,
                vimBufferData.StatusUtil,
                VisualKind.Character);
            _modeRaw = new NormalMode(
                vimBufferData,
                operations,
                motionUtil,
                _displayWindowBroker.Object,
                runner,
                capture);
            _mode = _modeRaw;
            _mode.OnEnter(ModeArgument.None);
        }
Esempio n. 23
0
 protected void runFubu(string commands)
 {
     var runner = new CommandRunner();
     commands.ReadLines(x =>
     {
         if (x.Trim().IsNotEmpty())
         {
             runner.RunFubu(x);
         }
     });
 }
Esempio n. 24
0
    public async Task LinkFormatShort()
    {
        await CommandRunner.RunCommand(Capture, "-l", "tfs");

        await VerifyResult();
    }
Esempio n. 25
0
    public async Task ReadOnlyShort()
    {
        await CommandRunner.RunCommand(Capture, "-r", "false");

        await VerifyResult();
    }
Esempio n. 26
0
    public async Task ValidateContentShort()
    {
        await CommandRunner.RunCommand(Capture, "-v", "false");

        await VerifyResult();
    }
Esempio n. 27
0
    public async Task UrlPrefix()
    {
        await CommandRunner.RunCommand(Capture, "--urlPrefix", "the prefix");

        await VerifyResult();
    }
Esempio n. 28
0
        public void InstallCommand_DownloadPackageWhenHashChanges()
        {
            var targetDir          = ConfigurationManager.AppSettings["TargetDir"];
            var nugetexe           = Path.Combine(targetDir, "nuget.exe");
            var tempPath           = Path.GetTempPath();
            var packageDirectory   = Path.Combine(tempPath, Guid.NewGuid().ToString());
            var workingDirectory   = Path.Combine(tempPath, Guid.NewGuid().ToString());
            var mockServerEndPoint = "http://localhost:1234/";

            try
            {
                // Arrange
                Util.CreateDirectory(packageDirectory);
                Util.CreateDirectory(workingDirectory);
                var packageFileName = Util.CreateTestPackage("testPackage1", "1.1.0", packageDirectory);
                var package         = new ZipPackage(packageFileName);
                MachineCache.Default.RemovePackage(package);

                // add the package to machine cache
                MachineCache.Default.AddPackage(package);

                // create a new package. Now this package has different hash value from the package in
                // the machine cache.
                packageFileName = Util.CreateTestPackage("testPackage1", "1.1.0", packageDirectory);
                package         = new ZipPackage(packageFileName);

                var    server = new MockServer(mockServerEndPoint);
                string findPackagesByIdRequest = string.Empty;
                bool   packageDownloadIsCalled = false;

                server.Get.Add("/nuget/FindPackagesById()", r =>
                               new Action <HttpListenerResponse>(response =>
                {
                    findPackagesByIdRequest = r.Url.ToString();
                    response.ContentType    = "application/atom+xml;type=feed;charset=utf-8";
                    string feed             = server.ToODataFeed(new[] { package }, "FindPackagesById");
                    MockServer.SetResponseContent(response, feed);
                }));

                server.Get.Add("/nuget/Packages(Id='testPackage1',Version='1.1.0')", r =>
                               new Action <HttpListenerResponse>(response =>
                {
                    response.ContentType = "application/atom+xml;type=entry;charset=utf-8";
                    var p1 = server.ToOData(package);
                    MockServer.SetResponseContent(response, p1);
                }));

                server.Get.Add("/package/testPackage1", r =>
                               new Action <HttpListenerResponse>(response =>
                {
                    packageDownloadIsCalled = true;
                    response.ContentType    = "application/zip";
                    using (var stream = package.GetStream())
                    {
                        var content = stream.ReadAllBytes();
                        MockServer.SetResponseContent(response, content);
                    }
                }));

                server.Get.Add("/nuget", r => "OK");

                server.Start();

                // Act
                var args = "install testPackage1 -Source " + mockServerEndPoint + "nuget";
                var r1   = CommandRunner.Run(
                    nugetexe,
                    workingDirectory,
                    args,
                    waitForExit: true);
                server.Stop();

                // Assert
                Assert.Equal(0, r1.Item1);
                Assert.Contains("$filter=IsLatestVersion", findPackagesByIdRequest);

                // verifies that package is downloaded from server since the cached version has
                // a different hash from the package on the server.
                Assert.True(packageDownloadIsCalled);
            }
            finally
            {
                // Cleanup
                Util.DeleteDirectory(packageDirectory);
                Util.DeleteDirectory(workingDirectory);
            }
        }
Esempio n. 29
0
        public void InstallCommand_NoOptOutMessage(string configFileName)
        {
            // Arrange
            var tempPath         = Path.GetTempPath();
            var workingPath      = Path.Combine(tempPath, Guid.NewGuid().ToString());
            var repositoryPath   = Path.Combine(workingPath, Guid.NewGuid().ToString());
            var proj1Directory   = Path.Combine(workingPath, "proj1");
            var currentDirectory = Directory.GetCurrentDirectory();
            var targetDir        = ConfigurationManager.AppSettings["TargetDir"];
            var nugetexe         = Path.Combine(targetDir, "nuget.exe");

            try
            {
                Util.CreateDirectory(workingPath);
                Util.CreateDirectory(repositoryPath);
                Util.CreateDirectory(proj1Directory);

                Util.CreateTestPackage("packageA", "1.1.0", repositoryPath);
                Util.CreateTestPackage("packageB", "2.2.0", repositoryPath);

                Util.CreateFile(workingPath, "my.config",
                                @"
<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
  <packageRestore>
    <add key=""enabled"" value=""True"" />
  </packageRestore>
</configuration>");

                Util.CreateFile(proj1Directory, "proj1.csproj",
                                @"<Project ToolsVersion='4.0' DefaultTargets='Build' 
    xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
  <PropertyGroup>
    <OutputType>Library</OutputType>
    <OutputPath>out</OutputPath>
    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
  </PropertyGroup>
  <ItemGroup>
    <None Include='packages.config' />
  </ItemGroup>
</Project>");
                Util.CreateFile(proj1Directory, configFileName,
                                @"<packages>
  <package id=""packageA"" version=""1.1.0"" targetFramework=""net45"" />
</packages>");
                // Act
                var r = CommandRunner.Run(
                    nugetexe,
                    proj1Directory,
                    "install " + configFileName + " -Source " + repositoryPath + @" -ConfigFile ..\my.config",
                    waitForExit: true);

                // Assert
                Assert.Equal(0, r.Item1);
                string optOutMessage = String.Format(
                    CultureInfo.CurrentCulture,
                    NuGetResources.RestoreCommandPackageRestoreOptOutMessage,
                    NuGet.Resources.NuGetResources.PackageRestoreConsentCheckBoxText.Replace("&", ""));
                Assert.DoesNotContain(optOutMessage, r.Item2);
            }
            finally
            {
                Directory.SetCurrentDirectory(currentDirectory);
                Util.DeleteDirectory(workingPath);
            }
        }
Esempio n. 30
0
 public void Create2(
     ModeKind kind = ModeKind.VisualCharacter,
     params string[] lines)
 {
     _textView = EditorUtil.CreateTextView(lines);
     _textBuffer = _textView.TextBuffer;
     _selection = _textView.Selection;
     _factory = new MockRepository(MockBehavior.Strict);
     _map = VimUtil.CreateRegisterMap(MockObjectFactory.CreateClipboardDevice(_factory).Object);
     _markMap = new MarkMap(new TrackingLineColumnService());
     _tracker = _factory.Create<ISelectionTracker>();
     _tracker.Setup(x => x.Start());
     _tracker.Setup(x => x.ResetCaret());
     _tracker.Setup(x => x.UpdateSelection());
     _jumpList = _factory.Create<IJumpList>(MockBehavior.Loose);
     _undoRedoOperations = _factory.Create<IUndoRedoOperations>();
     _foldManager = _factory.Create<IFoldManager>();
     _editorOperations = _factory.Create<IEditorOperations>();
     _operations = _factory.Create<ICommonOperations>();
     _operations.SetupGet(x => x.UndoRedoOperations).Returns(_undoRedoOperations.Object);
     _operations.SetupGet(x => x.EditorOperations).Returns(_editorOperations.Object);
     _operations.SetupGet(x => x.TextView).Returns(_textView);
     _host = _factory.Create<IVimHost>(MockBehavior.Loose);
     _commandUtil = _factory.Create<ICommandUtil>();
     _incrementalSearch = MockObjectFactory.CreateIncrementalSearch(factory: _factory);
     var globalSettings = new GlobalSettings();
     var localSettings = new LocalSettings(globalSettings, EditorUtil.GetEditorOptions(_textView), _textView);
     var motionUtil = VimUtil.CreateTextViewMotionUtil(
         _textView,
         _markMap,
         localSettings);
     _bufferData = MockObjectFactory.CreateVimBuffer(
         _textView,
         "test",
         MockObjectFactory.CreateVim(_map, host: _host.Object, settings: globalSettings).Object,
         incrementalSearch: _incrementalSearch.Object,
         jumpList: _jumpList.Object,
         motionUtil: motionUtil);
     var capture = new MotionCapture(
         _host.Object,
         _textView,
         _incrementalSearch.Object,
         localSettings);
     var runner = new CommandRunner(
         _textView,
         _map,
         capture,
         _commandUtil.Object,
         (new Mock<IStatusUtil>()).Object,
         VisualKind.Character);
     _modeRaw = new VisualMode(_bufferData.Object, _operations.Object, kind, runner, capture, _tracker.Object);
     _mode = _modeRaw;
     _mode.OnEnter(ModeArgument.None);
 }
        public CreatePackageCommandFixture(CommandRunner runner)
        {
            Title = "Create Package Command";

            _runner = runner;
        }
Esempio n. 32
0
        public void CreateCore(IMotionUtil motionUtil, params string[] lines)
        {
            _textView = EditorUtil.CreateTextView(lines);
            _textView.Caret.MoveTo(new SnapshotPoint(_textView.TextSnapshot, 0));
            _map = VimUtil.CreateRegisterMap(MockObjectFactory.CreateClipboardDevice().Object);
            _unnamedRegister = _map.GetRegister(RegisterName.Unnamed);
            _factory = new MockRepository(MockBehavior.Strict);
            _editorOperations = _factory.Create<IEditorOperations>(MockBehavior.Loose);
            _incrementalSearch = MockObjectFactory.CreateIncrementalSearch(factory: _factory);
            _jumpList = _factory.Create<IJumpList>(MockBehavior.Strict);
            _statusUtil = _factory.Create<IStatusUtil>(MockBehavior.Strict);
            _foldManager = _factory.Create<IFoldManager>(MockBehavior.Strict);
            _host = _factory.Create<IVimHost>(MockBehavior.Loose);
            _commandUtil = _factory.Create<ICommandUtil>();
            _displayWindowBroker = _factory.Create<IDisplayWindowBroker>(MockBehavior.Strict);
            _displayWindowBroker.SetupGet(x => x.IsCompletionActive).Returns(false);
            _displayWindowBroker.SetupGet(x => x.IsSignatureHelpActive).Returns(false);
            _displayWindowBroker.SetupGet(x => x.IsSmartTagSessionActive).Returns(false);
            _vimData = new VimData();

            _globalSettings = new Vim.GlobalSettings();
            _localSettings = new LocalSettings(_globalSettings, EditorUtil.GetEditorOptions(_textView), _textView);
            motionUtil = motionUtil ?? VimUtil.CreateTextViewMotionUtil(
                _textView,
                new MarkMap(new TrackingLineColumnService()),
                _localSettings);
            _buffer = MockObjectFactory.CreateVimBuffer(
                _textView,
                "test",
                MockObjectFactory.CreateVim(_map, host: _host.Object, vimData: _vimData).Object,
                _jumpList.Object,
                incrementalSearch: _incrementalSearch.Object,
                motionUtil: motionUtil,
                settings: _localSettings);
            _operations = _factory.Create<ICommonOperations>(MockBehavior.Strict);
            _operations.SetupGet(x => x.EditorOperations).Returns(_editorOperations.Object);
            _operations.SetupGet(x => x.TextView).Returns(_textView);

            var capture = new MotionCapture(
                _host.Object,
                _textView,
                _incrementalSearch.Object,
                new LocalSettings(new GlobalSettings(), EditorUtil.GetEditorOptions(_textView), _textView));
            var runner = new CommandRunner(_textView, _map, capture, _commandUtil.Object, _statusUtil.Object, VisualKind.Character);
            _modeRaw = new NormalMode(
                _buffer.Object,
                _operations.Object,
                _statusUtil.Object,
                _displayWindowBroker.Object,
                runner,
                capture);
            _mode = _modeRaw;
            _mode.OnEnter(ModeArgument.None);
        }
Esempio n. 33
0
    public async Task SingleUnNamedArg()
    {
        await CommandRunner.RunCommand(Capture, "dir");

        await VerifyResult();
    }
Esempio n. 34
0
 public void ExcludeDuplicates()
 {
     Assert.Throws <CommandLineException>(() => CommandRunner.RunCommand(Capture, "-e", "dir:dir"));
 }
Esempio n. 35
0
    public async Task Header()
    {
        await CommandRunner.RunCommand(Capture, "--header", "the header");

        await VerifyResult();
    }
Esempio n. 36
0
 public void ExcludeWhitespace()
 {
     Assert.Throws <CommandLineException>(() => CommandRunner.RunCommand(Capture, "-e", ": :"));
 }
Esempio n. 37
0
    public async Task WriteHeader()
    {
        await CommandRunner.RunCommand(Capture, "--write-header", "false");

        await VerifyResult();
    }
Esempio n. 38
0
 public Task UrlsAsSnippetsShort()
 {
     CommandRunner.RunCommand(Capture, "-u", "url");
     return(VerifyResult());
 }
Esempio n. 39
0
    public async Task ValidateContentLong()
    {
        await CommandRunner.RunCommand(Capture, "--validate-content", "false");

        await VerifyResult();
    }
Esempio n. 40
0
 public SequenceFactory(IDocumentSchema schema, CommandRunner runner, IDocumentSchemaCreation creation)
 {
     _schema = schema;
     _runner = runner;
     _creation = creation;
 }
Esempio n. 41
0
    public async Task ReadOnlyLong()
    {
        await CommandRunner.RunCommand(Capture, "--readonly", "false");

        await VerifyResult();
    }
Esempio n. 42
0
            /// <summary>
            ///     Starts a new instance of this process unconditionally (regardless of whether one is already running). See
            ///     also <see cref="SetRunning"/>. Verifies that the executable exists and logs an error if not. Pauses for a
            ///     configurable interval before starting the process to allow the script to be interrupted if desired (see
            ///     <see cref="WaitBeforeAction"/>). To verify that the process didn't exit a few seconds later, see <see
            ///     cref="Logmeon.CheckStarted"/>. Chainable.</summary>
            public Process Run()
            {
                var args = _startCommand ?? Args;

                if (!File.Exists(args[0]))
                {
                    WriteLineColored($"{{green}}{Name}{{}}: {{red}}file not found: {{}}{{yellow}}{args[0]}{{}}");
                    Logmeon.AnyFailures = true;
                    return(this);
                }
                WriteColored($"{{green}}{Name}{{}}: starting process in {_waitBeforeAction.TotalSeconds:0} seconds... ");
                Thread.Sleep(_waitBeforeAction);

                int processId;

                try
                {
                    var hToken        = IntPtr.Zero;
                    var pi            = new WinAPI.PROCESS_INFORMATION();
                    var hShellProcess = IntPtr.Zero;
                    var hShellToken   = IntPtr.Zero;
                    try
                    {
                        var si = new WinAPI.STARTUPINFO();
                        si.cb = Marshal.SizeOf(si);
                        var processAttributes = new WinAPI.SECURITY_ATTRIBUTES();
                        var threadAttributes  = new WinAPI.SECURITY_ATTRIBUTES();

                        if (_elevated)
                        {
                            WriteColored($"starting elevated... ");
                            if (!WinAPI.CreateProcess(null, CommandRunner.ArgsToCommandLine(args), ref processAttributes, ref threadAttributes, false, 0, IntPtr.Zero, WorkDir, ref si, out pi))
                            {
                                throw new Win32Exception();
                            }
                        }
                        else
                        {
                            WriteColored($"starting... ");
                            var shellWnd = WinAPI.GetShellWindow();
                            if (shellWnd == IntPtr.Zero)
                            {
                                throw new Exception("Could not find shell window");
                            }

                            uint shellProcessId;
                            WinAPI.GetWindowThreadProcessId(shellWnd, out shellProcessId);

                            hShellProcess = WinAPI.OpenProcess(0x00000400 /* QueryInformation */, false, shellProcessId);

                            if (!WinAPI.OpenProcessToken(hShellProcess, 2 /* TOKEN_DUPLICATE */, out hShellToken))
                            {
                                throw new Win32Exception();
                            }

                            uint tokenAccess = 8 /*TOKEN_QUERY*/ | 1 /*TOKEN_ASSIGN_PRIMARY*/ | 2 /*TOKEN_DUPLICATE*/ | 0x80 /*TOKEN_ADJUST_DEFAULT*/ | 0x100 /*TOKEN_ADJUST_SESSIONID*/;
                            WinAPI.DuplicateTokenEx(hShellToken, tokenAccess, IntPtr.Zero, 2 /* SecurityImpersonation */, 1 /* TokenPrimary */, out hToken);

                            if (!WinAPI.CreateProcessWithTokenW(hToken, 0, null, CommandRunner.ArgsToCommandLine(args), 0, IntPtr.Zero, WorkDir, ref si, out pi))
                            {
                                throw new Win32Exception();
                            }
                        }
                        processId = pi.dwProcessId;
                    }
                    finally
                    {
                        if (hToken != IntPtr.Zero && !WinAPI.CloseHandle(hToken))
                        {
                            throw new Win32Exception();
                        }
                        if (hShellToken != IntPtr.Zero && !WinAPI.CloseHandle(hShellToken))
                        {
                            throw new Win32Exception();
                        }
                        if (hShellProcess != IntPtr.Zero && !WinAPI.CloseHandle(hShellProcess))
                        {
                            throw new Win32Exception();
                        }
                        if (pi.hProcess != IntPtr.Zero && !WinAPI.CloseHandle(pi.hProcess))
                        {
                            throw new Win32Exception();
                        }
                        if (pi.hThread != IntPtr.Zero && !WinAPI.CloseHandle(pi.hThread))
                        {
                            throw new Win32Exception();
                        }
                    }
                }
                catch (Exception e)
                {
                    WriteLineColored($"{{green}}{Name}{{}}: {{red}}ERROR while starting process: {e.Message}{{}}");
                    AnyFailures = true;
                    return(this);
                }

                WriteLineColored($"done, ID={processId}.");
                _startedProcesses.Add(this);
                StartedAt = DateTime.UtcNow;
                return(this);
            }
Esempio n. 43
0
    public async Task LinkFormatLong()
    {
        await CommandRunner.RunCommand(Capture, "--link-format", "tfs");

        await VerifyResult();
    }
Esempio n. 44
0
            public CommandResult ExecuteCommand(IEnumerable<string> arguments, string stdin)
            {
                var runner = new CommandRunner();
                var command = new Command(ToolPath, arguments)
                {
                    Input = new MemoryStream(Encoding.UTF8.GetBytes(stdin))
                };

                return runner.Run(command);
            }
Esempio n. 45
0
        public void PushCommand_Server_ContinueOn_Duplicate_PushProceeds()
        {
            // Arrange
            using (var packageDirectory = TestDirectory.Create())
            {
                var nuget      = Util.GetNuGetExePath();
                var sourcePath = Util.CreateTestPackage("PackageA", "1.1.0", packageDirectory);
                var outputPath = Path.Combine(packageDirectory, "pushed.nupkg");

                var sourcePath2 = Util.CreateTestPackage("PackageB", "1.1.0", packageDirectory);
                var outputPath2 = Path.Combine(packageDirectory, "pushed2.nupkg");

                using (var server = new MockServer())
                {
                    SetupMockServerForContinueOnError(server,
                                                      FuncOutputPath_SwitchesOnThirdPush(outputPath, outputPath2),
                                                      FuncStatusDuplicate_OccursOnSecondPush());

                    server.Start();

                    // Act
                    var result = CommandRunner.Run(
                        nuget,
                        packageDirectory,
                        $"push {sourcePath} -Source {server.Uri}push -Timeout 110 -SkipDuplicate",
                        waitForExit: true,
                        timeOutInMilliseconds: 120 * 1000); // 120 seconds

                    //Run again so that it will be a duplicate push but use the option to continue on errors.
                    var result2 = CommandRunner.Run(
                        nuget,
                        packageDirectory,
                        $"push {sourcePath} -Source {server.Uri}push -Timeout 110 -SkipDuplicate",
                        waitForExit: true,
                        timeOutInMilliseconds: 120 * 1000); // 120 seconds

                    //Third run with a different package.
                    var result3 = CommandRunner.Run(
                        nuget,
                        packageDirectory,
                        $"push {sourcePath2} -Source {server.Uri}push -Timeout 110 -SkipDuplicate",
                        waitForExit: true,
                        timeOutInMilliseconds: 120 * 1000); // 120 seconds

                    // Assert
                    server.Stop();
                    Assert.True(0 == result.Item1, $"{result.Item2} {result.Item3}");
                    Assert.Contains(MESSAGE_PACKAGE_PUSHED, result.AllOutput);
                    Assert.True(File.Exists(outputPath), TEST_PACKAGE_SHOULD_PUSH);
                    Assert.DoesNotContain(MESSAGE_RESPONSE_NO_SUCCESS, result.AllOutput);
                    Assert.Equal(File.ReadAllBytes(sourcePath), File.ReadAllBytes(outputPath));

                    // Second run of command is the duplicate.
                    Assert.True(0 == result2.Item1, result2.AllOutput);
                    Assert.DoesNotContain(MESSAGE_PACKAGE_PUSHED, result2.AllOutput);
                    Assert.Contains(MESSAGE_EXISTING_PACKAGE, result2.AllOutput);
                    Assert.DoesNotContain(MESSAGE_RESPONSE_NO_SUCCESS, result2.AllOutput);

                    // Third run after a duplicate should be successful with the ContinueOnError flag.
                    Assert.True(0 == result3.Item1, $"{result3.Item2} {result3.Item3}");
                    Assert.Contains(MESSAGE_PACKAGE_PUSHED, result3.AllOutput);
                    Assert.True(File.Exists(outputPath2), TEST_PACKAGE_SHOULD_PUSH);

                    Assert.Equal(File.ReadAllBytes(sourcePath2), File.ReadAllBytes(outputPath2));
                }
            }
        }
Esempio n. 46
0
 public Task UrlsAsSnippetsDuplicates()
 {
     return(Assert.ThrowsAsync <CommandLineException>(() => CommandRunner.RunCommand(Capture, "-u", "url url")));
 }
Esempio n. 47
0
 public DocumentSchema(IConnectionFactory connections, IDocumentSchemaCreation creation)
 {
     _creation = creation;
     _runner = new CommandRunner(connections);
 }
Esempio n. 48
0
 public Task UrlsAsSnippetsWhitespace()
 {
     return(Assert.ThrowsAsync <CommandLineException>(() => CommandRunner.RunCommand(Capture, "-u", ": :")));
 }
Esempio n. 49
0
		public PoshHost(IPSUI psUi)
		{
			_buffer = psUi.Console;
			_tabExpander = new TabExpander(this);

			MakeConsole();

			Options = new PoshOptions(this, _buffer);
			_psUi = psUi;

			try
			{
				// we have to be careful here, because this is an interface member ...
				// but in the current implementation, _buffer.RawUI returns _buffer
				_rawUI = new PoshRawUI(_buffer.RawUI);
				_UI = new PoshUI(_rawUI, psUi);

				// pre-create this
				_outDefault = new Command("Out-Default");
				// for now, merge the errors with the rest of the output
				_outDefault.MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
				_outDefault.MergeUnclaimedPreviousCommandResults = PipelineResultTypes.Error | PipelineResultTypes.Output;
			}
			catch (Exception ex)
			{
				MessageBox.Show(
					"Can't create PowerShell interface, are you sure PowerShell is installed? \n" + ex.Message + "\nAt:\n" +
						ex.Source, "Error Starting PoshConsole", MessageBoxButton.OK, MessageBoxImage.Stop);
				throw;
			}
			_buffer.CommandBox.IsEnabled = false;
			_buffer.Expander.TabComplete += _tabExpander.Expand;
			_buffer.Command += OnGotUserInput;

			// Some delegates we think we can get away with making only once...
			Properties.Settings.Default.PropertyChanged += SettingsPropertyChanged;

			_runner = new CommandRunner(this, Resources.Prompt);
			_runner.RunspaceReady += (source, args) => _buffer.Dispatcher.BeginInvoke((Action) (() =>
				{
					_buffer.CommandBox.IsEnabled = true;
					ExecutePromptFunction(null, PipelineState.Completed);
				}));

			_runner.ShouldExit += (source, args) => SetShouldExit(args);
		}
Esempio n. 50
0
 public DevelopmentSchemaCreation(IConnectionFactory factory)
 {
     _runner = new CommandRunner(factory);
 }
Esempio n. 51
0
        public void InstallCommand_WithVersionSpecified()
        {
            var targetDir          = ConfigurationManager.AppSettings["TargetDir"];
            var nugetexe           = Path.Combine(targetDir, "nuget.exe");
            var tempPath           = Path.GetTempPath();
            var workingDirectory   = Path.Combine(tempPath, Guid.NewGuid().ToString());
            var packageDirectory   = Path.Combine(tempPath, Guid.NewGuid().ToString());
            var mockServerEndPoint = "http://localhost:1234/";

            try
            {
                // Arrange
                Util.CreateDirectory(packageDirectory);
                Util.CreateDirectory(workingDirectory);
                var packageFileName = Util.CreateTestPackage("testPackage1", "1.1.0", packageDirectory);
                var package         = new ZipPackage(packageFileName);
                MachineCache.Default.RemovePackage(package);

                var  server = new MockServer(mockServerEndPoint);
                bool getPackageByVersionIsCalled = false;
                bool packageDownloadIsCalled     = false;

                server.Get.Add("/nuget/Packages(Id='testPackage1',Version='1.1.0')", r =>
                               new Action <HttpListenerResponse>(response =>
                {
                    getPackageByVersionIsCalled = true;
                    response.ContentType        = "application/atom+xml;type=entry;charset=utf-8";
                    var p1 = server.ToOData(package);
                    MockServer.SetResponseContent(response, p1);
                }));

                server.Get.Add("/package/testPackage1", r =>
                               new Action <HttpListenerResponse>(response =>
                {
                    packageDownloadIsCalled = true;
                    response.ContentType    = "application/zip";
                    using (var stream = package.GetStream())
                    {
                        var content = stream.ReadAllBytes();
                        MockServer.SetResponseContent(response, content);
                    }
                }));

                server.Get.Add("/nuget", r => "OK");

                server.Start();

                // Act
                var args = "install testPackage1 -Version 1.1.0 -Source " + mockServerEndPoint + "nuget";
                var r1   = CommandRunner.Run(
                    nugetexe,
                    workingDirectory,
                    args,
                    waitForExit: true);
                server.Stop();

                // Assert
                Assert.Equal(0, r1.Item1);
                Assert.True(getPackageByVersionIsCalled);
                Assert.True(packageDownloadIsCalled);
            }
            finally
            {
                // Cleanup
                Util.DeleteDirectory(packageDirectory);
                Util.DeleteDirectory(workingDirectory);
            }
        }
Esempio n. 52
0
 public Task ExcludeDuplicates()
 {
     return(Assert.ThrowsAsync <CommandLineException>(() => CommandRunner.RunCommand(Capture, "-e", "dir:dir")));
 }
Esempio n. 53
0
 public Task ExcludeMultiple()
 {
     CommandRunner.RunCommand(Capture, "-e", "dir1:dir2");
     return(VerifyResult());
 }
Esempio n. 54
0
 public Task ExcludeWhitespace()
 {
     return(Assert.ThrowsAsync <CommandLineException>(() => CommandRunner.RunCommand(Capture, "-e", ": :")));
 }
Esempio n. 55
0
 public Task Empty()
 {
     CommandRunner.RunCommand(Capture);
     return(VerifyResult());
 }
Esempio n. 56
0
    public async Task ExcludeLong()
    {
        await CommandRunner.RunCommand(Capture, "--exclude", "dir");

        await VerifyResult();
    }
Esempio n. 57
0
 public Task ExcludeLong()
 {
     CommandRunner.RunCommand(Capture, "--exclude", "dir");
     return(VerifyResult());
 }
Esempio n. 58
0
    public async Task UrlsAsSnippetsShort()
    {
        await CommandRunner.RunCommand(Capture, "-u", "url");

        await VerifyResult();
    }
Esempio n. 59
0
 public void UrlsAsSnippetsMultiple()
 {
     CommandRunner.RunCommand(Capture, "-u", "url1 url2");
     VerifyResult();
 }
Esempio n. 60
0
    public async Task UrlsAsSnippetsMultiple()
    {
        await CommandRunner.RunCommand(Capture, "-u", "url1 url2");

        await VerifyResult();
    }