update for version 1.0.1

This commit is contained in:
sujitprasad
2015-10-23 14:15:29 +05:30
parent 82b878e93b
commit 3d425dc380
8348 changed files with 10020 additions and 4171 deletions

View File

@@ -0,0 +1,23 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 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\Autoloader;
class AutoloaderTest extends \PHPUnit_Framework_TestCase
{
public function testRegister()
{
Autoloader::register();
$this->assertTrue(spl_autoload_unregister(array('Psy\Autoloader', 'autoload')));
}
}

View File

@@ -0,0 +1,61 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 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 as NodeTraverser;
use Psy\CodeCleaner\AbstractClassPass;
class AbstractClassPassTest extends CodeCleanerTestCase
{
public function setUp()
{
$this->pass = new AbstractClassPass();
$this->traverser = new NodeTraverser();
$this->traverser->addVisitor($this->pass);
}
/**
* @dataProvider invalidStatements
* @expectedException \Psy\Exception\FatalErrorException
*/
public function testProcessStatementFails($code)
{
$stmts = $this->parse($code);
$this->traverser->traverse($stmts);
}
public function invalidStatements()
{
return array(
array('class A { abstract function a(); }'),
array('abstract class B { abstract function b() {} }'),
array('abstract class B { abstract function b() { echo "yep"; } }'),
);
}
/**
* @dataProvider validStatements
*/
public function testProcessStatementPasses($code)
{
$stmts = $this->parse($code);
$this->traverser->traverse($stmts);
}
public function validStatements()
{
return array(
array('abstract class C { function c() {} }'),
array('abstract class D { abstract function d(); }'),
);
}
}

View File

@@ -0,0 +1,62 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 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 as NodeTraverser;
use Psy\CodeCleaner\AssignThisVariablePass;
class AssignThisVariablePassTest extends CodeCleanerTestCase
{
public function setUp()
{
$this->pass = new AssignThisVariablePass();
$this->traverser = new NodeTraverser();
$this->traverser->addVisitor($this->pass);
}
/**
* @dataProvider invalidStatements
* @expectedException \Psy\Exception\FatalErrorException
*/
public function testProcessStatementFails($code)
{
$stmts = $this->parse($code);
$this->traverser->traverse($stmts);
}
public function invalidStatements()
{
return array(
array('$this = 3'),
array('strtolower($this = "this")'),
);
}
/**
* @dataProvider validStatements
*/
public function testProcessStatementPasses($code)
{
$stmts = $this->parse($code);
$this->traverser->traverse($stmts);
}
public function validStatements()
{
return array(
array('$this'),
array('$a = $this'),
array('$a = "this"; $$a = 3'),
array('$$this = "b"'),
);
}
}

View File

@@ -0,0 +1,73 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 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 as NodeTraverser;
use Psy\CodeCleaner\CallTimePassByReferencePass;
class CallTimePassByReferencePassTest extends CodeCleanerTestCase
{
public function setUp()
{
$this->pass = new CallTimePassByReferencePass();
$this->traverser = new NodeTraverser();
$this->traverser->addVisitor($this->pass);
}
/**
* @dataProvider invalidStatements
* @expectedException \Psy\Exception\FatalErrorException
*/
public function testProcessStatementFails($code)
{
if (version_compare(PHP_VERSION, '5.4', '<')) {
$this->markTestSkipped();
}
$stmts = $this->parse($code);
$this->traverser->traverse($stmts);
}
public function invalidStatements()
{
return array(
array('f(&$arg)'),
array('$object->method($first, &$arg)'),
array('$closure($first, &$arg, $last)'),
array('A::b(&$arg)'),
);
}
/**
* @dataProvider validStatements
*/
public function testProcessStatementPasses($code)
{
$stmts = $this->parse($code);
$this->traverser->traverse($stmts);
}
public function validStatements()
{
$data = array(
array('array(&$var)'),
array('$a = &$b'),
array('f(array(&$b))'),
);
if (version_compare(PHP_VERSION, '5.4', '<')) {
$data = array_merge($data, $this->invalidStatements());
}
return $data;
}
}

View File

@@ -0,0 +1,98 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 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 as NodeTraverser;
use Psy\CodeCleaner\CalledClassPass;
class CalledClassPassTest extends CodeCleanerTestCase
{
public function setUp()
{
$this->pass = new CalledClassPass();
$this->traverser = new NodeTraverser();
$this->traverser->addVisitor($this->pass);
}
/**
* @dataProvider invalidStatements
* @expectedException \Psy\Exception\ErrorException
*/
public function testProcessStatementFails($code)
{
$stmts = $this->parse($code);
$this->traverser->traverse($stmts);
}
public function invalidStatements()
{
return array(
array('get_class()'),
array('get_class(null)'),
array('get_called_class()'),
array('get_called_class(null)'),
array('function foo() { return get_class(); }'),
array('function foo() { return get_class(null); }'),
array('function foo() { return get_called_class(); }'),
array('function foo() { return get_called_class(null); }'),
);
}
/**
* @dataProvider validStatements
*/
public function testProcessStatementPasses($code)
{
$stmts = $this->parse($code);
$this->traverser->traverse($stmts);
}
public function validStatements()
{
return array(
array('get_class($foo)'),
array('get_class(bar())'),
array('get_called_class($foo)'),
array('get_called_class(bar())'),
array('function foo($bar) { return get_class($bar); }'),
array('function foo($bar) { return get_called_class($bar); }'),
array('class Foo { function bar() { return get_class(); } }'),
array('class Foo { function bar() { return get_class(null); } }'),
array('class Foo { function bar() { return get_called_class(); } }'),
array('class Foo { function bar() { return get_called_class(null); } }'),
array('$foo = function () {}; $foo()'),
);
}
/**
* @dataProvider validTraitStatements
*/
public function testProcessTraitStatementPasses($code)
{
if (version_compare(PHP_VERSION, '5.4', '<')) {
$this->markTestSkipped();
}
$stmts = $this->parse($code);
$this->traverser->traverse($stmts);
}
public function validTraitStatements()
{
return array(
array('trait Foo { function bar() { return get_class(); } }'),
array('trait Foo { function bar() { return get_class(null); } }'),
array('trait Foo { function bar() { return get_called_class(); } }'),
array('trait Foo { function bar() { return get_called_class(null); } }'),
);
}
}

View File

@@ -0,0 +1,97 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 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_Lexer as Lexer;
use PHPParser_NodeTraverser as NodeTraverser;
use PHPParser_Parser as Parser;
use PHPParser_PrettyPrinter_Default as Printer;
use Psy\CodeCleaner\CodeCleanerPass;
use Psy\Exception\ParseErrorException;
class CodeCleanerTestCase extends \PHPUnit_Framework_TestCase
{
protected $pass;
protected $traverser;
private $parser;
private $printer;
protected function setPass(CodeCleanerPass $pass)
{
$this->pass = $pass;
if (!isset($this->traverser)) {
$this->traverser = new NodeTraverser();
}
$this->traverser->addVisitor($this->pass);
}
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)
{
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);
$this->assertEquals($to, $this->prettyPrint($stmts));
}
private function getParser()
{
if (!isset($this->parser)) {
$this->parser = new Parser(new Lexer());
}
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,20 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 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-2014 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,75 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 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 as NodeTraverser;
use Psy\CodeCleaner\FunctionReturnInWriteContextPass;
use Psy\Exception\FatalErrorException;
class FunctionReturnInWriteContextPassTest extends CodeCleanerTestCase
{
public function setUp()
{
$this->pass = new FunctionReturnInWriteContextPass();
$this->traverser = new NodeTraverser();
$this->traverser->addVisitor($this->pass);
}
/**
* @dataProvider invalidStatements
* @expectedException \Psy\Exception\FatalErrorException
* @expectedExceptionMessage Can't use function return value in write context
*/
public function testProcessStatementFails($code)
{
$stmts = $this->parse($code);
$this->traverser->traverse($stmts);
}
public function invalidStatements()
{
return array(
array('f(&g())'),
array('array(& $object->method())'),
array('$a->method(& $closure())'),
array('array(& A::b())'),
array('f() = 5'),
);
}
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"))'));
}
}

