Example #1
0
 public function testShouldNotClearScreenInNotInteractiveMode()
 {
     $SUT = $this->createSUT();
     $this->input->setInteractive(false);
     $SUT->cls();
     $this->assertEquals('', $this->output->fetch());
 }
Example #2
0
 /**
  * {@inheritdoc}
  */
 public function serialize(ReportComposerInterface $report)
 {
     $this->output->writeln($this->getHeader($report));
     $rows = $report->getReportHeader()->getRows();
     $this->printBody($rows);
     $this->output->writeln($this->getFooter($report));
     return $this->output->fetch();
 }
 /**
  * @medium
  */
 public function testPlaintextReportIsCorrectlyGenerated()
 {
     $file1 = new File('foobar.tys');
     $file1->addWarning(new Warning(123, 12, 'Message #1', Warning::SEVERITY_INFO, 'foobar'));
     $file1->addWarning(new Warning(124, NULL, 'Message #2', Warning::SEVERITY_WARNING, 'foobar'));
     $file2 = new File('bar.txt');
     $file2->addWarning(new Warning(412, 141, 'Message #3', Warning::SEVERITY_ERROR, 'barbaz'));
     $report = new Report();
     $report->addFile($file1);
     $report->addFile($file2);
     $this->printer->writeReport($report);
     $this->assertEquals(self::EXPECTED_XML_DOCUMENT, $this->output->fetch());
 }
 /**
  * Check that we have a correct CLI executable of PHP.
  *
  * @return void
  */
 public function doTest()
 {
     $this->setMessage('Check if a valid PHP CLI executable is available.');
     $this->log = new BufferedOutput();
     // Prefer compile time configuration over path environment.
     if ($this->isBinaryAvailableFromConstants()) {
         return;
     }
     if ($this->isBinaryAvailableInPath()) {
         return;
     }
     $this->markFailed('Could not find any PHP CLI executable, running tenside tasks will not work. ' . $this->log->fetch());
 }
Example #5
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $watch = $input->getOption('watch');
     $buffered = new BufferedOutput($output->getVerbosity(), $output->isDecorated());
     $service = new StatsService($this->getBeanstalk());
     do {
         $tubes = $service->getAllTubeStats();
         if (empty($tubes)) {
             $output->writeln('No tubes found.');
             return;
         }
         $table = new Table($buffered);
         $table->setHeaders($service->getTubeHeaderMapping());
         foreach ($tubes as $stats) {
             if ($stats['current-jobs-buried'] > 0) {
                 $stats['name'] = "<error>{$stats['name']}</error>";
                 $stats['current-jobs-buried'] = "<error>{$stats['current-jobs-buried']}</error>";
             }
             $table->addRow($stats);
         }
         $table->render();
         $clearScreen = $watch ? "" : '';
         $output->write($clearScreen . $buffered->fetch());
         $watch && sleep(1);
     } while ($watch);
 }
 public function testQuietLogDebug()
 {
     $bufferedOutput = new BufferedOutput(OutputInterface::VERBOSITY_VERY_VERBOSE);
     $installOutput = new InstallOutput(new ConsoleLogger($bufferedOutput));
     $installOutput->debug('Testing log');
     $this->assertEmpty($bufferedOutput->fetch());
 }
Example #7
0
 /**
  * @return Response
  * @Route("/swagger.yml", name="swagger", methods="GET")
  */
 public function dump() : Response
 {
     $output = new BufferedOutput();
     $event = new ConsoleEvent('swagger:dump', $output);
     $this->dispatchEvent($event);
     return new Response($output->fetch(), 200, ['Content-Type' => 'text/x-yaml']);
 }
Example #8
0
 /**
  * @dataProvider provideOutputMappingParams
  */
 public function testOutputMapping($logLevel, $outputVerbosity, $isOutput, $addVerbosityLevelMap = array())
 {
     $out = new BufferedOutput($outputVerbosity);
     $logger = new ConsoleLogger($out, $addVerbosityLevelMap);
     $logger->log($logLevel, 'foo bar');
     $logs = $out->fetch();
     $this->assertEquals($isOutput ? "[{$logLevel}] foo bar\n" : '', $logs);
 }
