Update Composer, update everything

This commit is contained in:
Oliver Davies 2018-11-23 12:29:20 +00:00
parent ea3e94409f
commit dda5c284b6
19527 changed files with 1135420 additions and 351004 deletions

View file

@ -0,0 +1,37 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test;
class ClassWithSecrets
{
private const PRIVATE_CONST = 'private and const';
private static $privateStaticProp = 'private and static and prop';
private $privateProp = 'private and prop';
private static function privateStaticMethod($extra = null)
{
if ($extra !== null) {
return 'private and static and method with ' . \json_encode($extra);
}
return 'private and static and method';
}
private function privateMethod($extra = null)
{
if ($extra !== null) {
return 'private and method with ' . \json_encode($extra);
}
return 'private and method';
}
}

View file

@ -0,0 +1,57 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\CodeCleaner;
use Psy\CodeCleaner\AbstractClassPass;
class AbstractClassPassTest extends CodeCleanerTestCase
{
public function setUp()
{
$this->setPass(new AbstractClassPass());
}
/**
* @dataProvider invalidStatements
* @expectedException \Psy\Exception\FatalErrorException
*/
public function testProcessStatementFails($code)
{
$this->parseAndTraverse($code);
}
public function invalidStatements()
{
return [
['class A { abstract function a(); }'],
['abstract class B { abstract function b() {} }'],
['abstract class B { abstract function b() { echo "yep"; } }'],
];
}
/**
* @dataProvider validStatements
*/
public function testProcessStatementPasses($code)
{
$this->parseAndTraverse($code);
$this->assertTrue(true);
}
public function validStatements()
{
return [
['abstract class C { function c() {} }'],
['abstract class D { abstract function d(); }'],
];
}
}

View file

@ -0,0 +1,58 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\CodeCleaner;
use Psy\CodeCleaner\AssignThisVariablePass;
class AssignThisVariablePassTest extends CodeCleanerTestCase
{
public function setUp()
{
$this->setPass(new AssignThisVariablePass());
}
/**
* @dataProvider invalidStatements
* @expectedException \Psy\Exception\FatalErrorException
*/
public function testProcessStatementFails($code)
{
$this->parseAndTraverse($code);
}
public function invalidStatements()
{
return [
['$this = 3'],
['strtolower($this = "this")'],
];
}
/**
* @dataProvider validStatements
*/
public function testProcessStatementPasses($code)
{
$this->parseAndTraverse($code);
$this->assertTrue(true);
}
public function validStatements()
{
return [
['$this'],
['$a = $this'],
['$a = "this"; $$a = 3'],
['$$this = "b"'],
];
}
}

View file

@ -0,0 +1,59 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\CodeCleaner;
use Psy\CodeCleaner\CallTimePassByReferencePass;
class CallTimePassByReferencePassTest extends CodeCleanerTestCase
{
public function setUp()
{
$this->setPass(new CallTimePassByReferencePass());
}
/**
* @dataProvider invalidStatements
* @expectedException \Psy\Exception\FatalErrorException
*/
public function testProcessStatementFails($code)
{
$this->parseAndTraverse($code);
}
public function invalidStatements()
{
return [
['f(&$arg)'],
['$object->method($first, &$arg)'],
['$closure($first, &$arg, $last)'],
['A::b(&$arg)'],
];
}
/**
* @dataProvider validStatements
*/
public function testProcessStatementPasses($code)
{
$this->parseAndTraverse($code);
$this->assertTrue(true);
}
public function validStatements()
{
return [
['array(&$var)'],
['$a = &$b'],
['f(array(&$b))'],
];
}
}

View file

@ -0,0 +1,90 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\CodeCleaner;
use Psy\CodeCleaner\CalledClassPass;
class CalledClassPassTest extends CodeCleanerTestCase
{
public function setUp()
{
$this->setPass(new CalledClassPass());
}
/**
* @dataProvider invalidStatements
* @expectedException \Psy\Exception\ErrorException
*/
public function testProcessStatementFails($code)
{
$this->parseAndTraverse($code);
}
public function invalidStatements()
{
return [
['get_class()'],
['get_class(null)'],
['get_called_class()'],
['get_called_class(null)'],
['function foo() { return get_class(); }'],
['function foo() { return get_class(null); }'],
['function foo() { return get_called_class(); }'],
['function foo() { return get_called_class(null); }'],
];
}
/**
* @dataProvider validStatements
*/
public function testProcessStatementPasses($code)
{
$this->parseAndTraverse($code);
$this->assertTrue(true);
}
public function validStatements()
{
return [
['get_class($foo)'],
['get_class(bar())'],
['get_called_class($foo)'],
['get_called_class(bar())'],
['function foo($bar) { return get_class($bar); }'],
['function foo($bar) { return get_called_class($bar); }'],
['class Foo { function bar() { return get_class(); } }'],
['class Foo { function bar() { return get_class(null); } }'],
['class Foo { function bar() { return get_called_class(); } }'],
['class Foo { function bar() { return get_called_class(null); } }'],
['$foo = function () {}; $foo()'],
];
}
/**
* @dataProvider validTraitStatements
*/
public function testProcessTraitStatementPasses($code)
{
$this->parseAndTraverse($code);
$this->assertTrue(true);
}
public function validTraitStatements()
{
return [
['trait Foo { function bar() { return get_class(); } }'],
['trait Foo { function bar() { return get_class(null); } }'],
['trait Foo { function bar() { return get_called_class(); } }'],
['trait Foo { function bar() { return get_called_class(null); } }'],
];
}
}

View file

@ -0,0 +1,41 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\CodeCleaner;
use PhpParser\NodeTraverser;
use Psy\CodeCleaner\CodeCleanerPass;
use Psy\Test\ParserTestCase;
class CodeCleanerTestCase extends ParserTestCase
{
protected $pass;
public function tearDown()
{
$this->pass = null;
parent::tearDown();
}
protected function setPass(CodeCleanerPass $pass)
{
$this->pass = $pass;
if (!isset($this->traverser)) {
$this->traverser = new NodeTraverser();
}
$this->traverser->addVisitor($this->pass);
}
protected function parseAndTraverse($code, $prefix = '<?php ')
{
return $this->traverse($this->parse($code, $prefix));
}
}

View file

@ -0,0 +1,59 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\CodeCleaner;
use Psy\CodeCleaner\ExitPass;
class ExitPassTest extends CodeCleanerTestCase
{
/**
* @var string
*/
private $expectedExceptionString = '\\Psy\\Exception\\BreakException::exitShell()';
public function setUp()
{
$this->setPass(new ExitPass());
}
/**
* @dataProvider dataProviderExitStatement
*/
public function testExitStatement($from, $to)
{
$this->assertProcessesAs($from, $to);
}
/**
* Data provider for testExitStatement.
*
* @return array
*/
public function dataProviderExitStatement()
{
return [
['exit;', "{$this->expectedExceptionString};"],
['exit();', "{$this->expectedExceptionString};"],
['die;', "{$this->expectedExceptionString};"],
['exit(die(die));', "{$this->expectedExceptionString};"],
['if (true) { exit; }', "if (true) {\n {$this->expectedExceptionString};\n}"],
['if (false) { exit; }', "if (false) {\n {$this->expectedExceptionString};\n}"],
['1 and exit();', "1 and {$this->expectedExceptionString};"],
['foo() or die', "foo() or {$this->expectedExceptionString};"],
['exit and 1;', "{$this->expectedExceptionString} and 1;"],
['if (exit) { echo $wat; }', "if ({$this->expectedExceptionString}) {\n echo \$wat;\n}"],
['exit or die;', "{$this->expectedExceptionString} or {$this->expectedExceptionString};"],
['switch (die) { }', "switch ({$this->expectedExceptionString}) {\n}"],
['for ($i = 1; $i < 10; die) {}', "for (\$i = 1; \$i < 10; {$this->expectedExceptionString}) {\n}"],
];
}
}

View file

@ -0,0 +1,65 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\CodeCleaner;
use Psy\CodeCleaner\FinalClassPass;
class FinalClassPassTest extends CodeCleanerTestCase
{
public function setUp()
{
$this->setPass(new FinalClassPass());
}
/**
* @dataProvider invalidStatements
* @expectedException \Psy\Exception\FatalErrorException
*/
public function testProcessStatementFails($code)
{
$this->parseAndTraverse($code);
}
public function invalidStatements()
{
$data = [
['final class A {} class B extends A {}'],
['class A {} final class B extends A {} class C extends B {}'],
// array('namespace A { final class B {} } namespace C { class D extends \\A\\B {} }'),
];
if (!\defined('HHVM_VERSION')) {
// For some reason Closure isn't final in HHVM?
$data[] = ['class A extends \\Closure {}'];
}
return $data;
}
/**
* @dataProvider validStatements
*/
public function testProcessStatementPasses($code)
{
$this->parseAndTraverse($code);
$this->assertTrue(true);
}
public function validStatements()
{
return [
['class A extends \\stdClass {}'],
['final class A extends \\stdClass {}'],
['class A {} class B extends A {}'],
];
}
}

View file

@ -0,0 +1,20 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\CodeCleaner\Fixtures;
class ClassWithCallStatic
{
public static function __callStatic($name, $arguments)
{
// wheee!
}
}

View file

@ -0,0 +1,20 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\CodeCleaner\Fixtures;
class ClassWithStatic
{
public static function doStuff()
{
// Don't actually do stuff.
}
}

View file

@ -0,0 +1,20 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\CodeCleaner\Fixtures;
trait TraitWithStatic
{
public static function doStuff()
{
// Don't actually do stuff.
}
}

View file

@ -0,0 +1,56 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\CodeCleaner;
use Psy\CodeCleaner\FunctionContextPass;
class FunctionContextPassTest extends CodeCleanerTestCase
{
public function setUp()
{
$this->setPass(new FunctionContextPass());
}
/**
* @dataProvider validStatements
*/
public function testProcessStatementPasses($code)
{
$this->parseAndTraverse($code);
$this->assertTrue(true);
}
public function validStatements()
{
return [
['function foo() { yield; }'],
['if (function(){ yield; })'],
];
}
/**
* @dataProvider invalidYieldStatements
* @expectedException \Psy\Exception\FatalErrorException
*/
public function testInvalidYield($code)
{
$this->parseAndTraverse($code);
}
public function invalidYieldStatements()
{
return [
['yield'],
['if (yield)'],
];
}
}

View file

@ -0,0 +1,91 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\CodeCleaner;
use Psy\CodeCleaner\FunctionReturnInWriteContextPass;
use Psy\Exception\FatalErrorException;
class FunctionReturnInWriteContextPassTest extends CodeCleanerTestCase
{
public function setUp()
{
$this->setPass(new FunctionReturnInWriteContextPass());
}
/**
* @dataProvider invalidStatements
* @expectedException \Psy\Exception\FatalErrorException
* @expectedExceptionMessage Can't use function return value in write context
*/
public function testProcessStatementFails($code)
{
$this->parseAndTraverse($code);
}
public function invalidStatements()
{
return [
['f(&g())'],
['array(& $object->method())'],
['$a->method(& $closure())'],
['array(& A::b())'],
['f() = 5'],
['unset(h())'],
];
}
public function testIsset()
{
try {
$this->traverser->traverse($this->parse('isset(strtolower("A"))'));
$this->fail();
} catch (FatalErrorException $e) {
if (\version_compare(PHP_VERSION, '5.5', '>=')) {
$this->assertContains(
'Cannot use isset() on the result of a function call (you can use "null !== func()" instead)',
$e->getMessage()
);
} else {
$this->assertContains("Can't use function return value in write context", $e->getMessage());
}
}
}
/**
* @expectedException \Psy\Exception\FatalErrorException
* @expectedExceptionMessage Can't use function return value in write context
*/
public function testEmpty()
{
if (\version_compare(PHP_VERSION, '5.5', '>=')) {
$this->markTestSkipped();
}
$this->traverser->traverse($this->parse('empty(strtolower("A"))'));
}
/**
* @dataProvider validStatements
*/
public function testValidStatements($code)
{
$this->parseAndTraverse($code);
$this->assertTrue(true);
}
public function validStatements()
{
return [
['isset($foo)'],
];
}
}

View file

@ -0,0 +1,112 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\CodeCleaner;
use Psy\CodeCleaner\ImplicitReturnPass;
class ImplicitReturnPassTest extends CodeCleanerTestCase
{
public function setUp()
{
$this->setPass(new ImplicitReturnPass());
}
/**
* @dataProvider implicitReturns
*/
public function testProcess($from, $to)
{
$this->assertProcessesAs($from, $to);
}
public function implicitReturns()
{
$data = [
['4', 'return 4;'],
['foo()', 'return foo();'],
['return 1', 'return 1;'],
['', 'return new \Psy\CodeCleaner\NoReturnValue();'],
];
$from = 'echo "foo";';
$to = <<<'EOS'
echo "foo";
return new \Psy\CodeCleaner\NoReturnValue();
EOS;
$data[] = [$from, $to];
$from = 'if (true) { 1; } elseif (true) { 2; } else { 3; }';
$to = <<<'EOS'
if (true) {
return 1;
} elseif (true) {
return 2;
} else {
return 3;
}
return new \Psy\CodeCleaner\NoReturnValue();
EOS;
$data[] = [$from, $to];
$from = 'class A {}';
$to = <<<'EOS'
class A
{
}
return new \Psy\CodeCleaner\NoReturnValue();
EOS;
$data[] = [$from, $to];
$from = <<<'EOS'
switch (false) {
case 0:
0;
case 1:
1;
break;
case 2:
2;
return;
}
EOS;
$to = <<<'EOS'
switch (false) {
case 0:
0;
case 1:
return 1;
break;
case 2:
2;
return;
}
return new \Psy\CodeCleaner\NoReturnValue();
EOS;
$data[] = [$from, $to];
$from = <<<'EOS'
namespace Foo {
1 + 1;
}
EOS;
$to = <<<'EOS'
namespace Foo;
return 1 + 1;
EOS;
$data[] = [$from, $to];
$data[] = ['exit()', 'exit;'];
return $data;
}
}

View file

@ -0,0 +1,72 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\CodeCleaner;
use Psy\CodeCleaner\InstanceOfPass;
class InstanceOfPassTest extends CodeCleanerTestCase
{
protected function setUp()
{
$this->setPass(new InstanceOfPass());
}
/**
* @dataProvider invalidStatements
* @expectedException \Psy\Exception\FatalErrorException
*/
public function testProcessInvalidStatement($code)
{
$this->parseAndTraverse($code);
}
public function invalidStatements()
{
return [
['null instanceof stdClass'],
['true instanceof stdClass'],
['9 instanceof stdClass'],
['1.0 instanceof stdClass'],
['"foo" instanceof stdClass'],
['__DIR__ instanceof stdClass'],
['PHP_SAPI instanceof stdClass'],
['1+1 instanceof stdClass'],
['true && false instanceof stdClass'],
['"a"."b" instanceof stdClass'],
['!5 instanceof stdClass'],
];
}
/**
* @dataProvider validStatements
*/
public function testProcessValidStatement($code)
{
$this->parseAndTraverse($code);
$this->assertTrue(true);
}
public function validStatements()
{
$data = [
['$a instanceof stdClass'],
['strtolower("foo") instanceof stdClass'],
['array(1) instanceof stdClass'],
['(string) "foo" instanceof stdClass'],
['(1+1) instanceof stdClass'],
['"foo ${foo} $bar" instanceof stdClass'],
['DateTime::ISO8601 instanceof stdClass'],
];
return $data;
}
}

View file

@ -0,0 +1,69 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\CodeCleaner;
use Psy\CodeCleaner\LeavePsyshAlonePass;
class LeavePsyshAlonePassTest extends CodeCleanerTestCase
{
public function setUp()
{
$this->setPass(new LeavePsyshAlonePass());
}
public function testPassesInlineHtmlThroughJustFine()
{
$inline = $this->parse('not php at all!', '');
$this->traverse($inline);
$this->assertTrue(true);
}
/**
* @dataProvider validStatements
*/
public function testProcessStatementPasses($code)
{
$this->parseAndTraverse($code);
$this->assertTrue(true);
}
public function validStatements()
{
return [
['array_merge()'],
['__psysh__()'],
['$this'],
['$psysh'],
['$__psysh'],
['$banana'],
];
}
/**
* @dataProvider invalidStatements
* @expectedException \Psy\Exception\RuntimeException
*/
public function testProcessStatementFails($code)
{
$this->parseAndTraverse($code);
}
public function invalidStatements()
{
return [
['$__psysh__'],
['var_dump($__psysh__)'],
['$__psysh__ = "your mom"'],
['$__psysh__->fakeFunctionCall()'],
];
}
}

View file

@ -0,0 +1,76 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\CodeCleaner;
use Psy\CodeCleaner\LegacyEmptyPass;
class LegacyEmptyPassTest extends CodeCleanerTestCase
{
public function setUp()
{
$this->setPass(new LegacyEmptyPass());
}
/**
* @dataProvider invalidStatements
* @expectedException \Psy\Exception\ParseErrorException
*/
public function testProcessInvalidStatement($code)
{
$this->parseAndTraverse($code);
}
public function invalidStatements()
{
if (\version_compare(PHP_VERSION, '5.5', '>=')) {
return [
['empty()'],
];
}
return [
['empty()'],
['empty(null)'],
['empty(PHP_EOL)'],
['empty("wat")'],
['empty(1.1)'],
['empty(Foo::$bar)'],
];
}
/**
* @dataProvider validStatements
*/
public function testProcessValidStatement($code)
{
$this->parseAndTraverse($code);
$this->assertTrue(true);
}
public function validStatements()
{
if (\version_compare(PHP_VERSION, '5.5', '<')) {
return [
['empty($foo)'],
];
}
return [
['empty($foo)'],
['empty(null)'],
['empty(PHP_EOL)'],
['empty("wat")'],
['empty(1.1)'],
['empty(Foo::$bar)'],
];
}
}

View file