View File

@@ -0,0 +1,38 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 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()
{
return array(
array('4', 'return 4;'),
array('foo()', 'return foo();'),
);
}
}

View File

@@ -0,0 +1,74 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 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)
{
$stmts = $this->parse($code);
$this->traverser->traverse($stmts);
}
public function invalidStatements()
{
return array(
array('null instanceof stdClass'),
array('true instanceof stdClass'),
array('9 instanceof stdClass'),
array('1.0 instanceof stdClass'),
array('"foo" instanceof stdClass'),
array('__DIR__ instanceof stdClass'),
array('PHP_SAPI instanceof stdClass'),
array('1+1 instanceof stdClass'),
array('true && false instanceof stdClass'),
array('"a"."b" instanceof stdClass'),
array('!5 instanceof stdClass'),
);
}
/**
* @dataProvider validStatements
*/
public function testProcessValidStatement($code)
{
$stmts = $this->parse($code);
$this->traverser->traverse($stmts);
}
public function validStatements()
{
$data = array(
array('$a instanceof stdClass'),
array('strtolower("foo") instanceof stdClass'),
array('array(1) instanceof stdClass'),
array('(string) "foo" instanceof stdClass'),
array('(1+1) instanceof stdClass'),
array('"foo ${foo} $bar" instanceof stdClass'),
array('DateTime::ISO8601 instanceof stdClass'),
);
return $data;
}
}

View File

@@ -0,0 +1,69 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 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);
}
/**
* @dataProvider validStatements
*/
public function testProcessStatementPasses($code)
{
$stmts = $this->parse($code);
$this->traverse($stmts);
}
public function validStatements()
{
return array(
array('array_merge()'),
array('__psysh__()'),
array('$this'),
array('$psysh'),
array('$__psysh'),
array('$banana'),
);
}
/**
* @dataProvider invalidStatements
* @expectedException \Psy\Exception\RuntimeException
*/
public function testProcessStatementFails($code)
{
$stmts = $this->parse($code);
$this->traverse($stmts);
}
public function invalidStatements()
{
return array(
array('$__psysh__'),
array('var_dump($__psysh__)'),
array('$__psysh__ = "your mom"'),
array('$__psysh__->fakeFunctionCall()'),
);
}
}

View File

@@ -0,0 +1,77 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 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)
{
$stmts = $this->parse($code);
$this->traverser->traverse($stmts);
}
public function invalidStatements()
{
if (version_compare(PHP_VERSION, '5.5', '>=')) {
return array(
array('empty()'),
);
}
return array(
array('empty()'),
array('empty(null)'),
array('empty(PHP_EOL)'),
array('empty("wat")'),
array('empty(1.1)'),
array('empty(Foo::$bar)'),
);
}
/**
* @dataProvider validStatements
*/
public function testProcessValidStatement($code)
{
$stmts = $this->parse($code);
$this->traverser->traverse($stmts);
}
public function validStatements()
{
if (version_compare(PHP_VERSION, '5.5', '<')) {
return array(
array('empty($foo)'),
);
}
return array(
array('empty($foo)'),
array('empty(null)'),
array('empty(PHP_EOL)'),
array('empty("wat")'),
array('empty(1.1)'),
array('empty(Foo::$bar)'),
);
}
}

View File

@@ -0,0 +1,39 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 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 array(
array('__DIR__;', 'getcwd();'),
array('__FILE__;', "'';"),
array('___FILE___;', "___FILE___;"),
);
}
}

View File

@@ -0,0 +1,49 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 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->process('array_merge()');
$this->assertNull($this->cleaner->getNamespace());
// A non-block namespace statement should set the current namespace.
$this->process('namespace Alpha');
$this->assertEquals(array('Alpha'), $this->cleaner->getNamespace());
// A new non-block namespace statement should override the current namespace.
$this->process('namespace Beta');
$this->assertEquals(array('Beta'), $this->cleaner->getNamespace());
$this->process('namespace Gamma { array_merge(); }');
$this->assertNull($this->cleaner->getNamespace());
}
private function process($code)
{
$stmts = $this->parse($code);
$this->traverse($stmts);
}
}

View File

@@ -0,0 +1,91 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 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\StaticConstructorPass;
class StaticConstructorPassTest extends CodeCleanerTestCase
{
protected function setUp()
{
$this->setPass(new StaticConstructorPass());
}
/**
* @dataProvider invalidStatements
* @expectedException \Psy\Exception\FatalErrorException
*/
public function testProcessInvalidStatement($code)
{
$stmts = $this->parse($code);
$this->traverser->traverse($stmts);
}
/**
* @dataProvider invalidParserStatements
* @expectedException \Psy\Exception\ParseErrorException
*/
public function testProcessInvalidStatementCatchedByParser($code)
{
$stmts = $this->parse($code);
$this->traverser->traverse($stmts);
}
public function invalidStatements()
{
$statements = array(
array('class A { public static function A() {}}'),
array('class A { private static function A() {}}'),
);
if (version_compare(PHP_VERSION, '5.3.3', '<')) {
$statements[] = array('namespace B; class A { private static function A() {}}');
}
return $statements;
}
public function invalidParserStatements()
{
$statements = array(
array('class A { public static function __construct() {}}'),
array('class A { private static function __construct() {}}'),
array('class A { private static function __construct() {} public function A() {}}'),
array('namespace B; class A { private static function __construct() {}}'),
);
return $statements;
}
/**
* @dataProvider validStatements
*/
public function testProcessValidStatement($code)
{
$stmts = $this->parse($code);
$this->traverser->traverse($stmts);
}
public function validStatements()
{
$statements = array(
array('class A { public static function A() {} public function __construct() {}}'),
array('class A { private function __construct() {} public static function A() {}}'),
);
if (version_compare(PHP_VERSION, '5.3.3', '>=')) {
$statements[] = array('namespace B; class A { private static function A() {}}');
}
return $statements;
}
}

View File

@@ -0,0 +1,52 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 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 array(
array(
"use StdClass as NotSoStd;\n\$std = new NotSoStd();",
"\$std = new \\StdClass();",
),
array(
"namespace Foo;\n\nuse StdClass as S;\n\$std = new S();",
"namespace Foo;\n\n\$std = new \\StdClass();",
),
array(
"namespace Foo;\n\nuse \\StdClass as S;\n\$std = new S();",
"namespace Foo;\n\n\$std = new \\StdClass();",
),
array(
"use Foo\\Bar as fb;\n\$baz = new fb\\Baz();",
"\$baz = new \\Foo\\Bar\\Baz();",
),
);
}
}