Example #9
0
 public function testOutputFormatting()
 {
     $console = new ConsoleApplication();
     $console->add($command = new FooCommand());
     $command->run(new ArrayInput(array('')), $output = new BufferedOutput());
     $output->setFormatter(new RawOutputFormatter());
     $command->line('foo');
     $this->assertEquals('foo', rtrim($output->fetch()));
     $command->info('foo');
     $this->assertEquals('<info>foo</info>', rtrim($output->fetch()));
     $command->comment('foo');
     $this->assertEquals('<comment>foo</comment>', rtrim($output->fetch()));
     $command->question('foo');
     $this->assertEquals('<question>foo</question>', rtrim($output->fetch()));
     $command->error('foo');
     $this->assertEquals('<error>foo</error>', rtrim($output->fetch()));
 }
 public function testAllowFailingCommand()
 {
     $output = new BufferedOutput();
     $executor = new ProcessExecutor($output, 60);
     $expectedOutput = "ls: cannot access '/no-such-file': No such file or directory\n";
     $exitCode = $executor->execute('LC_ALL=C ls /no-such-file', null, true);
     $this->assertEquals(2, $exitCode);
     $this->assertEquals($expectedOutput, $output->fetch());
 }
 /**
  * Test that the execution is successful.
  *
  * @return void
  */
 public function testExecution()
 {
     $project = $this->getMockBuilder('CyberSpectrum\\PharPiler\\Project')->disableOriginalConstructor()->getMock();
     $task = new RunCommandTask(['command' => 'echo "hello world"', 'working_dir' => getcwd(), 'timeout' => null]);
     $task->setLogger(new ConsoleLogger($output = new BufferedOutput()));
     $output->setVerbosity(BufferedOutput::VERBOSITY_DEBUG);
     $task->execute($project);
     $this->assertEquals('[info] echo "hello world": hello world' . "\n" . '[info] echo "hello world": ' . "\n", $output->fetch());
 }
Example #12
0
 /**
  * Check that we have a correct CLI executable of PHP.
  *
  * @return void
  */
 public function doTest()
 {
     $this->setMessage('Check which arguments to pass to the PHP CLI executable.');
     if (!$this->hasInterpreter()) {
         $this->markFailed('No PHP interpreter detected, can not test.');
         return;
     }
     $this->log = new BufferedOutput();
     if ($this->check()) {
         $data = $this->log->fetch();
         if (empty($data)) {
             $data = 'No special arguments needed.';
         }
         $this->markSuccess($data);
         return;
     }
     $this->markWarning('Could not determine command line arguments, leaving unconfigured and hope the best.');
 }
Example #13
0
 /**
  * @param array $args
  * @return string output
  */
 protected function runCommand(array $args)
 {
     $app = new Application(static::$kernel);
     $app->setAutoExit(false);
     // run application prepending application name
     $code = $app->run(new ArgvInput(array_merge(['cli.php'], $args)), $out = new BufferedOutput());
     $output = $out->fetch();
     $this->assertEquals(0, $code, sprintf('The command "%s" was failed. (code: %d) %s', implode(' ', $args), $code, $output));
     return $output;
 }
Example #14
0
 public function testEmit()
 {
     $output = new BufferedOutput();
     $emitter = new ConsoleEmitter($output);
     $response = new TextResponse('The Test');
     $emitter->emit($response);
     $result = $output->fetch();
     $this->assertContains('200', $result);
     $this->assertContains('text/plain', $result);
     $this->assertContains('The Test', $result);
 }