@ -0,0 +1,115 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\CodeCleaner;
use Psy\CodeCleaner\ListPass;
class ListPassTest extends CodeCleanerTestCase
{
public function setUp()
{
$this->setPass(new ListPass());
}
/**
* @dataProvider invalidStatements
* @expectedException \Psy\Exception\ParseErrorException
*/
public function testProcessInvalidStatement($code, $expectedMessage)
{
if (\method_exists($this, 'setExpectedException')) {
$this->setExpectedException('Psy\Exception\ParseErrorException', $expectedMessage);
} else {
$this->expectExceptionMessage($expectedMessage);
}
$stmts = $this->parse($code);
$this->traverser->traverse($stmts);
}
public function invalidStatements()
{
// Not typo. It is ambiguous whether "Syntax" or "syntax".
$errorShortListAssign = "yntax error, unexpected '='";
$errorEmptyList = 'Cannot use empty list';
$errorAssocListAssign = 'Syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting \',\' or \')\'';
$errorNonVariableAssign = 'Assignments can only happen to writable values';
$errorPhpParserSyntax = 'PHP Parse error: Syntax error, unexpected';
$invalidExpr = [
['list() = array()', $errorEmptyList],
['list("a") = array(1)', $errorPhpParserSyntax],
];
if (\version_compare(PHP_VERSION, '7.1', '<')) {
return \array_merge($invalidExpr, [
['list("a" => _) = array("a" => 1)', $errorPhpParserSyntax],
['[] = []', $errorShortListAssign],
['[$a] = [1]', $errorShortListAssign],
['list("a" => $a) = array("a" => 1)', $errorAssocListAssign],
['[$a[0], $a[1]] = [1, 2]', $errorShortListAssign],
['[$a->b, $a->c] = [1, 2]', $errorShortListAssign],
]);
}
return \array_merge($invalidExpr, [
['list("a" => _) = array("a" => 1)', $errorPhpParserSyntax],
['["a"] = [1]', $errorNonVariableAssign],
['[] = []', $errorEmptyList],
['[,] = [1,2]', $errorEmptyList],
['[,,] = [1,2,3]', $errorEmptyList],
]);
}
/**
* @dataProvider validStatements
*/
public function testProcessValidStatement($code)
{
$stmts = $this->parse($code);
$this->traverser->traverse($stmts);
$this->assertTrue(true);
}
public function validStatements()
{
$validExpr = [
['list($a) = array(1)'],
['list($x, $y) = array(1, 2)'],
];
if (\version_compare(PHP_VERSION, '7.1', '>=')) {
return \array_merge($validExpr, [
['[$a] = array(1)'],
['list($b) = [2]'],
['[$x, $y] = array(1, 2)'],
['[$a] = [1]'],
['[$x, $y] = [1, 2]'],
['["_" => $v] = ["_" => 1]'],
['[$a,] = [1,2,3]'],
['[,$b] = [1,2,3]'],
['[$a,,$c] = [1,2,3]'],
['[$a,,,] = [1,2,3]'],
['[$a[0], $a[1]] = [1, 2]'],
['[$a[0][0][0], $a[0][0][1]] = [1, 2]'],
['[$a->b, $a->c] = [1, 2]'],
['[$a->b[0], $a->c[1]] = [1, 2]'],
['[$a[0]->b[0], $a[0]->c[1]] = [1, 2]'],
['[$a[$b->c + $b->d]] = [1]'],
['[$a->c()->d, $a->c()->e] = [1, 2]'],
['[x()->a, x()->b] = [1, 2]'],
]);
}
return $validExpr;
}
}

View file

@ -0,0 +1,108 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\CodeCleaner;
use Psy\CodeCleaner\LoopContextPass;
class LoopContextPassTest extends CodeCleanerTestCase
{
public function setUp()
{
$this->setPass(new LoopContextPass());
}
/**
* @dataProvider invalidStatements
* @expectedException \Psy\Exception\FatalErrorException
*/
public function testProcessStatementFails($code)
{
$this->parseAndTraverse($code);
}
public function invalidStatements()
{
return [
['continue'],
['break'],
['if (true) { continue; }'],
['if (true) { break; }'],
['if (false) { continue; }'],
['if (false) { break; }'],
['function foo() { break; }'],
['function foo() { continue; }'],
// actually enforce break/continue depth argument
['do { break 2; } while (true)'],
['do { continue 2; } while (true)'],
['for ($a; $b; $c) { break 2; }'],
['for ($a; $b; $c) { continue 2; }'],
['foreach ($a as $b) { break 2; }'],
['foreach ($a as $b) { continue 2; }'],
['switch (true) { default: break 2; }'],
['switch (true) { default: continue 2; }'],
['while (true) { break 2; }'],
['while (true) { continue 2; }'],
// In PHP 5.4+, only positive literal integers are allowed
['while (true) { break $n; }'],
['while (true) { continue $n; }'],
['while (true) { break N; }'],
['while (true) { continue N; }'],
['while (true) { break 0; }'],
['while (true) { continue 0; }'],
['while (true) { break -1; }'],
['while (true) { continue -1; }'],
['while (true) { break 1.0; }'],
['while (true) { continue 1.0; }'],
['while (true) { break 2.0; }'],
['while (true) { continue 2.0; }'],
// and once with nested loops, just for good measure
['while (true) { while (true) { break 3; } }'],
['while (true) { while (true) { continue 3; } }'],
];
}
/**
* @dataProvider validStatements
*/
public function testProcessStatementPasses($code)
{
$this->parseAndTraverse($code);
$this->assertTrue(true);
}
public function validStatements()
{
return [
['do { break; } while (true)'],
['do { continue; } while (true)'],
['for ($a; $b; $c) { break; }'],
['for ($a; $b; $c) { continue; }'],
['foreach ($a as $b) { break; }'],
['foreach ($a as $b) { continue; }'],
['switch (true) { default: break; }'],
['switch (true) { default: continue; }'],
['while (true) { break; }'],
['while (true) { continue; }'],
// `break 1` is redundant, but not invalid
['while (true) { break 1; }'],
['while (true) { continue 1; }'],
// and once with nested loops just for good measure
['while (true) { while (true) { break 2; } }'],
['while (true) { while (true) { continue 2; } }'],
];
}
}

View file

@ -0,0 +1,39 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\CodeCleaner;
use Psy\CodeCleaner\MagicConstantsPass;
class MagicConstantsPassTest extends CodeCleanerTestCase
{
public function setUp()
{
$this->setPass(new MagicConstantsPass());
}
/**
* @dataProvider magicConstants
*/
public function testProcess($from, $to)
{
$this->assertProcessesAs($from, $to);
}
public function magicConstants()
{
return [
['__DIR__;', 'getcwd();'],
['__FILE__;', "'';"],
['___FILE___;', '___FILE___;'],
];
}
}

View file

@ -0,0 +1,59 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\CodeCleaner;
use Psy\CodeCleaner;
use Psy\CodeCleaner\NamespacePass;
class NamespacePassTest extends CodeCleanerTestCase
{
private $cleaner;
public function setUp()
{
$this->cleaner = new CodeCleaner();
$this->setPass(new NamespacePass($this->cleaner));
}
public function testProcess()
{
$this->parseAndTraverse('');
$this->assertNull($this->cleaner->getNamespace());
$this->parseAndTraverse('array_merge()');
$this->assertNull($this->cleaner->getNamespace());
// A non-block namespace statement should set the current namespace.
$this->parseAndTraverse('namespace Alpha');
$this->assertSame(['Alpha'], $this->cleaner->getNamespace());
// A new non-block namespace statement should override the current namespace.
$this->parseAndTraverse('namespace Beta; class B {}');
$this->assertSame(['Beta'], $this->cleaner->getNamespace());
// A new block namespace clears out the current namespace...
$this->parseAndTraverse('namespace Gamma { array_merge(); }');
if (\defined('PhpParser\\Node\\Stmt\\Namespace_::KIND_SEMICOLON')) {
$this->assertNull($this->cleaner->getNamespace());
} else {
// But not for PHP-Parser < v3.1.2 :(
$this->assertSame(['Gamma'], $this->cleaner->getNamespace());
}
$this->parseAndTraverse('namespace Delta');
// A null namespace clears out the current namespace.
$this->parseAndTraverse('namespace { array_merge(); }');
$this->assertNull($this->cleaner->getNamespace());
}
}

View file

@ -0,0 +1,32 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\CodeCleaner;
use PhpParser\Node\Stmt\Expression;
use Psy\CodeCleaner\NoReturnValue;
use Psy\Test\ParserTestCase;
class NoReturnValueTest extends ParserTestCase
{
public function testCreate()
{
$stmt = NoReturnValue::create();
if (\class_exists('PhpParser\Node\Stmt\Expression')) {
$stmt = new Expression($stmt);
}
$this->assertSame(
$this->prettyPrint($this->parse('new \\Psy\CodeCleaner\\NoReturnValue()')),
$this->prettyPrint([$stmt])
);
}
}

View file

@ -0,0 +1,104 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\CodeCleaner;
use Psy\CodeCleaner\PassableByReferencePass;
class PassableByReferencePassTest extends CodeCleanerTestCase
{
public function setUp()
{
$this->setPass(new PassableByReferencePass());
}
/**
* @dataProvider invalidStatements
* @expectedException \Psy\Exception\FatalErrorException
*/
public function testProcessStatementFails($code)
{
$this->parseAndTraverse($code);
}
public function invalidStatements()
{
return [
['array_pop(array())'],
['array_pop(array($foo))'],
['array_shift(array())'],
];
}
/**
* @dataProvider validStatements
*/
public function testProcessStatementPasses($code)
{
$this->parseAndTraverse($code);
$this->assertTrue(true);
}
public function validStatements()
{
return [
['array_pop(json_decode("[]"))'],
['array_pop($foo)'],
['array_pop($foo->bar)'],
['array_pop($foo::baz)'],
['array_pop(Foo::qux)'],
];
}
/**
* @dataProvider validArrayMultisort
*/
public function testArrayMultisort($code)
{
$this->parseAndTraverse($code);
$this->assertTrue(true);
}
public function validArrayMultisort()
{
return [
['array_multisort($a)'],
['array_multisort($a, $b)'],
['array_multisort($a, SORT_NATURAL, $b)'],
['array_multisort($a, SORT_NATURAL | SORT_FLAG_CASE, $b)'],
['array_multisort($a, SORT_ASC, SORT_NATURAL | SORT_FLAG_CASE, $b)'],
['array_multisort($a, SORT_NATURAL | SORT_FLAG_CASE, SORT_ASC, $b)'],
['array_multisort($a, $b, SORT_ASC, SORT_NATURAL | SORT_FLAG_CASE)'],
['array_multisort($a, SORT_NATURAL | SORT_FLAG_CASE, $b, SORT_ASC, SORT_NATURAL | SORT_FLAG_CASE)'],
['array_multisort($a, 1, $b)'],
['array_multisort($a, 1 + 2, $b)'],
['array_multisort($a, getMultisortFlags(), $b)'],
];
}
/**
* @dataProvider invalidArrayMultisort
* @expectedException \Psy\Exception\FatalErrorException
*/
public function testInvalidArrayMultisort($code)
{
$this->parseAndTraverse($code);
}
public function invalidArrayMultisort()
{
return [
['array_multisort(1)'],
['array_multisort(array(1, 2, 3))'],
['array_multisort($a, SORT_NATURAL, SORT_ASC, SORT_NATURAL, $b)'],
];
}
}

View file

@ -0,0 +1,93 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\CodeCleaner;
use Psy\CodeCleaner\RequirePass;
class RequirePassTest extends CodeCleanerTestCase
{
public function setUp()
{
$this->setPass(new RequirePass());
}
/**
* @dataProvider exitStatements
*/
public function testExitStatement($from, $to)
{
$this->assertProcessesAs($from, $to);
}
public function exitStatements()
{
$resolve = '\\Psy\\CodeCleaner\\RequirePass::resolve';
return [
// The basics
['require "a"', "require $resolve(\"a\", 1);"],
['require "b.php"', "require $resolve(\"b.php\", 1);"],
['require_once "c"', "require_once $resolve(\"c\", 1);"],
['require_once "d.php"', "require_once $resolve(\"d.php\", 1);"],
// Ensure that line numbers work correctly
["null;\nrequire \"e.php\"", "null;\nrequire $resolve(\"e.php\", 2);"],
["null;\nrequire_once \"f.php\"", "null;\nrequire_once $resolve(\"f.php\", 2);"],
// Things with expressions
['require $foo', "require $resolve(\$foo, 1);"],
['require_once $foo', "require_once $resolve(\$foo, 1);"],
['require ($bar = "g.php")', "require $resolve(\$bar = \"g.php\", 1);"],
['require_once ($bar = "h.php")', "require_once $resolve(\$bar = \"h.php\", 1);"],
['$bar = require ($baz = "i.php")', "\$bar = (require $resolve(\$baz = \"i.php\", 1));"],
['$bar = require_once ($baz = "j.php")', "\$bar = (require_once $resolve(\$baz = \"j.php\", 1));"],
];
}
/**
* @expectedException \Psy\Exception\FatalErrorException
* @expectedExceptionMessage Failed opening required 'not a file name' in eval()'d code on line 2
*/
public function testResolve()
{
RequirePass::resolve('not a file name', 2);
}
/**
* @dataProvider emptyWarnings
*
* @expectedException \Psy\Exception\ErrorException
* @expectedExceptionMessage Filename cannot be empty on line 1
*/
public function testResolveEmptyWarnings($file)
{
if (!E_WARNING & \error_reporting()) {
$this->markTestSkipped();
}
RequirePass::resolve($file, 1);
}
public function emptyWarnings()
{
return [
[null],
[false],
[''],
];
}
public function testResolveWorks()
{
$this->assertEquals(__FILE__, RequirePass::resolve(__FILE__, 3));
}
}

View file

@ -0,0 +1,52 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\CodeCleaner;
use Psy\CodeCleaner\StrictTypesPass;
class StrictTypesPassTest extends CodeCleanerTestCase
{
public function setUp()
{
if (\version_compare(PHP_VERSION, '7.0', '<')) {
$this->markTestSkipped();
}
$this->setPass(new StrictTypesPass());
}
public function testProcess()
{
$this->assertProcessesAs('declare(strict_types=1)', 'declare (strict_types=1);');
$this->assertProcessesAs('null', "declare (strict_types=1);\nnull;");
$this->assertProcessesAs('declare(strict_types=0)', 'declare (strict_types=0);');
$this->assertProcessesAs('null', 'null;');
}
/**
* @dataProvider invalidDeclarations
* @expectedException \Psy\Exception\FatalErrorException
*/
public function testInvalidDeclarations($code)
{
$this->parseAndTraverse($code);
}
public function invalidDeclarations()
{
return [
['declare(strict_types=-1)'],
['declare(strict_types=2)'],
['declare(strict_types="foo")'],
];
}
}

View file

@ -0,0 +1,102 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\CodeCleaner;
use Psy\CodeCleaner\UseStatementPass;
class UseStatementPassTest extends CodeCleanerTestCase
{
public function setUp()
{
$this->setPass(new UseStatementPass());
}
/**
* @dataProvider useStatements
*/
public function testProcess($from, $to)
{
$this->assertProcessesAs($from, $to);
}
public function useStatements()
{
return [
[
"use StdClass as NotSoStd;\n\$std = new NotSoStd();",
'$std = new \\StdClass();',
],
[
"namespace Foo;\n\nuse StdClass as S;\n\$std = new S();",
"namespace Foo;\n\n\$std = new \\StdClass();",
],
[
"namespace Foo;\n\nuse \\StdClass as S;\n\$std = new S();",
"namespace Foo;\n\n\$std = new \\StdClass();",
],
[
"use Foo\\Bar as fb;\n\$baz = new fb\\Baz();",
'$baz = new \\Foo\\Bar\\Baz();',
],
[
"use Foo\\Bar;\n\$baz = new Bar\\Baz();",
'$baz = new \\Foo\\Bar\\Baz();',
],
[
"namespace Foo;\nuse Bar;\n\$baz = new Bar\\Baz();",
"namespace Foo;\n\n\$baz = new \\Bar\\Baz();",
],
[
"namespace Foo;\n\nuse \\StdClass as S;\n\$std = new S();\nnamespace Foo;\n\n\$std = new S();",
"namespace Foo;\n\n\$std = new \\StdClass();\nnamespace Foo;\n\n\$std = new \\StdClass();",
],
[
"namespace Foo;\n\nuse \\StdClass as S;\n\$std = new S();\nnamespace Bar;\n\n\$std = new S();",
"namespace Foo;\n\n\$std = new \\StdClass();\nnamespace Bar;\n\n\$std = new S();",
],
[
"use Foo\\Bar as fb, Qux as Q;\n\$baz = new fb\\Baz();\n\$qux = new Q();",
"\$baz = new \\Foo\\Bar\\Baz();\n\$qux = new \\Qux();",
],
];
}
/**
* @dataProvider groupUseStatements
*/
public function testGroupUseProcess($from, $to)
{
$this->assertProcessesAs($from, $to);
}
public function groupUseStatements()
{
if (\version_compare(PHP_VERSION, '7.0', '<')) {
$this->markTestSkipped();
}
return [
[
"use Foo\\{Bar, Baz, Qux as Q};\n\$bar = new Bar();\n\$baz = new Baz();\n\$qux = new Q();",
"\$bar = new \\Foo\\Bar();\n\$baz = new \\Foo\\Baz();\n\$qux = new \\Foo\\Qux();",
],
[
"use X\\{Foo, Bar as B};\n\$foo = new Foo();\n\$baz = new B\\Baz();",
"\$foo = new \\X\\Foo();\n\$baz = new \\X\\Bar\\Baz();",
],
[
"use X\\{Foo, Bar as B};\n\$foo = new Foo();\n\$bar = new Bar();\n\$baz = new B\\Baz();",
"\$foo = new \\X\\Foo();\n\$bar = new Bar();\n\$baz = new \\X\\Bar\\Baz();",
],
];
}
}

View file