View File

@@ -0,0 +1,185 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 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;
use Psy\Exception\Exception;
class ValidClassNamePassTest extends CodeCleanerTestCase
{
public function setUp()
{
$this->setPass(new ValidClassNamePass());
}
/**
* @dataProvider getInvalid
*/
public function testProcessInvalid($code, $php54 = false)
{
try {
$stmts = $this->parse($code);
$this->traverse($stmts);
$this->fail();
} catch (Exception $e) {
if ($php54 && version_compare(PHP_VERSION, '5.4', '<')) {
$this->assertInstanceOf('Psy\Exception\ParseErrorException', $e);
} else {
$this->assertInstanceOf('Psy\Exception\FatalErrorException', $e);
}
}
}
public function getInvalid()
{
// class declarations
return array(
// core class
array('class stdClass {}'),
// capitalization
array('class stdClass {}'),
// collisions with interfaces and traits
array('interface stdClass {}'),
array('trait stdClass {}', true),
// collisions inside the same code snippet
array("
class Psy_Test_CodeCleaner_ValidClassNamePass_Alpha {}
class Psy_Test_CodeCleaner_ValidClassNamePass_Alpha {}
"),
array("
class Psy_Test_CodeCleaner_ValidClassNamePass_Alpha {}
trait Psy_Test_CodeCleaner_ValidClassNamePass_Alpha {}
", true),
array("
trait Psy_Test_CodeCleaner_ValidClassNamePass_Alpha {}
class Psy_Test_CodeCleaner_ValidClassNamePass_Alpha {}
", true),
array("
trait Psy_Test_CodeCleaner_ValidClassNamePass_Alpha {}
interface Psy_Test_CodeCleaner_ValidClassNamePass_Alpha {}
", true),
array("
interface Psy_Test_CodeCleaner_ValidClassNamePass_Alpha {}
trait Psy_Test_CodeCleaner_ValidClassNamePass_Alpha {}
", true),
array("
interface Psy_Test_CodeCleaner_ValidClassNamePass_Alpha {}
class Psy_Test_CodeCleaner_ValidClassNamePass_Alpha {}
"),
array("
class Psy_Test_CodeCleaner_ValidClassNamePass_Alpha {}
interface Psy_Test_CodeCleaner_ValidClassNamePass_Alpha {}
"),
// namespaced collisions
array("
namespace Psy\\Test\\CodeCleaner {
class ValidClassNamePassTest {}
}
"),
array("
namespace Psy\\Test\\CodeCleaner\\ValidClassNamePass {
class Beta {}
}
namespace Psy\\Test\\CodeCleaner\\ValidClassNamePass {
class Beta {}
}
"),
// extends and implements
array('class ValidClassNamePassTest extends NotAClass {}'),
array('class ValidClassNamePassTest extends ArrayAccess {}'),
array('class ValidClassNamePassTest implements stdClass {}'),
array('class ValidClassNamePassTest implements ArrayAccess, stdClass {}'),
array('interface ValidClassNamePassTest extends stdClass {}'),
array('interface ValidClassNamePassTest extends ArrayAccess, stdClass {}'),
// class instantiations
array('new Psy_Test_CodeCleaner_ValidClassNamePass_Gamma();'),
array("
namespace Psy\\Test\\CodeCleaner\\ValidClassNamePass {
new Psy_Test_CodeCleaner_ValidClassNamePass_Delta();
}
"),
// class constant fetch
array('Psy\\Test\\CodeCleaner\\ValidClassNamePass\\NotAClass::FOO'),
// static call
array('Psy\\Test\\CodeCleaner\\ValidClassNamePass\\NotAClass::foo()'),
array('Psy\\Test\\CodeCleaner\\ValidClassNamePass\\NotAClass::$foo()'),
);
}
/**
* @dataProvider getValid
*/
public function testProcessValid($code)
{
$stmts = $this->parse($code);
$this->traverse($stmts);
}
public function getValid()
{
return array(
// class declarations
array('class Psy_Test_CodeCleaner_ValidClassNamePass_Epsilon {}'),
array('namespace Psy\Test\CodeCleaner\ValidClassNamePass; class Zeta {}'),
array("
namespace { class Psy_Test_CodeCleaner_ValidClassNamePass_Eta {}; }
namespace Psy\\Test\\CodeCleaner\\ValidClassNamePass {
class Psy_Test_CodeCleaner_ValidClassNamePass_Eta {}
}
"),
array('namespace Psy\Test\CodeCleaner\ValidClassNamePass { class stdClass {} }'),
// class instantiations
array('new stdClass();'),
array('new stdClass();'),
array("
namespace Psy\\Test\\CodeCleaner\\ValidClassNamePass {
class Theta {}
}
namespace Psy\\Test\\CodeCleaner\\ValidClassNamePass {
new Theta();
}
"),
array("
namespace Psy\\Test\\CodeCleaner\\ValidClassNamePass {
class Iota {}
new Iota();
}
"),
array("
namespace Psy\\Test\\CodeCleaner\\ValidClassNamePass {
class Kappa {}
}
namespace {
new \\Psy\\Test\\CodeCleaner\\ValidClassNamePass\\Kappa();
}
"),
// Class constant fetch (ValidConstantPassTest validates the actual constant)
array('class A {} A::FOO'),
array('$a = new DateTime; $a::ATOM'),
// static call
array('DateTime::createFromFormat()'),
array('DateTime::$someMethod()'),
array('Psy\Test\CodeCleaner\Fixtures\ClassWithStatic::doStuff()'),
array('Psy\Test\CodeCleaner\Fixtures\ClassWithCallStatic::doStuff()'),
);
}
}

View File

@@ -0,0 +1,64 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 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)
{
$stmts = $this->parse($code);
$this->traverse($stmts);
}
public function getInvalidReferences()
{
return array(
array('Foo\BAR'),
// class constant fetch
array('Psy\Test\CodeCleaner\ValidConstantPassTest::FOO'),
array('DateTime::BACON'),
);
}
/**
* @dataProvider getValidReferences
*/
public function testProcessValidConstantReferences($code)
{
$stmts = $this->parse($code);
$this->traverse($stmts);
}
public function getValidReferences()
{
return array(
array('PHP_EOL'),
// class constant fetch
array('NotAClass::FOO'),
array('DateTime::ATOM'),
array('$a = new DateTime; $a::ATOM'),
);
}
}

View File

@@ -0,0 +1,124 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 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)
{
$stmts = $this->parse($code);
$this->traverse($stmts);
}
public function getInvalidFunctions()
{
return array(
// function declarations
array('function array_merge() {}'),
array('function Array_Merge() {}'),
array("
function psy_test_codecleaner_validfunctionnamepass_alpha() {}
function psy_test_codecleaner_validfunctionnamepass_alpha() {}
"),
array("
namespace Psy\\Test\\CodeCleaner\\ValidFunctionNamePass {
function beta() {}
}
namespace Psy\\Test\\CodeCleaner\\ValidFunctionNamePass {
function beta() {}
}
"),
// function calls
array('psy_test_codecleaner_validfunctionnamepass_gamma()'),
array("
namespace Psy\\Test\\CodeCleaner\\ValidFunctionNamePass {
delta();
}
"),
);
}
/**
* @dataProvider getValidFunctions
*/
public function testProcessValidFunctionCallsAndDeclarations($code)
{
$stmts = $this->parse($code);
$this->traverse($stmts);
}
public function getValidFunctions()
{
return array(
array('function psy_test_codecleaner_validfunctionnamepass_epsilon() {}'),
array("
namespace Psy\\Test\\CodeCleaner\\ValidFunctionNamePass {
function zeta() {}
}
"),
array("
namespace {
function psy_test_codecleaner_validfunctionnamepass_eta() {}
}
namespace Psy\\Test\\CodeCleaner\\ValidFunctionNamePass {
function psy_test_codecleaner_validfunctionnamepass_eta() {}
}
"),
array("
namespace Psy\\Test\\CodeCleaner\\ValidFunctionNamePass {
function psy_test_codecleaner_validfunctionnamepass_eta() {}
}
namespace {
function psy_test_codecleaner_validfunctionnamepass_eta() {}
}
"),
array("
namespace Psy\\Test\\CodeCleaner\\ValidFunctionNamePass {
function array_merge() {}
}
"),
// function calls
array('array_merge();'),
array("
namespace Psy\\Test\\CodeCleaner\\ValidFunctionNamePass {
function theta() {}
}
namespace Psy\\Test\\CodeCleaner\\ValidFunctionNamePass {
theta();
}
"),
// closures
array('$test = function(){};$test()'),
array("
namespace Psy\\Test\\CodeCleaner\\ValidFunctionNamePass {
function theta() {}
}
namespace {
Psy\\Test\\CodeCleaner\\ValidFunctionNamePass\\theta();
}
"),
);
}
}

View File

@@ -0,0 +1,39 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 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 codeProvider
*/
public function testAutomaticSemicolons(array $lines, $requireSemicolons, $expected)
{
$cc = new CodeCleaner();
$this->assertEquals($expected, $cc->clean($lines, $requireSemicolons));
}
public function codeProvider()
{
return array(
array(array('true'), false, 'return true;'),
array(array('true;'), false, 'return true;'),
array(array('true;'), true, 'return true;'),
array(array('true'), true, false),
array(array('echo "foo";', 'true'), false, "echo 'foo';\nreturn true;"),
array(array('echo "foo";', 'true'), true , false),
);
}
}

View File

@@ -0,0 +1,174 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 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\ExecutionLoop\Loop;
use Psy\Output\PassthruPager;
use Symfony\Component\Console\Output\ConsoleOutput;
class ConfigurationTest extends \PHPUnit_Framework_TestCase
{
public function testDefaults()
{
$config = new Configuration();
$this->assertEquals(function_exists('readline'), $config->hasReadline());
$this->assertEquals(function_exists('readline'), $config->useReadline());
$this->assertEquals(function_exists('pcntl_signal'), $config->hasPcntl());
$this->assertEquals(function_exists('pcntl_signal'), $config->usePcntl());
$this->assertFalse($config->requireSemicolons());
}
public function testGettersAndSetters()
{
$config = new Configuration();
$this->assertNull($config->getDataDir());
$config->setDataDir('wheee');
$this->assertEquals('wheee', $config->getDataDir());
$this->assertNull($config->getConfigDir());
$config->setConfigDir('wheee');
$this->assertEquals('wheee', $config->getConfigDir());
}
/**
* @dataProvider directories
*/
public function testFilesAndDirectories($home, $configFile, $historyFile, $manualDbFile)
{
$oldHome = getenv('HOME');
putenv("HOME=$home");
$config = new Configuration();
$this->assertEquals(realpath($configFile), realpath($config->getConfigFile()));
$this->assertEquals(realpath($historyFile), realpath($config->getHistoryFile()));
$this->assertEquals(realpath($manualDbFile), realpath($config->getManualDbFile()));
putenv("HOME=$oldHome");
}
public function directories()
{
$base = realpath(__DIR__ . '/../../fixtures');
return array(
array(
$base . '/default',
$base . '/default/.config/psysh/config.php',
$base . '/default/.config/psysh/psysh_history',
$base . '/default/.local/share/psysh/php_manual.sqlite',
),
array(
$base . '/legacy',
$base . '/legacy/.psysh/rc.php',
$base . '/legacy/.psysh/history',
$base . '/legacy/.psysh/php_manual.sqlite',
),
array(
$base . '/mixed',
$base . '/mixed/.psysh/config.php',
$base . '/mixed/.psysh/psysh_history',
null,
),
);
}
public function testLoadConfig()
{
$config = new Configuration();
$cleaner = new CodeCleaner();
$pager = new PassthruPager(new ConsoleOutput());
$loop = new Loop($config);
$config->loadConfig(array(
'useReadline' => false,
'usePcntl' => false,
'codeCleaner' => $cleaner,
'pager' => $pager,
'loop' => $loop,
'requireSemicolons' => true,
));
$this->assertFalse($config->useReadline());
$this->assertFalse($config->usePcntl());
$this->assertSame($cleaner, $config->getCodeCleaner());
$this->assertSame($pager, $config->getPager());
$this->assertSame($loop, $config->getLoop());
$this->assertTrue($config->requireSemicolons());
}
public function testLoadConfigFile()
{
$config = new Configuration(array('configFile' => __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 will be deprecated, but we want to actually test the value.
$was = error_reporting(error_reporting() & ~E_USER_DEPRECATED);
$this->assertStringStartsWith($runtimeDir, realpath($config->getTempDir()));
error_reporting($was);
$this->assertStringStartsWith($runtimeDir, realpath($config->getRuntimeDir()));
$this->assertEquals(function_exists('readline'), $config->useReadline());
$this->assertFalse($config->usePcntl());
}
/**
* @expectedException PHPUnit_Framework_Error_Deprecated
*/
public function testSetTempDirIsDeprecated()
{
$config = new Configuration();
$config->setTempDir('fake');
}
/**
* @expectedException PHPUnit_Framework_Error_Deprecated
*/
public function testGetTempDirIsDeprecated()
{
$config = new Configuration();
$config->getTempDir();
}
/**
* @expectedException PHPUnit_Framework_Error_Deprecated
*/
public function testBaseDirConfigIsDeprecated()
{
$config = new Configuration(array('baseDir' => 'fake'));
}
private function joinPath()
{
return implode(DIRECTORY_SEPARATOR, func_get_args());
}
public function testConfigIncludes()
{
$config = new Configuration(array(
'defaultIncludes' => array('/file.php'),
'configFile' => __DIR__ . '/../../fixtures/empty.php',
));
$includes = $config->getDefaultIncludes();
$this->assertCount(1, $includes);
$this->assertEquals('/file.php', $includes[0]);
}
}

View File

@@ -0,0 +1,34 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 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;
use Psy\Exception\Exception;
class BreakExceptionTest extends \PHPUnit_Framework_TestCase
{
public function testInstance()
{
$e = new BreakException();
$this->assertTrue($e instanceof Exception);
$this->assertTrue($e instanceof BreakException);
}
public function testMessage()
{
$e = new BreakException('foo');
$this->assertContains('foo', $e->getMessage());
$this->assertEquals('foo', $e->getRawMessage());
}
}

View File

@@ -0,0 +1,108 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 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;
use Psy\Exception\Exception;
class ErrorExceptionTest extends \PHPUnit_Framework_TestCase
{
public function testInstance()
{
$e = new ErrorException();
$this->assertTrue($e instanceof Exception);
$this->assertTrue($e instanceof \ErrorException);
$this->assertTrue($e instanceof ErrorException);
}
public function testMessage()
{
$e = new ErrorException('foo');
$this->assertContains('foo', $e->getMessage());
$this->assertEquals('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 array(
array(E_WARNING, 'warning'),
array(E_CORE_WARNING, 'warning'),
array(E_COMPILE_WARNING, 'warning'),
array(E_USER_WARNING, 'warning'),
array(E_STRICT, 'Strict error'),
array(0, 'error'),
);
}
/**
* @dataProvider getUserLevels
*/
public function testThrowExceptionAsErrorHandler($level, $type)
{
set_error_handler(array('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 array(
array(E_USER_ERROR, 'error'),
array(E_USER_WARNING, 'warning'),
array(E_USER_NOTICE, 'error'),
array(E_USER_DEPRECATED, 'error'),
);
}
public function testIgnoreExecutionLoopFilename()
{
$e = new ErrorException('{{message}}', 0, 1, '/fake/path/to/Psy/ExecutionLoop/Loop.php');
$this->assertEmpty($e->getFile());
$e = new ErrorException('{{message}}', 0, 1, 'c:\fake\path\to\Psy\ExecutionLoop\Loop.php');
$this->assertEmpty($e->getFile());
$e = new ErrorException('{{message}}', 0, 1, '/fake/path/to/Psy/File.php');
$this->assertNotEmpty($e->getFile());
}
}

View File

@@ -0,0 +1,46 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 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\Exception;
use Psy\Exception\FatalErrorException;
class FatalErrorExceptionTest extends \PHPUnit_Framework_TestCase
{
public function testInstance()
{
$e = new FatalErrorException();
$this->assertTrue($e instanceof Exception);
$this->assertTrue($e instanceof \ErrorException);
$this->assertTrue($e instanceof FatalErrorException);
}
public function testMessage()
{
$e = new FatalErrorException('{msg}', 0, 0, '{filename}', 13);
$this->assertEquals('{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->assertEquals('{msg}', $e->getRawMessage());
$this->assertContains('{msg}', $e->getMessage());
$this->assertContains('eval()\'d code', $e->getMessage());
}
}

View File

@@ -0,0 +1,43 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 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\Exception;
use Psy\Exception\ParseErrorException;
class ParseErrorExceptionTest extends \PHPUnit_Framework_TestCase
{
public function testInstance()
{
$e = new ParseErrorException();
$this->assertTrue($e instanceof Exception);
$this->assertTrue($e instanceof \PHPParser_Error);
$this->assertTrue($e instanceof ParseErrorException);
}
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,31 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 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\Exception;
use Psy\Exception\RuntimeException;
class RuntimeExceptionTest extends \PHPUnit_Framework_TestCase
{
public function testException()
{
$msg = 'bananas';
$e = new RuntimeException($msg);
$this->assertTrue($e instanceof Exception);
$this->assertTrue($e instanceof \RuntimeException);
$this->assertTrue($e instanceof RuntimeException);
$this->assertEquals($msg, $e->getMessage());
$this->assertEquals($msg, $e->getRawMessage());
}
}

View File

@@ -0,0 +1,61 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 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;
class CodeFormatterTest extends \PHPUnit_Framework_TestCase
{
private function ignoreThisMethod($arg)
{
echo "whot!";
}
public function testFormat()
{
$expected = <<<EOS
> 18| private function ignoreThisMethod(\$arg)
19| {
20| echo "whot!";
21| }
EOS;
$formatted = CodeFormatter::format(new \ReflectionMethod($this, 'ignoreThisMethod'));
$formattedWithoutColors = preg_replace('#' . chr(27) . '\[\d\d?m#', '', $formatted);
$this->assertEquals($expected, rtrim($formattedWithoutColors));
$this->assertNotEquals($expected, rtrim($formatted));
}
/**
* @dataProvider filenames
* @expectedException Psy\Exception\RuntimeException
*/
public function testCodeFormatterThrowsException($filename)
{
$reflector = $this->getMockBuilder('ReflectionClass')
->disableOriginalConstructor()
->getMock();
$reflector
->expects($this->once())
->method('getFileName')
->will($this->returnValue($filename));
CodeFormatter::format($reflector);
}
public function filenames()
{
return array(array(null), array('not a file'));
}
}

View File

@@ -0,0 +1,63 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 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->assertEquals(
$expected,
DocblockFormatter::format(new \ReflectionMethod($this, 'methodWithDocblock'))
);
}
}

View File

@@ -0,0 +1,79 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 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\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->assertEquals($expected, strip_tags(SignatureFormatter::format($reflector)));
// $this->assertEquals(
// ,
// strip_tags(SignatureFormatter::format(new \ReflectionFunction('sort')))
// );
}
public function signatureReflectors()
{
return array(
array(
new \ReflectionClass($this),
"class Psy\Test\Formatter\SignatureFormatterTest "
. "extends PHPUnit_Framework_TestCase implements "
. "PHPUnit_Framework_SelfDescribing, Countable, "
. "PHPUnit_Framework_Test",
),
array(
new \ReflectionFunction('implode'),
'function implode($glue, $pieces)',
),
array(
new ReflectionConstant($this, 'FOO'),
'const FOO = "foo value"',
),
array(
new \ReflectionMethod($this, 'someFakeMethod'),
'private function someFakeMethod(array $one, $two = \'TWO\', Reflector $three = null)',
),
array(
new \ReflectionProperty($this, 'bar'),
'private static $bar',
),
array(
new \ReflectionClass('Psy\CodeCleaner\CodeCleanerPass'),
'abstract class Psy\CodeCleaner\CodeCleanerPass extends PhpParser\NodeVisitorAbstract implements PhpParser\NodeVisitor',
),
);
}
/**
* @expectedException InvalidArgumentException
*/
public function testSignatureFormatterThrowsUnknownReflectorExpeption()
{
$refl = $this->getMock('Reflector');
SignatureFormatter::format($refl);
}
}

View File

@@ -0,0 +1,127 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Presenter;
use Psy\Presenter\ArrayPresenter;
use Psy\Presenter\ObjectPresenter;
use Psy\Presenter\PresenterManager;
use Psy\Presenter\ScalarPresenter;
class ArrayPresenterTest extends \PHPUnit_Framework_TestCase
{
private $presenter;
private $manager;
public function setUp()
{
$this->presenter = new ArrayPresenter();
$this->manager = new PresenterManager();
$this->manager->addPresenter(new ScalarPresenter());
$this->manager->addPresenter(new ObjectPresenter());
$this->manager->addPresenter($this->presenter);
}
/**
* @dataProvider presentData
*/
public function testPresent($array, $expect)
{
$this->assertEquals($expect, self::strip($this->presenter->present($array)));
}
public function presentData()
{
return array(
array(array(), '[]'),
array(array(1), '[<number>1</number>]'),
array(array(2, "string"), '[<number>2</number>,<string>"string"</string>]'),
array(array('a' => 1, 'b' => 2), '[<string>"a"</string>=><number>1</number>,<string>"b"</string>=><number>2</number>]'),
);
}
/**
* @dataProvider presentRefData
*/
public function testPresentRef($array, $expect)
{
$this->assertEquals($expect, $this->presenter->presentRef($array));
}
public function presentRefData()
{
return array(
array(array(), '[]'),
array(array(1), 'Array(<number>1</number>)'),
array(array(1, 2), 'Array(<number>2</number>)'),
array(array(1, 2, 3), 'Array(<number>3</number>)'),
);
}
/**
* @dataProvider presentArrayObjectsData
*/
public function testPresentArrayObjects($arrayObj, $expect, $expectRef)
{
$this->assertEquals($expect, $this->presenter->present($arrayObj));
$this->assertEquals($expectRef, $this->presenter->presentRef($arrayObj));
}
public function presentArrayObjectsData()
{
$obj1 = new \ArrayObject(array(1, "string"));
$hash1 = spl_object_hash($obj1);
$ref1 = '<object>\\<<class>ArrayObject</class> <strong>#' . $hash1 . '</strong>></object>';
$expect1 = <<<EOS
$ref1 [
<number>1</number>,
<string>"string"</string>
]
EOS;
$obj2 = new FakeArrayObject(array('a' => 'AAA', 'b' => 'BBB'));
$hash2 = spl_object_hash($obj2);
$ref2 = '<object>\\<<class>Psy\\Test\\Presenter\\FakeArrayObject</class> <strong>#' . $hash2 . '</strong>></object>';
$expect2 = <<<EOS
$ref2 [
<string>"a"</string> => <string>"AAA"</string>,
<string>"b"</string> => <string>"BBB"</string>
]
EOS;
return array(
array($obj1, $expect1, $ref1),
array($obj2, $expect2, $ref2),
);
}
public function testPresentsRecursively()
{
$obj = new \StdClass();
$array = array(1, $obj, "a");
$hash = spl_object_hash($obj);
$expected = <<<EOS
[
<number>1</number>,
<object>\<<class>stdClass</class> <strong>#$hash</strong>></object> {},
<string>"a"</string>
]
EOS;
$this->assertEquals($expected, $this->presenter->present($array));
}
private static function strip($text)
{
return preg_replace('/\\s/', '', $text);
}
}

View File

@@ -0,0 +1,88 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Presenter;
use Psy\Presenter\ClosurePresenter;
use Psy\Presenter\ObjectPresenter;
use Psy\Presenter\PresenterManager;
use Psy\Presenter\ScalarPresenter;
class ClosurePresenterTest extends \PHPUnit_Framework_TestCase
{
private $presenter;
private $manager;
public function setUp()
{
$this->presenter = new ClosurePresenter();
$this->manager = new PresenterManager();
$this->manager->addPresenter(new ScalarPresenter());
$this->manager->addPresenter(new ObjectPresenter());
$this->manager->addPresenter($this->presenter);
}
/**
* @dataProvider presentData
*/
public function testPresent($closure, $expect)
{
$this->assertEquals($expect, $this->presenter->present($closure));
}
/**
* @dataProvider presentData
*/
public function testPresentRef($closure, $expect)
{
$this->assertEquals($expect, $this->presenter->presentRef($closure));
}
public function presentData()
{
$null = null;
$eol = version_compare(PHP_VERSION, '5.4.3', '>=') ? '<const>PHP_EOL</const>' : '<string>"\n"</string>';
return array(
array(
function () {
},
'<keyword>function</keyword> () { <comment>...</comment> }',
),
array(
function ($foo) {
},
'<keyword>function</keyword> ($<strong>foo</strong>) { <comment>...</comment> }',
),
array(
function ($foo, $bar = null) {
},
'<keyword>function</keyword> ($<strong>foo</strong>, $<strong>bar</strong> = <bool>null</bool>) { <comment>...</comment> }',
),
array(
function ($foo = "bar") {
},
'<keyword>function</keyword> ($<strong>foo</strong> = <string>"bar"</string>) { <comment>...</comment> }',
),
array(
function ($foo = \PHP_EOL) {
},
'<keyword>function</keyword> ($<strong>foo</strong> = ' . $eol . ') { <comment>...</comment> }',
),
array(
function ($foo) use ($eol, $null) {
},
'<keyword>function</keyword> ($<strong>foo</strong>) use ($<strong>eol</strong>, $<strong>null</strong>) { <comment>...</comment> }',
),
);
}
}

View File

@@ -0,0 +1,17 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Presenter;
class FakeArrayObject extends \ArrayObject
{
// this space intentionally left blank.
}

View File

@@ -0,0 +1,21 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Presenter\Fixtures;
class SimpleClass
{
public $hello = 'Hello world!';
protected $foo = 'bar';
private $secret = 42;
}

View File

@@ -0,0 +1,123 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Presenter;
use Psy\Presenter\ArrayPresenter;
use Psy\Presenter\ObjectPresenter;
use Psy\Presenter\Presenter;
use Psy\Presenter\PresenterManager;
use Psy\Presenter\ScalarPresenter;
use Psy\Test\Presenter\Fixtures\SimpleClass;
class ObjectPresenterTest extends \PHPUnit_Framework_TestCase
{
private $presenter;
private $manager;
public function setUp()
{
$this->presenter = new ObjectPresenter();
$this->manager = new PresenterManager();
$this->manager->addPresenter(new ScalarPresenter());
$this->manager->addPresenter(new ArrayPresenter());
$this->manager->addPresenter($this->presenter);
}
public function testPresentEmptyObject()
{
$empty = new \StdClass();
$this->assertEquals(
$this->presenter->presentRef($empty) . ' {}',
$this->presenter->present($empty)
);
}
public function testPresentWithDepth()
{
$obj = new \StdClass();
$obj->name = 'std';
$obj->type = 'class';
$obj->tags = array('stuff', 'junk');
$obj->child = new \StdClass();
$obj->child->name = 'std, jr';
$hash = spl_object_hash($obj);
$childHash = spl_object_hash($obj->child);
$expected = <<<EOS
<object>\<<class>stdClass</class> <strong>#$hash</strong>></object> {
name: <string>"std"</string>,
type: <string>"class"</string>,
tags: Array(<number>2</number>),
child: <object>\<<class>stdClass</class> <strong>#$childHash</strong>></object>
}
EOS;
$this->assertStringMatchesFormat($expected, $this->presenter->present($obj, 1));
}
public function testPresentWithoutDepth()
{
$obj = new \StdClass();
$obj->name = 'std';
$obj->type = 'class';
$obj->tags = array('stuff', 'junk');
$obj->child = new \StdClass();
$obj->child->name = 'std, jr';
$hash = spl_object_hash($obj);
$childHash = spl_object_hash($obj->child);
$expected = <<<EOS
<object>\<<class>stdClass</class> <strong>#$hash</strong>></object> {
name: <string>"std"</string>,
type: <string>"class"</string>,
tags: [
<string>"stuff"</string>,
<string>"junk"</string>
],
child: <object>\<<class>stdClass</class> <strong>#$childHash</strong>></object> {
name: <string>"std, jr"</string>
}
}
EOS;
$this->assertStringMatchesFormat($expected, $this->presenter->present($obj));
}
public function testPresentRef()
{
$obj = new \StdClass();
$formatted = $this->presenter->presentRef($obj);
$this->assertStringMatchesFormat('<object>\<<class>stdClass</class> <strong>#%s</strong>></object>', $formatted);
$this->assertContains(spl_object_hash($obj), $formatted);
}
public function testPresentVerbose()
{
$obj = new SimpleClass();
$hash = spl_object_hash($obj);
$expected = <<<EOS
<object>\<<class>Psy\Test\Presenter\Fixtures\SimpleClass</class> <strong>#$hash</strong>></object> {
hello: <string>"Hello world!"</string>,
<protected>foo</protected>: <string>"bar"</string>,
<private>secret</private>: <number>42</number>
}
EOS;
$this->assertStringMatchesFormat($expected, $this->presenter->present($obj, null, Presenter::VERBOSE));
}
}

View File

@@ -0,0 +1,31 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Presenter;
use Psy\Presenter\ResourcePresenter;
class ResourcePresenterTest extends \PHPUnit_Framework_TestCase
{
private $presenter;
public function setUp()
{
$this->presenter = new ResourcePresenter();
}
public function testPresent()
{
$resource = fopen('php://stdin', 'r');
$this->assertStringMatchesFormat('<resource>\<STDIO stream <strong>resource #%d</strong>></resource>', $this->presenter->present($resource));
fclose($resource);
}
}

View File

@@ -0,0 +1,53 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Presenter;
use Psy\Presenter\ScalarPresenter;
class ScalarPresenterTest extends \PHPUnit_Framework_TestCase
{
private $presenter;
public function setUp()
{
$this->presenter = new ScalarPresenter();
}
/**
* @dataProvider scalarData
*/
public function testPresent($value, $expect)
{
$this->assertEquals($expect, $this->presenter->present($value));
}
public function scalarData()
{
return array(
array(1, '<number>1</number>'),
array(1.0, '<number>1.0</number>'),
array(1.5, '<number>1.5</number>'),
array('2', '<string>"2"</string>'),
array('2.5', '<string>"2.5"</string>'),
array('alpha', '<string>"alpha"</string>'),
array("a\nb", '<string>"a\\nb"</string>'),
array(true, '<bool>true</bool>'),
array(false, '<bool>false</bool>'),
array(null, '<bool>null</bool>'),
array(NAN, '<number>NAN</number>'), // heh.
array(acos(8), '<number>NAN</number>'),
array(INF, '<number>INF</number>'),
array(-INF, '<number>-INF</number>'),
array(log(0), '<number>-INF</number>'),
);
}
}

View File

@@ -0,0 +1,80 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 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->assertEquals(array('foo'), $readline->listHistory());
$readline->addHistory('bar');
$this->assertEquals(array('foo', 'bar'), $readline->listHistory());
$readline->addHistory('baz');
$this->assertEquals(array('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->assertEquals(array('foo', 'bar'), $readline->listHistory());
$readline->addHistory('baz');
$this->assertEquals(array('bar', 'baz'), $readline->listHistory());
$readline->addHistory('w00t');
$this->assertEquals(array('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->assertEquals(array('bar', 'foo'), $readline->listHistory());
$readline->addHistory('baz');
$readline->addHistory('w00t');
$readline->addHistory('baz');
$this->assertEquals(array('bar', 'foo', 'w00t', '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-2014 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->assertEquals(array('foo'), $readline->listHistory());
$readline->addHistory('bar');
$this->assertEquals(array('foo', 'bar'), $readline->listHistory());
$readline->addHistory('baz');
$this->assertEquals(array('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->assertEquals(array('foo', 'bar'), $readline->listHistory());
$readline->addHistory('baz');
$this->assertEquals(array('bar', 'baz'), $readline->listHistory());
$readline->addHistory('w00t');
$this->assertEquals(array('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->assertEquals(array('bar', 'foo'), $readline->listHistory());
$readline->addHistory('baz');
$readline->addHistory('w00t');
$readline->addHistory('baz');
$this->assertEquals(array('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->assertEquals(array(
'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->assertEquals(array(
"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-2014 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->assertEquals(array('foo'), $readline->listHistory());
$readline->addHistory('bar');
$this->assertEquals(array('foo', 'bar'), $readline->listHistory());
$readline->addHistory('baz');
$this->assertEquals(array('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->assertEquals(array('foo', 'bar'), $readline->listHistory());
$readline->addHistory('baz');
$this->assertEquals(array('bar', 'baz'), $readline->listHistory());
$readline->addHistory('w00t');
$this->assertEquals(array('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->assertEquals(array('bar', 'foo'), $readline->listHistory());
$readline->addHistory('baz');
$readline->addHistory('w00t');
$readline->addHistory('baz');
$this->assertEquals(array('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,60 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 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 ReflectionConstantTest extends \PHPUnit_Framework_TestCase
{
const CONSTANT_ONE = 'one';
public function testConstruction()
{
$refl = new ReflectionConstant($this, 'CONSTANT_ONE');
$class = $refl->getDeclaringClass();
$this->assertTrue($class instanceof \ReflectionClass);
$this->assertEquals('Psy\Test\Reflection\ReflectionConstantTest', $class->getName());
$this->assertEquals('CONSTANT_ONE', $refl->getName());
$this->assertEquals('CONSTANT_ONE', (string) $refl);
$this->assertEquals('one', $refl->getValue());
$this->assertEquals(null, $refl->getFileName());
$this->assertFalse($refl->getDocComment());
}
/**
* @expectedException InvalidArgumentException
*/
public function testUnknownConstantThrowsException()
{
new ReflectionConstant($this, 'UNKNOWN_CONSTANT');
}
/**
* @expectedException \RuntimeException
* @dataProvider notYetImplemented
*/
public function testNotYetImplemented($method)
{
$refl = new ReflectionConstant($this, 'CONSTANT_ONE');
$refl->$method();
}
public function notYetImplemented()
{
return array(
array('getStartLine'),
array('getEndLine'),
array('export'),
);
}
}

View File

@@ -0,0 +1,339 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 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 = array();
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->assertNotContains('__psysh__', $shell->getScopeVariableNames());
$this->assertEquals(array('one', 'two', 'three', '_'), $shell->getScopeVariableNames());
$this->assertEquals('banana', $shell->getScopeVariable('one'));
$this->assertEquals(123, $shell->getScopeVariable('two'));
$this->assertSame($three, $shell->getScopeVariable('three'));
$this->assertNull($shell->getScopeVariable('_'));
$shell->setScopeVariables(array());
$this->assertEquals(array('_'), $shell->getScopeVariableNames());
}
/**
* @expectedException \InvalidArgumentException
*/
public function testUnknownScopeVariablesThrowExceptions()
{
$shell = new Shell($this->getConfig());
$shell->setScopeVariables(array('foo' => 'FOO', 'bar' => 1));
$shell->getScopeVariable('baz');
}
public function testIncludes()
{
$config = $this->getConfig(array('configFile' => __DIR__ . '/../../fixtures/empty.php'));
$shell = new Shell($config);
$this->assertEmpty($shell->getIncludes());
$shell->setIncludes(array('foo', 'bar', 'baz'));
$this->assertEquals(array('foo', 'bar', 'baz'), $shell->getIncludes());
}
public function testIncludesConfig()
{
$config = $this->getConfig(array(
'defaultIncludes' => array('/file.php'),
'configFile' => __DIR__ . '/../../fixtures/empty.php',
));
$shell = new Shell($config);
$includes = $shell->getIncludes();
$this->assertEquals('/file.php', $includes[0]);
}
public function testAddMatchersViaConfig()
{
$config = $this->getConfig(array(
'tabCompletionMatchers' => array(
new ClassMethodsMatcher(),
),
));
$matchers = $config->getTabCompletionMatchers();
$this->assertTrue(array_pop($matchers) instanceof ClassMethodsMatcher);
}
public function testRenderingExceptions()
{
$shell = new Shell($this->getConfig());
$output = $this->getOutput();
$stream = $output->getStream();
$e = new ParseErrorException('message', 13);
$shell->addCode('code');
$this->assertTrue($shell->hasCode());
$this->assertNotEmpty($shell->getCodeBuffer());
$shell->renderException($e, $output);
$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 error:', $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(phpversion(), $shell->getVersion());
$this->assertContains(php_sapi_name(), $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->assertEquals('class a { }', $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->assertEquals('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);
$shell->flushCode();
}
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->assertEquals('{{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->assertEquals('{{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 array(
array('{{return value}}', '=> <string>"{{return value}}"</string>' . PHP_EOL),
array(1, '=> <number>1</number>' . 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->assertEquals($expected, stream_get_contents($stream));
}
public function getRenderedExceptions()
{
return array(
array(new \Exception('{{message}}'), "Exception with message '{{message}}'" . PHP_EOL),
);
}
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 = array())
{
// Mebbe there's a better way than this?
$dir = tempnam(sys_get_temp_dir(), 'psysh_shell_test_');
unlink($dir);
$defaults = array(
'configDir' => $dir,
'dataDir' => $dir,
'runtimeDir' => $dir,
);
return new Configuration(array_merge($defaults, $config));
}
}

View File

@@ -0,0 +1,141 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 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 $line
* @param $mustContain
* @param $mustNotContain
* @dataProvider classesInput
*/
public function testClassesCompletion($line, $mustContain, $mustNotContain)
{
$context = new Context();
$commands = array(
new ShowCommand(),
new ListCommand(),
);
$matchers = array(
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(array('foo' => 12, 'bar' => new \DOMDocument()));
$code = $tabCompletion->processCallback('', 0, array(
'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 array(
// input, must had, must not had
array('T_OPE', array('T_OPEN_TAG'), array()),
array('st', array('stdClass'), array()),
array('stdCla', array('stdClass'), array()),
array('new s', array('stdClass'), array()),
array(
'new ',
array('stdClass', 'Psy\\Context', 'Psy\\Configuration'),
array('require', 'array_search', 'T_OPEN_TAG', '$foo'),
),
array('new Psy\\C', array('Context'), array('CASE_LOWER')),
array('\s', array('stdClass'), array()),
array('array_', array('array_search', 'array_map', 'array_merge'), array()),
array('$bar->', array('load'), array()),
array('$b', array('bar'), array()),
array('6 + $b', array('bar'), array()),
array('$f', array('foo'), array()),
array('l', array('ls'), array()),
array('ls ', array(), array('ls')),
array('sho', array('show'), array()),
array('12 + clone $', array('foo'), array()),
// array('$foo ', array('+', 'clone'), array('$foo', 'DOMDocument', 'array_map')), requires a operator matcher?
array('$', array('foo', 'bar'), array('require', 'array_search', 'T_OPEN_TAG', 'Psy')),
array(
'Psy\\',
array('Context', 'TabCompletion\\Matcher\\AbstractMatcher'),
array('require', 'array_search'),
),
array(
'Psy\Test\TabCompletion\StaticSample::CO',
array('Psy\Test\TabCompletion\StaticSample::CONSTANT_VALUE'),
array(),
),
array(
'Psy\Test\TabCompletion\StaticSample::',
array('Psy\Test\TabCompletion\StaticSample::$staticVariable'),
array(),
),
array(
'Psy\Test\TabCompletion\StaticSample::',
array('Psy\Test\TabCompletion\StaticSample::staticFunction'),
array(),
),
);
}
}

View File

@@ -0,0 +1,27 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 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,96 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 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->assertEquals($body, $docblock->desc);
foreach ($tags as $tag => $value) {
$this->assertTrue($docblock->hasTag($tag));
$this->assertEquals($value, $docblock->tag($tag));
}
}
public function comments()
{
return array(
array('', '', array()),
array(
'/**
* This is a docblock
*
* @throws \Exception with a description
*/',
"This is a docblock",
array(
'throws' => array(array('type' => '\Exception', 'desc' => 'with a description')),
),
),
array(
'/**
* 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',
array(
'param' => array(
array('type' => 'int', 'desc' => 'Is a Foo', 'var' => '$foo'),
array('type' => 'string', 'desc' => 'With some sort of description', 'var' => '$bar'),
array('type' => '\ClassName', 'desc' => 'is cool too', 'var' => '$baz'),
),
'return' => array(
array('type' => 'int', 'desc' => 'At least it isn\'t a string'),
),
),
),
array(
'/**
* This is a docblock!
*
* It spans lines, too!
*
* @tagname plus a description
*
* @return
*/',
"This is a docblock!\n\nIt spans lines, too!",
array(
'tagname' => array('plus a description'),
),
),
);
}
}

View File

@@ -0,0 +1,80 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 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\Reflection\ReflectionConstant;
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->assertTrue($refl instanceof \ReflectionFunction);
$refl = Mirror::get('Psy\Test\Util\MirrorTest');
$this->assertTrue($refl instanceof \ReflectionClass);
$refl = Mirror::get($this);
$this->assertTrue($refl instanceof \ReflectionObject);
$refl = Mirror::get($this, 'FOO');
$this->assertTrue($refl instanceof ReflectionConstant);
$refl = Mirror::get($this, 'bar');
$this->assertTrue($refl instanceof \ReflectionProperty);
$refl = Mirror::get($this, 'baz');
$this->assertTrue($refl instanceof \ReflectionProperty);
$refl = Mirror::get($this, 'aPublicMethod');
$this->assertTrue($refl instanceof \ReflectionMethod);
$refl = Mirror::get($this, 'baz', Mirror::STATIC_PROPERTY);
$this->assertTrue($refl instanceof \ReflectionProperty);
}
/**
* @expectedException \RuntimeException
*/
public function testMirrorThrowsExceptions()
{
Mirror::get($this, 'notAMethod');
}
/**
* @expectedException \InvalidArgumentException
* @dataProvider invalidArguments
*/
public function testMirrorThrowsInvalidArgumentExceptions($value)
{
Mirror::get($value);
}
public function invalidArguments()
{
return array(
array('not_a_function_or_class'),
array(array()),
array(1),
);
}
}

View File

@@ -0,0 +1,30 @@
<?php
/*
* This file is part of Psy Shell
*
* (c) 2012-2014 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\String;
class StringTest extends \PHPUnit_Framework_TestCase
{
/**
* @dataProvider testUnvisProvider
*/
public function testUnvis($input, $expected)
{
$this->assertEquals($expected, String::unvis($input));
}
public function testUnvisProvider()
{
//return require_once(__DIR__.'/../../../fixtures/unvis_fixtures.php');
return json_decode(file_get_contents(__DIR__ . '/../../../fixtures/unvis_fixtures.json'));
}
}