Example #15
0
 /**
  * @dataProvider inputProvider
  * @param string $stringInput
  * @param string $expectedIdeKey
  */
 public function testShouldGetIdeKeyFromCommandOptionOnCommandInitialization($stringInput, $expectedIdeKey)
 {
     $this->mockXdebugExtension($isExtensionLoaded = true, $isRemoteEnabled = true);
     $command = new RunCommand(new EventDispatcher());
     $input = new StringInput($stringInput);
     $output = new BufferedOutput();
     $output->setVerbosity(OutputInterface::VERBOSITY_DEBUG);
     // Trigger event to add the xdebug option to the command and bind the definition to the input
     $this->listener->onCommandConfigure(new BasicConsoleEvent($command));
     $input->bind($command->getDefinition());
     // Trigger command initialization event
     $event = new ExtendedConsoleEvent($command, $input, $output);
     $this->listener->onCommandRunTestsInit($event);
     if ($expectedIdeKey !== null) {
         $this->assertContains('Xdebug remote debugging initialized with IDE key: ' . $expectedIdeKey, $output->fetch());
     } else {
         // no output expected (xdebug not triggered)
         $this->assertEmpty($output->fetch());
     }
 }
 public function testShouldPassFilterOptionToPhpunitProcess()
 {
     $processSet = $this->creator->createFromFiles($this->findDummyTests(), [], [], 'testCase::testName');
     $processes = $processSet->get(ProcessSet::PROCESS_STATUS_QUEUED);
     /** @var Process $dummyTestProcess */
     $dummyTestProcess = $processes[self::NAME_DUMMY_TEST]->process;
     $testCommand = $dummyTestProcess->getCommandLine();
     $output = $this->bufferedOutput->fetch();
     $this->assertContains('Filtering testcases:', $output);
     $this->assertContains('by testcase/test name: testCase::testName', $output);
     $this->assertContains('--filter=testCase::testName', $testCommand);
 }
Example #17
0
 public function testRightColumnsHeadersNamesAfterItemConverter()
 {
     $data = array(array('first' => 'John', 'lastname' => 'Doe'), array('first' => 'Ivan', 'lastname' => 'Sidorov'));
     $reader = new ArrayReader($data);
     $converter = new MappingItemConverter();
     $converter->addMapping('first', 'firstname');
     $output = new BufferedOutput();
     $table = new Table($output);
     $table->setStyle('compact');
     $workflow = new Workflow($reader);
     $workflow->addItemConverter($converter)->addWriter(new ConsoleTableWriter($output, $table))->process();
     $this->assertRegExp('/\\s+lastname\\s+firstname\\s+Doe\\s+John\\s+Sidorov\\s+Ivan\\s+/', $output->fetch());
 }
 public function helpAction()
 {
     $model = $this->getModel();
     $requestCommand = $this->getRequest()->get('command');
     $cli = $this->getCliApplication();
     $command = $cli->get($requestCommand);
     $model['definition'] = $command->getDefinition();
     $input = new ArrayInput(array(sprintf("help %s", $requestCommand)));
     $output = new BufferedOutput();
     // $cli->run($input, $output);
     $model['output'] = $output->fetch();
     return $this->render('SKITCBundle:Console:help.html.twig', $model);
 }
Example #19
0
 /**
  * @param JobStats[]|ArrayCollection $statsList
  * @return string
  */
 private function renderStats($statsList)
 {
     $buffer = new BufferedOutput();
     $buffer->setDecorated(true);
     $width = $this->getConsoleWidth();
     $table = $width ? new AutoHidingTable($buffer, $width) : new Table($buffer);
     $table->setHeaders(array('ID', 'Tube', 'State', '# Reserves', '# Releases', '# Buries', '# Kicks', 'Priority', 'Time left (secs)', '# Timeouts', 'Age (secs)', 'File'));
     foreach ($statsList as $stats) {
         $table->addRow(array($stats->id(), $stats->tube(), $stats->state(), $stats->reserves(), $stats->releases(), $stats->buries(), $stats->kicks(), $stats->priority(), in_array($stats->state(), array('reserved', 'delayed')) ? $stats->timeLeft() : 'N/A', $stats->timeouts(), $stats->age(), $stats->file() === 0 ? 'N/A' : $stats->file()));
     }
     $table->render();
     return $buffer->fetch();
 }