@ -0,0 +1,325 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\CodeCleaner;
use Psy\CodeCleaner\ValidClassNamePass;
class ValidClassNamePassTest extends CodeCleanerTestCase
{
public function setUp()
{
$this->setPass(new ValidClassNamePass());
}
/**
* @dataProvider getInvalid
* @expectedException \Psy\Exception\FatalErrorException
*/
public function testProcessInvalid($code)
{
$this->parseAndTraverse($code);
}
public function getInvalid()
{
// class declarations
return [
// core class
['class stdClass {}'],
// capitalization
['class stdClass {}'],
// collisions with interfaces and traits
['interface stdClass {}'],
['trait stdClass {}'],
// collisions inside the same code snippet
['
class Psy_Test_CodeCleaner_ValidClassNamePass_Alpha {}
class Psy_Test_CodeCleaner_ValidClassNamePass_Alpha {}
'],
['
class Psy_Test_CodeCleaner_ValidClassNamePass_Alpha {}
trait Psy_Test_CodeCleaner_ValidClassNamePass_Alpha {}
'],
['
trait Psy_Test_CodeCleaner_ValidClassNamePass_Alpha {}
class Psy_Test_CodeCleaner_ValidClassNamePass_Alpha {}
'],
['
trait Psy_Test_CodeCleaner_ValidClassNamePass_Alpha {}
interface Psy_Test_CodeCleaner_ValidClassNamePass_Alpha {}
'],
['
interface Psy_Test_CodeCleaner_ValidClassNamePass_Alpha {}
trait Psy_Test_CodeCleaner_ValidClassNamePass_Alpha {}
'],
['
interface Psy_Test_CodeCleaner_ValidClassNamePass_Alpha {}
class Psy_Test_CodeCleaner_ValidClassNamePass_Alpha {}
'],
['
class Psy_Test_CodeCleaner_ValidClassNamePass_Alpha {}
interface Psy_Test_CodeCleaner_ValidClassNamePass_Alpha {}
'],
// namespaced collisions
['
namespace Psy\\Test\\CodeCleaner {
class ValidClassNamePassTest {}
}
'],
['
namespace Psy\\Test\\CodeCleaner\\ValidClassNamePass {
class Beta {}
}
namespace Psy\\Test\\CodeCleaner\\ValidClassNamePass {
class Beta {}
}
'],
// extends and implements
['class ValidClassNamePassTest extends NotAClass {}'],
['class ValidClassNamePassTest extends ArrayAccess {}'],
['class ValidClassNamePassTest implements stdClass {}'],
['class ValidClassNamePassTest implements ArrayAccess, stdClass {}'],
['interface ValidClassNamePassTest extends stdClass {}'],
['interface ValidClassNamePassTest extends ArrayAccess, stdClass {}'],
// class instantiations
['new Psy_Test_CodeCleaner_ValidClassNamePass_Gamma();'],
['
namespace Psy\\Test\\CodeCleaner\\ValidClassNamePass {
new Psy_Test_CodeCleaner_ValidClassNamePass_Delta();
}
'],
// class constant fetch
['Psy\\Test\\CodeCleaner\\ValidClassNamePass\\NotAClass::FOO'],
// static call
['Psy\\Test\\CodeCleaner\\ValidClassNamePass\\NotAClass::foo()'],
['Psy\\Test\\CodeCleaner\\ValidClassNamePass\\NotAClass::$foo()'],
['Psy\\Test\\CodeCleaner\\ValidClassNamePassTest::notAMethod()'],
];
}
/**
* @dataProvider getValid
*/
public function testProcessValid($code)
{
$this->parseAndTraverse($code);
$this->assertTrue(true);
}
public function getValid()
{
$valid = [
// class declarations
['class Psy_Test_CodeCleaner_ValidClassNamePass_Epsilon {}'],
['namespace Psy\Test\CodeCleaner\ValidClassNamePass; class Zeta {}'],
['
namespace { class Psy_Test_CodeCleaner_ValidClassNamePass_Eta {}; }
namespace Psy\\Test\\CodeCleaner\\ValidClassNamePass {
class Psy_Test_CodeCleaner_ValidClassNamePass_Eta {}
}
'],
['namespace Psy\Test\CodeCleaner\ValidClassNamePass { class stdClass {} }'],
// class instantiations
['new stdClass();'],
['new stdClass();'],
['
namespace Psy\\Test\\CodeCleaner\\ValidClassNamePass {
class Theta {}
}
namespace Psy\\Test\\CodeCleaner\\ValidClassNamePass {
new Theta();
}
'],
['
namespace Psy\\Test\\CodeCleaner\\ValidClassNamePass {
class Iota {}
new Iota();
}
'],
['
namespace Psy\\Test\\CodeCleaner\\ValidClassNamePass {
class Kappa {}
}
namespace {
new \\Psy\\Test\\CodeCleaner\\ValidClassNamePass\\Kappa();
}
'],
// Class constant fetch (ValidConstantPassTest validates the actual constant)
['class A {} A::FOO'],
['$a = new DateTime; $a::ATOM'],
['interface A { const B = 1; } A::B'],
// static call
['DateTime::createFromFormat()'],
['DateTime::$someMethod()'],
['Psy\Test\CodeCleaner\Fixtures\ClassWithStatic::doStuff()'],
['Psy\Test\CodeCleaner\Fixtures\ClassWithCallStatic::doStuff()'],
['Psy\Test\CodeCleaner\Fixtures\TraitWithStatic::doStuff()'],
// Allow `self` and `static` as class names.
['
class Psy_Test_CodeCleaner_ValidClassNamePass_ClassWithStatic {
public static function getInstance() {
return new self();
}
}
'],
['
class Psy_Test_CodeCleaner_ValidClassNamePass_ClassWithStatic {
public static function getInstance() {
return new SELF();
}
}
'],
['
class Psy_Test_CodeCleaner_ValidClassNamePass_ClassWithStatic {
public static function getInstance() {
return new self;
}
}
'],
['
class Psy_Test_CodeCleaner_ValidClassNamePass_ClassWithStatic {
public static function getInstance() {
return new static();
}
}
'],
['
class Psy_Test_CodeCleaner_ValidClassNamePass_ClassWithStatic {
public static function getInstance() {
return new Static();
}
}
'],
['
class Psy_Test_CodeCleaner_ValidClassNamePass_ClassWithStatic {
public static function getInstance() {
return new static;
}
}
'],
['
class Psy_Test_CodeCleaner_ValidClassNamePass_ClassWithStatic {
public static function foo() {
return parent::bar();
}
}
'],
['
class Psy_Test_CodeCleaner_ValidClassNamePass_ClassWithStatic {
public static function foo() {
return self::bar();
}
}
'],
['
class Psy_Test_CodeCleaner_ValidClassNamePass_ClassWithStatic {
public static function foo() {
return static::bar();
}
}
'],
['class A { static function b() { return new A; } }'],
['
class A {
const B = 123;
function c() {
return A::B;
}
}
'],
['class A {} class B { function c() { return new A; } }'],
// recursion
['class A { function a() { A::a(); } }'],
// conditionally defined classes
['
class A {}
if (false) {
class A {}
}
'],
['
class A {}
if (true) {
class A {}
} else if (false) {
class A {}
} else {
class A {}
}
'],
// ewww
['
class A {}
if (true):
class A {}
elseif (false):
class A {}
else:
class A {}
endif;
'],
['
class A {}
while (false) { class A {} }
'],
['
class A {}
do { class A {} } while (false);
'],
['
class A {}
switch (1) {
case 0:
class A {}
break;
case 1:
class A {}
break;
case 2:
class A {}
break;
}
'],
];
// Ugh. There's gotta be a better way to test for this.
if (\class_exists('PhpParser\ParserFactory')) {
// PHP 7.0 anonymous classes, only supported by PHP Parser v2.x
$valid[] = ['$obj = new class() {}'];
}
if (\version_compare(PHP_VERSION, '5.5', '>=')) {
$valid[] = ['interface A {} A::class'];
$valid[] = ['interface A {} A::CLASS'];
$valid[] = ['class A {} A::class'];
$valid[] = ['class A {} A::CLASS'];
$valid[] = ['A::class'];
$valid[] = ['A::CLASS'];
}
return $valid;
}
}

View file

@ -0,0 +1,65 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\CodeCleaner;
use Psy\CodeCleaner\ValidConstantPass;
class ValidConstantPassTest extends CodeCleanerTestCase
{
public function setUp()
{
$this->setPass(new ValidConstantPass());
}
/**
* @dataProvider getInvalidReferences
* @expectedException \Psy\Exception\FatalErrorException
*/
public function testProcessInvalidConstantReferences($code)
{
$this->parseAndTraverse($code);
}
public function getInvalidReferences()
{
return [
['Foo\BAR'],
// class constant fetch
['Psy\Test\CodeCleaner\ValidConstantPassTest::FOO'],
['DateTime::BACON'],
];
}
/**
* @dataProvider getValidReferences
*/
public function testProcessValidConstantReferences($code)
{
$this->parseAndTraverse($code);
$this->assertTrue(true);
}
public function getValidReferences()
{
return [
['PHP_EOL'],
// class constant fetch
['NotAClass::FOO'],
['DateTime::ATOM'],
['$a = new DateTime; $a::ATOM'],
['DateTime::class'],
['$a = new DateTime; $a::class'],
];
}
}

View file

@ -0,0 +1,93 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\CodeCleaner;
use Psy\CodeCleaner\ValidConstructorPass;
class ValidConstructorPassTest extends CodeCleanerTestCase
{
protected function setUp()
{
$this->setPass(new ValidConstructorPass());
}
/**
* @dataProvider invalidStatements
* @expectedException \Psy\Exception\FatalErrorException
*/
public function testProcessInvalidStatement($code)
{
$this->parseAndTraverse($code);
}
/**
* @dataProvider invalidParserStatements
* @expectedException \Psy\Exception\ParseErrorException
*/
public function testProcessInvalidStatementCatchedByParser($code)
{
$this->parseAndTraverse($code);
}
public function invalidStatements()
{
$data = [
['class A { public static function A() {}}'],
['class A { public static function a() {}}'],
['class A { private static function A() {}}'],
['class A { private static function a() {}}'],
];
if (\version_compare(PHP_VERSION, '7.0', '>=')) {
$data[] = ['class A { public function A(): ?array {}}'];
$data[] = ['class A { public function a(): ?array {}}'];
}
return $data;
}
public function invalidParserStatements()
{
return [
['class A { public static function __construct() {}}'],
['class A { private static function __construct() {}}'],
['class A { private static function __construct() {} public function A() {}}'],
['namespace B; class A { private static function __construct() {}}'],
];
}
/**
* @dataProvider validStatements
*/
public function testProcessValidStatement($code)
{
$this->parseAndTraverse($code);
$this->assertTrue(true);
}
public function validStatements()
{
$data = [
['class A { public static function A() {} public function __construct() {}}'],
['class A { private function __construct() {} public static function A() {}}'],
['namespace B; class A { private static function A() {}}'],
];
if (\version_compare(PHP_VERSION, '7.0', '>=')) {
$data[] = ['class A { public static function A() {} public function __construct() {}}'];
$data[] = ['class A { private function __construct() {} public static function A(): ?array {}}'];
$data[] = ['namespace B; class A { private static function A(): ?array {}}'];
}
return $data;
}
}

View file

@ -0,0 +1,180 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\CodeCleaner;
use Psy\CodeCleaner\ValidFunctionNamePass;
class ValidFunctionNamePassTest extends CodeCleanerTestCase
{
public function setUp()
{
$this->setPass(new ValidFunctionNamePass());
}
/**
* @dataProvider getInvalidFunctions
* @expectedException \Psy\Exception\FatalErrorException
*/
public function testProcessInvalidFunctionCallsAndDeclarations($code)
{
$this->parseAndTraverse($code);
}
public function getInvalidFunctions()
{
return [
// function declarations
['function array_merge() {}'],
['function Array_Merge() {}'],
['
function psy_test_codecleaner_validfunctionnamepass_alpha() {}
function psy_test_codecleaner_validfunctionnamepass_alpha() {}
'],
['
namespace Psy\\Test\\CodeCleaner\\ValidFunctionNamePass {
function beta() {}
}
namespace Psy\\Test\\CodeCleaner\\ValidFunctionNamePass {
function beta() {}
}
'],
// function calls
['psy_test_codecleaner_validfunctionnamepass_gamma()'],
['
namespace Psy\\Test\\CodeCleaner\\ValidFunctionNamePass {
delta();
}
'],
// recursion
['function a() { a(); } function a() {}'],
];
}
/**
* @dataProvider getValidFunctions
*/
public function testProcessValidFunctionCallsAndDeclarations($code)
{
$this->parseAndTraverse($code);
$this->assertTrue(true);
}
public function getValidFunctions()
{
return [
['function psy_test_codecleaner_validfunctionnamepass_epsilon() {}'],
['
namespace Psy\\Test\\CodeCleaner\\ValidFunctionNamePass {
function zeta() {}
}
'],
['
namespace {
function psy_test_codecleaner_validfunctionnamepass_eta() {}
}
namespace Psy\\Test\\CodeCleaner\\ValidFunctionNamePass {
function psy_test_codecleaner_validfunctionnamepass_eta() {}
}
'],
['
namespace Psy\\Test\\CodeCleaner\\ValidFunctionNamePass {
function psy_test_codecleaner_validfunctionnamepass_eta() {}
}
namespace {
function psy_test_codecleaner_validfunctionnamepass_eta() {}
}
'],
['
namespace Psy\\Test\\CodeCleaner\\ValidFunctionNamePass {
function array_merge() {}
}
'],
// function calls
['array_merge();'],
['
namespace Psy\\Test\\CodeCleaner\\ValidFunctionNamePass {
function theta() {}
}
namespace Psy\\Test\\CodeCleaner\\ValidFunctionNamePass {
theta();
}
'],
// closures
['$test = function(){};$test()'],
['
namespace Psy\\Test\\CodeCleaner\\ValidFunctionNamePass {
function theta() {}
}
namespace {
Psy\\Test\\CodeCleaner\\ValidFunctionNamePass\\theta();
}
'],
// recursion
['function a() { a(); }'],
// conditionally defined functions
['
function a() {}
if (false) {
function a() {}
}
'],
['
function a() {}
if (true) {
function a() {}
} else if (false) {
function a() {}
} else {
function a() {}
}
'],
// ewww
['
function a() {}
if (true):
function a() {}
elseif (false):
function a() {}
else:
function a() {}
endif;
'],
['
function a() {}
while (false) { function a() {} }
'],
['
function a() {}
do { function a() {} } while (false);
'],
['
function a() {}
switch (1) {
case 0:
function a() {}
break;
case 1:
function a() {}
break;
case 2:
function a() {}
break;
}
'],
];
}
}

View file

@ -0,0 +1,131 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test;
use Psy\CodeCleaner;
class CodeCleanerTest extends \PHPUnit\Framework\TestCase
{
/**
* @dataProvider semicolonCodeProvider
*/
public function testAutomaticSemicolons(array $lines, $requireSemicolons, $expected)
{
$cc = new CodeCleaner();
$this->assertSame($expected, $cc->clean($lines, $requireSemicolons));
}
public function semicolonCodeProvider()
{
return [
[['true'], false, 'return true;'],
[['true;'], false, 'return true;'],
[['true;'], true, 'return true;'],
[['true'], true, false],
[['echo "foo";', 'true'], true, false],
[['echo "foo";', 'true'], false, "echo \"foo\";\nreturn true;"],
];
}
/**
* @dataProvider unclosedStatementsProvider
*/
public function testUnclosedStatements(array $lines, $isUnclosed)
{
$cc = new CodeCleaner();
$res = $cc->clean($lines);
if ($isUnclosed) {
$this->assertFalse($res);
} else {
$this->assertNotFalse($res);
}
}
public function unclosedStatementsProvider()
{
return [
[['echo "'], true],
[['echo \''], true],
[['if (1) {'], true],
[['echo "foo",'], true],
[['echo ""'], false],
[["echo ''"], false],
[['if (1) {}'], false],
[['// closed comment'], false],
[['function foo() { /**'], true],
[['var_dump(1, 2,'], true],
[['var_dump(1, 2,', '3)'], false],
];
}
/**
* @dataProvider moreUnclosedStatementsProvider
*/
public function testMoreUnclosedStatements(array $lines)
{
if (\defined('HHVM_VERSION')) {
$this->markTestSkipped('HHVM not supported.');
}
$cc = new CodeCleaner();
$res = $cc->clean($lines);
$this->assertFalse($res);
}
public function moreUnclosedStatementsProvider()
{
return [
[["\$content = <<<EOS\n"]],
[["\$content = <<<'EOS'\n"]],
[['/* unclosed comment']],
[['/** unclosed comment']],
];
}
/**
* @dataProvider invalidStatementsProvider
* @expectedException \Psy\Exception\ParseErrorException
*/
public function testInvalidStatementsThrowParseErrors($code)
{
$cc = new CodeCleaner();
$cc->clean([$code]);
}
public function invalidStatementsProvider()
{
// n.b. We used to check that `var_dump(1,2,)` failed, but PHP Parser
// 4.x backported trailing comma function calls from PHP 7.3 for free!
// so we're not going to spend too much time worrying about it :)
return [
['function "what'],
["function 'what"],
['echo }'],
['echo {'],
['if (1) }'],
['echo """'],
["echo '''"],
['$foo "bar'],
['$foo \'bar'],
];
}
}

View file

@ -0,0 +1,29 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Console\Tests\Command;
use Psy\Command\ExitCommand;
use Symfony\Component\Console\Tester\CommandTester;
class ExitCommandTest extends \PHPUnit\Framework\TestCase
{
/**
* @expectedException \Psy\Exception\BreakException
* @expectedExceptionMessage Goodbye
*/
public function testExecute()
{
$command = new ExitCommand();
$tester = new CommandTester($command);
$tester->execute([]);
}
}

View file

@ -0,0 +1,89 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Console\Tests\Command;
use Psy\Command\ThrowUpCommand;
use Psy\Shell;
use Symfony\Component\Console\Tester\CommandTester;
class ThrowUpCommandTest extends \PHPUnit\Framework\TestCase
{
/**
* @dataProvider executeThis
*/
public function testExecute($args, $hasCode, $expect, $addSilent = true)
{
$shell = $this->getMockBuilder('Psy\\Shell')
->setMethods(['hasCode', 'addCode'])
->getMock();
$shell->expects($this->once())->method('hasCode')->willReturn($hasCode);
$shell->expects($this->once())
->method('addCode')
->with($this->equalTo($expect), $this->equalTo($addSilent));
$command = new ThrowUpCommand();
$command->setApplication($shell);
$tester = new CommandTester($command);
$tester->execute($args);
$this->assertEquals('', $tester->getDisplay());
}
public function executeThis()
{
$throw = 'throw \Psy\Exception\ThrowUpException::fromThrowable';
return [
[[], false, $throw . '($_e);'],
[['exception' => '$ex'], false, $throw . '($ex);'],
[['exception' => 'getException()'], false, $throw . '(getException());'],
[['exception' => 'new \\Exception("WAT")'], false, $throw . '(new \\Exception("WAT"));'],
[['exception' => '\'some string\''], false, $throw . '(new \\Exception(\'some string\'));'],
[['exception' => '"WHEEEEEEE!"'], false, $throw . '(new \\Exception("WHEEEEEEE!"));'],
// Everything should work with or without semicolons.
[['exception' => '$ex;'], false, $throw . '($ex);'],
[['exception' => '"WHEEEEEEE!";'], false, $throw . '(new \\Exception("WHEEEEEEE!"));'],
// Don't add as silent code if we've already got code.
[[], true, $throw . '($_e);', false],
[['exception' => 'getException()'], true, $throw . '(getException());', false],
[['exception' => '\'some string\''], true, $throw . '(new \\Exception(\'some string\'));', false],
];
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage No idea how to throw this
*/
public function testMultipleArgsThrowsException()
{
$command = new ThrowUpCommand();
$command->setApplication(new Shell());
$tester = new CommandTester($command);
$tester->execute(['exception' => 'foo(); bar()']);
}
/**
* @expectedException \PhpParser\Error
* @expectedExceptionMessage Syntax error, unexpected ')' on line 1
*/
public function testParseErrorThrowsException()
{
$command = new ThrowUpCommand();
$command->setApplication(new Shell());
$tester = new CommandTester($command);
$tester->execute(['exception' => 'foo)']);
}
}

View file

@ -0,0 +1,52 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Command\TimeitCommand;
use PhpParser\NodeTraverser;
use Psy\Command\TimeitCommand\TimeitVisitor;
use Psy\Test\ParserTestCase;
class TimeitVisitorTest extends ParserTestCase
{
public function setUp()
{
$this->traverser = new NodeTraverser();
$this->traverser->addVisitor(new TimeitVisitor());
}
/**
* @dataProvider codez
*/
public function testProcess($from, $to)
{
$this->assertProcessesAs($from, $to);
}
public function codez()
{
$start = '\Psy\Command\TimeitCommand::markStart';
$end = '\Psy\Command\TimeitCommand::markEnd';
$noReturn = 'new \Psy\CodeCleaner\NoReturnValue()';
return [
['', "$end($start());"], // heh
['a()', "$start(); $end(a());"],
['$b()', "$start(); $end(\$b());"],
['$c->d()', "$start(); $end(\$c->d());"],
['e(); f()', "$start(); e(); $end(f());"],
['function g() { return 1; }', "$start(); function g() {return 1;} $end($noReturn);"],
['return 1', "$start(); return $end(1);"],
['return 1; 2', "$start(); return $end(1); $end(2);"],
['return 1; function h() {}', "$start(); return $end(1); function h() {} $end($noReturn);"],
];
}
}

View file

@ -0,0 +1,256 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test;
use Psy\CodeCleaner;
use Psy\Configuration;
use Psy\Output\PassthruPager;
use Psy\VersionUpdater\GitHubChecker;
use Symfony\Component\Console\Output\ConsoleOutput;
class ConfigurationTest extends \PHPUnit\Framework\TestCase
{
private function getConfig($configFile = null)
{
return new Configuration([
'configFile' => $configFile ?: __DIR__ . '/fixtures/empty.php',
]);
}
public function testDefaults()
{
$config = $this->getConfig();
$this->assertSame(\function_exists('readline'), $config->hasReadline());
$this->assertSame(\function_exists('readline'), $config->useReadline());
$this->assertSame(\function_exists('pcntl_signal'), $config->hasPcntl());
$this->assertSame(\function_exists('pcntl_signal'), $config->usePcntl());
$this->assertFalse($config->requireSemicolons());
$this->assertSame(Configuration::COLOR_MODE_AUTO, $config->colorMode());
$this->assertNull($config->getStartupMessage());
}
public function testGettersAndSetters()
{
$config = $this->getConfig();
$this->assertNull($config->getDataDir());
$config->setDataDir('wheee');
$this->assertSame('wheee', $config->getDataDir());
$this->assertNull($config->getConfigDir());
$config->setConfigDir('wheee');
$this->assertSame('wheee', $config->getConfigDir());
}
/**
* @dataProvider directories
*/
public function testFilesAndDirectories($home, $configFile, $historyFile, $manualDbFile)
{
$oldHome = \getenv('HOME');
\putenv("HOME=$home");
$config = new Configuration();
$this->assertSame(\realpath($configFile), \realpath($config->getConfigFile()));
$this->assertSame(\realpath($historyFile), \realpath($config->getHistoryFile()));
$this->assertSame(\realpath($manualDbFile), \realpath($config->getManualDbFile()));
\putenv("HOME=$oldHome");
}
public function directories()
{
$base = \realpath(__DIR__ . '/fixtures');
return [
[
$base . '/default',
$base . '/default/.config/psysh/config.php',
$base . '/default/.config/psysh/psysh_history',
$base . '/default/.local/share/psysh/php_manual.sqlite',
],
[
$base . '/legacy',
$base . '/legacy/.psysh/rc.php',
$base . '/legacy/.psysh/history',
$base . '/legacy/.psysh/php_manual.sqlite',
],
[
$base . '/mixed',
$base . '/mixed/.psysh/config.php',
$base . '/mixed/.psysh/psysh_history',
null,
],
];
}
public function testLoadConfig()
{
$config = $this->getConfig();
$cleaner = new CodeCleaner();
$pager = new PassthruPager(new ConsoleOutput());
$config->loadConfig([
'useReadline' => false,
'usePcntl' => false,
'codeCleaner' => $cleaner,
'pager' => $pager,
'requireSemicolons' => true,
'errorLoggingLevel' => E_ERROR | E_WARNING,
'colorMode' => Configuration::COLOR_MODE_FORCED,
'startupMessage' => 'Psysh is awesome!',
]);
$this->assertFalse($config->useReadline());
$this->assertFalse($config->usePcntl());
$this->assertSame($cleaner, $config->getCodeCleaner());
$this->assertSame($pager, $config->getPager());
$this->assertTrue($config->requireSemicolons());
$this->assertSame(E_ERROR | E_WARNING, $config->errorLoggingLevel());
$this->assertSame(Configuration::COLOR_MODE_FORCED, $config->colorMode());
$this->assertSame('Psysh is awesome!', $config->getStartupMessage());
}
public function testLoadConfigFile()
{
$config = $this->getConfig(__DIR__ . '/fixtures/config.php');
$runtimeDir = $this->joinPath(\realpath(\sys_get_temp_dir()), 'psysh_test', 'withconfig', 'temp');
$this->assertStringStartsWith($runtimeDir, \realpath($config->getTempFile('foo', 123)));
$this->assertStringStartsWith($runtimeDir, \realpath(\dirname($config->getPipe('pipe', 123))));
$this->assertStringStartsWith($runtimeDir, \realpath($config->getRuntimeDir()));
$this->assertSame(\function_exists('readline'), $config->useReadline());
$this->assertFalse($config->usePcntl());
$this->assertSame(E_ALL & ~E_NOTICE, $config->errorLoggingLevel());
}
public function testLoadLocalConfigFile()
{
$oldPwd = \getcwd();
\chdir(\realpath(__DIR__ . '/fixtures/project/'));
$config = new Configuration();
// When no configuration file is specified local project config is merged
$this->assertTrue($config->requireSemicolons());
$this->assertFalse($config->useUnicode());
$config = new Configuration(['configFile' => __DIR__ . '/fixtures/config.php']);
// Defining a configuration file skips loading local project config
$this->assertFalse($config->requireSemicolons());
$this->assertTrue($config->useUnicode());
\chdir($oldPwd);
}
/**
* @expectedException \Psy\Exception\DeprecatedException
*/
public function testBaseDirConfigIsDeprecated()
{
$config = new Configuration(['baseDir' => 'fake']);
}
private function joinPath()
{
return \implode(DIRECTORY_SEPARATOR, \func_get_args());
}
public function testConfigIncludes()
{
$config = new Configuration([
'defaultIncludes' => ['/file.php'],
'configFile' => __DIR__ . '/fixtures/empty.php',
]);
$includes = $config->getDefaultIncludes();
$this->assertCount(1, $includes);
$this->assertSame('/file.php', $includes[0]);
}
public function testGetOutput()
{
$config = $this->getConfig();
$output = $config->getOutput();
$this->assertInstanceOf('Psy\Output\ShellOutput', $output);
}
public function getOutputDecoratedProvider()
{
return [
'auto' => [
null,
Configuration::COLOR_MODE_AUTO,
],
'forced' => [
true,
Configuration::COLOR_MODE_FORCED,
],
'disabled' => [
false,
Configuration::COLOR_MODE_DISABLED,
],
];
}
/** @dataProvider getOutputDecoratedProvider */
public function testGetOutputDecorated($expectation, $colorMode)
{
$config = $this->getConfig();
$config->setColorMode($colorMode);
$this->assertSame($expectation, $config->getOutputDecorated());
}
public function setColorModeValidProvider()
{
return [
'auto' => [Configuration::COLOR_MODE_AUTO],
'forced' => [Configuration::COLOR_MODE_FORCED],
'disabled' => [Configuration::COLOR_MODE_DISABLED],
];
}
/** @dataProvider setColorModeValidProvider */
public function testSetColorModeValid($colorMode)
{
$config = $this->getConfig();
$config->setColorMode($colorMode);
$this->assertSame($colorMode, $config->colorMode());
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage invalid color mode: some invalid mode
*/
public function testSetColorModeInvalid()
{
$config = $this->getConfig();
$config->setColorMode('some invalid mode');
}
public function testSetCheckerValid()
{
$config = $this->getConfig();
$checker = new GitHubChecker();
$config->setChecker($checker);
$this->assertSame($checker, $config->getChecker());
}
}

View file

@ -0,0 +1,51 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test;
use Psy\Configuration;
use Psy\ConsoleColorFactory;
class ConsoleColorFactoryTest extends \PHPUnit\Framework\TestCase
{
public function testGetConsoleColorAuto()
{
$colorMode = Configuration::COLOR_MODE_AUTO;
$factory = new ConsoleColorFactory($colorMode);
$colors = $factory->getConsoleColor();
$themes = $colors->getThemes();
$this->assertFalse($colors->isStyleForced());
$this->assertSame(['blue'], $themes['line_number']);
}
public function testGetConsoleColorForced()
{
$colorMode = Configuration::COLOR_MODE_FORCED;
$factory = new ConsoleColorFactory($colorMode);
$colors = $factory->getConsoleColor();
$themes = $colors->getThemes();
$this->assertTrue($colors->isStyleForced());
$this->assertSame(['blue'], $themes['line_number']);
}
public function testGetConsoleColorDisabled()
{
$colorMode = Configuration::COLOR_MODE_DISABLED;
$factory = new ConsoleColorFactory($colorMode);
$colors = $factory->getConsoleColor();
$themes = $colors->getThemes();
$this->assertFalse($colors->isStyleForced());
$this->assertSame(['none'], $themes['line_number']);
}
}

325
vendor/psy/psysh/test/ContextTest.php vendored Normal file
View file

@ -0,0 +1,325 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test;
use Psy\Context;
class ContextTest extends \PHPUnit\Framework\TestCase
{
public function testGet()
{
$this->assertTrue(true);
}
public function testGetAll()
{
$this->assertTrue(true);
}
public function testGetSpecialVariables()
{
$context = new Context();
$this->assertNull($context->get('_'));
$this->assertNull($context->getReturnValue());
$this->assertEquals(['_' => null], $context->getAll());
$e = new \Exception('eeeeeee');
$obj = new \StdClass();
$context->setLastException($e);
$context->setLastStdout('out');
$context->setBoundObject($obj);
$context->setCommandScopeVariables([
'__function' => 'function',
'__method' => 'method',
'__class' => 'class',
'__namespace' => 'namespace',
'__file' => 'file',
'__line' => 'line',
'__dir' => 'dir',
]);
$expected = [
'_' => null,
'_e' => $e,
'__out' => 'out',
'this' => $obj,
'__function' => 'function',
'__method' => 'method',
'__class' => 'class',
'__namespace' => 'namespace',
'__file' => 'file',
'__line' => 'line',
'__dir' => 'dir',
];
$this->assertEquals($expected, $context->getAll());
}
public function testSetAll()
{
$context = new Context();
$baz = new \StdClass();
$vars = [
'foo' => 'Foo',
'bar' => 123,
'baz' => $baz,
'_' => 'fail',
'_e' => 'fail',
'__out' => 'fail',
'this' => 'fail',
'__psysh__' => 'fail',
'__function' => 'fail',
'__method' => 'fail',
'__class' => 'fail',
'__namespace' => 'fail',
'__file' => 'fail',
'__line' => 'fail',
'__dir' => 'fail',
];
$context->setAll($vars);
$this->assertEquals('Foo', $context->get('foo'));
$this->assertEquals(123, $context->get('bar'));
$this->assertSame($baz, $context->get('baz'));
$this->assertEquals(['foo' => 'Foo', 'bar' => 123, 'baz' => $baz, '_' => null], $context->getAll());
}
/**
* @dataProvider specialNames
* @expectedException \InvalidArgumentException
* @expectedExceptionMessageRegEx /Unknown variable: \$\w+/
*/
public function testSetAllDoesNotSetSpecial($name)
{
$context = new Context();
$context->setAll([$name => 'fail']);
$context->get($name);
}
public function specialNames()
{
return [
['_e'],
['__out'],
['this'],
['__psysh__'],
['__function'],
['__method'],
['__class'],
['__namespace'],
['__file'],
['__line'],
['__dir'],
];
}
public function testReturnValue()
{
$context = new Context();
$this->assertNull($context->getReturnValue());
$val = 'some string';
$context->setReturnValue($val);
$this->assertEquals($val, $context->getReturnValue());
$this->assertEquals($val, $context->get('_'));
$obj = new \StdClass();
$context->setReturnValue($obj);
$this->assertSame($obj, $context->getReturnValue());
$this->assertSame($obj, $context->get('_'));
$context->setReturnValue(null);
$this->assertNull($context->getReturnValue());
}
public function testLastException()
{
$context = new Context();
$e = new \Exception('wat');
$context->setLastException($e);
$this->assertSame($e, $context->getLastException());
$this->assertSame($e, $context->get('_e'));
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage No most-recent exception
*/
public function testLastExceptionThrowsSometimes()
{
$context = new Context();
$context->getLastException();
}
public function testLastStdout()
{
$context = new Context();
$context->setLastStdout('ouuuuut');
$this->assertEquals('ouuuuut', $context->getLastStdout());
$this->assertEquals('ouuuuut', $context->get('__out'));
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage No most-recent output
*/
public function testLastStdoutThrowsSometimes()
{
$context = new Context();
$context->getLastStdout();
}
public function testBoundObject()
{
$context = new Context();
$this->assertNull($context->getBoundObject());
$obj = new \StdClass();
$context->setBoundObject($obj);
$this->assertSame($obj, $context->getBoundObject());
$this->assertSame($obj, $context->get('this'));
$context->setBoundObject(null);
$this->assertNull($context->getBoundObject());
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Unknown variable: $this
*/
public function testBoundObjectThrowsSometimes()
{
$context = new Context();
$context->get('this');
}
public function testBoundClass()
{
$context = new Context();
$this->assertNull($context->getBoundClass());
$context->setBoundClass('');
$this->assertNull($context->getBoundClass());
$context->setBoundClass('Psy\Shell');
$this->assertEquals('Psy\Shell', $context->getBoundClass());
$context->setBoundObject(new \StdClass());
$this->assertNotNull($context->getBoundObject());
$this->assertNull($context->getBoundClass());
$context->setBoundClass('Psy\Shell');
$this->assertEquals('Psy\Shell', $context->getBoundClass());
$this->assertNull($context->getBoundObject());
$context->setBoundClass(null);
$this->assertNull($context->getBoundClass());
$this->assertNull($context->getBoundObject());
}
public function testCommandScopeVariables()
{
$__function = 'donkey';
$__method = 'diddy';
$__class = 'cranky';
$__namespace = 'funky';
$__file = 'candy';
$__line = 'dixie';
$__dir = 'wrinkly';
$vars = \compact('__function', '__method', '__class', '__namespace', '__file', '__line', '__dir');
$context = new Context();
$context->setCommandScopeVariables($vars);
$this->assertEquals($vars, $context->getCommandScopeVariables());
$this->assertEquals($__function, $context->get('__function'));
$this->assertEquals($__method, $context->get('__method'));
$this->assertEquals($__class, $context->get('__class'));
$this->assertEquals($__namespace, $context->get('__namespace'));
$this->assertEquals($__file, $context->get('__file'));
$this->assertEquals($__line, $context->get('__line'));
$this->assertEquals($__dir, $context->get('__dir'));
$someVars = \compact('__function', '__namespace', '__file', '__line', '__dir');
$context->setCommandScopeVariables($someVars);
}
public function testGetUnusedCommandScopeVariableNames()
{
$context = new Context();
$this->assertEquals(
['__function', '__method', '__class', '__namespace', '__file', '__line', '__dir'],
$context->getUnusedCommandScopeVariableNames()
);
$context->setCommandScopeVariables([
'__function' => 'foo',
'__namespace' => 'bar',
'__file' => 'baz',
'__line' => 123,
'__dir' => 'qux',
]);
$this->assertEquals(
['__method', '__class'],
\array_values($context->getUnusedCommandScopeVariableNames())
);
}
/**
* @dataProvider specialAndNotSpecialVariableNames
*/
public function testIsSpecialVariableName($name, $isSpecial)
{
$context = new Context();
if ($isSpecial) {
$this->assertTrue($context->isSpecialVariableName($name));
} else {
$this->assertFalse($context->isSpecialVariableName($name));
}
}
public function specialAndNotSpecialVariableNames()
{
return [
['foo', false],
['psysh', false],
['__psysh', false],
['_', true],
['_e', true],
['__out', true],
['this', true],
['__psysh__', true],
['__function', true],
['__method', true],
['__class', true],
['__namespace', true],
['__file', true],
['__line', true],
['__dir', true],
];
}
}

View file

@ -0,0 +1,42 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Exception;
use Psy\Exception\BreakException;
class BreakExceptionTest extends \PHPUnit\Framework\TestCase
{
public function testInstance()
{
$e = new BreakException();
$this->assertInstanceOf('Psy\Exception\Exception', $e);
$this->assertInstanceOf('Psy\Exception\BreakException', $e);
}
public function testMessage()
{
$e = new BreakException('foo');
$this->assertContains('foo', $e->getMessage());
$this->assertSame('foo', $e->getRawMessage());
}
/**
* @expectedException \Psy\Exception\BreakException
* @expectedExceptionMessage Goodbye
*/
public function testExitShell()
{
BreakException::exitShell();
}
}

View file

@ -0,0 +1,125 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Exception;
use Psy\Exception\ErrorException;
class ErrorExceptionTest extends \PHPUnit\Framework\TestCase
{
public function testInstance()
{
$e = new ErrorException();
$this->assertInstanceOf('Psy\Exception\Exception', $e);
$this->assertInstanceOf('ErrorException', $e);
$this->assertInstanceOf('Psy\Exception\ErrorException', $e);
}
public function testMessage()
{
$e = new ErrorException('foo');
$this->assertContains('foo', $e->getMessage());
$this->assertSame('foo', $e->getRawMessage());
}
/**
* @dataProvider getLevels
*/
public function testErrorLevels($level, $type)
{
$e = new ErrorException('foo', 0, $level);
$this->assertContains('PHP ' . $type, $e->getMessage());
}
/**
* @dataProvider getLevels
*/
public function testThrowException($level, $type)
{
try {
ErrorException::throwException($level, '{whot}', '{file}', '13');
} catch (ErrorException $e) {
$this->assertContains('PHP ' . $type, $e->getMessage());
$this->assertContains('{whot}', $e->getMessage());
$this->assertContains('in {file}', $e->getMessage());
$this->assertContains('on line 13', $e->getMessage());
}
}
public function getLevels()
{
return [
[E_WARNING, 'Warning'],
[E_CORE_WARNING, 'Warning'],
[E_COMPILE_WARNING, 'Warning'],
[E_USER_WARNING, 'Warning'],
[E_STRICT, 'Strict error'],
[E_DEPRECATED, 'Deprecated'],
[E_USER_DEPRECATED, 'Deprecated'],
[E_RECOVERABLE_ERROR, 'Recoverable fatal error'],
[0, 'Error'],
];
}
/**
* @dataProvider getUserLevels
*/
public function testThrowExceptionAsErrorHandler($level, $type)
{
\set_error_handler(['Psy\Exception\ErrorException', 'throwException']);
try {
\trigger_error('{whot}', $level);
} catch (ErrorException $e) {
$this->assertContains('PHP ' . $type, $e->getMessage());
$this->assertContains('{whot}', $e->getMessage());
}
\restore_error_handler();
}
public function getUserLevels()
{
return [
[E_USER_ERROR, 'Error'],
[E_USER_WARNING, 'Warning'],
[E_USER_NOTICE, 'Notice'],
[E_USER_DEPRECATED, 'Deprecated'],
];
}
public function testIgnoreExecutionLoopFilename()
{
$e = new ErrorException('{{message}}', 0, 1, '/fake/path/to/Psy/ExecutionLoop.php');
$this->assertEmpty($e->getFile());
$e = new ErrorException('{{message}}', 0, 1, 'c:\fake\path\to\Psy\ExecutionLoop.php');
$this->assertEmpty($e->getFile());
$e = new ErrorException('{{message}}', 0, 1, '/fake/path/to/Psy/File.php');
$this->assertNotEmpty($e->getFile());
}
public function testFromError()
{
if (\version_compare(PHP_VERSION, '7.0.0', '<')) {
$this->markTestSkipped();
}
$error = new \Error('{{message}}', 0);
$exception = ErrorException::fromError($error);
$this->assertContains('PHP Error: {{message}}', $exception->getMessage());
$this->assertEquals(0, $exception->getCode());
$this->assertEquals($error->getFile(), $exception->getFile());
$this->assertSame($exception->getPrevious(), $error);
}
}

View file

@ -0,0 +1,51 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Exception;
use Psy\Exception\FatalErrorException;
class FatalErrorExceptionTest extends \PHPUnit\Framework\TestCase
{
public function testInstance()
{
$e = new FatalErrorException();
$this->assertInstanceOf('Psy\Exception\Exception', $e);
$this->assertInstanceOf('ErrorException', $e);
$this->assertInstanceOf('Psy\Exception\FatalErrorException', $e);
}
public function testMessage()
{
$e = new FatalErrorException('{msg}', 0, 0, '{filename}', 13);
$this->assertSame('{msg}', $e->getRawMessage());
$this->assertContains('{msg}', $e->getMessage());
$this->assertContains('{filename}', $e->getMessage());
$this->assertContains('line 13', $e->getMessage());
}
public function testMessageWithNoFilename()
{
$e = new FatalErrorException('{msg}');
$this->assertSame('{msg}', $e->getRawMessage());
$this->assertContains('{msg}', $e->getMessage());
$this->assertContains('eval()\'d code', $e->getMessage());
}
public function testNegativeOneLineNumberIgnored()
{
$e = new FatalErrorException('{msg}', 0, 1, null, -1);
$this->assertEquals(0, $e->getLine());
}
}

View file

@ -0,0 +1,42 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Exception;
use Psy\Exception\ParseErrorException;
class ParseErrorExceptionTest extends \PHPUnit\Framework\TestCase
{
public function testInstance()
{
$e = new ParseErrorException();
$this->assertInstanceOf('Psy\Exception\Exception', $e);
$this->assertInstanceOf('PhpParser\Error', $e);
$this->assertInstanceOf('Psy\Exception\ParseErrorException', $e);
}
public function testMessage()
{
$e = new ParseErrorException('{msg}', 1);
$this->assertContains('{msg}', $e->getMessage());
$this->assertContains('PHP Parse error:', $e->getMessage());
}
public function testConstructFromParseError()
{
$e = ParseErrorException::fromParseError(new \PhpParser\Error('{msg}'));
$this->assertContains('{msg}', $e->getRawMessage());
$this->assertContains('PHP Parse error:', $e->getMessage());
}
}

View file

@ -0,0 +1,30 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Exception;
use Psy\Exception\RuntimeException;
class RuntimeExceptionTest extends \PHPUnit\Framework\TestCase
{
public function testException()
{
$msg = 'bananas';
$e = new RuntimeException($msg);
$this->assertInstanceOf('Psy\Exception\Exception', $e);
$this->assertInstanceOf('RuntimeException', $e);
$this->assertInstanceOf('Psy\Exception\RuntimeException', $e);
$this->assertSame($msg, $e->getMessage());
$this->assertSame($msg, $e->getRawMessage());
}
}

View file

@ -0,0 +1,66 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Exception;
use Psy\Exception\ThrowUpException;
class ThrowUpExceptionTest extends \PHPUnit\Framework\TestCase
{
public function testException()
{
$previous = new \Exception('{{message}}', 123);
$e = new ThrowUpException($previous);
$this->assertInstanceOf('Psy\Exception\Exception', $e);
$this->assertInstanceOf('Psy\Exception\ThrowUpException', $e);
$this->assertEquals("Throwing Exception with message '{{message}}'", $e->getMessage());
$this->assertEquals('{{message}}', $e->getRawMessage());
$this->assertEquals(123, $e->getCode());
$this->assertSame($previous, $e->getPrevious());
}
public function testFromThrowable()
{
$previous = new \Exception('{{message}}');
$e = ThrowUpException::fromThrowable($previous);
$this->assertInstanceOf('Psy\Exception\ThrowUpException', $e);
$this->assertSame($previous, $e->getPrevious());
}
public function testFromThrowableWithError()
{
if (\version_compare(PHP_VERSION, '7.0.0', '<')) {
$this->markTestSkipped();
}
$previous = new \Error('{{message}}');
$e = ThrowUpException::fromThrowable($previous);
$this->assertInstanceOf('Psy\Exception\ThrowUpException', $e);
$this->assertInstanceOf('Psy\Exception\ErrorException', $e->getPrevious());
$this->assertNotSame($previous, $e->getPrevious());
$this->assertSame($previous, $e->getPrevious()->getPrevious());
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage throw-up can only throw Exceptions and Errors
*/
public function testFromThrowableThrowsError()
{
$notThrowable = new \StdClass();
ThrowUpException::fromThrowable($notThrowable);
}
}

View file

@ -0,0 +1,52 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Exception;
use Psy\Exception\TypeErrorException;
class TypeErrorExceptionTest extends \PHPUnit\Framework\TestCase
{
public function testException()
{
$e = new TypeErrorException('{{message}}', 13);
$this->assertInstanceOf('Psy\Exception\Exception', $e);
$this->assertInstanceOf('Psy\Exception\TypeErrorException', $e);
$this->assertEquals('TypeError: {{message}}', $e->getMessage());
$this->assertEquals('{{message}}', $e->getRawMessage());
$this->assertEquals(13, $e->getCode());
}
public function testStripsEvalFromMessage()
{
$message = 'Something or other, called in line 10: eval()\'d code';
$e = new TypeErrorException($message);
$this->assertEquals($message, $e->getRawMessage());
$this->assertEquals('TypeError: Something or other', $e->getMessage());
}
public function testFromTypeError()
{
if (\version_compare(PHP_VERSION, '7.0.0', '<')) {
$this->markTestSkipped();
}
$previous = new \TypeError('{{message}}', 13);
$e = TypeErrorException::fromTypeError($previous);
$this->assertInstanceOf('Psy\Exception\TypeErrorException', $e);
$this->assertEquals('TypeError: {{message}}', $e->getMessage());
$this->assertEquals('{{message}}', $e->getRawMessage());
$this->assertEquals(13, $e->getCode());
}
}

29
vendor/psy/psysh/test/FakeShell.php vendored Normal file
View file

@ -0,0 +1,29 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test;
use Psy\Shell;
class FakeShell extends Shell
{
public $matchers;
public function __construct(Configuration $config = null)
{
// This space intentionally left blank
}
public function addMatchers(array $matchers)
{
$this->matchers = $matchers;
}
}

View file

@ -0,0 +1,129 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Formatter;
use Psy\Formatter\CodeFormatter;
use Psy\Test\Formatter\Fixtures\SomeClass;
class CodeFormatterTest extends \PHPUnit\Framework\TestCase
{
/**
* @dataProvider reflectors
*/
public function testFormat($reflector, $expected)
{
$formatted = CodeFormatter::format($reflector);
$formattedWithoutColors = \preg_replace('#' . \chr(27) . '\[\d\d?m#', '', $formatted);
$this->assertEquals($expected, self::trimLines($formattedWithoutColors));
$this->assertNotEquals($expected, self::trimLines($formatted));
}
public function reflectors()
{
$expectClass = <<<'EOS'
> 14| class SomeClass
15| {
16| const SOME_CONST = 'some const';
17| private $someProp = 'some prop';
18|
19| public function someMethod($someParam)
20| {
21| return 'some method';
22| }
23|
24| public static function someClosure()
25| {
26| return function () {
27| return 'some closure';
28| };
29| }
30| }
EOS;
$expectMethod = <<<'EOS'
> 19| public function someMethod($someParam)
20| {
21| return 'some method';
22| }
EOS;
$expectClosure = <<<'EOS'
> 26| return function () {
27| return 'some closure';
28| };
EOS;
return [
[new \ReflectionClass('Psy\Test\Formatter\Fixtures\SomeClass'), $expectClass],
[new \ReflectionObject(new SomeClass()), $expectClass],
[new \ReflectionMethod('Psy\Test\Formatter\Fixtures\SomeClass', 'someMethod'), $expectMethod],
[new \ReflectionFunction(SomeClass::someClosure()), $expectClosure],
];
}
/**
* @dataProvider invalidReflectors
* @expectedException \Psy\Exception\RuntimeException
*/
public function testCodeFormatterThrowsExceptionForReflectorsItDoesntUnderstand($reflector)
{
CodeFormatter::format($reflector);
}
public function invalidReflectors()
{
$reflectors = [
[new \ReflectionExtension('json')],
[new \ReflectionParameter(['Psy\Test\Formatter\Fixtures\SomeClass', 'someMethod'], 'someParam')],
[new \ReflectionProperty('Psy\Test\Formatter\Fixtures\SomeClass', 'someProp')],
];
if (\version_compare(PHP_VERSION, '7.1.0', '>=')) {
$reflectors[] = [new \ReflectionClassConstant('Psy\Test\Formatter\Fixtures\SomeClass', 'SOME_CONST')];
}
return $reflectors;
}
/**
* @dataProvider filenames
* @expectedException \Psy\Exception\RuntimeException
*/
public function testCodeFormatterThrowsExceptionForMissingFile($filename)
{
$reflector = $this->getMockBuilder('ReflectionClass')
->disableOriginalConstructor()
->getMock();
$reflector
->expects($this->once())
->method('getFileName')
->will($this->returnValue($filename));
CodeFormatter::format($reflector);
}
public function filenames()
{
if (\defined('HHVM_VERSION')) {
$this->markTestSkipped('We have issues with PHPUnit mocks on HHVM.');
}
return [[null], ['not a file']];
}
private static function trimLines($code)
{
return \rtrim(\implode("\n", \array_map('rtrim', \explode("\n", $code))));
}
}

View file

@ -0,0 +1,63 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Formatter;
use Psy\Formatter\DocblockFormatter;
class DocblockFormatterTest extends \PHPUnit\Framework\TestCase
{
/**
* This is a docblock!
*
* @author Justin Hileman <justin@justinhileman.info>
*
* @throws InvalidArgumentException if $foo is empty
*
* @param mixed $foo It's a foo thing
* @param int $bar This is definitely bar
*
* @return string A string of no consequence
*/
private function methodWithDocblock($foo, $bar = 1)
{
if (empty($foo)) {
throw new \InvalidArgumentException();
}
return 'method called';
}
public function testFormat()
{
$expected = <<<EOS
<comment>Description:</comment>
This is a docblock!
<comment>Throws:</comment>
<info>InvalidArgumentException </info> if \$foo is empty
<comment>Param:</comment>
<info>mixed </info> <strong>\$foo </strong> It's a foo thing
<info>int </info> <strong>\$bar </strong> This is definitely bar
<comment>Return:</comment>
<info>string </info> A string of no consequence
<comment>Author:</comment> Justin Hileman \<justin@justinhileman.info>
EOS;
$this->assertSame(
$expected,
DocblockFormatter::format(new \ReflectionMethod($this, 'methodWithDocblock'))
);
}
}

View file

@ -0,0 +1,20 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Formatter\Fixtures;
trait BoringTrait
{
public function boringMethod($one = 1)
{
// Do nothing.
}
}

View file

@ -0,0 +1,30 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Formatter\Fixtures;
class SomeClass
{
const SOME_CONST = 'some const';
private $someProp = 'some prop';
public function someMethod($someParam)
{
return 'some method';
}
public static function someClosure()
{
return function () {
return 'some closure';
};
}
}

View file

@ -0,0 +1,95 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Formatter;
use Psy\Formatter\SignatureFormatter;
use Psy\Reflection\ReflectionClassConstant;
use Psy\Reflection\ReflectionConstant_;
class SignatureFormatterTest extends \PHPUnit\Framework\TestCase
{
const FOO = 'foo value';
private static $bar = 'bar value';
private function someFakeMethod(array $one, $two = 'TWO', \Reflector $three = null)
{
}
/**
* @dataProvider signatureReflectors
*/
public function testFormat($reflector, $expected)
{
$this->assertSame($expected, \strip_tags(SignatureFormatter::format($reflector)));
}
public function signatureReflectors()
{
return [
[
new \ReflectionFunction('implode'),
\defined('HHVM_VERSION') ? 'function implode($arg1, $arg2 = null)' : 'function implode($glue, $pieces)',
],
[
ReflectionClassConstant::create($this, 'FOO'),
'const FOO = "foo value"',
],
[
new \ReflectionMethod($this, 'someFakeMethod'),
'private function someFakeMethod(array $one, $two = \'TWO\', Reflector $three = null)',
],
[
new \ReflectionProperty($this, 'bar'),
'private static $bar',
],
[
new \ReflectionClass('Psy\CodeCleaner\CodeCleanerPass'),
'abstract class Psy\CodeCleaner\CodeCleanerPass '
. 'extends PhpParser\NodeVisitorAbstract '
. 'implements PhpParser\NodeVisitor',
],
[
new \ReflectionFunction('array_chunk'),
'function array_chunk($arg, $size, $preserve_keys = unknown)',
],
[
new \ReflectionClass('Psy\Test\Formatter\Fixtures\BoringTrait'),
'trait Psy\Test\Formatter\Fixtures\BoringTrait',
],
[
new \ReflectionMethod('Psy\Test\Formatter\Fixtures\BoringTrait', 'boringMethod'),
'public function boringMethod($one = 1)',
],
[
new ReflectionConstant_('E_ERROR'),
'define("E_ERROR", 1)',
],
[
new ReflectionConstant_('PHP_VERSION'),
'define("PHP_VERSION", "' . PHP_VERSION . '")',
],
[
new ReflectionConstant_('__LINE__'),
'define("__LINE__", null)', // @todo show this as `unknown` in red or something?
],
];
}
/**
* @expectedException \InvalidArgumentException
*/
public function testSignatureFormatterThrowsUnknownReflectorExpeption()
{
$refl = $this->getMockBuilder('Reflector')->getMock();
SignatureFormatter::format($refl);
}
}

View file

@ -0,0 +1,52 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Input;
use Psy\Input\CodeArgument;
use Symfony\Component\Console\Input\InputArgument;
class CodeArgumentTest extends \PHPUnit\Framework\TestCase
{
/**
* @dataProvider getInvalidModes
* @expectedException \InvalidArgumentException
*/
public function testInvalidModes($mode)
{
new CodeArgument('wat', $mode);
}
public function getInvalidModes()
{
return [
[InputArgument::IS_ARRAY],
[InputArgument::IS_ARRAY | InputArgument::REQUIRED],
[InputArgument::IS_ARRAY | InputArgument::OPTIONAL],
];
}
/**
* @dataProvider getValidModes
*/
public function testValidModes($mode)
{
$this->assertInstanceOf('Psy\Input\CodeArgument', new CodeArgument('yeah', $mode));
}
public function getValidModes()
{
return [
[InputArgument::REQUIRED],
[InputArgument::OPTIONAL],
];
}
}

View file

@ -0,0 +1,105 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Input;
use Psy\Input\FilterOptions;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\StringInput;
class FilterOptionsTest extends \PHPUnit\Framework\TestCase
{
public function testGetOptions()
{
$opts = FilterOptions::getOptions();
$this->assertCount(3, $opts);
}
/**
* @dataProvider validInputs
*/
public function testBindValidInput($input, $hasFilter = true)
{
$input = $this->getInput($input);
$filterOptions = new FilterOptions();
$filterOptions->bind($input);
$this->assertEquals($hasFilter, $filterOptions->hasFilter());
}
public function validInputs()
{
return [
['--grep="bar"'],
['--grep="bar" --invert'],
['--grep="bar" --insensitive'],
['--grep="bar" --invert --insensitive'],
['', false],
];
}
/**
* @dataProvider invalidInputs
* @expectedException \Psy\Exception\RuntimeException
*/
public function testBindInvalidInput($input)
{
$input = $this->getInput($input);
$filterOptions = new FilterOptions();
$filterOptions->bind($input);
}
public function invalidInputs()
{
return [
['--invert'],
['--insensitive'],
['--invert --insensitive'],
// invalid because regex
['--grep /*/'],
];
}
/**
* @dataProvider matchData
*/
public function testMatch($input, $str, $matches)
{
$input = $this->getInput($input);
$filterOptions = new FilterOptions();
$filterOptions->bind($input);
$this->assertEquals($matches, $filterOptions->match($str));
}
public function matchData()
{
return [
['', 'whatever', true],
['--grep FOO', 'foo', false],
['--grep foo', 'foo', true],
['--grep foo', 'food', true],
['--grep oo', 'Food', true],
['--grep oo -i', 'FOOD', true],
['--grep foo -v', 'food', false],
['--grep foo -v', 'whatever', true],
];
}
private function getInput($input)
{
$input = new StringInput($input);
$input->bind(new InputDefinition(FilterOptions::getOptions()));
return $input;
}
}

View file

@ -0,0 +1,254 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Input;
use Psy\Input\CodeArgument;
use Psy\Input\ShellInput;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputOption;
class ShellInputTest extends \PHPUnit\Framework\TestCase
{
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Unexpected CodeArgument before the final position: a
*/
public function testThrowsWhenCodeArgumentNotInFinalPosition()
{
$definition = new InputDefinition([
new CodeArgument('a', null, CodeArgument::REQUIRED),
new InputArgument('b', null, InputArgument::REQUIRED),
]);
$input = new ShellInput('foo bar');
$input->bind($definition);
}
public function testInputOptionWithGivenString()
{
$definition = new InputDefinition([
new InputOption('foo', null, InputOption::VALUE_REQUIRED),
new CodeArgument('code', null, CodeArgument::REQUIRED),
]);
$input = new ShellInput('--foo=bar echo "baz\\\\n";');
$input->bind($definition);
$this->assertSame('bar', $input->getOption('foo'));
$this->assertSame('echo "baz\n";', $input->getArgument('code'));
}
public function testInputOptionWithoutCodeArguments()
{
$definition = new InputDefinition([
new InputOption('foo', null, InputOption::VALUE_REQUIRED),
new InputOption('qux', 'q', InputOption::VALUE_REQUIRED),
new InputArgument('bar', null, InputArgument::REQUIRED),
new InputArgument('baz', null, InputArgument::REQUIRED),
]);
$input = new ShellInput('--foo=foo -q qux bar "baz\\\\n"');
$input->bind($definition);
$this->assertSame('foo', $input->getOption('foo'));
$this->assertSame('qux', $input->getOption('qux'));
$this->assertSame('bar', $input->getArgument('bar'));
$this->assertSame('baz\\n', $input->getArgument('baz'));
}
public function testInputWithDashDash()
{
$definition = new InputDefinition([
new InputOption('foo', null, InputOption::VALUE_REQUIRED),
new CodeArgument('code', null, CodeArgument::REQUIRED),
]);
$input = new ShellInput('-- echo --foo::$bar');
$input->bind($definition);
$this->assertNull($input->getOption('foo'));
$this->assertSame('echo --foo::$bar', $input->getArgument('code'));
}
public function testInputWithEmptyString()
{
$definition = new InputDefinition([
new InputOption('foo', null, InputOption::VALUE_REQUIRED),
new CodeArgument('code', null, CodeArgument::REQUIRED),
]);
$input = new ShellInput('"" --foo bar');
$input->bind($definition);
$this->assertSame('"" --foo bar', $input->getArgument('code'));
}
/**
* @dataProvider getTokenizeData
*/
public function testTokenize($input, $tokens, $message)
{
$input = new ShellInput($input);
$r = new \ReflectionClass('Psy\Input\ShellInput');
$p = $r->getProperty('tokenPairs');
$p->setAccessible(true);
$this->assertSame($tokens, $p->getValue($input), $message);
}
public function getTokenizeData()
{
// Test all the cases from StringInput test, ensuring they have an appropriate $rest token.
return [
[
'',
[],
'->tokenize() parses an empty string',
],
[
'foo',
[['foo', 'foo']],
'->tokenize() parses arguments',
],
[
' foo bar ',
[['foo', 'foo bar '], ['bar', 'bar ']],
'->tokenize() ignores whitespaces between arguments',
],
[
'"quoted"',
[['quoted', '"quoted"']],
'->tokenize() parses quoted arguments',
],
[
"'quoted'",
[['quoted', "'quoted'"]],
'->tokenize() parses quoted arguments',
],
[
"'a\rb\nc\td'",
[["a\rb\nc\td", "'a\rb\nc\td'"]],
'->tokenize() parses whitespace chars in strings',
],
[
"'a'\r'b'\n'c'\t'd'",
[
['a', "'a'\r'b'\n'c'\t'd'"],
['b', "'b'\n'c'\t'd'"],
['c', "'c'\t'd'"],
['d', "'d'"],
],
'->tokenize() parses whitespace chars between args as spaces',
],
/*
* These don't play nice with unescaping input, but the end result
* is correct, so disable the tests for now.
*
* @todo Sort this out and re-enable these test cases.
*/
// [
// '\"quoted\"',
// [['"quoted"', '\"quoted\"']],
// '->tokenize() parses escaped-quoted arguments',
// ],
// [
// "\'quoted\'",
// [['\'quoted\'', "\'quoted\'"]],
// '->tokenize() parses escaped-quoted arguments',
// ],
[
'-a',
[['-a', '-a']],
'->tokenize() parses short options',
],
[
'-azc',
[['-azc', '-azc']],
'->tokenize() parses aggregated short options',
],
[
'-awithavalue',
[['-awithavalue', '-awithavalue']],
'->tokenize() parses short options with a value',
],
[
'-a"foo bar"',
[['-afoo bar', '-a"foo bar"']],
'->tokenize() parses short options with a value',
],
[
'-a"foo bar""foo bar"',
[['-afoo barfoo bar', '-a"foo bar""foo bar"']],
'->tokenize() parses short options with a value',
],
[
'-a\'foo bar\'',
[['-afoo bar', '-a\'foo bar\'']],
'->tokenize() parses short options with a value',
],
[
'-a\'foo bar\'\'foo bar\'',
[['-afoo barfoo bar', '-a\'foo bar\'\'foo bar\'']],
'->tokenize() parses short options with a value',
],
[
'-a\'foo bar\'"foo bar"',
[['-afoo barfoo bar', '-a\'foo bar\'"foo bar"']],
'->tokenize() parses short options with a value',
],
[
'--long-option',
[['--long-option', '--long-option']],
'->tokenize() parses long options',
],
[
'--long-option=foo',
[['--long-option=foo', '--long-option=foo']],
'->tokenize() parses long options with a value',
],
[
'--long-option="foo bar"',
[['--long-option=foo bar', '--long-option="foo bar"']],
'->tokenize() parses long options with a value',
],
[
'--long-option="foo bar""another"',
[['--long-option=foo baranother', '--long-option="foo bar""another"']],
'->tokenize() parses long options with a value',
],
[
'--long-option=\'foo bar\'',
[['--long-option=foo bar', '--long-option=\'foo bar\'']],
'->tokenize() parses long options with a value',
],
[
"--long-option='foo bar''another'",
[['--long-option=foo baranother', "--long-option='foo bar''another'"]],
'->tokenize() parses long options with a value',
],
[
"--long-option='foo bar'\"another\"",
[['--long-option=foo baranother', "--long-option='foo bar'\"another\""]],
'->tokenize() parses long options with a value',
],
[
'foo -a -ffoo --long bar',
[
['foo', 'foo -a -ffoo --long bar'],
['-a', '-a -ffoo --long bar'],
['-ffoo', '-ffoo --long bar'],
['--long', '--long bar'],
['bar', 'bar'],
],
'->tokenize() parses when several arguments and options',
],
];
}
}

View file

@ -0,0 +1,97 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test;
use PhpParser\PrettyPrinter\Standard as Printer;
use Psy\Exception\ParseErrorException;
use Psy\ParserFactory;
class ParserTestCase extends \PHPUnit\Framework\TestCase
{
protected $traverser;
private $parser;
private $printer;
public function tearDown()
{
$this->traverser = null;
$this->parser = null;
$this->printer = null;
}
protected function parse($code, $prefix = '<?php ')
{
$code = $prefix . $code;
try {
return $this->getParser()->parse($code);
} catch (\PhpParser\Error $e) {
if (!$this->parseErrorIsEOF($e)) {
throw ParseErrorException::fromParseError($e);
}
try {
// Unexpected EOF, try again with an implicit semicolon
return $this->getParser()->parse($code . ';');
} catch (\PhpParser\Error $e) {
return false;
}
}
}
protected function traverse(array $stmts)
{
if (!isset($this->traverser)) {
throw new \RuntimeException('Test cases must provide a traverser');
}
return $this->traverser->traverse($stmts);
}
protected function prettyPrint(array $stmts)
{
return $this->getPrinter()->prettyPrint($stmts);
}
protected function assertProcessesAs($from, $to)
{
$stmts = $this->parse($from);
$stmts = $this->traverse($stmts);
$toStmts = $this->parse($to);
$this->assertSame($this->prettyPrint($toStmts), $this->prettyPrint($stmts));
}
private function getParser()
{
if (!isset($this->parser)) {
$parserFactory = new ParserFactory();
$this->parser = $parserFactory->createParser();
}
return $this->parser;
}
private function getPrinter()
{
if (!isset($this->printer)) {
$this->printer = new Printer();
}
return $this->printer;
}
private function parseErrorIsEOF(\PhpParser\Error $e)
{
$msg = $e->getRawMessage();
return ($msg === 'Unexpected token EOF') || (\strpos($msg, 'Syntax error, unexpected EOF') !== false);
}
}

View file

@ -0,0 +1,80 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Readline;
use Psy\Readline\GNUReadline;
class GNUReadlineTest extends \PHPUnit\Framework\TestCase
{
private $historyFile;
public function setUp()
{
if (!GNUReadline::isSupported()) {
$this->markTestSkipped('GNUReadline not enabled');
}
$this->historyFile = \tempnam(\sys_get_temp_dir(), 'psysh_test_history');
\file_put_contents($this->historyFile, "_HiStOrY_V2_\n");
}
public function testHistory()
{
$readline = new GNUReadline($this->historyFile);
$this->assertEmpty($readline->listHistory());
$readline->addHistory('foo');
$this->assertSame(['foo'], $readline->listHistory());
$readline->addHistory('bar');
$this->assertSame(['foo', 'bar'], $readline->listHistory());
$readline->addHistory('baz');
$this->assertSame(['foo', 'bar', 'baz'], $readline->listHistory());
$readline->clearHistory();
$this->assertEmpty($readline->listHistory());
}
/**
* @depends testHistory
*/
public function testHistorySize()
{
$readline = new GNUReadline($this->historyFile, 2);
$this->assertEmpty($readline->listHistory());
$readline->addHistory('foo');
$readline->addHistory('bar');
$this->assertSame(['foo', 'bar'], $readline->listHistory());
$readline->addHistory('baz');
$this->assertSame(['bar', 'baz'], $readline->listHistory());
$readline->addHistory('w00t');
$this->assertSame(['baz', 'w00t'], $readline->listHistory());
$readline->clearHistory();
$this->assertEmpty($readline->listHistory());
}
/**
* @depends testHistory
*/
public function testHistoryEraseDups()
{
$readline = new GNUReadline($this->historyFile, 0, true);
$this->assertEmpty($readline->listHistory());
$readline->addHistory('foo');
$readline->addHistory('bar');
$readline->addHistory('foo');
$this->assertSame(['bar', 'foo'], $readline->listHistory());
$readline->addHistory('baz');
$readline->addHistory('w00t');
$readline->addHistory('baz');
$this->assertSame(['bar', 'foo', 'w00t', 'baz'], $readline->listHistory());
$readline->clearHistory();
$this->assertEmpty($readline->listHistory());
}
}

View file

@ -0,0 +1,31 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Readline;
use Psy\Readline\HoaConsole;
class HoaConsoleTest extends \PHPUnit\Framework\TestCase
{
public function testHistory()
{
$readline = new HoaConsole();
$this->assertEmpty($readline->listHistory());
$readline->addHistory('foo');
$this->assertSame(['foo'], $readline->listHistory());
$readline->addHistory('bar');
$this->assertSame(['foo', 'bar'], $readline->listHistory());
$readline->addHistory('baz');
$this->assertSame(['foo', 'bar', 'baz'], $readline->listHistory());
$readline->clearHistory();
$this->assertEmpty($readline->listHistory());
}
}

View file

@ -0,0 +1,128 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Readline;
use Psy\Readline\Libedit;
class LibeditTest extends \PHPUnit\Framework\TestCase
{
private $historyFile;
public function setUp()
{
if (!Libedit::isSupported()) {
$this->markTestSkipped('Libedit not enabled');
}
$this->historyFile = \tempnam(\sys_get_temp_dir(), 'psysh_test_history');
if (false === \file_put_contents($this->historyFile, "_HiStOrY_V2_\n")) {
$this->fail('Unable to write history file: ' . $this->historyFile);
}
// Calling readline_read_history before readline_clear_history
// avoids segfault with PHP 5.5.7 & libedit v3.1
\readline_read_history($this->historyFile);
\readline_clear_history();
}
public function tearDown()
{
if (\is_file($this->historyFile)) {
\unlink($this->historyFile);
}
}
public function testHistory()
{
$readline = new Libedit($this->historyFile);
$this->assertEmpty($readline->listHistory());
$readline->addHistory('foo');
$this->assertSame(['foo'], $readline->listHistory());
$readline->addHistory('bar');
$this->assertSame(['foo', 'bar'], $readline->listHistory());
$readline->addHistory('baz');
$this->assertSame(['foo', 'bar', 'baz'], $readline->listHistory());
$readline->clearHistory();
$this->assertEmpty($readline->listHistory());
}
/**
* @depends testHistory
*/
public function testHistorySize()
{
$readline = new Libedit($this->historyFile, 2);
$this->assertEmpty($readline->listHistory());
$readline->addHistory('foo');
$readline->addHistory('bar');
$this->assertSame(['foo', 'bar'], $readline->listHistory());
$readline->addHistory('baz');
$this->assertSame(['bar', 'baz'], $readline->listHistory());
$readline->addHistory('w00t');
$this->assertSame(['baz', 'w00t'], $readline->listHistory());
$readline->clearHistory();
$this->assertEmpty($readline->listHistory());
}
/**
* @depends testHistory
*/
public function testHistoryEraseDups()
{
$readline = new Libedit($this->historyFile, 0, true);
$this->assertEmpty($readline->listHistory());
$readline->addHistory('foo');
$readline->addHistory('bar');
$readline->addHistory('foo');
$this->assertSame(['bar', 'foo'], $readline->listHistory());
$readline->addHistory('baz');
$readline->addHistory('w00t');
$readline->addHistory('baz');
$this->assertSame(['bar', 'foo', 'w00t', 'baz'], $readline->listHistory());
$readline->clearHistory();
$this->assertEmpty($readline->listHistory());
}
public function testListHistory()
{
$readline = new Libedit($this->historyFile);
\file_put_contents(
$this->historyFile,
"This is an entry\n\0This is a comment\nThis is an entry\0With a comment\n",
FILE_APPEND
);
$this->assertSame([
'This is an entry',
'This is an entry',
], $readline->listHistory());
$readline->clearHistory();
}
/**
* Libedit being a BSD library,
* it doesn't support non-unix line separators.
*/
public function testLinebreaksSupport()
{
$readline = new Libedit($this->historyFile);
\file_put_contents(
$this->historyFile,
"foo\rbar\nbaz\r\nw00t",
FILE_APPEND
);
$this->assertSame([
"foo\rbar",
"baz\r",
'w00t',
], $readline->listHistory());
$readline->clearHistory();
}
}

View file

@ -0,0 +1,76 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Readline;
use Psy\Readline\Transient;
class TransientTest extends \PHPUnit\Framework\TestCase
{
public function testHistory()
{
$readline = new Transient();
$this->assertEmpty($readline->listHistory());
$readline->addHistory('foo');
$this->assertSame(['foo'], $readline->listHistory());
$readline->addHistory('bar');
$this->assertSame(['foo', 'bar'], $readline->listHistory());
$readline->addHistory('baz');
$this->assertSame(['foo', 'bar', 'baz'], $readline->listHistory());
$readline->clearHistory();
$this->assertEmpty($readline->listHistory());
}
/**
* @depends testHistory
*/
public function testHistorySize()
{
$readline = new Transient(null, 2);
$this->assertEmpty($readline->listHistory());
$readline->addHistory('foo');
$readline->addHistory('bar');
$this->assertSame(['foo', 'bar'], $readline->listHistory());
$readline->addHistory('baz');
$this->assertSame(['bar', 'baz'], $readline->listHistory());
$readline->addHistory('w00t');
$this->assertSame(['baz', 'w00t'], $readline->listHistory());
$readline->clearHistory();
$this->assertEmpty($readline->listHistory());
}
/**
* @depends testHistory
*/
public function testHistoryEraseDups()
{
$readline = new Transient(null, 0, true);
$this->assertEmpty($readline->listHistory());
$readline->addHistory('foo');
$readline->addHistory('bar');
$readline->addHistory('foo');
$this->assertSame(['bar', 'foo'], $readline->listHistory());
$readline->addHistory('baz');
$readline->addHistory('w00t');
$readline->addHistory('baz');
$this->assertSame(['bar', 'foo', 'w00t', 'baz'], $readline->listHistory());
$readline->clearHistory();
$this->assertEmpty($readline->listHistory());
}
public function testSomeThingsAreAlwaysTrue()
{
$readline = new Transient();
$this->assertTrue(Transient::isSupported());
$this->assertTrue($readline->readHistory());
$this->assertTrue($readline->writeHistory());
}
}

View file

@ -0,0 +1,81 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Reflection;
use Psy\Reflection\ReflectionClassConstant;
class ReflectionClassConstantTest extends \PHPUnit\Framework\TestCase
{
const CONSTANT_ONE = 'one';
public function testConstruction()
{
$refl = new ReflectionClassConstant($this, 'CONSTANT_ONE');
$class = $refl->getDeclaringClass();
$this->assertInstanceOf('ReflectionClass', $class);
$this->assertSame('Psy\Test\Reflection\ReflectionClassConstantTest', $class->getName());
$this->assertSame('CONSTANT_ONE', $refl->getName());
$this->assertSame('CONSTANT_ONE', (string) $refl);
$this->assertSame('one', $refl->getValue());
$this->assertNull($refl->getFileName());
$this->assertFalse($refl->getDocComment());
}
/**
* @expectedException \InvalidArgumentException
*/
public function testUnknownConstantThrowsException()
{
new ReflectionClassConstant($this, 'UNKNOWN_CONSTANT');
}
public function testExport()
{
$ret = ReflectionClassConstant::export($this, 'CONSTANT_ONE', true);
$this->assertEquals($ret, 'Constant [ public string CONSTANT_ONE ] { one }');
}
public function testExportOutput()
{
$this->expectOutputString("Constant [ public string CONSTANT_ONE ] { one }\n");
ReflectionClassConstant::export($this, 'CONSTANT_ONE', false);
}
public function testModifiers()
{
$refl = new ReflectionClassConstant($this, 'CONSTANT_ONE');
$this->assertEquals(\ReflectionMethod::IS_PUBLIC, $refl->getModifiers());
$this->assertFalse($refl->isPrivate());
$this->assertFalse($refl->isProtected());
$this->assertTrue($refl->isPublic());
}
/**
* @expectedException \RuntimeException
* @dataProvider notYetImplemented
*/
public function testNotYetImplemented($method)
{
$refl = new ReflectionClassConstant($this, 'CONSTANT_ONE');
$refl->$method();
}
public function notYetImplemented()
{
return [
['getStartLine'],
['getEndLine'],
];
}
}

View file

@ -0,0 +1,26 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Reflection;
use Psy\Reflection\ReflectionConstant;
class ReflectionConstantBCTest extends \PHPUnit\Framework\TestCase
{
const CONSTANT_ONE = 'one';
public function testConstruction()
{
$refl = new ReflectionConstant($this, 'CONSTANT_ONE');
$this->assertInstanceOf('Psy\Reflection\ReflectionConstant', $refl);
$this->assertInstanceOf('Psy\Reflection\ReflectionClassConstant', $refl);
}
}

View file

@ -0,0 +1,114 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Reflection;
use Psy\Reflection\ReflectionConstant_;
\define('Psy\\Test\\Reflection\\SOME_CONSTANT', 'yep');
class ReflectionConstantTest extends \PHPUnit\Framework\TestCase
{
public function testConstruction()
{
$refl = new ReflectionConstant_('Psy\\Test\\Reflection\\SOME_CONSTANT');
$this->assertFalse($refl->getDocComment());
$this->assertEquals('Psy\\Test\\Reflection\\SOME_CONSTANT', $refl->getName());
$this->assertEquals('Psy\\Test\\Reflection', $refl->getNamespaceName());
$this->assertEquals('yep', $refl->getValue());
$this->assertTrue($refl->inNamespace());
$this->assertEquals('Psy\\Test\\Reflection\\SOME_CONSTANT', (string) $refl);
$this->assertNull($refl->getFileName());
}
public function testBuiltInConstant()
{
$refl = new ReflectionConstant_('PHP_VERSION');
$this->assertEquals('PHP_VERSION', $refl->getName());
$this->assertEquals('PHP_VERSION', (string) $refl);
$this->assertEquals(PHP_VERSION, $refl->getValue());
$this->assertFalse($refl->inNamespace());
$this->assertSame('', $refl->getNamespaceName());
}
/**
* @dataProvider magicConstants
*/
public function testIsMagicConstant($name, $is)
{
$this->assertEquals($is, ReflectionConstant_::isMagicConstant($name));
}
public function magicConstants()
{
return [
['__LINE__', true],
['__FILE__', true],
['__DIR__', true],
['__FUNCTION__', true],
['__CLASS__', true],
['__TRAIT__', true],
['__METHOD__', true],
['__NAMESPACE__', true],
['__COMPILER_HALT_OFFSET__', true],
['PHP_VERSION', false],
['PHP_EOL', false],
['Psy\\Test\\Reflection\\SOME_CONSTANT', false],
['What if it isn\'t even a valid constant name?', false],
];
}
/**
* @expectedException \InvalidArgumentException
*/
public function testUnknownConstantThrowsException()
{
new ReflectionConstant_('UNKNOWN_CONSTANT');
}
public function testExport()
{
$ret = ReflectionConstant_::export('Psy\\Test\\Reflection\\SOME_CONSTANT', true);
$this->assertEquals($ret, 'Constant [ string Psy\\Test\\Reflection\\SOME_CONSTANT ] { yep }');
}
public function testExportOutput()
{
$this->expectOutputString("Constant [ string Psy\\Test\\Reflection\\SOME_CONSTANT ] { yep }\n");
ReflectionConstant_::export('Psy\\Test\\Reflection\\SOME_CONSTANT', false);
}
public function testGetFileName()
{
$refl = new ReflectionConstant_('Psy\\Test\\Reflection\\SOME_CONSTANT');
$this->assertNull($refl->getFileName());
}
/**
* @expectedException \RuntimeException
* @dataProvider notYetImplemented
*/
public function testNotYetImplemented($method)
{
$refl = new ReflectionConstant_('Psy\\Test\\Reflection\\SOME_CONSTANT');
$refl->$method();
}
public function notYetImplemented()
{
return [
['getStartLine'],
['getEndLine'],
];
}
}

View file

@ -0,0 +1,64 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Reflection;
use Psy\Reflection\ReflectionLanguageConstruct;
use Psy\Reflection\ReflectionLanguageConstructParameter;
class ReflectionLanguageConstructParameterTest extends \PHPUnit\Framework\TestCase
{
public function testOptions()
{
$keyword = new ReflectionLanguageConstruct('die');
$refl = new ReflectionLanguageConstructParameter($keyword, 'one', [
'isArray' => false,
'defaultValue' => null,
'isOptional' => false,
'isPassedByReference' => false,
]);
$this->assertNull($refl->getClass());
$this->assertEquals('one', $refl->getName());
$this->assertFalse($refl->isArray());
$this->assertTrue($refl->isDefaultValueAvailable());
$this->assertNull($refl->getDefaultValue());
$this->assertFalse($refl->isOptional());
$this->assertFalse($refl->isPassedByReference());
$reflTwo = new ReflectionLanguageConstructParameter($keyword, 'two', [
'isArray' => true,
'isOptional' => true,
'isPassedByReference' => true,
]);
$this->assertNull($refl->getClass());
$this->assertEquals('two', $reflTwo->getName());
$this->assertTrue($reflTwo->isArray());
$this->assertFalse($reflTwo->isDefaultValueAvailable());
$this->assertNull($reflTwo->getDefaultValue());
$this->assertTrue($reflTwo->isOptional());
$this->assertTrue($reflTwo->isPassedByReference());
$refl = new ReflectionLanguageConstructParameter($keyword, 'three', [
'defaultValue' => 3,
]);
$this->assertNull($refl->getClass());
$this->assertEquals('three', $refl->getName());
$this->assertFalse($refl->isArray());
$this->assertTrue($refl->isDefaultValueAvailable());
$this->assertEquals(3, $refl->getDefaultValue());
$this->assertFalse($refl->isOptional());
$this->assertFalse($refl->isPassedByReference());
}
}

View file

@ -0,0 +1,102 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Reflection;
use Psy\Reflection\ReflectionLanguageConstruct;
class ReflectionLanguageConstructTest extends \PHPUnit\Framework\TestCase
{
/**
* @dataProvider languageConstructs
*/
public function testConstruction($keyword)
{
$refl = new ReflectionLanguageConstruct($keyword);
$this->assertEquals($keyword, $refl->getName());
$this->assertEquals($keyword, (string) $refl);
}
/**
* @dataProvider languageConstructs
*/
public function testKnownLanguageConstructs($keyword)
{
$this->assertTrue(ReflectionLanguageConstruct::isLanguageConstruct($keyword));
}
/**
* @dataProvider languageConstructs
*/
public function testFileName($keyword)
{
$refl = new ReflectionLanguageConstruct($keyword);
$this->assertFalse($refl->getFileName());
}
/**
* @dataProvider languageConstructs
*/
public function testReturnsReference($keyword)
{
$refl = new ReflectionLanguageConstruct($keyword);
$this->assertFalse($refl->returnsReference());
}
/**
* @dataProvider languageConstructs
*/
public function testGetParameters($keyword)
{
$refl = new ReflectionLanguageConstruct($keyword);
$this->assertNotEmpty($refl->getParameters());
}
/**
* @dataProvider languageConstructs
* @expectedException \RuntimeException
*/
public function testExportThrows($keyword)
{
ReflectionLanguageConstruct::export($keyword);
}
public function languageConstructs()
{
return [
['isset'],
['unset'],
['empty'],
['echo'],
['print'],
['die'],
['exit'],
];
}
/**
* @dataProvider unknownLanguageConstructs
* @expectedException \InvalidArgumentException
*/
public function testUnknownLanguageConstructsThrowExceptions($keyword)
{
new ReflectionLanguageConstruct($keyword);
}
public function unknownLanguageConstructs()
{
return [
['async'],
['await'],
['comefrom'],
];
}
}

442
vendor/psy/psysh/test/ShellTest.php vendored Normal file
View file

@ -0,0 +1,442 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test;
use Psy\Configuration;
use Psy\Exception\ErrorException;
use Psy\Exception\ParseErrorException;
use Psy\Shell;
use Psy\TabCompletion\Matcher\ClassMethodsMatcher;
use Symfony\Component\Console\Output\StreamOutput;
class ShellTest extends \PHPUnit\Framework\TestCase
{
private $streams = [];
public function tearDown()
{
foreach ($this->streams as $stream) {
\fclose($stream);
}
}
public function testScopeVariables()
{
$one = 'banana';
$two = 123;
$three = new \StdClass();
$__psysh__ = 'ignore this';
$_ = 'ignore this';
$_e = 'ignore this';
$shell = new Shell($this->getConfig());
$shell->setScopeVariables(\compact('one', 'two', 'three', '__psysh__', '_', '_e', 'this'));
$this->assertNotContains('__psysh__', $shell->getScopeVariableNames());
$this->assertSame(['one', 'two', 'three', '_'], $shell->getScopeVariableNames());
$this->assertSame('banana', $shell->getScopeVariable('one'));
$this->assertSame(123, $shell->getScopeVariable('two'));
$this->assertSame($three, $shell->getScopeVariable('three'));
$this->assertNull($shell->getScopeVariable('_'));
$diff = $shell->getScopeVariablesDiff(['one' => $one, 'two' => 'not two']);
$this->assertSame(['two' => $two, 'three' => $three, '_' => null], $diff);
$shell->setScopeVariables([]);
$this->assertSame(['_'], $shell->getScopeVariableNames());
$shell->setBoundObject($this);
$this->assertSame(['_', 'this'], $shell->getScopeVariableNames());
$this->assertSame($this, $shell->getScopeVariable('this'));
$this->assertSame(['_' => null], $shell->getScopeVariables(false));
$this->assertSame(['_' => null, 'this' => $this], $shell->getScopeVariables());
}
/**
* @expectedException \InvalidArgumentException
*/
public function testUnknownScopeVariablesThrowExceptions()
{
$shell = new Shell($this->getConfig());
$shell->setScopeVariables(['foo' => 'FOO', 'bar' => 1]);
$shell->getScopeVariable('baz');
}
public function testIncludesWithScopeVariables()
{
$one = 'banana';
$two = 123;
$three = new \StdClass();
$__psysh__ = 'ignore this';
$_ = 'ignore this';
$_e = 'ignore this';
$config = $this->getConfig(['usePcntl' => false]);
$shell = new Shell($config);
$shell->setScopeVariables(\compact('one', 'two', 'three', '__psysh__', '_', '_e', 'this'));
$shell->addInput('exit', true);
// This is super slow and we shouldn't do this :(
$shell->run(null, $this->getOutput());
$this->assertNotContains('__psysh__', $shell->getScopeVariableNames());
$this->assertSame(['one', 'two', 'three', '_', '_e'], $shell->getScopeVariableNames());
$this->assertSame('banana', $shell->getScopeVariable('one'));
$this->assertSame(123, $shell->getScopeVariable('two'));
$this->assertSame($three, $shell->getScopeVariable('three'));
$this->assertNull($shell->getScopeVariable('_'));
}
public function testIncludes()
{
$config = $this->getConfig(['configFile' => __DIR__ . '/fixtures/empty.php']);
$shell = new Shell($config);
$this->assertEmpty($shell->getIncludes());
$shell->setIncludes(['foo', 'bar', 'baz']);
$this->assertSame(['foo', 'bar', 'baz'], $shell->getIncludes());
}
public function testIncludesConfig()
{
$config = $this->getConfig([
'defaultIncludes' => ['/file.php'],
'configFile' => __DIR__ . '/fixtures/empty.php',
]);
$shell = new Shell($config);
$includes = $shell->getIncludes();
$this->assertSame('/file.php', $includes[0]);
}
public function testAddMatchersViaConfig()
{
$shell = new FakeShell();
$matcher = new ClassMethodsMatcher();
$config = $this->getConfig([
'matchers' => [$matcher],
]);
$config->setShell($shell);
$this->assertSame([$matcher], $shell->matchers);
}
public function testAddMatchersViaConfigAfterShell()
{
$shell = new FakeShell();
$matcher = new ClassMethodsMatcher();
$config = $this->getConfig([]);
$config->setShell($shell);
$config->addMatchers([$matcher]);
$this->assertSame([$matcher], $shell->matchers);
}
public function testRenderingExceptions()
{
$shell = new Shell($this->getConfig());
$output = $this->getOutput();
$stream = $output->getStream();
$e = new ParseErrorException('message', 13);
$shell->setOutput($output);
$shell->addCode('code');
$this->assertTrue($shell->hasCode());
$this->assertNotEmpty($shell->getCodeBuffer());
$shell->writeException($e);
$this->assertSame($e, $shell->getScopeVariable('_e'));
$this->assertFalse($shell->hasCode());
$this->assertEmpty($shell->getCodeBuffer());
\rewind($stream);
$streamContents = \stream_get_contents($stream);
$this->assertContains('PHP Parse error', $streamContents);
$this->assertContains('message', $streamContents);
$this->assertContains('line 13', $streamContents);
}
public function testHandlingErrors()
{
$shell = new Shell($this->getConfig());
$output = $this->getOutput();
$stream = $output->getStream();
$shell->setOutput($output);
$oldLevel = \error_reporting();
\error_reporting($oldLevel & ~E_USER_NOTICE);
try {
$shell->handleError(E_USER_NOTICE, 'wheee', null, 13);
} catch (ErrorException $e) {
\error_reporting($oldLevel);
$this->fail('Unexpected error exception');
}
\error_reporting($oldLevel);
\rewind($stream);
$streamContents = \stream_get_contents($stream);
$this->assertContains('PHP Notice:', $streamContents);
$this->assertContains('wheee', $streamContents);
$this->assertContains('line 13', $streamContents);
}
/**
* @expectedException \Psy\Exception\ErrorException
*/
public function testNotHandlingErrors()
{
$shell = new Shell($this->getConfig());
$oldLevel = \error_reporting();
\error_reporting($oldLevel | E_USER_NOTICE);
try {
$shell->handleError(E_USER_NOTICE, 'wheee', null, 13);
} catch (ErrorException $e) {
\error_reporting($oldLevel);
throw $e;
}
}
public function testVersion()
{
$shell = new Shell($this->getConfig());
$this->assertInstanceOf('Symfony\Component\Console\Application', $shell);
$this->assertContains(Shell::VERSION, $shell->getVersion());
$this->assertContains(PHP_VERSION, $shell->getVersion());
$this->assertContains(PHP_SAPI, $shell->getVersion());
}
public function testCodeBuffer()
{
$shell = new Shell($this->getConfig());
$shell->addCode('class');
$this->assertNull($shell->flushCode());
$this->assertTrue($shell->hasCode());
$shell->addCode('a');
$this->assertNull($shell->flushCode());
$this->assertTrue($shell->hasCode());
$shell->addCode('{}');
$code = $shell->flushCode();
$this->assertFalse($shell->hasCode());
$code = \preg_replace('/\s+/', ' ', $code);
$this->assertNotNull($code);
$this->assertSame('class a { } return new \\Psy\\CodeCleaner\\NoReturnValue();', $code);
}
public function testKeepCodeBufferOpen()
{
$shell = new Shell($this->getConfig());
$shell->addCode('1 \\');
$this->assertNull($shell->flushCode());
$this->assertTrue($shell->hasCode());
$shell->addCode('+ 1 \\');
$this->assertNull($shell->flushCode());
$this->assertTrue($shell->hasCode());
$shell->addCode('+ 1');
$code = $shell->flushCode();
$this->assertFalse($shell->hasCode());
$code = \preg_replace('/\s+/', ' ', $code);
$this->assertNotNull($code);
$this->assertSame('return 1 + 1 + 1;', $code);
}
/**
* @expectedException \Psy\Exception\ParseErrorException
*/
public function testCodeBufferThrowsParseExceptions()
{
$shell = new Shell($this->getConfig());
$shell->addCode('this is not valid');
$shell->flushCode();
}
public function testClosuresSupport()
{
$shell = new Shell($this->getConfig());
$code = '$test = function () {}';
$shell->addCode($code);
$shell->flushCode();
$code = '$test()';
$shell->addCode($code);
$this->assertSame($shell->flushCode(), 'return $test();');
}
public function testWriteStdout()
{
$output = $this->getOutput();
$stream = $output->getStream();
$shell = new Shell($this->getConfig());
$shell->setOutput($output);
$shell->writeStdout("{{stdout}}\n");
\rewind($stream);
$streamContents = \stream_get_contents($stream);
$this->assertSame('{{stdout}}' . PHP_EOL, $streamContents);
}
public function testWriteStdoutWithoutNewline()
{
$output = $this->getOutput();
$stream = $output->getStream();
$shell = new Shell($this->getConfig());
$shell->setOutput($output);
$shell->writeStdout('{{stdout}}');
\rewind($stream);
$streamContents = \stream_get_contents($stream);
$this->assertSame('{{stdout}}<aside>⏎</aside>' . PHP_EOL, $streamContents);
}
/**
* @dataProvider getReturnValues
*/
public function testWriteReturnValue($input, $expected)
{
$output = $this->getOutput();
$stream = $output->getStream();
$shell = new Shell($this->getConfig());
$shell->setOutput($output);
$shell->writeReturnValue($input);
\rewind($stream);
$this->assertEquals($expected, \stream_get_contents($stream));
}
public function getReturnValues()
{
return [
['{{return value}}', "=> \"\033[32m{{return value}}\033[39m\"" . PHP_EOL],
[1, "=> \033[35m1\033[39m" . PHP_EOL],
];
}
/**
* @dataProvider getRenderedExceptions
*/
public function testWriteException($exception, $expected)
{
$output = $this->getOutput();
$stream = $output->getStream();
$shell = new Shell($this->getConfig());
$shell->setOutput($output);
$shell->writeException($exception);
\rewind($stream);
$this->assertSame($expected, \stream_get_contents($stream));
}
public function getRenderedExceptions()
{
return [
[new \Exception('{{message}}'), "Exception with message '{{message}}'" . PHP_EOL],
];
}
/**
* @dataProvider getExecuteValues
*/
public function testShellExecute($input, $expected)
{
$output = $this->getOutput();
$stream = $output->getStream();
$shell = new Shell($this->getConfig());
$shell->setOutput($output);
$this->assertEquals($expected, $shell->execute($input));
\rewind($stream);
$this->assertSame('', \stream_get_contents($stream));
}
public function getExecuteValues()
{
return [
['return 12', 12],
['"{{return value}}"', '{{return value}}'],
['1', '1'],
];
}
/**
* @dataProvider commandsToHas
*/
public function testHasCommand($command, $has)
{
$shell = new Shell($this->getConfig());
// :-/
$refl = new \ReflectionClass('Psy\\Shell');
$method = $refl->getMethod('hasCommand');
$method->setAccessible(true);
$this->assertEquals($method->invokeArgs($shell, [$command]), $has);
}
public function commandsToHas()
{
return [
['help', true],
['help help', true],
['"help"', false],
['"help help"', false],
['ls -al ', true],
['ls "-al" ', true],
['ls"-al"', false],
[' q', true],
[' q --help', true],
['"q"', false],
['"q",', false],
];
}
private function getOutput()
{
$stream = \fopen('php://memory', 'w+');
$this->streams[] = $stream;
$output = new StreamOutput($stream, StreamOutput::VERBOSITY_NORMAL, false);
return $output;
}
private function getConfig(array $config = [])
{
// Mebbe there's a better way than this?
$dir = \tempnam(\sys_get_temp_dir(), 'psysh_shell_test_');
\unlink($dir);
$defaults = [
'configDir' => $dir,
'dataDir' => $dir,
'runtimeDir' => $dir,
];
return new Configuration(\array_merge($defaults, $config));
}
}

View file

@ -0,0 +1,142 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Sudo;
use PhpParser\NodeTraverser;
use Psy\Sudo\SudoVisitor;
use Psy\Test\ParserTestCase;
class SudoVisitorTest extends ParserTestCase
{
public function setUp()
{
$this->traverser = new NodeTraverser();
$this->traverser->addVisitor(new SudoVisitor());
}
/**
* @dataProvider propertyFetches
*/
public function testPropertyFetch($from, $to)
{
$this->assertProcessesAs($from, $to);
}
public function propertyFetches()
{
return [
['$a->b', "\Psy\Sudo::fetchProperty(\$a, 'b');"],
['$a->$b', '\Psy\Sudo::fetchProperty($a, $b);'],
["\$a->{'b'}", "\Psy\Sudo::fetchProperty(\$a, 'b');"],
];
}
/**
* @dataProvider propertyAssigns
*/
public function testPropertyAssign($from, $to)
{
$this->assertProcessesAs($from, $to);
}
public function propertyAssigns()
{
return [
['$a->b = $c', "\Psy\Sudo::assignProperty(\$a, 'b', \$c);"],
['$a->$b = $c', '\Psy\Sudo::assignProperty($a, $b, $c);'],
["\$a->{'b'} = \$c", "\Psy\Sudo::assignProperty(\$a, 'b', \$c);"],
];
}
/**
* @dataProvider methodCalls
*/
public function testMethodCall($from, $to)
{
$this->assertProcessesAs($from, $to);
}
public function methodCalls()
{
return [
['$a->b()', "\Psy\Sudo::callMethod(\$a, 'b');"],
['$a->$b()', '\Psy\Sudo::callMethod($a, $b);'],
["\$a->b(\$c, 'd')", "\Psy\Sudo::callMethod(\$a, 'b', \$c, 'd');"],
["\$a->\$b(\$c, 'd')", "\Psy\Sudo::callMethod(\$a, \$b, \$c, 'd');"],
];
}
/**
* @dataProvider staticPropertyFetches
*/
public function testStaticPropertyFetch($from, $to)
{
$this->assertProcessesAs($from, $to);
}
public function staticPropertyFetches()
{
return [
['A::$b', "\Psy\Sudo::fetchStaticProperty('A', 'b');"],
['$a::$b', "\Psy\Sudo::fetchStaticProperty(\$a, 'b');"],
];
}
/**
* @dataProvider staticPropertyAssigns
*/
public function testStaticPropertyAssign($from, $to)
{
$this->assertProcessesAs($from, $to);
}
public function staticPropertyAssigns()
{
return [
['A::$b = $c', "\Psy\Sudo::assignStaticProperty('A', 'b', \$c);"],
['$a::$b = $c', "\Psy\Sudo::assignStaticProperty(\$a, 'b', \$c);"],
];
}
/**
* @dataProvider staticCalls
*/
public function testStaticCall($from, $to)
{
$this->assertProcessesAs($from, $to);
}
public function staticCalls()
{
return [
['A::b()', "\Psy\Sudo::callStatic('A', 'b');"],
['A::$b()', "\Psy\Sudo::callStatic('A', \$b);"],
["A::b(\$c, 'd')", "\Psy\Sudo::callStatic('A', 'b', \$c, 'd');"],
["A::\$b(\$c, 'd')", "\Psy\Sudo::callStatic('A', \$b, \$c, 'd');"],
];
}
/**
* @dataProvider classConstFetches
*/
public function testClassConstFetch($from, $to)
{
$this->assertProcessesAs($from, $to);
}
public function classConstFetches()
{
return [
['A::B', "\Psy\Sudo::fetchClassConst('A', 'B');"],
];
}
}

80
vendor/psy/psysh/test/SudoTest.php vendored Normal file
View file

@ -0,0 +1,80 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test;
use Psy\Sudo;
class SudoTest extends \PHPUnit\Framework\TestCase
{
public function setUp()
{
if (\version_compare(PHP_VERSION, '7.1.0', '<')) {
$this->markTestSkipped('YOLO');
}
}
public function testFetchProperty()
{
$obj = new ClassWithSecrets();
$this->assertSame('private and prop', Sudo::fetchProperty($obj, 'privateProp'));
}
public function testAssignProperty()
{
$obj = new ClassWithSecrets();
$this->assertSame('private and prop', Sudo::fetchProperty($obj, 'privateProp'));
$this->assertSame('not so private now', Sudo::assignProperty($obj, 'privateProp', 'not so private now'));
$this->assertSame('not so private now', Sudo::fetchProperty($obj, 'privateProp'));
}
public function testCallMethod()
{
$obj = new ClassWithSecrets();
$this->assertSame('private and method', Sudo::callMethod($obj, 'privateMethod'));
$this->assertSame('private and method with 1', Sudo::callMethod($obj, 'privateMethod', 1));
$this->assertSame(
'private and method with ["foo",2]',
Sudo::callMethod($obj, 'privateMethod', ['foo', 2]
));
}
public function testFetchStaticProperty()
{
$obj = new ClassWithSecrets();
$this->assertSame('private and static and prop', Sudo::fetchStaticProperty($obj, 'privateStaticProp'));
}
public function testAssignStaticProperty()
{
$obj = new ClassWithSecrets();
$this->assertSame('private and static and prop', Sudo::fetchStaticProperty($obj, 'privateStaticProp'));
$this->assertSame('not so private now', Sudo::assignStaticProperty($obj, 'privateStaticProp', 'not so private now'));
$this->assertSame('not so private now', Sudo::fetchStaticProperty($obj, 'privateStaticProp'));
}
public function testCallStatic()
{
$obj = new ClassWithSecrets();
$this->assertSame('private and static and method', Sudo::callStatic($obj, 'privateStaticMethod'));
$this->assertSame('private and static and method with 1', Sudo::callStatic($obj, 'privateStaticMethod', 1));
$this->assertSame(
'private and static and method with ["foo",2]',
Sudo::callStatic($obj, 'privateStaticMethod', ['foo', 2]
));
}
public function testFetchClassConst()
{
$obj = new ClassWithSecrets();
$this->assertSame('private and const', Sudo::fetchClassConst($obj, 'PRIVATE_CONST'));
}
}

View file

@ -0,0 +1,145 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\TabCompletion;
use Psy\Command\ListCommand;
use Psy\Command\ShowCommand;
use Psy\Configuration;
use Psy\Context;
use Psy\ContextAware;
use Psy\TabCompletion\Matcher;
class AutoCompleterTest extends \PHPUnit\Framework\TestCase
{
/**
* @param string $line
* @param array $mustContain
* @param array $mustNotContain
* @dataProvider classesInput
*/
public function testClassesCompletion($line, $mustContain, $mustNotContain)
{
$context = new Context();
$commands = [
new ShowCommand(),
new ListCommand(),
];
$matchers = [
new Matcher\VariablesMatcher(),
new Matcher\ClassNamesMatcher(),
new Matcher\ConstantsMatcher(),
new Matcher\FunctionsMatcher(),
new Matcher\ObjectMethodsMatcher(),
new Matcher\ObjectAttributesMatcher(),
new Matcher\KeywordsMatcher(),
new Matcher\ClassAttributesMatcher(),
new Matcher\ClassMethodsMatcher(),
new Matcher\CommandsMatcher($commands),
];
$config = new Configuration();
$tabCompletion = $config->getAutoCompleter();
foreach ($matchers as $matcher) {
if ($matcher instanceof ContextAware) {
$matcher->setContext($context);
}
$tabCompletion->addMatcher($matcher);
}
$context->setAll(['foo' => 12, 'bar' => new \DOMDocument()]);
$code = $tabCompletion->processCallback('', 0, [
'line_buffer' => $line,
'point' => 0,
'end' => \strlen($line),
]);
foreach ($mustContain as $mc) {
$this->assertContains($mc, $code);
}
foreach ($mustNotContain as $mnc) {
$this->assertNotContains($mnc, $code);
}
}
/**
* TODO
* ====
* draft, open to modifications
* - [ ] if the variable is an array, return the square bracket for completion
* - [ ] if the variable is a constructor or method, reflect to complete as a function call
* - [ ] if the preceding token is a variable, call operators or keywords compatible for completion
* - [X] a command always should be the second token after php_open_tag
* - [X] keywords are never consecutive
* - [X] namespacing completion should work just fine
* - [X] after a new keyword, should always be a class constructor, never a function call or keyword, constant,
* or variable that does not contain a existing class name.
* - [X] on a namespaced constructor the completion must show the classes related, not constants.
*
* @return array
*/
public function classesInput()
{
return [
// input, must had, must not had
['T_OPE', ['T_OPEN_TAG'], []],
['st', ['stdClass'], []],
['stdCla', ['stdClass'], []],
['new s', ['stdClass'], []],
[
'new ',
['stdClass', 'Psy\\Context', 'Psy\\Configuration'],
['require', 'array_search', 'T_OPEN_TAG', '$foo'],
],
['new Psy\\C', ['Context'], ['CASE_LOWER']],
['\s', ['stdClass'], []],
['array_', ['array_search', 'array_map', 'array_merge'], []],
['$bar->', ['load'], []],
['$b', ['bar'], []],
['6 + $b', ['bar'], []],
['$f', ['foo'], []],
['l', ['ls'], []],
['ls ', [], ['ls']],
['sho', ['show'], []],
['12 + clone $', ['foo'], []],
// array(
// '$foo ',
// array('+', 'clone'),
// array('$foo', 'DOMDocument', 'array_map')
// ), requires a operator matcher?
['$', ['foo', 'bar'], ['require', 'array_search', 'T_OPEN_TAG', 'Psy']],
[
'Psy\\',
['Context', 'TabCompletion\\Matcher\\AbstractMatcher'],
['require', 'array_search'],
],
[
'Psy\Test\TabCompletion\StaticSample::CO',
['StaticSample::CONSTANT_VALUE'],
[],
],
[
'Psy\Test\TabCompletion\StaticSample::',
['StaticSample::$staticVariable'],
[],
],
[
'Psy\Test\TabCompletion\StaticSample::',
['StaticSample::staticFunction'],
[],
],
];
}
}

View file

@ -0,0 +1,27 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\TabCompletion;
/**
* Class StaticSample.
*/
class StaticSample
{
const CONSTANT_VALUE = 12;
public static $staticVariable;
public static function staticFunction()
{
return self::CONSTANT_VALUE;
}
}

View file

@ -0,0 +1,100 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Util;
use Psy\Util\Docblock;
class DocblockTest extends \PHPUnit\Framework\TestCase
{
/**
* @dataProvider comments
*/
public function testDocblockParsing($comment, $body, $tags)
{
$reflector = $this
->getMockBuilder('ReflectionClass')
->disableOriginalConstructor()
->getMock();
$reflector->expects($this->once())
->method('getDocComment')
->will($this->returnValue($comment));
$docblock = new Docblock($reflector);
$this->assertSame($body, $docblock->desc);
foreach ($tags as $tag => $value) {
$this->assertTrue($docblock->hasTag($tag));
$this->assertEquals($value, $docblock->tag($tag));
}
}
public function comments()
{
if (\defined('HHVM_VERSION')) {
$this->markTestSkipped('We have issues with PHPUnit mocks on HHVM.');
}
return [
['', '', []],
[
'/**
* This is a docblock
*
* @throws \Exception with a description
*/',
'This is a docblock',
[
'throws' => [['type' => '\Exception', 'desc' => 'with a description']],
],
],
[
'/**
* This is a slightly longer docblock
*
* @param int $foo Is a Foo
* @param string $bar With some sort of description
* @param \ClassName $baz is cool too
*
* @return int At least it isn\'t a string
*/',
'This is a slightly longer docblock',
[
'param' => [
['type' => 'int', 'desc' => 'Is a Foo', 'var' => '$foo'],
['type' => 'string', 'desc' => 'With some sort of description', 'var' => '$bar'],
['type' => '\ClassName', 'desc' => 'is cool too', 'var' => '$baz'],
],
'return' => [
['type' => 'int', 'desc' => 'At least it isn\'t a string'],
],
],
],
[
'/**
* This is a docblock!
*
* It spans lines, too!
*
* @tagname plus a description
*
* @return
*/',
"This is a docblock!\n\nIt spans lines, too!",
[
'tagname' => ['plus a description'],
],
],
];
}
}

View file

@ -0,0 +1,86 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Util;
use Psy\Util\Mirror;
class MirrorTest extends \PHPUnit\Framework\TestCase
{
const FOO = 1;
private $bar = 2;
private static $baz = 3;
public function aPublicMethod()
{
// nada
}
public function testMirror()
{
$refl = Mirror::get('sort');
$this->assertInstanceOf('ReflectionFunction', $refl);
$refl = Mirror::get('Psy\Test\Util\MirrorTest');
$this->assertInstanceOf('ReflectionClass', $refl);
$refl = Mirror::get($this);
$this->assertInstanceOf('ReflectionObject', $refl);
$refl = Mirror::get($this, 'FOO');
if (\version_compare(PHP_VERSION, '7.1.0', '>=')) {
$this->assertInstanceOf('ReflectionClassConstant', $refl);
} else {
$this->assertInstanceOf('Psy\Reflection\ReflectionClassConstant', $refl);
}
$refl = Mirror::get('PHP_VERSION');
$this->assertInstanceOf('Psy\Reflection\ReflectionConstant_', $refl);
$refl = Mirror::get($this, 'bar');
$this->assertInstanceOf('ReflectionProperty', $refl);
$refl = Mirror::get($this, 'baz');
$this->assertInstanceOf('ReflectionProperty', $refl);
$refl = Mirror::get($this, 'aPublicMethod');
$this->assertInstanceOf('ReflectionMethod', $refl);
$refl = Mirror::get($this, 'baz', Mirror::STATIC_PROPERTY);
$this->assertInstanceOf('ReflectionProperty', $refl);
}
/**
* @expectedException \RuntimeException
*/
public function testMirrorThrowsExceptions()
{
Mirror::get($this, 'notAMethod');
}
/**
* @expectedException \InvalidArgumentException
* @dataProvider invalidArguments
*/
public function testMirrorThrowsInvalidArgumentExceptions($value)
{
Mirror::get($value);
}
public function invalidArguments()
{
return [
['not_a_function_or_class'],
[[]],
[1],
];
}
}

31
vendor/psy/psysh/test/Util/StrTest.php vendored Normal file
View file

@ -0,0 +1,31 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Util;
use Psy\Util\Str;
class StrTest extends \PHPUnit\Framework\TestCase
{
/**
* @dataProvider unvisProvider
*/
public function testUnvis($input, $expected)
{
$this->assertSame($expected, Str::unvis($input));
}
public function unvisProvider()
{
//return require_once(__DIR__.'/../fixtures/unvis_fixtures.php');
return \json_decode(\file_get_contents(__DIR__ . '/../fixtures/unvis_fixtures.json'));
}
}

View file

@ -0,0 +1,82 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\VersionUpdater;
use Psy\Shell;
class GitHubCheckerTest extends \PHPUnit\Framework\TestCase
{
/**
* @dataProvider malformedResults
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Unable to check for updates
*
* @param mixed $input
*/
public function testExceptionInvocation($input)
{
$checker = $this->getMockBuilder('Psy\\VersionUpdater\\GitHubChecker')
->setMethods(['fetchLatestRelease'])
->getMock();
$checker->expects($this->once())->method('fetchLatestRelease')->willReturn($input);
$checker->isLatest();
}
/**
* @dataProvider jsonResults
*
* @param bool $assertion
* @param mixed $input
*/
public function testDataSetResults($assertion, $input)
{
$checker = $this->getMockBuilder('Psy\\VersionUpdater\\GitHubChecker')
->setMethods(['fetchLatestRelease'])
->getMock();
$checker->expects($this->once())->method('fetchLatestRelease')->willReturn($input);
$this->assertSame($assertion, $checker->isLatest());
}
/**
* @return array
*/
public function jsonResults()
{
return [
[false, \json_decode('{"tag_name":"v9.0.0"}')],
[true, \json_decode('{"tag_name":"v' . Shell::VERSION . '"}')],
[true, \json_decode('{"tag_name":"v0.0.1"}')],
[true, \json_decode('{"tag_name":"v0.4.1-alpha"}')],
[true, \json_decode('{"tag_name":"v0.4.2-beta3"}')],
[true, \json_decode('{"tag_name":"v0.0.1"}')],
[true, \json_decode('{"tag_name":""}')],
];
}
/**
* @return array
*/
public function malformedResults()
{
return [
[null],
[false],
[true],
[\json_decode('{"foo":"bar"}')],
[\json_decode('{}')],
[\json_decode('[]')],
[[]],
[\json_decode('{"tag_name":false"}')],
[\json_decode('{"tag_name":true"}')],
];
}
}

View file

@ -0,0 +1,25 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\VersionUpdater;
use Psy\Shell;
use Psy\VersionUpdater\NoopChecker;
class NoopCheckerTest extends \PHPUnit\Framework\TestCase
{
public function testTheThings()
{
$checker = new NoopChecker();
$this->assertTrue($checker->isLatest());
$this->assertEquals(Shell::VERSION, $checker->getLatest());
}
}

View file

@ -0,0 +1,20 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
$config->setRuntimeDir(\sys_get_temp_dir() . '/psysh_test/withconfig/temp');
return [
'useReadline' => true,
'usePcntl' => false,
'requireSemicolons' => false,
'useUnicode' => true,
'errorLoggingLevel' => E_ALL & ~E_NOTICE,
];

View file

@ -0,0 +1 @@
<?php

View file

@ -0,0 +1,12 @@
<?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2018 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/* this space intentionally left blank */

View file

View file

@ -0,0 +1 @@
<?php

View file

@ -0,0 +1 @@
<?php

View file

@ -0,0 +1 @@
<?php

View file

@ -0,0 +1,17 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2017 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
return array(
'useReadline' => false,
'usePcntl' => true,
'requireSemicolons' => true,
'useUnicode' => false,
);

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,94 @@
#! /usr/bin/env python3
import sys
from os.path import abspath, expanduser, dirname, join
from itertools import chain
import json
import argparse
from vis import vis, unvis, VIS_WHITE
__dir__ = dirname(abspath(__file__))
OUTPUT_FILE = join(__dir__, '..', 'fixtures', 'unvis_fixtures.json')
# Add custom fixtures here
CUSTOM_FIXTURES = [
# test long multibyte string
''.join(chr(cp) for cp in range(1024)),
'foo bar',
'foo\nbar',
"$bar = 'baz';",
r'$foo = "\x20\\x20\\\x20\\\\x20"',
'$foo = function($bar) use($baz) {\n\treturn $baz->getFoo()\n};'
]
RANGES = {
# All valid codepoints in the BMP
'bmp': chain(range(0x0000, 0xD800), range(0xE000, 0xFFFF)),
# Smaller set of pertinent? codepoints inside BMP
# see: http://en.wikipedia.org/wiki/Plane_(Unicode)#Basic_Multilingual_Plane
'small': chain(
# latin blocks
range(0x0000, 0x0250),
# Greek, Cyrillic
range(0x0370, 0x0530),
# Hebrew, Arabic
range(0x590, 0x0700),
# CJK radicals
range(0x2E80, 0x2F00),
# Hiragana, Katakana
range(0x3040, 0x3100)
)
}
if __name__ == '__main__':
argp = argparse.ArgumentParser(
description='Generates test data for Psy\\Test\\Util\\StrTest')
argp.add_argument('-f', '--format-output', action='store_true',
help='Indent JSON output to ease debugging')
argp.add_argument('-a', '--all', action='store_true',
help="""Generates test data for all codepoints of the BMP.
(same as --range=bmp). WARNING: You will need quite
a lot of RAM to run the testsuite !
""")
argp.add_argument('-r', '--range',
help="""Choose the range of codepoints used to generate
test data.""",
choices=list(RANGES.keys()),
default='small')
argp.add_argument('-o', '--output-file',
help="""Write test data to OUTPUT_FILE
(defaults to PSYSH_DIR/test/fixtures)""")
args = argp.parse_args()
cp_range = RANGES['bmp'] if args.all else RANGES[args.range]
indent = 2 if args.format_output else None
if args.output_file:
OUTPUT_FILE = abspath(expanduser(args.output_file))
fixtures = []
# use SMALL_RANGE by default, it should be enough.
# use BMP_RANGE for a more complete smoke test
for codepoint in cp_range:
char = chr(codepoint)
encoded = vis(char, VIS_WHITE)
decoded = unvis(encoded)
fixtures.append((encoded, decoded))
# Add our own custom fixtures at the end,
# since they would fail anyway if one of the previous did.
for fixture in CUSTOM_FIXTURES:
encoded = vis(fixture, VIS_WHITE)
decoded = unvis(encoded)
fixtures.append((encoded, decoded))
with open(OUTPUT_FILE, 'w') as fp:
# dump as json to avoid backslashin and quotin nightmare
# between php and python
json.dump(fixtures, fp, indent=indent)
sys.exit(0)

126
vendor/psy/psysh/test/tools/vis.py vendored Executable file
View file

@ -0,0 +1,126 @@
"""
vis.py
======
Ctypes based module to access libbsd's strvis & strunvis functions.
The `vis` function is the equivalent of strvis.
The `unvis` function is the equivalent of strunvis.
All functions accept unicode string as input and return a unicode string.
Constants:
----------
* to select alternate encoding format
`VIS_OCTAL`: use octal \ddd format
`VIS_CSTYLE`: use \[nrft0..] where appropiate
* to alter set of characters encoded
(default is to encode all non-graphic except space, tab, and newline).
`VIS_SP`: also encode space
`VIS_TAB`: also encode tab
`VIS_NL`: also encode newline
`VIS_WHITE`: same as (VIS_SP | VIS_TAB | VIS_NL)
`VIS_SAFE`: only encode "unsafe" characters
* other
`VIS_NOSLASH`: inhibit printing '\'
`VIS_HTTP1808`: http-style escape % hex hex
`VIS_HTTPSTYLE`: http-style escape % hex hex
`VIS_MIMESTYLE`: mime-style escape = HEX HEX
`VIS_HTTP1866`: http-style &#num; or &string;
`VIS_NOESCAPE`: don't decode `\'
`VIS_GLOB`: encode glob(3) magic characters
:Authors:
- ju1ius (http://github.com/ju1ius)
:Version: 1
:Date: 2014-01-05
"""
from ctypes import CDLL, c_char_p, c_int
from ctypes.util import find_library
__all__ = [
'vis', 'unvis',
'VIS_OCTAL', 'VIS_CSTYLE',
'VIS_SP', 'VIS_TAB', 'VIS_NL', 'VIS_WHITE', 'VIS_SAFE',
'VIS_NOSLASH', 'VIS_HTTP1808', 'VIS_HTTPSTYLE', 'VIS_MIMESTYLE',
'VIS_HTTP1866', 'VIS_NOESCAPE', 'VIS_GLOB'
]
#############################################################
# Constants from bsd/vis.h
#############################################################
#to select alternate encoding format
VIS_OCTAL = 0x0001
VIS_CSTYLE = 0x0002
# to alter set of characters encoded
# (default is to encode all non-graphic except space, tab, and newline).
VIS_SP = 0x0004
VIS_TAB = 0x0008
VIS_NL = 0x0010
VIS_WHITE = VIS_SP | VIS_TAB | VIS_NL
VIS_SAFE = 0x0020
# other
VIS_NOSLASH = 0x0040
VIS_HTTP1808 = 0x0080
VIS_HTTPSTYLE = 0x0080
VIS_MIMESTYLE = 0x0100
VIS_HTTP1866 = 0x0200
VIS_NOESCAPE = 0x0400
VIS_GLOB = 0x1000
#############################################################
# Import libbsd/vis functions
#############################################################
_libbsd = CDLL(find_library('bsd'))
_strvis = _libbsd.strvis
_strvis.argtypes = [c_char_p, c_char_p, c_int]
_strvis.restype = c_int
_strunvis = _libbsd.strunvis
_strvis.argtypes = [c_char_p, c_char_p]
_strvis.restype = c_int
def vis(src, flags=VIS_WHITE):
"""
Encodes the string `src` into libbsd's vis encoding.
`flags` must be one of the VIS_* constants
C definition:
int strvis(char *dst, char *src, int flags);
"""
src = bytes(src, 'utf-8')
dst_p = c_char_p(bytes(len(src) * 4))
src_p = c_char_p(src)
flags = c_int(flags)
bytes_written = _strvis(dst_p, src_p, flags)
if -1 == bytes_written:
raise RuntimeError('vis failed to encode string "{}"'.format(src))
return dst_p.value.decode('utf-8')
def unvis(src):
"""
Decodes a string encoded by vis.
C definition:
int strunvis(char *dst, char *src);
"""
src = bytes(src, 'utf-8')
dst_p = c_char_p(bytes(len(src)))
src_p = c_char_p(src)
bytes_written = _strunvis(dst_p, src_p)
if -1 == bytes_written:
raise RuntimeError('unvis failed to decode string "{}"'.format(src))
return dst_p.value.decode('utf-8')