Example #20
0
 /**
  * @param WorkerInfo[]|ArrayCollection $workers
  * @return string
  */
 protected function renderStats($workers)
 {
     $buffer = new BufferedOutput();
     $buffer->setDecorated(true);
     $width = $this->getConsoleWidth();
     $table = $width ? new AutoHidingTable($buffer, $width) : new Table($buffer);
     $table->setHeaders(array('Worker', 'Running', 'Total', 'PIDs'));
     foreach ($workers as $worker) {
         $table->addRow(array($worker->getName(), $worker->getNumRunning(), $worker->getTotal(), $worker->getPids()->join(', ')));
     }
     $table->render();
     return $buffer->fetch();
 }
 /**
  * @inheritdoc
  */
 function format($result)
 {
     $out = new BufferedOutput();
     $table = new Table($out);
     $rows = array();
     $headers = array('Function description', 'Execution time (s)', 'Memory usage (mb)', 'Times faster');
     foreach ($result->getResults() as $result) {
         $rows[] = array($result->getDescription(), $result->getTime(), $result->getMemUsage(), $result->getTimesFaster());
     }
     $table->setHeaders($headers);
     $table->setRows($rows);
     $table->render();
     return $out->fetch();
 }
 /**
  * Run composer command
  *
  * @param array $commandParams
  * @return bool
  * @throws \RuntimeException
  */
 protected function runComposerCommand(array $commandParams)
 {
     $input = $this->consoleArrayInputFactory->create($commandParams);
     $this->consoleApplication->setAutoExit(false);
     putenv('COMPOSER_HOME=' . $this->composerConfigFileDir . '/' . self::COMPOSER_HOME_DIR);
     putenv('COMPOSER=' . $this->composerConfigFileDir . '/composer.json');
     $exitCode = $this->consoleApplication->run($input, $this->consoleOutput);
     $output = $this->consoleOutput->fetch();
     if ($exitCode) {
         $commandParamsString = json_encode($commandParams, JSON_UNESCAPED_SLASHES);
         throw new \RuntimeException(sprintf('Command "%s"%s failed: %s', $commandParams['command'], $commandParamsString, $output));
     }
     return $output;
 }
 /**
  * Runs composer command
  *
  * @param array $commandParams
  * @param string|null $workingDir
  * @return bool
  * @throws \RuntimeException
  */
 public function runComposerCommand(array $commandParams, $workingDir = null)
 {
     $this->consoleApplication->resetComposer();
     if ($workingDir) {
         $commandParams[self::COMPOSER_WORKING_DIR] = $workingDir;
     } else {
         $commandParams[self::COMPOSER_WORKING_DIR] = dirname($this->composerJson);
     }
     $input = $this->consoleArrayInputFactory->create($commandParams);
     $exitCode = $this->consoleApplication->run($input, $this->consoleOutput);
     if ($exitCode) {
         throw new \RuntimeException(sprintf('Command "%s" failed: %s', $commandParams['command'], $this->consoleOutput->fetch()));
     }
     return $this->consoleOutput->fetch();
 }
 /**
  * Test that a wide table is adapted to a maximum width.
  */
 public function testAdaptedRowsFitMaxTableWidth()
 {
     $maxTableWidth = 60;
     $buffer = new BufferedOutput();
     $table = new AdaptiveTable($buffer, $maxTableWidth);
     $table->setHeaders([['Row', 'Lorem', 'ipsum', 'dolor', 'sit']]);
     $table->setRows([['#1', 'amet', 'consectetur', 'adipiscing elit', 'Quisque pulvinar'], ['#2', 'tellus sit amet', 'sollicitudin', 'tincidunt', 'risus'], ['#3', 'risus', 'sem', 'mattis', 'ex'], ['#4', 'quis', 'luctus metus', 'lorem cursus', 'ligula']]);
     $table->render();
     // Test that the table fits into the maximum width.
     $lineWidths = [];
     foreach (explode(PHP_EOL, $buffer->fetch()) as $line) {
         $lineWidths[] = strlen($line);
     }
     $this->assertLessThanOrEqual($maxTableWidth, max($lineWidths));
 }
Example #25
0
 /**
  * @param TubeStats[]|ArrayCollection $stats
  * @param int|null                    $width
  * @return string
  */
 private function renderStats(ArrayCollection $stats, $width = null)
 {
     if ($stats->isEmpty()) {
         return 'There are no current tubes';
     }
     $buffer = new BufferedOutput();
     $buffer->setDecorated(true);
     $width = $width ?: $this->getConsoleWidth();
     $table = $width ? new AutoHidingTable($buffer, $width) : new Table($buffer);
     $table->setHeaders(array('Tube', 'Ready', 'Buried', 'Reserved', 'Delayed', 'Urgent', 'Total', '', 'Using', 'Watching', 'Waiting', '', 'Pause Elapsed', 'Pause Left', '', 'Delete Count', 'Pause Count'));
     foreach ($stats as $tubeStats) {
         $table->addRow(array($tubeStats->name(), $tubeStats->readyJobs(), $tubeStats->buriedJobs(), $tubeStats->reservedJobs(), $tubeStats->delayedJobs(), $tubeStats->urgentJobs(), $tubeStats->totalJobs(), '', $tubeStats->usingCount(), $tubeStats->watchingCount(), $tubeStats->waitingCount(), '', $tubeStats->pause(), $tubeStats->pauseTimeLeft(), '', $tubeStats->cmdDeleteCount(), $tubeStats->cmdPauseTubeCount()));
     }
     $table->render();
     return $buffer->fetch();
 }
 public function onKernelException(GetResponseForExceptionEvent $event)
 {
     $request = $event->getRequest();
     if ($this->isRequestAcceptsJson($request)) {
         $exception = $event->getException();
         $response = new JsonResponse(['message' => $exception->getMessage(), 'trace' => $exception->getTrace(), 'code' => $exception->getCode()]);
         $event->setResponse($response);
     }
     if ($this->isRequestFromTests($request)) {
         $exception = $event->getException();
         $output = new BufferedOutput(OutputInterface::VERBOSITY_VERBOSE, true);
         $output->writeln($exception->getMessage());
         $output->writeln($exception->getCode());
         $output->writeln($exception->getTraceAsString());
         $response = new Response($output->fetch());
         $event->setResponse($response);
     }
 }
Example #27
0
 /**
  * @inheritdoc
  */
 public function terminate(ResultCollection $collection, ResultCollection $groupedResults)
 {
     $output = new BufferedOutput(OutputInterface::VERBOSITY_NORMAL, true);
     //        $output->write(str_pad("\x0D", 80, "\x20"));
     //        $output->writeln('');
     // overview
     $total = $this->bound->calculate($collection);
     $output->writeln(sprintf('<info>%d</info> files have been analyzed. Read and understand these <info>%s</info> lines of code will take around <info>%s</info>.', sizeof($collection, COUNT_NORMAL), $total->getSum('loc'), $this->formatTime($total->getSum('time'))));
     $output->writeln('<info>Average for each module:</info>');
     $output->writeln('');
     $hasOOP = null !== $total->getSum('instability');
     $table = new \Symfony\Component\Console\Helper\Table($output);
     $table->setHeaders(array_merge(array('Name', 'Complexity', 'Myer Distance', 'Maintainability', 'LLOC', 'Comment weight', 'Vocabulary', 'Volume', 'Bugs', 'Difficulty'), $hasOOP ? array('lcom', 'SysComplexity', 'Instability', 'Abstractness', 'ce', 'ca') : array()));
     foreach ($groupedResults as $result) {
         $table->addRow(array_merge(array(str_repeat('  ', $result->getDepth()) . $result->getName(), $this->getRow($result->getBounds(), 'cyclomaticComplexity', 'average', 0), $this->getRow($result->getBounds(), 'myerDistance', 'average', 0), $this->getRow($result->getBounds(), 'maintainabilityIndex', 'average', 0), $this->getRow($result->getBounds(), 'logicalLoc', 'sum', 0), $this->getRow($result->getBounds(), 'commentWeight', 'average', 0), $this->getRow($result->getBounds(), 'vocabulary', 'average', 0), $this->getRow($result->getBounds(), 'volume', 'average', 0), $this->getRow($result->getBounds(), 'bugs', 'sum', 2), $this->getRow($result->getBounds(), 'difficulty', 'average', 0)), $hasOOP ? array($this->getRow($result->getBounds(), 'lcom', 'average', 2), $this->getRow($result->getBounds(), 'rsysc', 'average', 2), $result->getInstability()->getInstability(), $result->getAbstractness()->getAbstractness(), $this->getRow($result->getBounds(), 'efferentCoupling', 'average', 2), $this->getRow($result->getBounds(), 'afferentCoupling', 'average', 2)) : array()));
     }
     $table->render();
     return $output->fetch();
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $componentName = $input->getOption('component');
     if (!$componentName) {
         $output->writeln('<error>Component name must be given</error>');
         $output->writeln('<comment>Use -c option to specify component name</comment>');
         return 1;
         // set error status code
     }
     $component = new BitrixComponent($componentName);
     if (!$component->exists()) {
         $output->writeln("<error>Component {$componentName} not found </error>");
         return 1;
     }
     $templateName = $input->getArgument('template');
     if (!$templateName) {
         $templateName = '';
     }
     $buff = new BufferedOutput();
     $buff->writeln(sprintf('<?$APPLICATION->IncludeComponent("%s", "%s", array(', $component->getFullName(), $templateName));
     $parameters = $component->getParameters()['PARAMETERS'];
     if ($input->getOption('sort')) {
         ksort($parameters);
     }
     foreach ($parameters as $name => $settings) {
         // TODO: Добавить вывод комментария с именем параметра.
         $defaultValue = $settings['DEFAULT'] ? $settings['DEFAULT'] : '';
         $buff->writeln(sprintf('    "%s" => %s,', $name, var_export($defaultValue, true)));
     }
     $buff->writeln('  ),');
     $buff->writeln('  false');
     $buff->writeln(');/*' . $componentName . "*/?>");
     $code = $buff->fetch();
     if ($input->getOption('xclip')) {
         $clip = new ClipboardStream();
         $clip->write($code);
         $output->writeln('<comment>Generated code was copied to clipboard</comment>');
     } else {
         $output->write("<info>{$code}</info>");
     }
 }
 /**
  * @param string|array $php
  * @param string|array $zephirExpected
  */
 public function assertConvertToZephir($php, $zephir)
 {
     if (is_array($php) === false) {
         $php = array($php);
     }
     $bufferOutput = new BufferedOutput();
     $logger = new Logger($bufferOutput, false, false);
     $generated = array_values($this->getEngine()->convert(new StringCodeCollector($php), $logger));
     $this->assertCount(count($zephir), $generated, $bufferOutput->fetch());
     self::delTree('Code');
     foreach ($generated as $index => $file) {
         $zephirGenerated = $this->getRender()->render($file);
         if (is_array($zephir) === true) {
             $this->assertEquals($this->showWiteSpace($zephir[$index]), $this->showWiteSpace($zephirGenerated));
         } else {
             $this->assertEquals($this->showWiteSpace($zephir), $this->showWiteSpace($zephirGenerated));
         }
     }
     if (count($zephir) !== 0) {
         $this->assertTrue($this->getCodeValidator()->isValid('Code'));
     }
 }
Example #30
0
 public function testDumpDataWithFullConfiguration()
 {
     $outputBuffer = new BufferedOutput();
     $dumper = new Dumper($outputBuffer);
     $pdoMock = $this->getMock('\\stdClass', array('setAttribute'));
     $this->dbMock->expects($this->any())->method('getWrappedConnection')->willReturn($pdoMock);
     $this->dbMock->expects($this->any())->method('fetchColumn')->willReturn(2);
     $this->dbMock->expects($this->any())->method('fetchAll')->willReturnCallback(function ($query) {
         if (strpos($query, 'SHOW COLUMNS') !== false) {
             return array(array('Field' => 'col1', 'Type' => 'varchar'), array('Field' => 'col2', 'Type' => 'blob'));
         }
         throw new \RuntimeException('Unexpected fetchAll-call: ' . $query);
     });
     $this->dbMock->expects($this->any())->method('quote')->willReturnCallback(function ($value) {
         return $value;
     });
     $this->dbMock->expects($this->any())->method('query')->willReturn(array(array('col1' => 'value1.1', 'col2' => 'value1.2'), array('col1' => 'value2.1', 'col2' => 'value2.2')));
     $table = new Table(new \SimpleXMLElement('<table name="test" dump="full" />'));
     $dumper->dumpData('test', $table, $this->dbMock);
     $output = $outputBuffer->fetch();
     $this->assertContains('INSERT INTO', $output);
 }