Refactored structure

This commit is contained in:
Dmitry Khomutov 2016-04-17 12:34:12 +06:00
commit e5164ae1dd
329 changed files with 277 additions and 457 deletions

39
tests/B8Framework/CacheTest.php Executable file
View file

@ -0,0 +1,39 @@
<?php
namespace Tests\b8;
use b8\Config, b8\Cache;
class CacheTest extends PHPUnit_Framework_TestCase
{
public function testCreateSingleton()
{
$cache = Cache::getCache(Cache::TYPE_APC);
$this->assertTrue($cache instanceof Cache);
}
public function testDisableCaching()
{
$config = new Config();
Config::getInstance()->set('DisableCaching', true);
$cache = Cache::getCache(Cache::TYPE_APC);
$this->assertFalse($cache->isEnabled());
$this->assertFalse($cache->set('anything', 10));
$this->assertTrue(is_null($cache->get('anything')));
Config::getInstance()->set('DisableCaching', false);
}
public function testCaching()
{
$cache = Cache::getCache(Cache::TYPE_APC);
if($cache->isEnabled())
{
$this->assertTrue($cache->set('anything', 10));
$this->assertTrue($cache->get('anything') == 10);
$this->assertTrue(is_null($cache->get('invalid')));
}
}
}

View file

@ -0,0 +1,627 @@
<?php
namespace Tests\b8;
use b8\Database\Generator,
b8\Database\CodeGenerator,
b8\Database,
b8\Config;
class CodeGenerationTest extends \PHPUnit_Framework_TestCase
{
protected static $_db;
protected static $_base;
public static function setUpBeforeClass()
{
Database::setDetails('b8_test_' . getenv('PHPCI_BUILD'), 'b8_test', 'b8_test');
Database::setWriteServers(array('localhost'));
Database::setReadServers(array('localhost'));
$config = new Config();
Config::getInstance()->set('b8.app.namespace', 'Generation');
self::$_db = Database::getConnection('write');
self::$_db->query('DROP TABLE IF EXISTS tres');
self::$_db->query('DROP TABLE IF EXISTS dos');
self::$_db->query('DROP TABLE IF EXISTS uno');
self::$_base = dirname(__FILE__) . '/data/generation/';
$gen = new Generator(self::$_db, 'Test', self::$_base .'models/');
$gen->generate();
}
public static function tearDownAfterClass()
{
self::$_db->query('DROP TABLE IF EXISTS tres');
self::$_db->query('DROP TABLE IF EXISTS dos');
self::$_db->query('DROP TABLE IF EXISTS uno');
unlink(self::$_base . 'Generation/Model/Base/UnoBase.php');
unlink(self::$_base . 'Generation/Model/Base/DosBase.php');
unlink(self::$_base . 'Generation/Model/Base/TresBase.php');
unlink(self::$_base . 'Generation/Store/Base/UnoStoreBase.php');
unlink(self::$_base . 'Generation/Store/Base/DosStoreBase.php');
unlink(self::$_base . 'Generation/Store/Base/TresStoreBase.php');
unlink(self::$_base . 'Generation/Controller/Base/UnoControllerBase.php');
unlink(self::$_base . 'Generation/Controller/Base/DosControllerBase.php');
unlink(self::$_base . 'Generation/Controller/Base/TresControllerBase.php');
unlink(self::$_base . 'Generation/Model/Uno.php');
unlink(self::$_base . 'Generation/Model/Dos.php');
unlink(self::$_base . 'Generation/Model/Tres.php');
unlink(self::$_base . 'Generation/Store/UnoStore.php');
unlink(self::$_base . 'Generation/Store/DosStore.php');
unlink(self::$_base . 'Generation/Store/TresStore.php');
unlink(self::$_base . 'Generation/Controller/UnoController.php');
unlink(self::$_base . 'Generation/Controller/DosController.php');
unlink(self::$_base . 'Generation/Controller/TresController.php');
}
public function testGenerate()
{
error_reporting(E_ALL);
$codeGenerator = new CodeGenerator(self::$_db, 'Generation', self::$_base . 'Generation/');
$codeGenerator->generateModels();
$codeGenerator->generateStores();
$codeGenerator->generateControllers();
$this->assertFileExists(self::$_base . 'Generation/Model/Base/UnoBase.php');
$this->assertFileExists(self::$_base . 'Generation/Model/Base/DosBase.php');
$this->assertFileExists(self::$_base . 'Generation/Model/Base/TresBase.php');
$this->assertFileExists(self::$_base . 'Generation/Store/Base/UnoStoreBase.php');
$this->assertFileExists(self::$_base . 'Generation/Store/Base/DosStoreBase.php');
$this->assertFileExists(self::$_base . 'Generation/Store/Base/TresStoreBase.php');
$this->assertFileExists(self::$_base . 'Generation/Controller/Base/UnoControllerBase.php');
$this->assertFileExists(self::$_base . 'Generation/Controller/Base/DosControllerBase.php');
$this->assertFileExists(self::$_base . 'Generation/Controller/Base/TresControllerBase.php');
$this->assertFileExists(self::$_base . 'Generation/Model/Uno.php');
$this->assertFileExists(self::$_base . 'Generation/Model/Dos.php');
$this->assertFileExists(self::$_base . 'Generation/Model/Tres.php');
$this->assertFileExists(self::$_base . 'Generation/Store/UnoStore.php');
$this->assertFileExists(self::$_base . 'Generation/Store/DosStore.php');
$this->assertFileExists(self::$_base . 'Generation/Store/TresStore.php');
$this->assertFileExists(self::$_base . 'Generation/Controller/UnoController.php');
$this->assertFileExists(self::$_base . 'Generation/Controller/DosController.php');
$this->assertFileExists(self::$_base . 'Generation/Controller/TresController.php');
}
/**
* @depends testGenerate
*/
public function testGeneratedModels()
{
if(!defined('APPLICATION_PATH'))
{
define('APPLICATION_PATH', self::$_base);
}
require_once(self::$_base . 'Generation/Model/Base/UnoBase.php');
require_once(self::$_base . 'Generation/Model/Base/DosBase.php');
require_once(self::$_base . 'Generation/Model/Base/TresBase.php');
require_once(self::$_base . 'Generation/Model/Uno.php');
require_once(self::$_base . 'Generation/Model/Dos.php');
require_once(self::$_base . 'Generation/Model/Tres.php');
require_once(self::$_base . 'ArrayPropertyModel.php');
$uno = new Generation\Model\Uno();
$dos = new Generation\Model\Dos();
$tres = new Generation\Model\Tres();
$this->assertTrue($uno instanceof b8\Model);
$this->assertTrue($dos instanceof b8\Model);
$this->assertTrue($tres instanceof b8\Model);
$this->assertTrue($uno instanceof Generation\Model\Base\UnoBase);
$this->assertTrue($dos instanceof Generation\Model\Base\DosBase);
$this->assertTrue($tres instanceof Generation\Model\Base\TresBase);
$this->assertTrue($uno->getTableName() == 'uno');
$this->assertTrue($dos->getTableName() == 'dos');
$this->assertTrue($tres->getTableName() == 'tres');
$uno->setId(1);
$uno->setFieldDatetime(new DateTime());
$this->assertTrue($uno->getFieldDatetime() instanceof DateTime);
$unoArray = $uno->toArray();
$this->assertArrayHasKey('field_varchar', $unoArray);
$this->assertTrue($unoArray['field_datetime'] instanceof DateTime);
Generation\Model\Uno::$sleepable = array('id', 'field_varchar');
$unoArray = $uno->toArray();
$this->assertArrayHasKey('field_varchar', $unoArray);
$this->assertFalse(array_key_exists('field_datetime', $unoArray));
$tres->setField($uno);
$this->assertTrue($tres->getFieldInt() == 1);
$this->assertTrue(in_array('id', $uno->getModified()));
$this->assertTrue(is_array($uno->getDataArray()));
$uno->setValues(array('field_int' => 100, 'field_bob' => 100));
$this->assertFalse(in_array('field_bob', $uno->getModified()));
$this->assertTrue($uno->getFieldInt() === 100);
$uno->setFieldInt(true);
$this->assertTrue($uno->getFieldInt() === 1);
$caught = false;
try
{
$uno->setFieldInt('invalid');
}
catch(Exception $ex)
{
$caught = true;
}
$this->assertTrue($caught);
$uno->setFieldInt('500');
$this->assertTrue($uno->getFieldInt() === 500);
$caught = false;
try
{
$uno->setFieldFloat('invalid');
}
catch(Exception $ex)
{
$caught = true;
}
$this->assertTrue($caught);
$uno->setFieldFloat('4.12');
$this->assertTrue($uno->getFieldFloat() === 4.12);
$uno->setFieldDatetime('2014-01-01');
$this->assertTrue($uno->getFieldDatetime() instanceof DateTime);
$caught = false;
try
{
$uno->setFieldDatetime(2012);
}
catch(Exception $ex)
{
$caught = true;
}
$this->assertTrue($caught);
$caught = false;
try
{
$uno->setFieldInt(null);
}
catch(Exception $ex)
{
$caught = true;
}
$this->assertTrue($caught);
$caught = false;
try
{
$uno->setValues(array('field_int' => 'null'));
}
catch(Exception $ex)
{
$caught = true;
}
$this->assertTrue($caught);
$uno->setValues(array('field_int' => 'true'));
$this->assertTrue($uno->getFieldInt() === 1);
$uno->setValues(array('field_int' => 'false'));
$this->assertTrue($uno->getFieldInt() === 0);
$caught = false;
try
{
$uno->setFieldVarchar(false);
}
catch(Exception $ex)
{
$caught = true;
}
$this->assertTrue($caught);
$caught = false;
try
{
$uno->setFieldVarchar('Hi');
}
catch(Exception $ex)
{
$caught = true;
}
$this->assertFalse($caught);
// Test toArray() with an array property:
$aModel = new Generation\ArrayPropertyModel();
$array = $aModel->toArray();
$this->assertArrayHasKey('array_property', $array);
$this->assertTrue(is_array($array['array_property']));
$this->assertTrue(is_array($array['array_property']['three']));
$this->assertTrue($array['array_property']['one'] == 'two');
}
/**
* @depends testGeneratedModels
*/
public function testGeneratedStores()
{
require_once(self::$_base . 'Generation/Store/Base/UnoStoreBase.php');
require_once(self::$_base . 'Generation/Store/Base/DosStoreBase.php');
require_once(self::$_base . 'Generation/Store/Base/TresStoreBase.php');
require_once(self::$_base . 'Generation/Store/UnoStore.php');
require_once(self::$_base . 'Generation/Store/DosStore.php');
require_once(self::$_base . 'Generation/Store/TresStore.php');
$uno = new Generation\Store\UnoStore();
$dos = new Generation\Store\DosStore();
$tres = new Generation\Store\TresStore();
$this->assertTrue($uno instanceof b8\Store);
$this->assertTrue($dos instanceof b8\Store);
$this->assertTrue($tres instanceof b8\Store);
$this->assertTrue($uno instanceof Generation\Store\Base\UnoStoreBase);
$this->assertTrue($dos instanceof Generation\Store\Base\DosStoreBase);
$this->assertTrue($tres instanceof Generation\Store\Base\TresStoreBase);
$tresModel = new Generation\Model\Tres();
$tresModel->setFieldVarchar('Hi');
$caught = false;
try
{
$tres->save($tresModel);
}
catch(Exception $ex)
{
$caught = true;
}
$this->assertTrue($caught);
$caught = false;
try
{
$uno->save($tresModel);
}
catch(Exception $ex)
{
$caught = true;
}
$this->assertTrue($caught);
$unoModel = new Generation\Model\Uno();
$unoModel->setFieldVarchar('Hi');
$unoModel = $uno->save($unoModel);
$id = $unoModel->getId();
$this->assertTrue(!empty($id));
$this->assertTrue($unoModel->getFieldVarchar() == 'Hi');
$unoModel->setFieldVarchar('Ha');
$unoModel = $uno->save($unoModel);
$this->assertTrue($id == $unoModel->getId());
$this->assertTrue($unoModel->getFieldVarchar() == 'Ha');
$unoModel = $uno->save($unoModel);
$this->assertTrue($id == $unoModel->getId());
$this->assertTrue($unoModel->getFieldVarchar() == 'Ha');
$unoModel2 = $uno->getByPrimaryKey($id);
$this->assertTrue($unoModel2->getId() == $unoModel->getId());
$res = $uno->getWhere(array('field_varchar' => 'Ha'));
$this->assertTrue($res['count'] != 0);
$res = $uno->getWhere(array('id' => array('operator' => 'between', 'value' => array(0, 100))));
$this->assertTrue($res['count'] != 0);
$res = $uno->getWhere(array('id' => array('operator' => 'IN', 'value' => array(1, 2, 3, 4))));
$this->assertTrue($res['count'] != 0);
$res = $uno->getWhere(array('id' => array('operator' => '!=', 'value' => array('null', 100))));
$this->assertTrue($res['count'] != 0);
$res = $uno->getWhere(array('id' => array('operator' => '==', 'value' => array('null'))));
$this->assertTrue($res['count'] == 0);
$res = $uno->getWhere(array('id' => array('operator' => '==', 'value' => 'null')));
$this->assertTrue($res['count'] == 0);
$res = $uno->getWhere(array('id' => array('operator' => '!=', 'value' => 'null')));
$this->assertTrue($res['count'] != 0);
$res = $uno->getWhere(array('field_varchar' => array('operator' => 'like', 'value' => 'Ha')));
$this->assertTrue($res['count'] != 0);
$res = $uno->getWhere(array('field_varchar' => array('operator' => '!=', 'value' => 'Hi')));
$this->assertTrue($res['count'] != 0);
$res = $uno->getWhere(array('field_varchar' => array('Ha', 'Hi')));
$this->assertTrue($res['count'] != 0);
$res = $uno->getWhere(array('id' => 1), 1, 0, array('dos' => array('alias' => 'd', 'on' => 'd.id = uno.id')), array('id' => 'ASC'));
$this->assertTrue($res['count'] != 0);
$res = $uno->getWhere(array('id' => 1), 1, 0, array('dos' => array('alias' => 'd', 'on' => 'd.id = uno.id')), 'rand');
$this->assertTrue($res['count'] != 0);
$res = $uno->getWhere(array('id' => 1), 1, 10);
$this->assertTrue(count($res['items']) == 0 && $res['count'] == 1);
$caught = false;
try
{
$uno->getWhere(array('invalid_column' => 1));
}
catch(Exception $ex)
{
$caught = true;
}
$this->assertTrue($caught);
$res = $uno->getWhere(array('id' => 1), 1, 0, array(), 'rand', array('LEFT JOIN dos d ON d.id = uno.id'));
$this->assertTrue($res['count'] != 0);
$res = $uno->getWhere(array('id' => 1), 1, 0, array(), 'rand', array(), 'field_varchar');
$this->assertTrue($res['count'] != 0);
$res = $uno->getWhere(array(), 1, 0, array(), 'rand', array(), null, array(array('type' => 'AND', 'query' => 'id = 1', 'params' => array())));
$this->assertTrue($res['count'] != 0);
$res = $uno->getWhere(array('id' => 2), 1, 0, array(), 'rand', array(), null, array(array('type' => 'AND', 'query' => 'id = ?', 'params' => array('id'))));
$this->assertTrue($res['count'] == 0);
$caught = false;
try
{
$uno->getWhere(array('' => 1));
}
catch(Exception $ex)
{
$caught = true;
}
$this->assertTrue($caught);
// ----
// Tests for Model::toArray() with relationships:
// ----
$tresModel->setField($unoModel);
$array = $tresModel->toArray();
$this->assertTrue(array_key_exists('Field', $array));
$this->assertTrue(array_key_exists('id', $array['Field']));
$this->assertTrue($array['Field']['id'] == $unoModel->getId());
// ----
// Tests for Store::delete()
// ----
$caught = false;
try
{
$tres->delete($tresModel);
}
catch(Exception $ex)
{
$caught = true;
}
$this->assertTrue($caught);
$caught = false;
try
{
$uno->delete($tresModel);
}
catch(Exception $ex)
{
$caught = true;
}
$this->assertTrue($caught);
$this->assertTrue($uno->delete($unoModel));
$this->assertTrue(is_null($uno->getByPrimaryKey(1)));
}
/**
* @depends testGeneratedStores
*/
public function testGeneratedControllers()
{
require_once(self::$_base . 'Generation/Controller/Base/UnoControllerBase.php');
require_once(self::$_base . 'Generation/Controller/Base/DosControllerBase.php');
require_once(self::$_base . 'Generation/Controller/Base/TresControllerBase.php');
require_once(self::$_base . 'Generation/Controller/UnoController.php');
require_once(self::$_base . 'Generation/Controller/DosController.php');
require_once(self::$_base . 'Generation/Controller/TresController.php');
require_once(self::$_base . 'TestUser.php');
$uno = new Generation\Controller\UnoController();
$dos = new Generation\Controller\DosController();
$tres = new Generation\Controller\TresController();
$uno->init();
$dos->init();
$tres->init();
$this->assertTrue($uno instanceof b8\Controller);
$this->assertTrue($dos instanceof b8\Controller);
$this->assertTrue($tres instanceof b8\Controller);
$this->assertTrue($uno instanceof Generation\Controller\Base\UnoControllerBase);
$this->assertTrue($dos instanceof Generation\Controller\Base\DosControllerBase);
$this->assertTrue($tres instanceof Generation\Controller\Base\TresControllerBase);
$config = new Config();
Config::getInstance()->set('hello', 'world');
$this->assertTrue($uno->getParam('hello', 'dave') == 'world');
$uno->setParam('hello', 'dave');
$this->assertTrue($uno->getParam('hello', 'world') == 'dave');
$this->assertTrue(array_key_exists('hello', $uno->getParams()));
$uno->unsetParam('hello');
$this->assertFalse(array_key_exists('hello', $uno->getParams()));
$testUser = new \TestUser();
$uno->setActiveUser($testUser);
$dos->setActiveUser($uno->getActiveUser());
$tres->setActiveUser($uno->getActiveUser());
$unoModel = new Generation\Model\Uno();
$unoStore = \b8\Store\Factory::getStore('Uno');
$unoModel->setFieldVarchar('Hi');
$unoStore->save($unoModel);
$list = $uno->index();
$this->assertTrue(is_array($list));
$this->assertTrue(is_array($list['items']));
$this->assertTrue(count($list['items']) > 0);
$caught = false;
try
{
$dos->index();
}
catch(Exception $ex)
{
$caught = true;
}
$this->assertTrue($caught);
$first = array_shift($list['items']);
$uno1 = $uno->get($first['id']);
$this->assertTrue(is_array($uno1));
$this->assertTrue(isset($uno1['uno']));
$this->assertTrue($uno1['uno']['id'] == $first['id']);
$caught = false;
try
{
$dos->get(1);
}
catch(Exception $ex)
{
$caught = true;
}
$this->assertTrue($caught);
$uno->setParam('field_varchar', 'Un');
$uno1 = $uno->put($first['id']);
$this->assertTrue($uno1['uno']['id'] == $first['id']);
$caught = false;
try
{
$dos->put(1);
}
catch(Exception $ex)
{
$caught = true;
}
$this->assertTrue($caught);
$this->assertTrue(is_null($uno->put(10000)));
$uno->setParam('field_text', 'Hello');
$res = $uno->post();
$this->assertTrue($res['uno']['field_varchar'] == 'Un');
$this->assertTrue(!empty($res['uno']['id']));
$caught = false;
try
{
$dos->post();
}
catch(Exception $ex)
{
$caught = true;
}
$this->assertTrue($caught);
$del = $uno->delete($res['uno']['id']);
$this->assertTrue($del['deleted']);
$del = $uno->delete($res['uno']['id']);
$this->assertFalse($del['deleted']);
$del = $tres->delete(100);
$this->assertFalse($del['deleted']);
$caught = false;
try
{
$dos->delete(1000);
}
catch(Exception $ex)
{
$caught = true;
}
$this->assertTrue($caught);
//----
// Tests for _parseWhere()
//----
$uno->setParam('where', array('id' => array(1000)));
$uno->setParam('neq', 'id');
$list = $uno->index();
$this->assertTrue(is_array($list));
$this->assertTrue(count($list['items']) != 0);
$uno->setParam('where', array('id' => 1000));
$uno->setParam('fuzzy', 'id');
$list = $uno->index();
$this->assertTrue(is_array($list));
$this->assertTrue(count($list['items']) == 0);
}
}

View file

@ -0,0 +1,75 @@
<?php
namespace Tests\b8;
use b8\Database\Generator, b8\Database\Map, b8\Database;
class DatabaseGenerationTest extends \PHPUnit_Framework_TestCase
{
protected $_host = 'localhost';
protected $_user = 'b8_test';
protected $_pass = 'b8_test';
protected $_name = 'b8_test';
protected $_db;
public function setUp()
{
Database::setDetails($this->_name, $this->_user, $this->_pass);
Database::setWriteServers(array($this->_host));
$this->_db = Database::getConnection('write');
$this->_db->query('DROP TABLE IF EXISTS tres');
$this->_db->query('DROP TABLE IF EXISTS dos');
$this->_db->query('DROP TABLE IF EXISTS uno');
}
public function testCreateDatabase()
{
$gen = new Generator($this->_db, 'Test', dirname(__FILE__) . '/data/generation/models/');
$gen->generate();
$map = new Map($this->_db);
$t = $map->generate();
$this->assertTrue(array_key_exists('uno', $t));
$this->assertTrue(array_key_exists('dos', $t));
$this->assertTrue(array_key_exists('tres', $t));
$this->assertFalse(array_key_exists('bad_table', $t));
$this->assertTrue(count($t['uno']['indexes']) == 1);
$this->assertTrue(count($t['dos']['indexes']) == 3);
$this->assertTrue(count($t['tres']['indexes']) == 2);
$this->assertTrue(count($t['uno']['columns']) == 11);
$this->assertTrue(count($t['dos']['columns']) == 4);
$this->assertTrue(count($t['tres']['columns']) == 6);
$this->assertTrue(array_key_exists('PRIMARY', $t['uno']['indexes']));
$this->assertTrue(array_key_exists('PRIMARY', $t['dos']['indexes']));
$this->assertFalse(array_key_exists('PRIMARY', $t['tres']['indexes']));
}
public function testUpdateDatabase()
{
$gen = new Generator($this->_db, 'Test', dirname(__FILE__) . '/data/generation/models/');
$gen->generate();
$gen = new Generator($this->_db, 'Update', dirname(__FILE__) . '/data/generation/update_models/');
$gen->generate();
$map = new Map($this->_db);
$t = $map->generate();
$this->assertTrue(array_key_exists('uno', $t));
$this->assertTrue(array_key_exists('dos', $t));
$this->assertTrue(array_key_exists('tres', $t));
$this->assertFalse(array_key_exists('bad_table', $t));
$this->assertTrue(count($t['uno']['indexes']) == 1);
$this->assertTrue(count($t['dos']['indexes']) == 3);
$this->assertTrue(count($t['tres']['indexes']) == 3);
$this->assertTrue(count($t['uno']['columns']) == 10);
$this->assertTrue(count($t['dos']['columns']) == 4);
$this->assertTrue(count($t['tres']['columns']) == 10);
$this->assertTrue(array_key_exists('PRIMARY', $t['uno']['indexes']));
$this->assertTrue(array_key_exists('PRIMARY', $t['dos']['indexes']));
$this->assertTrue(array_key_exists('PRIMARY', $t['tres']['indexes']));
}
}

View file

@ -0,0 +1,55 @@
<?php
namespace Tests\b8;
use b8\Database;
class DatabaseTest extends \PHPUnit_Framework_TestCase
{
protected $_host = 'localhost';
protected $_user = 'b8_test';
protected $_pass = 'b8_test';
protected $_name = 'b8_test';
public function testGetReadConnection()
{
Database::setDetails($this->_name, $this->_user, $this->_pass);
Database::setReadServers(array($this->_host));
$connection = Database::getConnection('read');
$this->assertInstanceOf('\b8\Database', $connection);
}
public function testGetWriteConnection()
{
Database::setDetails($this->_name, $this->_user, $this->_pass);
Database::setWriteServers(array($this->_host));
$connection = Database::getConnection('write');
$this->assertInstanceOf('\b8\Database', $connection);
}
public function testGetDetails()
{
Database::setDetails($this->_name, $this->_user, $this->_pass);
Database::setReadServers(array('localhost'));
$details = Database::getConnection('read')->getDetails();
$this->assertTrue(is_array($details));
$this->assertTrue(($details['db'] == $this->_name));
$this->assertTrue(($details['user'] == $this->_user));
$this->assertTrue(($details['pass'] == $this->_pass));
}
/**
* @expectedException \Exception
*/
public function testConnectionFailure()
{
Database::setDetails('non_existant', 'invalid_user', 'incorrect_password');
Database::setReadServers(array('localhost'));
Database::getConnection('read');
}
}

178
tests/B8Framework/FormTest.php Executable file
View file

@ -0,0 +1,178 @@
<?php
namespace Tests\b8;
use b8\Form, b8\Config;
class FormTest extends \PHPUnit_Framework_TestCase
{
public function testFormBasics()
{
$f = new Form();
$f->setAction('/');
$f->setMethod('POST');
$this->assertTrue($f->getAction() == '/');
$this->assertTrue($f->getMethod() == 'POST');
$config = new Config();
Config::getInstance()->set('ViewPath', dirname(__FILE__) . '/data/view/');
$this->assertTrue($f->render('form') == '/POST');
Config::getInstance()->set('ViewPath', '');
$this->assertTrue(strpos((string)$f, '<form') !== false);
}
public function testElementBasics()
{
$f = new Form\Element\Text('element-name');
$f->setId('element-id');
$f->setLabel('element-label');
$f->setClass('element-class');
$f->setContainerClass('container-class');
$this->assertTrue($f->getName() == 'elementname');
$this->assertTrue($f->getId() == 'element-id');
$this->assertTrue($f->getLabel() == 'element-label');
$this->assertTrue($f->getClass() == 'element-class');
$this->assertTrue($f->getContainerClass() == 'container-class');
$output = $f->render();
$this->assertTrue(is_string($output));
$this->assertTrue(!empty($output));
$this->assertTrue(strpos($output, 'container-class') !== false);
}
public function testInputBasics()
{
$f = new Form\Element\Text();
$f->setValue('input-value');
$f->setRequired(true);
$f->setValidator(function($value) { return ($value == 'input-value'); });
$this->assertTrue($f->getValue() == 'input-value');
$this->assertTrue($f->getRequired() == true);
$this->assertTrue(is_callable($f->getValidator()));
}
public function testInputValidation()
{
$f = new Form\Element\Text();
$f->setRequired(true);
$this->assertFalse($f->validate());
$f->setRequired(false);
$f->setPattern('input\-value');
$this->assertFalse($f->validate());
$f->setValue('input-value');
$this->assertTrue($f->validate());
$f->setValidator(function($item)
{
if($item != 'input-value')
{
throw new \Exception('Invalid input value.');
}
});
$this->assertTrue($f->validate());
$f->setValue('fail');
$f->setPattern(null);
$this->assertFalse($f->validate());
}
public function testFieldSetBasics()
{
$f = new Form\FieldSet();
$f2 = new Form\FieldSet('group');
$f3 = new Form\FieldSet();
$t = new Form\Element\Text('one');
$t->setRequired(true);
$f2->addField($t);
$t = new Form\Element\Text('two');
$f2->addField($t);
$t = new Form\Element\Text('three');
$f3->addField($t);
$f->addField($f2);
$f->addField($f3);
$this->assertFalse($f->validate());
$f->setValues(array('group' => array('one' => 'ONE', 'two' => 'TWO'), 'three' => 'THREE'));
$values = $f->getValues();
$this->assertTrue(is_array($values));
$this->assertTrue(array_key_exists('group', $values));
$this->assertTrue(array_key_exists('one', $values['group']));
$this->assertTrue(array_key_exists('three', $values));
$this->assertTrue($values['group']['one'] == 'ONE');
$this->assertTrue($values['group']['two'] == 'TWO');
$this->assertTrue($values['three'] == 'THREE');
$this->assertTrue($f->validate());
$html = $f->render();
$this->assertTrue(strpos($html, 'one') !== false);
$this->assertTrue(strpos($html, 'two') !== false);
}
public function testElements()
{
$e = new Form\Element\Button();
$this->assertTrue($e->validate());
$this->assertTrue(strpos($e->render(), 'button') !== false);
$e = new Form\Element\Checkbox();
$e->setCheckedValue('ten');
$this->assertTrue($e->getCheckedValue() == 'ten');
$this->assertTrue(strpos($e->render(), 'checkbox') !== false);
$this->assertTrue(strpos($e->render(), 'checked') === false);
$e->setValue(true);
$this->assertTrue(strpos($e->render(), 'checked') !== false);
$e->setValue('ten');
$this->assertTrue(strpos($e->render(), 'checked') !== false);
$e->setValue('fail');
$this->assertTrue(strpos($e->render(), 'checked') === false);
$e = new Form\Element\CheckboxGroup();
$this->assertTrue(strpos($e->render(), 'group') !== false);
$e = new Form\ControlGroup();
$this->assertTrue(strpos($e->render(), 'group') !== false);
$e = new Form\Element\Email();
$this->assertTrue(strpos($e->render(), 'email') !== false);
$e = new Form\Element\Select();
$e->setOptions(array('key' => 'Val'));
$html = $e->render();
$this->assertTrue(strpos($html, 'select') !== false);
$this->assertTrue(strpos($html, 'option') !== false);
$this->assertTrue(strpos($html, 'key') !== false);
$this->assertTrue(strpos($html, 'Val') !== false);
$e = new Form\Element\Submit();
$this->assertTrue($e->validate());
$this->assertTrue(strpos($e->render(), 'submit') !== false);
$e = new Form\Element\Text();
$e->setValue('test');
$this->assertTrue(strpos($e->render(), 'test') !== false);
$e = new Form\Element\TextArea();
$e->setRows(10);
$this->assertTrue(strpos($e->render(), '10') !== false);
$e = new Form\Element\Url();
$this->assertTrue(strpos($e->render(), 'url') !== false);
}
}

View file

@ -0,0 +1,64 @@
<?php
namespace Tests\b8;
use b8\HttpClient;
class HttpClientTest extends \PHPUnit_Framework_TestCase
{
public function testSimpleRequest()
{
$http = new HttpClient();
$html = $http->request('GET', 'https://www.cloudflare.com/');
$this->assertContains('CloudFlare', $html['body']);
}
public function testBaseUrl()
{
$http = new HttpClient('https://www.cloudflare.com');
$html = $http->request('GET', '/');
$this->assertContains('CloudFlare', $html['body']);
}
public function testGet()
{
$http = new HttpClient('https://www.cloudflare.com');
$html = $http->get('overview', array('x' => 1));
$this->assertContains('CloudFlare', $html['body']);
}
public function testGetJson()
{
$http = new HttpClient('http://echo.jsontest.com');
$data = $http->get('/key/value');
$this->assertArrayHasKey('key', $data['body']);
}
public function testPost()
{
$http = new HttpClient('http://echo.jsontest.com');
$data = $http->post('/key/value', array('test' => 'x'));
$this->assertTrue(is_array($data));
}
public function testPut()
{
$http = new HttpClient('http://echo.jsontest.com');
$data = $http->put('/key/value', array('test' => 'x'));
$this->assertTrue(is_array($data));
}
public function testDelete()
{
$http = new HttpClient('http://echo.jsontest.com');
$data = $http->delete('/key/value', array('test' => 'x'));
$this->assertTrue(is_array($data));
}
}

View file

@ -0,0 +1,107 @@
<?php
namespace Tests\b8;
use b8\Exception\HttpException;
class HttpExceptionTest extends \PHPUnit_Framework_TestCase
{
public function testHttpExceptionIsException()
{
$ex = new HttpException();
$this->assertTrue($ex instanceof \Exception);
}
public function testHttpException()
{
try
{
throw new HttpException('Test');
}
catch(HttpException $ex)
{
$this->assertTrue($ex->getMessage() == 'Test');
$this->assertTrue($ex->getErrorCode() == 500);
$this->assertTrue($ex->getStatusMessage() == 'Internal Server Error');
$this->assertTrue($ex->getHttpHeader() == 'HTTP/1.1 500 Internal Server Error');
}
}
public function testBadRequestException()
{
try
{
throw new HttpException\BadRequestException('Test');
}
catch(HttpException $ex)
{
$this->assertTrue($ex->getErrorCode() == 400);
$this->assertTrue($ex->getStatusMessage() == 'Bad Request');
}
}
public function testForbiddenException()
{
try
{
throw new HttpException\ForbiddenException('Test');
}
catch(HttpException $ex)
{
$this->assertTrue($ex->getErrorCode() == 403);
$this->assertTrue($ex->getStatusMessage() == 'Forbidden');
}
}
public function testNotAuthorizedException()
{
try
{
throw new HttpException\NotAuthorizedException('Test');
}
catch(HttpException $ex)
{
$this->assertTrue($ex->getErrorCode() == 401);
$this->assertTrue($ex->getStatusMessage() == 'Not Authorized');
}
}
public function testNotFoundException()
{
try
{
throw new HttpException\NotFoundException('Test');
}
catch(HttpException $ex)
{
$this->assertTrue($ex->getErrorCode() == 404);
$this->assertTrue($ex->getStatusMessage() == 'Not Found');
}
}
public function testServerErrorException()
{
try
{
throw new HttpException\ServerErrorException('Test');
}
catch(HttpException $ex)
{
$this->assertTrue($ex->getErrorCode() == 500);
$this->assertTrue($ex->getStatusMessage() == 'Internal Server Error');
}
}
public function testValidationException()
{
try
{
throw new HttpException\ValidationException('Test');
}
catch(HttpException $ex)
{
$this->assertTrue($ex->getErrorCode() == 400);
$this->assertTrue($ex->getStatusMessage() == 'Bad Request');
}
}
}

136
tests/B8Framework/ViewTest.php Executable file
View file

@ -0,0 +1,136 @@
<?php
namespace Tests\b8;
use b8\View, b8\View\UserView;
class ViewTest extends \PHPUnit_Framework_TestCase
{
public function testSimpleView()
{
$view = new View('simple', dirname(__FILE__) . '/data/view/');
$this->assertTrue($view->render() == 'Hello');
}
/**
* @expectedException \Exception
*/
public function testInvalidView()
{
new View('dogs', dirname(__FILE__) . '/data/view/');
}
public function testViewVars()
{
$view = new View('vars', dirname(__FILE__) . '/data/view/');
$view->who = 'World';
$this->assertTrue(isset($view->who));
$this->assertFalse(isset($view->what));
$this->assertTrue($view->render() == 'Hello World');
}
public function testFormatViewHelper()
{
$view = new View('format', dirname(__FILE__) . '/data/view/');
$view->number = 1000000.25;
$view->symbol = true;
$this->assertTrue($view->render() == '£1,000,000.25');
$view->number = 1024;
$view->symbol = false;
$this->assertTrue($view->render() == '1,024.00');
}
/**
* @expectedException \b8\Exception\HttpException
*/
public function testInvalidHelper()
{
$view = new UserView('{@Invalid:test}');
$view->render();
}
public function testSimpleUserView()
{
$view = new UserView('Hello');
$this->assertTrue($view->render() == 'Hello');
}
public function testUserViewYear()
{
$view = new UserView('{@year}');
$this->assertTrue($view->render() == date('Y'));
}
public function testUserViewVars()
{
$view = new UserView('Hello {@who}');
$view->who = 'World';
$this->assertTrue($view->render() == 'Hello World');
$view = new UserView('Hello {@who}');
$this->assertTrue($view->render() == 'Hello ');
$view = new UserView('Hello {@who.name}');
$view->who = array('name' => 'Dan');
$this->assertTrue($view->render() == 'Hello Dan');
$tmp = new UserView('Hello');
$tmp->who = 'World';
$view = new UserView('Hello {@tmp.who}');
$view->tmp = $tmp;
$this->assertTrue($view->render() == 'Hello World');
$tmp = new UserView('Hello');
$view = new UserView('Hello {@tmp.who}');
$view->tmp = $tmp;
$this->assertTrue($view->render() == 'Hello ');
$view = new UserView('Hello {@who.toUpperCase}');
$view->who = 'World';
$this->assertTrue($view->render() == 'Hello WORLD');
$view = new UserView('Hello {@who.toLowerCase}');
$view->who = 'World';
$this->assertTrue($view->render() == 'Hello world');
}
public function testUserViewIf()
{
$view = new UserView('Hello{if who} World{/if}');
$view->who = true;
$this->assertTrue($view->render() == 'Hello World');
$view = new UserView('Hello{if who} World{/if}');
$view->who = false;
$this->assertTrue($view->render() == 'Hello');
$view = new UserView('Hello{ifnot who} World{/ifnot}');
$view->who = true;
$this->assertTrue($view->render() == 'Hello');
$view = new UserView('Hello {if Format:not_present}World{/if}');
$this->assertTrue($view->render() == 'Hello ');
$view = new UserView('Hello {ifnot Format:not_present}World{/ifnot}');
$this->assertTrue($view->render() == 'Hello World');
}
public function testUserViewLoop()
{
$view = new UserView('Hello {loop who}{@item}{/loop}');
$view->who = array('W', 'o', 'r', 'l', 'd');
$this->assertTrue($view->render() == 'Hello World');
$view = new UserView('Hello {loop who}{@item}{/loop}');
$this->assertTrue($view->render() == 'Hello ');
$view = new UserView('Hello {loop who}{@item}{/loop}');
$view->who = 'World';
$this->assertTrue($view->render() == 'Hello World');
}
}

View file

@ -0,0 +1,18 @@
<?php
namespace Generation;
use Generation\Model\Uno;
class ArrayPropertyModel extends Uno
{
public function __construct($initialData = array())
{
$this->_getters['array_property'] = 'getArrayProperty';
self::$sleepable[] = 'array_property';
}
public function getArrayProperty()
{
return array('one' => 'two', 'three' => array('four' => 'five'));
}
}

View file

@ -0,0 +1,13 @@
<?php
require_once(B8_PATH . 'Type/RestUser.php');
use b8\Type\RestUser;
class TestUser implements RestUser
{
public function checkPermission($permission, $resource)
{
return $resource == 'unos' || $resource == 'tress' ? true : false;
}
}

View file

@ -0,0 +1,18 @@
<?php
namespace Test\Model\Base;
use b8\Model;
class BadModel extends Model
{
protected $_tableName = 'bad_table';
public $columns = array(
'id' => array('type' => 'catfish'),
);
public $indexes = array(
);
public $foreignKeys = array(
);
}

View file

@ -0,0 +1,24 @@
<?php
namespace Test\Model\Base;
use b8\Model;
class Dos extends Model
{
protected $_tableName = 'dos';
public $columns = array(
'id' => array('type' => 'int', 'primary_key' => true, 'auto_increment' => false),
'field_varchar' => array('type' => 'varchar', 'length' => '250', 'default' => 'Hello World'),
'field_datetime'=> array('type' => 'datetime'),
'field_int' => array('type' => 'int'),
);
public $indexes = array(
'PRIMARY' => array('unique' => true, 'columns' => 'id'),
'idx_test_1' => array('unique' => true, 'columns' => 'field_int'),
'idx_test_2' => array('columns' => 'field_datetime'),
);
public $foreignKeys = array(
);
}

View file

@ -0,0 +1,27 @@
<?php
namespace Test\Model\Base;
use b8\Model;
class Tres extends Model
{
protected $_tableName = 'tres';
public $columns = array(
'id' => array('type' => 'int'),
'field_varchar' => array('type' => 'varchar', 'length' => '250'),
'field_date' => array('type' => 'date'),
'field_datetime'=> array('type' => 'datetime'),
'field_int' => array('type' => 'int'),
'field_int_2' => array('type' => 'int'),
);
public $indexes = array(
'fk_tres_uno' => array('columns' => 'field_int'),
'fk_tres_dos' => array('columns' => 'field_int_2'),
);
public $foreignKeys = array(
'fk_tres_uno' => array('local_col' => 'field_int', 'table' => 'uno', 'col' => 'id'),
'fk_tres_dos' => array('local_col' => 'field_int_2', 'update' => 'NO ACTION', 'delete' => 'CASCADE', 'table' => 'dos', 'col' => 'id'),
);
}

View file

@ -0,0 +1,28 @@
<?php
namespace Test\Model\Base;
use b8\Model;
class Uno extends Model
{
protected $_tableName = 'uno';
public $columns = array(
'id' => array('type' => 'int', 'primary_key' => true, 'auto_increment' => true),
'field_varchar' => array('type' => 'varchar', 'length' => '250'),
'field_text' => array('type' => 'text'),
'field_ltext' => array('type' => 'longtext'),
'field_mtext' => array('type' => 'mediumtext'),
'field_date' => array('type' => 'date'),
'field_datetime'=> array('type' => 'datetime'),
'field_int' => array('type' => 'int'),
'field_tinyint' => array('type' => 'tinyint', 'length' => '1'),
'field_float' => array('type' => 'float'),
'field_double' => array('type' => 'double', 'length' => '15,2'),
);
public $indexes = array(
);
public $foreignKeys = array(
);
}

View file

@ -0,0 +1,24 @@
<?php
namespace Update\Model\Base;
use b8\Model;
class Dos extends Model
{
protected $_tableName = 'dos';
public $columns = array(
'id' => array('type' => 'int', 'primary_key' => true, 'auto_increment' => true),
'field_varchar' => array('type' => 'varchar', 'length' => '250', 'default' => 'Hello World'),
'field_datetime'=> array('type' => 'datetime'),
'field_int' => array('type' => 'int'),
);
public $indexes = array(
'PRIMARY' => array('unique' => true, 'columns' => 'id'),
'idx_test_1' => array('unique' => false, 'columns' => 'field_int'),
'idx_test_2' => array('columns' => 'field_datetime'),
);
public $foreignKeys = array(
);
}

View file

@ -0,0 +1,32 @@
<?php
namespace Update\Model\Base;
use b8\Model;
class Tres extends Model
{
protected $_tableName = 'tres';
public $columns = array(
'key_col' => array('type' => 'int', 'primary_key' => true, 'auto_increment' => true),
'id' => array('type' => 'int'),
'field_varchar' => array('type' => 'varchar', 'length' => '250', 'default' => 'Hello World'),
'field_datetime'=> array('type' => 'datetime'),
'field_int' => array('type' => 'int'),
'field_int_2' => array('type' => 'int'),
'field_dt' => array('type' => 'date', 'rename' => 'field_date'),
'field_float_1' => array('type' => 'float', 'default' => '1'),
'field_varchar_2' => array('type' => 'varchar', 'length' => '10', 'default' => 'Hello'),
'dosid' => array('type' => 'int'),
);
public $indexes = array(
'PRIMARY' => array('unique' => true, 'columns' => 'key_col'),
'fk_tres_dos' => array('columns' => 'field_int_2'),
'fk_tres_dos_2' => array('columns' => 'dosid'),
);
public $foreignKeys = array(
'fk_tres_dos' => array('local_col' => 'field_int_2', 'update' => 'CASCADE', 'delete' => 'CASCADE', 'table' => 'dos', 'col' => 'id'),
'fk_tres_dos_2' => array('local_col' => 'dosid', 'update' => 'CASCADE', 'delete' => 'CASCADE', 'table' => 'dos', 'col' => 'id'),
);
}

View file

@ -0,0 +1,27 @@
<?php
namespace Update\Model\Base;
use b8\Model;
class Uno extends Model
{
protected $_tableName = 'uno';
public $columns = array(
'id' => array('type' => 'int', 'primary_key' => true),
'field_varchar' => array('type' => 'varchar', 'length' => '250'),
'field_text' => array('type' => 'text'),
'field_ltext' => array('type' => 'longtext'),
'field_mtext' => array('type' => 'mediumtext'),
'field_datetime'=> array('type' => 'datetime'),
'field_int' => array('type' => 'int'),
'field_tinyint' => array('type' => 'tinyint', 'length' => '1'),
'field_float' => array('type' => 'float'),
'field_double' => array('type' => 'double', 'length' => '15,2'),
);
public $indexes = array(
);
public $foreignKeys = array(
);
}

View file

@ -0,0 +1 @@
<?php print $action . $method; ?>

View file

@ -0,0 +1 @@
<?php print $this->Format()->Currency($number, $symbol); ?>

View file

@ -0,0 +1 @@
Hello

View file

@ -0,0 +1 @@
Hello <?php print $who; ?>

View file

@ -0,0 +1,79 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2014, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace Tests\PHPCI\Plugin\Command;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
class CreateAdminCommandTest extends \PHPUnit_Framework_TestCase
{
/**
* @var \PHPCI\Command\CreateAdminCommand|\PHPUnit_Framework_MockObject_MockObject
*/
protected $command;
/**
* @var \Symfony\Component\Console\Application|\PHPUnit_Framework_MockObject_MockObject
*/
protected $application;
/**
* @var \Symfony\Component\Console\Helper\DialogHelper|\PHPUnit_Framework_MockObject_MockObject
*/
protected $dialog;
public function setup()
{
parent::setup();
$this->command = $this->getMockBuilder('PHPCI\\Command\\CreateAdminCommand')
->setConstructorArgs(array($this->getMock('PHPCI\\Store\\UserStore')))
->setMethods(array('reloadConfig'))
->getMock()
;
$this->dialog = $this->getMockBuilder('Symfony\\Component\\Console\\Helper\\DialogHelper')
->setMethods(array(
'ask',
'askAndValidate',
'askHiddenResponse',
))
->getMock()
;
$this->application = new Application();
}
/**
* @return CommandTester
*/
protected function getCommandTester()
{
$this->application->getHelperSet()->set($this->dialog, 'dialog');
$this->application->add($this->command);
$command = $this->application->find('phpci:create-admin');
$commandTester = new CommandTester($command);
return $commandTester;
}
public function testExecute()
{
$this->dialog->expects($this->at(0))->method('askAndValidate')->will($this->returnValue('test@example.com'));
$this->dialog->expects($this->at(1))->method('ask')->will($this->returnValue('A name'));
$this->dialog->expects($this->at(2))->method('askHiddenResponse')->will($this->returnValue('foobar123'));
$commandTester = $this->getCommandTester();
$commandTester->execute(array());
$this->assertEquals('User account created!' . PHP_EOL, $commandTester->getDisplay());
}
}

View file

@ -0,0 +1,86 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2014, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link http://www.phptesting.org/
*/
namespace Tests\PHPCI\Command;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
class CreateBuildCommandTest extends \PHPUnit_Framework_TestCase
{
/**
* @var \PHPCI\Command\CreateAdminCommand|\PHPUnit_Framework_MockObject_MockObject
*/
protected $command;
/**
* @var \Symfony\Component\Console\Application|\PHPUnit_Framework_MockObject_MockObject
*/
protected $application;
public function setup()
{
parent::setup();
$projectMock = $this->getMock('PHPCI\\Model\\Project');
$projectStoreMock = $this->getMockBuilder('PHPCI\\Store\\ProjectStore')
->getMock();
$projectStoreMock->method('getById')
->will($this->returnValueMap(array(
array(1, 'read', $projectMock),
array(2, 'read', null),
)));
$buildServiceMock = $this->getMockBuilder('PHPCI\\Service\\BuildService')
->disableOriginalConstructor()
->getMock();
$buildServiceMock->method('createBuild')
->withConsecutive(
array($projectMock, null, null, null, null, null),
array($projectMock, '92c8c6e', null, null, null, null),
array($projectMock, null, 'master', null, null, null)
);
$this->command = $this->getMockBuilder('PHPCI\\Command\\CreateBuildCommand')
->setConstructorArgs(array($projectStoreMock, $buildServiceMock))
->setMethods(array('reloadConfig'))
->getMock();
$this->application = new Application();
}
protected function getCommandTester()
{
$this->application->add($this->command);
$command = $this->application->find('phpci:create-build');
$commandTester = new CommandTester($command);
return $commandTester;
}
public function testExecute()
{
$commandTester = $this->getCommandTester();
$commandTester->execute(array('projectId' => 1));
$commandTester->execute(array('projectId' => 1, '--commit' => '92c8c6e'));
$commandTester->execute(array('projectId' => 1, '--branch' => 'master'));
}
/**
* @expectedException \InvalidArgumentException
*/
public function testExecuteWithUnknownProjectId()
{
$commandTester = $this->getCommandTester();
$commandTester->execute(array('projectId' => 2));
}
}

View file

@ -0,0 +1,280 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2015, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace Tests\PHPCI\Plugin\Command;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Component\Console\Helper\HelperSet;
class InstallCommandTest extends \PHPUnit_Framework_TestCase
{
public $config;
public $admin;
protected $application;
public function setup()
{
parent::setup();
$this->application = new Application();
$this->application->setHelperSet(new HelperSet());
}
/**
* @return \PHPUnit_Framework_MockObject_MockBuilder
*/
protected function getDialogHelperMock()
{
// We check that there's no interaction with user.
$dialog = $this->getMockBuilder('Symfony\\Component\\Console\\Helper\\DialogHelper')
->setMethods(array(
'ask',
'askConfirmation',
'askAndValidate',
'askHiddenResponse',
'askHiddenResponseAndValidate',
))
->getMock();
return $dialog;
}
/**
* @return \PHPUnit_Framework_MockObject_MockBuilder
*/
protected function getInstallCommandMock()
{
// Current command, we need to mock all method that interact with
// Database & File system.
$command = $this->getMockBuilder('PHPCI\\Command\\InstallCommand')
->setMethods(array(
'reloadConfig',
'verifyNotInstalled',
'verifyDatabaseDetails',
'setupDatabase',
'createAdminUser',
'writeConfigFile',
'checkRequirements',
))
->getMock();
$self = $this;
$command->expects($this->once())->method('verifyNotInstalled')->willReturn(true);
$command->expects($this->once())->method('verifyDatabaseDetails')->willReturn(true);
$command->expects($this->once())->method('setupDatabase')->willReturn(true);
$command->expects($this->once())->method('createAdminUser')->will(
$this->returnCallback(function ($adm) use ($self) {
$self->admin = $adm;
})
);
$command->expects($this->once())->method('writeConfigFile')->will(
$this->returnCallback(function ($cfg) use ($self) {
$self->config = $cfg;
})
);
$command->expects($this->once())->method('checkRequirements');
return $command;
}
protected function getCommandTester($dialog)
{
$this->application->getHelperSet()->set($dialog, 'dialog');
$this->application->add($this->getInstallCommandMock());
$command = $this->application->find('phpci:install');
$commandTester = new CommandTester($command);
return $commandTester;
}
protected function getConfig($exclude = null)
{
$config = array(
'--db-host' => 'localhost',
'--db-name' => 'phpci1',
'--db-user' => 'phpci2',
'--db-pass' => 'phpci3',
'--admin-mail' => 'phpci@phpci.test',
'--admin-name' => 'phpci4',
'--admin-pass' => 'phpci5',
'--url' => 'http://test.phpci.org',
'--queue-disabled' => null,
);
if (!is_null($exclude)) {
unset($config[$exclude]);
}
return $config;
}
protected function executeWithoutParam($param = null, $dialog)
{
// Clean result variables.
$this->admin = array();
$this->config = array();
// Get tester and execute with extracted parameters.
$commandTester = $this->getCommandTester($dialog);
$parameters = $this->getConfig($param);
$commandTester->execute($parameters);
}
public function testAutomaticInstallation()
{
$dialog = $this->getDialogHelperMock();
$dialog->expects($this->never())->method('ask');
$dialog->expects($this->never())->method('askConfirmation');
$dialog->expects($this->never())->method('askAndValidate');
$dialog->expects($this->never())->method('askHiddenResponse');
$dialog->expects($this->never())->method('askHiddenResponseAndValidate');
$this->executeWithoutParam(null, $dialog);
}
public function testDatabaseHostnameConfig()
{
$dialog = $this->getDialogHelperMock();
// We specified an input value for hostname.
$dialog->expects($this->once())->method('ask')->willReturn('testedvalue');
$dialog->expects($this->never())->method('askConfirmation');
$dialog->expects($this->never())->method('askAndValidate');
$dialog->expects($this->never())->method('askHiddenResponse');
$dialog->expects($this->never())->method('askHiddenResponseAndValidate');
$this->executeWithoutParam('--db-host', $dialog);
// Check that specified arguments are correctly loaded.
$this->assertEquals('testedvalue', $this->config['b8']['database']['servers']['read']);
$this->assertEquals('testedvalue', $this->config['b8']['database']['servers']['write']);
}
public function testDatabaseNameConfig()
{
$dialog = $this->getDialogHelperMock();
// We specified an input value for hostname.
$dialog->expects($this->once())->method('ask')->willReturn('testedvalue');
$dialog->expects($this->never())->method('askConfirmation');
$dialog->expects($this->never())->method('askAndValidate');
$dialog->expects($this->never())->method('askHiddenResponse');
$dialog->expects($this->never())->method('askHiddenResponseAndValidate');
$this->executeWithoutParam('--db-name', $dialog);
// Check that specified arguments are correctly loaded.
$this->assertEquals('testedvalue', $this->config['b8']['database']['name']);
}
public function testDatabaseUserConfig()
{
$dialog = $this->getDialogHelperMock();
// We specified an input value for hostname.
$dialog->expects($this->once())->method('ask')->willReturn('testedvalue');
$dialog->expects($this->never())->method('askConfirmation');
$dialog->expects($this->never())->method('askAndValidate');
$dialog->expects($this->never())->method('askHiddenResponse');
$dialog->expects($this->never())->method('askHiddenResponseAndValidate');
$this->executeWithoutParam('--db-user', $dialog);
// Check that specified arguments are correctly loaded.
$this->assertEquals('testedvalue', $this->config['b8']['database']['username']);
}
public function testDatabasePasswordConfig()
{
$dialog = $this->getDialogHelperMock();
// We specified an input value for hostname.
$dialog->expects($this->never())->method('ask');
$dialog->expects($this->never())->method('askConfirmation');
$dialog->expects($this->never())->method('askAndValidate');
$dialog->expects($this->once())->method('askHiddenResponse')->willReturn('testedvalue');
$dialog->expects($this->never())->method('askHiddenResponseAndValidate');
$this->executeWithoutParam('--db-pass', $dialog);
// Check that specified arguments are correctly loaded.
$this->assertEquals('testedvalue', $this->config['b8']['database']['password']);
}
public function testPhpciUrlConfig()
{
$dialog = $this->getDialogHelperMock();
// We specified an input value for hostname.
$dialog->expects($this->never())->method('ask');
$dialog->expects($this->never())->method('askConfirmation');
$dialog->expects($this->once())->method('askAndValidate')->willReturn('http://testedvalue.com');
$dialog->expects($this->never())->method('askHiddenResponse');
$dialog->expects($this->never())->method('askHiddenResponseAndValidate');
$this->executeWithoutParam('--url', $dialog);
// Check that specified arguments are correctly loaded.
$this->assertEquals('http://testedvalue.com', $this->config['phpci']['url']);
}
public function testAdminEmailConfig()
{
$dialog = $this->getDialogHelperMock();
// We specified an input value for hostname.
$dialog->expects($this->never())->method('ask');
$dialog->expects($this->never())->method('askConfirmation');
$dialog->expects($this->once())->method('askAndValidate')->willReturn('test@phpci.com');
$dialog->expects($this->never())->method('askHiddenResponse');
$dialog->expects($this->never())->method('askHiddenResponseAndValidate');
$this->executeWithoutParam('--admin-mail', $dialog);
// Check that specified arguments are correctly loaded.
$this->assertEquals('test@phpci.com', $this->admin['mail']);
}
public function testAdminNameConfig()
{
$dialog = $this->getDialogHelperMock();
// Define expectation for dialog.
$dialog->expects($this->once())->method('ask')->willReturn('testedvalue');
$dialog->expects($this->never())->method('askConfirmation');
$dialog->expects($this->never())->method('askAndValidate');
$dialog->expects($this->never())->method('askHiddenResponse');
$dialog->expects($this->never())->method('askHiddenResponseAndValidate');
$this->executeWithoutParam('--admin-name', $dialog);
// Check that specified arguments are correctly loaded.
$this->assertEquals('testedvalue', $this->admin['name']);
}
public function testAdminPasswordConfig()
{
$dialog = $this->getDialogHelperMock();
// We specified an input value for hostname.
$dialog->expects($this->never())->method('ask');
$dialog->expects($this->never())->method('askConfirmation');
$dialog->expects($this->never())->method('askAndValidate');
$dialog->expects($this->once())->method('askHiddenResponse')->willReturn('testedvalue');
$dialog->expects($this->never())->method('askHiddenResponseAndValidate');
$this->executeWithoutParam('--admin-pass', $dialog);
// Check that specified arguments are correctly loaded.
$this->assertEquals('testedvalue', $this->admin['pass']);
}
}

View file

@ -0,0 +1,41 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2014, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace Tests\PHPCI\Controller;
use PHPCI\Controller\WebhookController;
class WebhookControllerTest extends \PHPUnit_Framework_TestCase
{
public function test_wrong_action_name_return_json_with_error()
{
$webController = new WebhookController(
$this->prophesize('b8\Config')->reveal(),
$this->prophesize('b8\Http\Request')->reveal(),
$this->prophesize('b8\Http\Response')->reveal()
);
$error = $webController->handleAction('test', []);
$this->assertInstanceOf('b8\Http\Response\JsonResponse', $error);
$responseData = $error->getData();
$this->assertEquals(500, $responseData['code']);
$this->assertEquals('failed', $responseData['body']['status']);
$this->assertEquals('application/json', $responseData['headers']['Content-Type']);
// @todo: we can't text the result is JSON file with
// $this->assertJson((string) $error);
// since the flush method automatically add the header and break the
// testing framework.
}
}

View file

@ -0,0 +1,35 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2015, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace Tests\PHPCI\Helper;
use PHPCI\Helper\AnsiConverter;
use PHPUnit_Framework_TestCase;
class AnsiConverterTest extends PHPUnit_Framework_TestCase
{
public function setUp()
{
if (version_compare(PHP_VERSION, '5.4.0', '<')) {
$this->markTestSkipped('External library do not support PHP 5.3');
}
}
public function testConvert_convertToHtml()
{
$input = "\e[31mThis is red !\e[0m";
$expectedOutput = '<span class="ansi_color_bg_black ansi_color_fg_red">This is red !</span>';
$actualOutput = AnsiConverter::convert($input);
$this->assertEquals($expectedOutput, $actualOutput);
}
}

View file

@ -0,0 +1,56 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2015, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace Tests\PHPCI\Plugin\Helper;
use PHPCI\Helper\BuildInterpolator;
class BuildInterpolatorTest extends \PHPUnit_Framework_TestCase
{
/**
* @var BuildInterpolator
*/
protected $testedInterpolator;
protected function setUp()
{
parent::setup();
$this->testedInterpolator = new BuildInterpolator();
}
public function testInterpolate_LeavesStringsUnchangedByDefault()
{
$string = "Hello World";
$expectedOutput = "Hello World";
$actualOutput = $this->testedInterpolator->interpolate($string);
$this->assertEquals($expectedOutput, $actualOutput);
}
public function testInterpolate_LeavesStringsUnchangedWhenBuildIsSet()
{
$build = $this->prophesize('PHPCI\\Model\\Build')->reveal();
$string = "Hello World";
$expectedOutput = "Hello World";
$this->testedInterpolator->setupInterpolationVars(
$build,
"/buildpath/",
"phpci.com"
);
$actualOutput = $this->testedInterpolator->interpolate($string);
$this->assertEquals($expectedOutput, $actualOutput);
}
}

View file

@ -0,0 +1,83 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2015, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace Tests\PHPCI\Plugin\Helper;
use PHPCI\Helper\UnixCommandExecutor;
class CommandExecutorTest extends \PHPUnit_Framework_TestCase
{
/**
* @var UnixCommandExecutor
*/
protected $testedExecutor;
protected function setUp()
{
if (IS_WIN) {
$this->markTestSkipped("Cannot test UnixCommandExecutor on ".PHP_OS);
return;
}
parent::setUp();
$mockBuildLogger = $this->prophesize('PHPCI\Logging\BuildLogger');
$class = IS_WIN ? 'PHPCI\Helper\WindowsCommandExecutor' : 'PHPCI\Helper\UnixCommandExecutor';
$this->testedExecutor = new $class($mockBuildLogger->reveal(), __DIR__ . "CommandExecutorTest.php/");
}
public function testGetLastOutput_ReturnsOutputOfCommand()
{
$this->testedExecutor->executeCommand(array('echo "%s"', 'Hello World'));
$output = $this->testedExecutor->getLastOutput();
$this->assertEquals("Hello World", $output);
}
public function testGetLastOutput_ForgetsPreviousCommandOutput()
{
$this->testedExecutor->executeCommand(array('echo "%s"', 'Hello World'));
$this->testedExecutor->executeCommand(array('echo "%s"', 'Hello Tester'));
$output = $this->testedExecutor->getLastOutput();
$this->assertEquals("Hello Tester", $output);
}
public function testExecuteCommand_ReturnsTrueForValidCommands()
{
$returnValue = $this->testedExecutor->executeCommand(array('echo "%s"', 'Hello World'));
$this->assertTrue($returnValue);
}
public function testExecuteCommand_ReturnsFalseForInvalidCommands()
{
$returnValue = $this->testedExecutor->executeCommand(array('eerfdcvcho "%s" > /dev/null 2>&1', 'Hello World'));
$this->assertFalse($returnValue);
}
public function testFindBinary_ReturnsPathInSpecifiedRoot()
{
$thisFileName = "CommandExecutorTest.php";
$returnValue = $this->testedExecutor->findBinary($thisFileName);
$this->assertEquals(__DIR__ . "CommandExecutorTest.php/" . $thisFileName, $returnValue);
}
/**
* @expectedException \Exception
* @expectedMessageRegex WorldWidePeace
*/
public function testFindBinary_ThrowsWhenNotFound()
{
$thisFileName = "WorldWidePeace";
$this->testedExecutor->findBinary($thisFileName);
}
public function testFindBinary_ReturnsNullWihQuietArgument()
{
$thisFileName = "WorldWidePeace";
$this->assertNull($this->testedExecutor->findBinary($thisFileName, true));
}
}

View file

@ -0,0 +1,35 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2015, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace Tests\PHPCI\Helper;
use DateTime;
use PHPCI\Helper\Lang;
class LangTest extends \PHPUnit_Framework_TestCase
{
public function testLang_UsePassedParameters()
{
$dateTime = $this->prophesize('DateTime');
$dateTime->format(DateTime::ISO8601)->willReturn("ISODATE");
$dateTime->format(DateTime::RFC2822)->willReturn("RFCDATE");
$this->assertEquals('<time datetime="ISODATE" data-format="FORMAT">RFCDATE</time>', Lang::formatDateTime($dateTime->reveal(), 'FORMAT'));
}
public function testLang_UseDefaultFormat()
{
$dateTime = $this->prophesize('DateTime');
$dateTime->format(DateTime::ISO8601)->willReturn("ISODATE");
$dateTime->format(DateTime::RFC2822)->willReturn("RFCDATE");
$this->assertEquals('<time datetime="ISODATE" data-format="lll">RFCDATE</time>', Lang::formatDateTime($dateTime->reveal()));
}
}

View file

@ -0,0 +1,72 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2014, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace tests\PHPCI\Service;
use PHPCI\Helper\MailerFactory;
/**
* Unit tests for the ProjectService class.
* @author Dan Cryer <dan@block8.co.uk>
*/
class MailerFactoryTest extends \PHPUnit_Framework_TestCase
{
public function setUp()
{
}
/**
* @covers PHPUnit::execute
*/
public function testExecute_TestGetMailConfig()
{
$config = array(
'smtp_address' => 'mail.example.com',
'smtp_port' => 225,
'smtp_encryption' => true,
'smtp_username' => 'example.user',
'smtp_password' => 'examplepassword',
'default_mailto_address' => 'phpci@example.com',
);
$factory = new MailerFactory(array('email_settings' => $config));
$this->assertEquals($config['smtp_address'], $factory->getMailConfig('smtp_address'));
$this->assertEquals($config['smtp_port'], $factory->getMailConfig('smtp_port'));
$this->assertEquals($config['smtp_encryption'], $factory->getMailConfig('smtp_encryption'));
$this->assertEquals($config['smtp_username'], $factory->getMailConfig('smtp_username'));
$this->assertEquals($config['smtp_password'], $factory->getMailConfig('smtp_password'));
$this->assertEquals($config['default_mailto_address'], $factory->getMailConfig('default_mailto_address'));
}
/**
* @covers PHPUnit::execute
*/
public function testExecute_TestMailer()
{
$config = array(
'smtp_address' => 'mail.example.com',
'smtp_port' => 225,
'smtp_encryption' => true,
'smtp_username' => 'example.user',
'smtp_password' => 'examplepassword',
'default_mailto_address' => 'phpci@example.com',
);
$factory = new MailerFactory(array('email_settings' => $config));
$mailer = $factory->getSwiftMailerFromConfig();
$this->assertEquals($config['smtp_address'], $mailer->getTransport()->getHost());
$this->assertEquals($config['smtp_port'], $mailer->getTransport()->getPort());
$this->assertEquals('tls', $mailer->getTransport()->getEncryption());
$this->assertEquals($config['smtp_username'], $mailer->getTransport()->getUsername());
$this->assertEquals($config['smtp_password'], $mailer->getTransport()->getPassword());
}
}

View file

@ -0,0 +1,114 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2015, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace Tests\PHPCI\Plugin\Helper;
use PHPCI\Logging\BuildLogger;
use Prophecy\Argument;
use Psr\Log\LogLevel;
class BuildLoggerTest extends \PHPUnit_Framework_TestCase
{
/**
* @var BuildLogger
*/
protected $testedBuildLogger;
protected $mockLogger;
protected $mockBuild;
protected function setUp()
{
parent::setUp();
$this->mockLogger = $this->prophesize('\Psr\Log\LoggerInterface');
$this->mockBuild = $this->prophesize('\PHPCI\Model\Build');
$this->testedBuildLogger = new BuildLogger(
$this->mockLogger->reveal(),
$this->mockBuild->reveal()
);
}
public function testLog_CallsWrappedLogger()
{
$level = LogLevel::NOTICE;
$message = "Testing";
$contextIn = array();
$this->mockLogger->log($level, $message, Argument::type('array'))
->shouldBeCalledTimes(1);
$this->testedBuildLogger->log($message, $level, $contextIn);
}
public function testLog_CallsWrappedLoggerForEachMessage()
{
$level = LogLevel::NOTICE;
$message = array("One", "Two", "Three");
$contextIn = array();
$this->mockLogger->log($level, "One", Argument::type('array'))
->shouldBeCalledTimes(1);
$this->mockLogger->log($level, "Two", Argument::type('array'))
->shouldBeCalledTimes(1);
$this->mockLogger->log($level, "Three", Argument::type('array'))
->shouldBeCalledTimes(1);
$this->testedBuildLogger->log($message, $level, $contextIn);
}
public function testLog_AddsBuildToContext()
{
$level = LogLevel::NOTICE;
$message = "Testing";
$contextIn = array();
$expectedContext = array(
'build' => $this->mockBuild->reveal()
);
$this->mockLogger->log($level, $message, $expectedContext)
->shouldBeCalledTimes(1);
$this->testedBuildLogger->log($message, $level, $contextIn);
}
public function testLogFailure_LogsAsErrorLevel()
{
$message = "Testing";
$expectedLevel = LogLevel::ERROR;
$this->mockLogger->log($expectedLevel,
Argument::type('string'),
Argument::type('array'))
->shouldBeCalledTimes(1);
$this->testedBuildLogger->logFailure($message);
}
public function testLogFailure_AddsExceptionContext()
{
$message = "Testing";
$exception = new \Exception("Expected Exception");
$this->mockLogger->log(Argument::type('string'),
Argument::type('string'),
Argument::withEntry('exception', $exception))
->shouldBeCalledTimes(1);
$this->testedBuildLogger->logFailure($message, $exception);
}
}

View file

@ -0,0 +1,94 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2015, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace Tests\PHPCI\Plugin\Helper;
use \PHPCI\Logging\LoggerConfig;
class LoggerConfigTest extends \PHPUnit_Framework_TestCase
{
public function testGetFor_ReturnsPSRLogger()
{
$config = new LoggerConfig(array());
$logger = $config->getFor("something");
$this->assertInstanceOf('\Psr\Log\LoggerInterface', $logger);
}
public function testGetFor_ReturnsMonologInstance()
{
$config = new LoggerConfig(array());
$logger = $config->getFor("something");
$this->assertInstanceOf('\Monolog\Logger', $logger);
}
public function testGetFor_AttachesAlwaysPresentHandlers()
{
$expectedHandler = new \Monolog\Handler\NullHandler();
$config = new LoggerConfig(array(
LoggerConfig::KEY_ALWAYS_LOADED => function() use ($expectedHandler) {
return array($expectedHandler);
}
));
/** @var \Monolog\Logger $logger */
$logger = $config->getFor("something");
$actualHandler = $logger->popHandler();
$this->assertEquals($expectedHandler, $actualHandler);
}
public function testGetFor_AttachesSpecificHandlers()
{
$expectedHandler = new \Monolog\Handler\NullHandler();
$config = new LoggerConfig(array(
"Specific" => function() use ($expectedHandler) {
return array($expectedHandler);
}
));
/** @var \Monolog\Logger $logger */
$logger = $config->getFor("Specific");
$actualHandler = $logger->popHandler();
$this->assertSame($expectedHandler, $actualHandler);
}
public function testGetFor_IgnoresAlternativeHandlers()
{
$expectedHandler = new \Monolog\Handler\NullHandler();
$alternativeHandler = new \Monolog\Handler\NullHandler();
$config = new LoggerConfig(array(
"Specific" => function() use ($expectedHandler) {
return array($expectedHandler);
},
"Other" => function() use ($alternativeHandler) {
return array($alternativeHandler);
}
));
/** @var \Monolog\Logger $logger */
$logger = $config->getFor("Specific");
$actualHandler = $logger->popHandler();
$this->assertSame($expectedHandler, $actualHandler);
$this->assertNotSame($alternativeHandler, $actualHandler);
}
public function testGetFor_SameInstance()
{
$config = new LoggerConfig(array());
$logger1 = $config->getFor("something");
$logger2 = $config->getFor("something");
$this->assertSame($logger1, $logger2);
}
}

View file

@ -0,0 +1,86 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2014, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace Tests\PHPCI\Model;
use PHPCI\Model\Build;
use PHPCI\Model;
/**
* Unit tests for the Build model class.
* @author Dan Cryer <dan@block8.co.uk>
*/
class BuildTest extends \PHPUnit_Framework_TestCase
{
public function setUp()
{
}
/**
* @covers PHPUnit::execute
*/
public function testExecute_TestIsAValidModel()
{
$build = new Build();
$this->assertTrue($build instanceof \b8\Model);
$this->assertTrue($build instanceof Model);
$this->assertTrue($build instanceof Model\Base\BuildBase);
}
/**
* @covers PHPUnit::execute
*/
public function testExecute_TestBaseBuildDefaults()
{
$build = new Build();
$this->assertEquals('#', $build->getCommitLink());
$this->assertEquals('#', $build->getBranchLink());
$this->assertEquals(null, $build->getFileLinkTemplate());
}
/**
* @covers PHPUnit::execute
*/
public function testExecute_TestIsSuccessful()
{
$build = new Build();
$build->setStatus(Build::STATUS_NEW);
$this->assertFalse($build->isSuccessful());
$build->setStatus(Build::STATUS_RUNNING);
$this->assertFalse($build->isSuccessful());
$build->setStatus(Build::STATUS_FAILED);
$this->assertFalse($build->isSuccessful());
$build->setStatus(Build::STATUS_SUCCESS);
$this->assertTrue($build->isSuccessful());
}
/**
* @covers PHPUnit::execute
*/
public function testExecute_TestBuildExtra()
{
$info = array(
'item1' => 'Item One',
'item2' => 2,
);
$build = new Build();
$build->setExtra(json_encode($info));
$this->assertEquals('Item One', $build->getExtra('item1'));
$this->assertEquals(2, $build->getExtra('item2'));
$this->assertNull($build->getExtra('item3'));
$this->assertEquals($info, $build->getExtra());
}
}

View file

@ -0,0 +1,111 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2014, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace Tests\PHPCI\Model;
use PHPCI\Model\Project;
use PHPCI\Model;
/**
* Unit tests for the Project model class.
* @author Dan Cryer <dan@block8.co.uk>
*/
class ProjectTest extends \PHPUnit_Framework_TestCase
{
public function setUp()
{
}
/**
* @covers PHPUnit::execute
*/
public function testExecute_TestIsAValidModel()
{
$project = new Project();
$this->assertTrue($project instanceof \b8\Model);
$this->assertTrue($project instanceof Model);
$this->assertTrue($project instanceof Model\Base\ProjectBase);
}
/**
* @covers PHPUnit::execute
*/
public function testExecute_TestGitDefaultBranch()
{
$project = new Project();
$project->setType('git');
$this->assertEquals('master', $project->getBranch());
}
/**
* @covers PHPUnit::execute
*/
public function testExecute_TestGithubDefaultBranch()
{
$project = new Project();
$project->setType('github');
$this->assertEquals('master', $project->getBranch());
}
/**
* @covers PHPUnit::execute
*/
public function testExecute_TestGitlabDefaultBranch()
{
$project = new Project();
$project->setType('gitlab');
$this->assertEquals('master', $project->getBranch());
}
/**
* @covers PHPUnit::execute
*/
public function testExecute_TestBitbucketDefaultBranch()
{
$project = new Project();
$project->setType('bitbucket');
$this->assertEquals('master', $project->getBranch());
}
/**
* @covers PHPUnit::execute
*/
public function testExecute_TestMercurialDefaultBranch()
{
$project = new Project();
$project->setType('hg');
$this->assertEquals('default', $project->getBranch());
}
/**
* @covers PHPUnit::execute
*/
public function testExecute_TestProjectAccessInformation()
{
$info = array(
'item1' => 'Item One',
'item2' => 2,
);
$project = new Project();
$project->setAccessInformation($info);
$this->assertEquals('Item One', $project->getAccessInformation('item1'));
$this->assertEquals(2, $project->getAccessInformation('item2'));
$this->assertNull($project->getAccessInformation('item3'));
$this->assertEquals($info, $project->getAccessInformation());
}
}

View file

@ -0,0 +1,408 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2013, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace Tests\PHPCI\Plugin;
use PHPCI\Plugin\Email as EmailPlugin;
use PHPCI\Model\Build;
/**
* Unit test for the PHPUnit plugin.
* @author meadsteve
*/
class EmailTest extends \PHPUnit_Framework_TestCase
{
/**
* @var EmailPlugin $testedPhpUnit
*/
protected $testedEmailPlugin;
/**
* @var \PHPUnit_Framework_MockObject_MockObject $mockCiBuilder
*/
protected $mockCiBuilder;
/**
* @var \PHPUnit_Framework_MockObject_MockObject $mockBuild
*/
protected $mockBuild;
/**
* @var \PHPUnit_Framework_MockObject_MockObject $mockProject
*/
protected $mockProject;
/**
* @var int buildStatus
*/
public $buildStatus;
/**
* @var array $message;
*/
public $message;
/**
* @var bool $mailDelivered
*/
public $mailDelivered;
public function setUp()
{
$this->message = array();
$this->mailDelivered = true;
$self = $this;
$this->mockProject = $this->getMock(
'\PHPCI\Model\Project',
array('getTitle'),
array(),
"mockProject",
false
);
$this->mockProject->expects($this->any())
->method('getTitle')
->will($this->returnValue("Test-Project"));
$this->mockBuild = $this->getMock(
'\PHPCI\Model\Build',
array('getLog', 'getStatus', 'getProject', 'getCommitterEmail'),
array(),
"mockBuild",
false
);
$this->mockBuild->expects($this->any())
->method('getLog')
->will($this->returnValue("Build Log"));
$this->mockBuild->expects($this->any())
->method('getStatus')
->will($this->returnCallback(function () use ($self) {
return $self->buildStatus;
}));
$this->mockBuild->expects($this->any())
->method('getProject')
->will($this->returnValue($this->mockProject));
$this->mockBuild->expects($this->any())
->method('getCommitterEmail')
->will($this->returnValue('committer-email@example.com'));
$this->mockCiBuilder = $this->getMock(
'\PHPCI\Builder',
array(
'getSystemConfig',
'getBuild',
'log'
),
array(),
"mockBuilder_email",
false
);
$this->mockCiBuilder->buildPath = "/";
$this->mockCiBuilder->expects($this->any())
->method('getSystemConfig')
->with('phpci')
->will(
$this->returnValue(
array(
'email_settings' => array(
'from_address' => "test-from-address@example.com"
)
)
)
);
}
protected function loadEmailPluginWithOptions($arrOptions = array(), $buildStatus = null, $mailDelivered = true)
{
$this->mailDelivered = $mailDelivered;
if (is_null($buildStatus)) {
$this->buildStatus = Build::STATUS_SUCCESS;
} else {
$this->buildStatus = $buildStatus;
}
// Reset current message.
$this->message = array();
$self = $this;
$this->testedEmailPlugin = $this->getMock(
'\PHPCI\Plugin\Email',
array('sendEmail'),
array(
$this->mockCiBuilder,
$this->mockBuild,
$arrOptions
)
);
$this->testedEmailPlugin->expects($this->any())
->method('sendEmail')
->will($this->returnCallback(function ($to, $cc, $subject, $body) use ($self) {
$self->message['to'][] = $to;
$self->message['cc'] = $cc;
$self->message['subject'] = $subject;
$self->message['body'] = $body;
return $self->mailDelivered;
}));
}
/**
* @covers PHPUnit::execute
*/
public function testReturnsFalseWithoutArgs()
{
$this->loadEmailPluginWithOptions();
$returnValue = $this->testedEmailPlugin->execute();
// As no addresses will have been mailed as non are configured.
$expectedReturn = false;
$this->assertEquals($expectedReturn, $returnValue);
}
/**
* @covers PHPUnit::execute
*/
public function testBuildsBasicEmails()
{
$this->loadEmailPluginWithOptions(
array(
'addresses' => array('test-receiver@example.com')
),
Build::STATUS_SUCCESS
);
$this->testedEmailPlugin->execute();
$this->assertContains('test-receiver@example.com', $this->message['to']);
}
/**
* @covers PHPUnit::execute
*/
public function testBuildsDefaultEmails()
{
$this->loadEmailPluginWithOptions(
array(
'default_mailto_address' => 'default-mailto-address@example.com'
),
Build::STATUS_SUCCESS
);
$this->testedEmailPlugin->execute();
$this->assertContains('default-mailto-address@example.com', $this->message['to']);
}
/**
* @covers PHPUnit::execute
*/
public function testExecute_UniqueRecipientsFromWithCommitter()
{
$this->loadEmailPluginWithOptions(
array(
'addresses' => array('test-receiver@example.com', 'test-receiver2@example.com')
)
);
$returnValue = $this->testedEmailPlugin->execute();
$this->assertTrue($returnValue);
$this->assertCount(2, $this->message['to']);
$this->assertContains('test-receiver@example.com', $this->message['to']);
$this->assertContains('test-receiver2@example.com', $this->message['to']);
}
/**
* @covers PHPUnit::execute
*/
public function testExecute_UniqueRecipientsWithCommitter()
{
$this->loadEmailPluginWithOptions(
array(
'committer' => true,
'addresses' => array('test-receiver@example.com', 'committer@test.com')
)
);
$returnValue = $this->testedEmailPlugin->execute();
$this->assertTrue($returnValue);
$this->assertContains('test-receiver@example.com', $this->message['to']);
$this->assertContains('committer@test.com', $this->message['to']);
}
/**
* @covers PHPUnit::execute
*/
public function testCcDefaultEmails()
{
$this->loadEmailPluginWithOptions(
array(
'default_mailto_address' => 'default-mailto-address@example.com',
'cc' => array(
'cc-email-1@example.com',
'cc-email-2@example.com',
'cc-email-3@example.com',
),
),
Build::STATUS_SUCCESS
);
$this->testedEmailPlugin->execute();
$this->assertEquals(
array(
'cc-email-1@example.com',
'cc-email-2@example.com',
'cc-email-3@example.com',
),
$this->message['cc']
);
}
/**
* @covers PHPUnit::execute
*/
public function testBuildsCommitterEmails()
{
$this->loadEmailPluginWithOptions(
array(
'committer' => true
),
Build::STATUS_SUCCESS
);
$this->testedEmailPlugin->execute();
$this->assertContains('committer-email@example.com', $this->message['to']);
}
/**
* @covers PHPUnit::execute
*/
public function testMailSuccessfulBuildHaveProjectName()
{
$this->loadEmailPluginWithOptions(
array(
'addresses' => array('test-receiver@example.com')
),
Build::STATUS_SUCCESS
);
$this->testedEmailPlugin->execute();
$this->assertContains('Test-Project', $this->message['subject']);
$this->assertContains('Test-Project', $this->message['body']);
}
/**
* @covers PHPUnit::execute
*/
public function testMailFailingBuildHaveProjectName()
{
$this->loadEmailPluginWithOptions(
array(
'addresses' => array('test-receiver@example.com')
),
Build::STATUS_FAILED
);
$this->testedEmailPlugin->execute();
$this->assertContains('Test-Project', $this->message['subject']);
$this->assertContains('Test-Project', $this->message['body']);
}
/**
* @covers PHPUnit::execute
*/
public function testMailSuccessfulBuildHaveStatus()
{
$this->loadEmailPluginWithOptions(
array(
'addresses' => array('test-receiver@example.com')
),
Build::STATUS_SUCCESS
);
$this->testedEmailPlugin->execute();
$this->assertContains('Passing', $this->message['subject']);
$this->assertContains('successful', $this->message['body']);
}
/**
* @covers PHPUnit::execute
*/
public function testMailFailingBuildHaveStatus()
{
$this->loadEmailPluginWithOptions(
array(
'addresses' => array('test-receiver@example.com')
),
Build::STATUS_FAILED
);
$this->testedEmailPlugin->execute();
$this->assertContains('Failing', $this->message['subject']);
$this->assertContains('failed', $this->message['body']);
}
/**
* @covers PHPUnit::execute
*/
public function testMailDeliverySuccess()
{
$this->loadEmailPluginWithOptions(
array(
'addresses' => array('test-receiver@example.com')
),
Build::STATUS_FAILED,
true
);
$returnValue = $this->testedEmailPlugin->execute();
$this->assertEquals(true, $returnValue);
}
/**
* @covers PHPUnit::execute
*/
public function testMailDeliveryFail()
{
$this->loadEmailPluginWithOptions(
array(
'addresses' => array('test-receiver@example.com')
),
Build::STATUS_FAILED,
false
);
$returnValue = $this->testedEmailPlugin->execute();
$this->assertEquals(false, $returnValue);
}
}

View file

@ -0,0 +1,209 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2015, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace Tests\PHPCI\Plugin;
use PHPCI\Plugin\Phar as PharPlugin;
use Phar as PHPPhar;
use RuntimeException;
class PharTest extends \PHPUnit_Framework_TestCase
{
protected $directory;
protected function tearDown()
{
$this->cleanSource();
}
protected function getPlugin(array $options = array())
{
$build = $this
->getMockBuilder('PHPCI\Model\Build')
->disableOriginalConstructor()
->getMock();
$phpci = $this
->getMockBuilder('PHPCI\Builder')
->disableOriginalConstructor()
->getMock();
return new PharPlugin($phpci, $build, $options);
}
protected function buildTemp()
{
$directory = tempnam(APPLICATION_PATH . '/Tests/temp', 'source');
unlink($directory);
return $directory;
}
protected function buildSource()
{
$directory = $this->buildTemp();
mkdir($directory);
file_put_contents($directory . '/one.php', '<?php echo "one";');
file_put_contents($directory . '/two.php', '<?php echo "two";');
mkdir($directory . '/config');
file_put_contents($directory . '/config/config.ini', '[config]');
mkdir($directory . '/views');
file_put_contents($directory . '/views/index.phtml', '<?php echo "hello";');
$this->directory = $directory;
return $directory;
}
protected function cleanSource()
{
if ($this->directory) {
$filenames = array(
'/build.phar',
'/stub.php',
'/views/index.phtml',
'/views',
'/config/config.ini',
'/config',
'/two.php',
'/one.php',
);
foreach ($filenames as $filename) {
if (is_dir($this->directory . $filename)) {
rmdir($this->directory . $filename);
} else if (is_file($this->directory . $filename)) {
unlink($this->directory . $filename);
}
}
rmdir($this->directory);
$this->directory = null;
}
}
protected function checkReadonly()
{
if (ini_get('phar.readonly')) {
$this->markTestSkipped('phar writing disabled in php.ini.');
}
}
public function testPlugin()
{
$plugin = $this->getPlugin();
$this->assertInstanceOf('PHPCI\Plugin', $plugin);
$this->assertInstanceOf('PHPCI\Model\Build', $plugin->getBuild());
$this->assertInstanceOf('PHPCI\Builder', $plugin->getPHPCI());
}
public function testDirectory()
{
$plugin = $this->getPlugin();
$plugin->getPHPCI()->buildPath = 'foo';
$this->assertEquals('foo', $plugin->getDirectory());
$plugin = $this->getPlugin(array('directory' => 'dirname'));
$this->assertEquals('dirname', $plugin->getDirectory());
}
public function testFilename()
{
$plugin = $this->getPlugin();
$this->assertEquals('build.phar', $plugin->getFilename());
$plugin = $this->getPlugin(array('filename' => 'another.phar'));
$this->assertEquals('another.phar', $plugin->getFilename());
}
public function testRegExp()
{
$plugin = $this->getPlugin();
$this->assertEquals('/\.php$/', $plugin->getRegExp());
$plugin = $this->getPlugin(array('regexp' => '/\.(php|phtml)$/'));
$this->assertEquals('/\.(php|phtml)$/', $plugin->getRegExp());
}
public function testStub()
{
$plugin = $this->getPlugin();
$this->assertNull($plugin->getStub());
$plugin = $this->getPlugin(array('stub' => 'stub.php'));
$this->assertEquals('stub.php', $plugin->getStub());
}
public function testExecute()
{
$this->checkReadonly();
$plugin = $this->getPlugin();
$path = $this->buildSource();
$plugin->getPHPCI()->buildPath = $path;
$this->assertTrue($plugin->execute());
$this->assertFileExists($path . '/build.phar');
PHPPhar::loadPhar($path . '/build.phar');
$this->assertFileEquals($path . '/one.php', 'phar://build.phar/one.php');
$this->assertFileEquals($path . '/two.php', 'phar://build.phar/two.php');
$this->assertFileNotExists('phar://build.phar/config/config.ini');
$this->assertFileNotExists('phar://build.phar/views/index.phtml');
}
public function testExecuteRegExp()
{
$this->checkReadonly();
$plugin = $this->getPlugin(array('regexp' => '/\.(php|phtml)$/'));
$path = $this->buildSource();
$plugin->getPHPCI()->buildPath = $path;
$this->assertTrue($plugin->execute());
$this->assertFileExists($path . '/build.phar');
PHPPhar::loadPhar($path . '/build.phar');
$this->assertFileEquals($path . '/one.php', 'phar://build.phar/one.php');
$this->assertFileEquals($path . '/two.php', 'phar://build.phar/two.php');
$this->assertFileNotExists('phar://build.phar/config/config.ini');
$this->assertFileEquals($path . '/views/index.phtml', 'phar://build.phar/views/index.phtml');
}
public function testExecuteStub()
{
$this->checkReadonly();
$content = <<<STUB
<?php
Phar::mapPhar();
__HALT_COMPILER(); ?>
STUB;
$path = $this->buildSource();
file_put_contents($path . '/stub.php', $content);
$plugin = $this->getPlugin(array('stub' => 'stub.php'));
$plugin->getPHPCI()->buildPath = $path;
$this->assertTrue($plugin->execute());
$this->assertFileExists($path . '/build.phar');
$phar = new PHPPhar($path . '/build.phar');
$this->assertEquals($content, trim($phar->getStub())); // + trim because PHP adds newline char
}
public function testExecuteUnknownDirectory()
{
$this->checkReadonly();
$directory = $this->buildTemp();
$plugin = $this->getPlugin(array('directory' => $directory));
$plugin->getPHPCI()->buildPath = $this->buildSource();
$this->assertFalse($plugin->execute());
}
}

View file

@ -0,0 +1,59 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2015, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace Tests\PHPCI\Plugin\Util;
use PHPCI\Plugin\Util\ComposerPluginInformation;
class ComposerPluginInformationTest extends \PHPUnit_Framework_TestCase
{
/**
* @var ComposerPluginInformation
*/
protected $testedInformation;
protected function setUpFromFile($file)
{
$this->testedInformation = ComposerPluginInformation::buildFromYaml($file);
}
protected function phpciSetup()
{
$this->setUpFromFile(
__DIR__ . "/../../../../vendor/composer/installed.json"
);
}
public function testBuildFromYaml_ReturnsInstance()
{
$this->phpciSetup();
$this->assertInstanceOf(
'\PHPCI\Plugin\Util\ComposerPluginInformation',
$this->testedInformation
);
}
public function testGetInstalledPlugins_ReturnsStdClassArray()
{
$this->phpciSetup();
$plugins = $this->testedInformation->getInstalledPlugins();
$this->assertInternalType("array", $plugins);
$this->assertContainsOnly("stdClass", $plugins);
}
public function testGetPluginClasses_ReturnsStringArray()
{
$this->phpciSetup();
$classes = $this->testedInformation->getPluginClasses();
$this->assertInternalType("array", $classes);
$this->assertContainsOnly("string", $classes);
}
}

View file

@ -0,0 +1,22 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2015, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
return function (PHPCI\Plugin\Util\Factory $factory) {
$factory->registerResource(
// This function will be called when the resource is needed.
function() {
return array(
'bar' => "Hello",
);
},
"requiredArgument",
null
);
};

View file

@ -0,0 +1,165 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2015, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace Tests\PHPCI\Plugin\Util;
use PHPCI\Plugin\Util\Executor;
use Prophecy\Argument;
class ExecutorTest extends \PHPUnit_Framework_TestCase
{
/**
* @var Executor
*/
protected $testedExecutor;
protected $mockBuildLogger;
protected $mockFactory;
protected $mockStore;
protected function setUp()
{
parent::setUp();
$this->mockBuildLogger = $this->prophesize('\PHPCI\Logging\BuildLogger');
$this->mockFactory = $this->prophesize('\PHPCI\Plugin\Util\Factory');
$this->mockStore = $this->prophesize('\PHPCI\Store\BuildStore');
$this->testedExecutor = new Executor(
$this->mockFactory->reveal(),
$this->mockBuildLogger->reveal(),
$this->mockStore->reveal()
);
}
public function testExecutePlugin_AssumesPHPCINamespaceIfNoneGiven()
{
$options = array();
$pluginName = 'PhpUnit';
$pluginNamespace = 'PHPCI\\Plugin\\';
$this->mockFactory->buildPlugin($pluginNamespace . $pluginName, $options)
->shouldBeCalledTimes(1)
->willReturn($this->prophesize('PHPCI\Plugin')->reveal());
$this->testedExecutor->executePlugin($pluginName, $options);
}
public function testExecutePlugin_KeepsCalledNameSpace()
{
$options = array();
$pluginClass = $this->getFakePluginClassName('ExamplePluginFull');
$this->mockFactory->buildPlugin($pluginClass, $options)
->shouldBeCalledTimes(1)
->willReturn($this->prophesize('PHPCI\Plugin')->reveal());
$this->testedExecutor->executePlugin($pluginClass, $options);
}
public function testExecutePlugin_CallsExecuteOnFactoryBuildPlugin()
{
$options = array();
$pluginName = 'PhpUnit';
$build = new \PHPCI\Model\Build();
$mockPlugin = $this->prophesize('PHPCI\Plugin');
$mockPlugin->execute()->shouldBeCalledTimes(1);
$this->mockFactory->buildPlugin(Argument::any(), Argument::any())->willReturn($mockPlugin->reveal());
$this->mockFactory->getResourceFor('PHPCI\Model\Build')->willReturn($build);
$this->testedExecutor->executePlugin($pluginName, $options);
}
public function testExecutePlugin_ReturnsPluginSuccess()
{
$options = array();
$pluginName = 'PhpUnit';
$expectedReturnValue = true;
$mockPlugin = $this->prophesize('PHPCI\Plugin');
$mockPlugin->execute()->willReturn($expectedReturnValue);
$this->mockFactory->buildPlugin(Argument::any(), Argument::any())->willReturn($mockPlugin->reveal());
$returnValue = $this->testedExecutor->executePlugin($pluginName, $options);
$this->assertEquals($expectedReturnValue, $returnValue);
}
public function testExecutePlugin_LogsFailureForNonExistentClasses()
{
$options = array();
$pluginName = 'DOESNTEXIST';
$this->mockBuildLogger->logFailure('Plugin does not exist: ' . $pluginName)->shouldBeCalledTimes(1);
$this->testedExecutor->executePlugin($pluginName, $options);
}
public function testExecutePlugin_LogsFailureWhenExceptionsAreThrownByPlugin()
{
$options = array();
$pluginName = 'PhpUnit';
$expectedException = new \RuntimeException("Generic Error");
$mockPlugin = $this->prophesize('PHPCI\Plugin');
$mockPlugin->execute()->willThrow($expectedException);
$this->mockFactory->buildPlugin(Argument::any(), Argument::any())->willReturn($mockPlugin->reveal());
$this->mockBuildLogger->logFailure('Exception: ' . $expectedException->getMessage(), $expectedException)
->shouldBeCalledTimes(1);
$this->testedExecutor->executePlugin($pluginName, $options);
}
public function testExecutePlugins_CallsEachPluginForStage()
{
$phpUnitPluginOptions = array();
$behatPluginOptions = array();
$build = new \PHPCI\Model\Build();
$config = array(
'stageOne' => array(
'PhpUnit' => $phpUnitPluginOptions,
'Behat' => $behatPluginOptions,
)
);
$pluginNamespace = 'PHPCI\\Plugin\\';
$mockPhpUnitPlugin = $this->prophesize('PHPCI\Plugin');
$mockPhpUnitPlugin->execute()->shouldBeCalledTimes(1)->willReturn(true);
$this->mockFactory->buildPlugin($pluginNamespace . 'PhpUnit', $phpUnitPluginOptions)
->willReturn($mockPhpUnitPlugin->reveal());
$this->mockFactory->getResourceFor('PHPCI\Model\Build')->willReturn($build);
$mockBehatPlugin = $this->prophesize('PHPCI\Plugin');
$mockBehatPlugin->execute()->shouldBeCalledTimes(1)->willReturn(true);
$this->mockFactory->buildPlugin($pluginNamespace . 'Behat', $behatPluginOptions)
->willReturn($mockBehatPlugin->reveal());
$this->testedExecutor->executePlugins($config, 'stageOne');
}
protected function getFakePluginClassName($pluginName)
{
$pluginNamespace = '\\Tests\\PHPCI\\Plugin\\Util\\Fake\\';
return $pluginNamespace . $pluginName;
}
}

View file

@ -0,0 +1,219 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2015, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace Tests\PHPCI\Plugin\Util;
use PHPCI\Plugin\Util\Factory;
class FactoryTest extends \PHPUnit_Framework_TestCase {
/**
* @var \PHPCI\Plugin\Util\Factory
*/
protected $testedFactory;
protected $expectedResource;
protected $resourceLoader;
protected function setUp()
{
$this->testedFactory = new Factory();
// Setup a resource that can be returned and asserted against
$this->expectedResource = new \stdClass();
$resourceLink = $this->expectedResource;
$this->resourceLoader = function() use (&$resourceLink) {
return $resourceLink;
};
}
protected function tearDown()
{
// Nothing to do.
}
public function testRegisterResourceThrowsExceptionWithoutTypeAndName()
{
$this->setExpectedException('InvalidArgumentException', 'Type or Name must be specified');
$this->testedFactory->registerResource($this->resourceLoader, null, null);
}
public function testRegisterResourceThrowsExceptionIfLoaderIsntFunction()
{
$this->setExpectedException('InvalidArgumentException', '$loader is expected to be a function');
$this->testedFactory->registerResource(array("dummy"), "TestName", "TestClass");
}
public function testBuildPluginWorksWithConstructorlessPlugins()
{
$pluginClass = $this->getFakePluginClassName('ExamplePluginWithNoConstructorArgs');
$plugin = $this->testedFactory->buildPlugin($pluginClass);
$this->assertInstanceOf($pluginClass, $plugin);
}
public function testBuildPluginFailsForNonPluginClasses()
{
$this->setExpectedException('InvalidArgumentException', 'Requested class must implement \PHPCI\Plugin');
$plugin = $this->testedFactory->buildPlugin("stdClass");
}
public function testBuildPluginWorksWithSingleOptionalArgConstructor()
{
$pluginClass = $this->getFakePluginClassName('ExamplePluginWithSingleOptionalArg');
$plugin = $this->testedFactory->buildPlugin($pluginClass);
$this->assertInstanceOf($pluginClass, $plugin);
}
public function testBuildPluginThrowsExceptionIfMissingResourcesForRequiredArg()
{
$this->setExpectedException(
'DomainException',
'Unsatisfied dependency: requiredArgument'
);
$pluginClass = $this->getFakePluginClassName('ExamplePluginWithSingleRequiredArg');
$plugin = $this->testedFactory->buildPlugin($pluginClass);
}
public function testBuildPluginLoadsArgumentsBasedOnName()
{
$pluginClass = $this->getFakePluginClassName('ExamplePluginWithSingleRequiredArg');
$this->testedFactory->registerResource(
$this->resourceLoader,
"requiredArgument"
);
/** @var ExamplePluginWithSingleRequiredArg $plugin */
$plugin = $this->testedFactory->buildPlugin($pluginClass);
$this->assertEquals($this->expectedResource, $plugin->RequiredArgument);
}
public function testBuildPluginLoadsArgumentsBasedOnType()
{
$pluginClass = $this->getFakePluginClassName('ExamplePluginWithSingleTypedRequiredArg');
$this->testedFactory->registerResource(
$this->resourceLoader,
null,
"stdClass"
);
/** @var ExamplePluginWithSingleTypedRequiredArg $plugin */
$plugin = $this->testedFactory->buildPlugin($pluginClass);
$this->assertEquals($this->expectedResource, $plugin->RequiredArgument);
}
public function testBuildPluginLoadsFullExample()
{
$pluginClass = $this->getFakePluginClassName('ExamplePluginFull');
$this->registerBuildAndBuilder();
/** @var ExamplePluginFull $plugin */
$plugin = $this->testedFactory->buildPlugin($pluginClass);
$this->assertInstanceOf($pluginClass, $plugin);
}
public function testBuildPluginLoadsFullExampleWithOptions()
{
$pluginClass = $this->getFakePluginClassName('ExamplePluginFull');
$expectedArgs = array(
'thing' => "stuff"
);
$this->registerBuildAndBuilder();
/** @var ExamplePluginFull $plugin */
$plugin = $this->testedFactory->buildPlugin(
$pluginClass,
$expectedArgs
);
$this->assertInternalType('array', $plugin->Options);
$this->assertArrayHasKey('thing', $plugin->Options);
}
public function testAddConfigFromFile_ReturnsTrueForValidFile()
{
$result = $this->testedFactory->addConfigFromFile(
realpath(__DIR__ . "/ExamplePluginConfig.php")
);
$this->assertTrue($result);
}
public function testAddConfigFromFile_RegistersResources()
{
$this->testedFactory->addConfigFromFile(
realpath(__DIR__ . "/ExamplePluginConfig.php")
);
$pluginClass = $this->getFakePluginClassName('ExamplePluginWithSingleRequiredArg');
$plugin = $this->testedFactory->buildPlugin($pluginClass);
// The Example config file defines an array as the resource.
$this->assertEquals(
array("bar" => "Hello"),
$plugin->RequiredArgument
);
}
/**
* Registers mocked Builder and Build classes so that realistic plugins
* can be tested.
*/
private function registerBuildAndBuilder()
{
$self = $this;
$this->testedFactory->registerResource(
function () use ($self) {
return $self->getMock(
'PHPCI\Builder',
array(),
array(),
'',
false
);
},
null,
'PHPCI\\Builder'
);
$this->testedFactory->registerResource(
function () use ($self) {
return $self->getMock(
'PHPCI\Model\Build',
array(),
array(),
'',
false
);
},
null,
'PHPCI\\Model\\Build'
);
}
protected function getFakePluginClassName($pluginName)
{
$pluginNamespace = '\\Tests\\PHPCI\\Plugin\\Util\\Fake\\';
return $pluginNamespace . $pluginName;
}
}

View file

@ -0,0 +1,36 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2015, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace Tests\PHPCI\Plugin\Util\Fake;
use PHPCI\Builder;
use PHPCI\Model\Build;
use PHPCI\Plugin;
class ExamplePluginFull implements Plugin {
/**
* @var array
*/
public $Options;
public function __construct(
Builder $phpci,
Build $build,
array $options = array()
)
{
$this->Options = $options;
}
public function execute()
{
}
}

View file

@ -0,0 +1,20 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2015, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace Tests\PHPCI\Plugin\Util\Fake;
use PHPCI\Plugin;
class ExamplePluginWithNoConstructorArgs implements Plugin
{
public function execute()
{
}
}

View file

@ -0,0 +1,26 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2015, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace Tests\PHPCI\Plugin\Util\Fake;
use PHPCI\Plugin;
class ExamplePluginWithSingleOptionalArg implements Plugin
{
function __construct($optional = null)
{
}
public function execute()
{
}
}

View file

@ -0,0 +1,29 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2015, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace Tests\PHPCI\Plugin\Util\Fake;
use PHPCI\Plugin;
class ExamplePluginWithSingleRequiredArg implements Plugin
{
public $RequiredArgument;
function __construct($requiredArgument)
{
$this->RequiredArgument = $requiredArgument;
}
public function execute()
{
}
}

View file

@ -0,0 +1,29 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2015, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace Tests\PHPCI\Plugin\Util\Fake;
use PHPCI\Plugin;
class ExamplePluginWithSingleTypedRequiredArg implements Plugin
{
public $RequiredArgument;
function __construct(\stdClass $requiredArgument)
{
$this->RequiredArgument = $requiredArgument;
}
public function execute()
{
}
}

View file

@ -0,0 +1,34 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2015, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace Tests\PHPCI\Plugin\Util;
use PHPCI\Plugin\Util\FilesPluginInformation;
class FilesPluginInformationTest extends \PHPUnit_Framework_TestCase
{
public function testGetInstalledPlugins_returnsObjects()
{
$pluginDirPath = realpath(__DIR__ . "/../../../../PHPCI/Plugin/");
$test = FilesPluginInformation::newFromDir($pluginDirPath);
$pluginInfos = $test->getInstalledPlugins();
$this->assertContainsOnlyInstancesOf('stdClass', $pluginInfos);
}
public function testGetPluginClasses_returnsStrings()
{
$pluginDirPath = realpath(__DIR__ . "/../../../../PHPCI/Plugin/");
$test = FilesPluginInformation::newFromDir($pluginDirPath);
$pluginInfos = $test->getPluginClasses();
$this->assertContainsOnly('string', $pluginInfos);
}
}

View file

@ -0,0 +1,303 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2015, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace Tests\PHPCI\Plugin\Util;
use PHPCI\Plugin\Util\TapParser;
class TapParserTest extends \PHPUnit_Framework_TestCase
{
public function testSimple()
{
$content = <<<TAP
Leading garbage !
TAP version 13
ok 1 - SomeTest::testAnother
not ok
1..2
Trailing garbage !
TAP;
$parser = new TapParser($content);
$result = $parser->parse();
$this->assertEquals(array(
array('pass' => true, 'severity' => 'success', 'message' => 'SomeTest::testAnother'),
array('pass' => false, 'severity' => 'fail', 'message' => ''),
), $result);
$this->assertEquals(1, $parser->getTotalFailures());
}
public function testSimple2()
{
$content = <<<TAP
Leading garbage !
TAP version 13
ok 1 - SomeTest::testAnother
not ok
1..2
TAP;
$parser = new TapParser($content);
$result = $parser->parse();
$this->assertEquals(array(
array('pass' => true, 'severity' => 'success', 'message' => 'SomeTest::testAnother'),
array('pass' => false, 'severity' => 'fail', 'message' => ''),
), $result);
$this->assertEquals(1, $parser->getTotalFailures());
}
/**
* @expectedException \Exception
* @expectedExceptionMessageRegExp /No TAP/
*/
public function testNoTapData()
{
$content = <<<TAP
Only garbage !
TAP;
$parser = new TapParser($content);
$parser->parse();
}
public function testTapCoverage()
{
$content = <<<TAP
TAP version 13
Generating code coverage report in HTML format ... done
TAP;
$parser = new TapParser($content);
$result = $parser->parse();
$this->assertEquals(array(), $result);
}
/**
* @expectedException \Exception
* @expectedExceptionMessageRegExp /Duplicated TAP/
*/
public function testDuplicateOutput()
{
$content = <<<TAP
TAP version 13
TAP version 13
ok 1 - SomeTest::testAnother
ok 1 - SomeTest::testAnother
not ok - Failure: SomeTest::testAnother
not ok - Failure: SomeTest::testAnother
not ok 3 - Error: SomeTest::testAnother
not ok 3 - Error: SomeTest::testAnother
1..3
1..3
TAP;
$parser = new TapParser($content);
$parser->parse();
}
public function testSuiteAndTest()
{
$content = <<<TAP
TAP version 13
ok 1 - SomeTest::testAnother
not ok - Failure: SomeTest::testAnother
not ok 3 - Error: SomeTest::testAnother
1..3
Trailing garbage !
TAP;
$parser = new TapParser($content);
$result = $parser->parse();
$this->assertEquals(array(
array('pass' => true, 'severity' => 'success', 'message' => 'SomeTest::testAnother',),
array('pass' => false, 'severity' => 'fail', 'message' => 'Failure: SomeTest::testAnother'),
array('pass' => false, 'severity' => 'error', 'message' => 'Error: SomeTest::testAnother'),
), $result);
$this->assertEquals(2, $parser->getTotalFailures());
}
public function testSkipped()
{
$content = <<<TAP
TAP version 13
ok 1 - # SKIP
ok 2 - # SKIP foobar
ok 3 - foo # SKIP bar
1..3
TAP;
$parser = new TapParser($content);
$result = $parser->parse();
$this->assertEquals(array(
array('pass' => true, 'severity' => 'skipped', 'message' => ''),
array('pass' => true, 'severity' => 'skipped', 'message' => 'foobar'),
array('pass' => true, 'severity' => 'skipped', 'message' => 'foo, skipped: bar'),
), $result);
$this->assertEquals(0, $parser->getTotalFailures());
}
public function testTodo()
{
$content = <<<TAP
TAP version 13
ok 1 - SomeTest::testAnother # TODO really implement this test
ok 2 - # TODO really implement this test
ok 3 - this is a message # TODO really implement this test
ok 4 - # TODO
1..4
TAP;
$parser = new TapParser($content);
$result = $parser->parse();
$this->assertEquals(array(
array('pass' => true, 'severity' => 'todo', 'message' => 'SomeTest::testAnother, todo: really implement this test'),
array('pass' => true, 'severity' => 'todo', 'message' => 'really implement this test'),
array('pass' => true, 'severity' => 'todo', 'message' => 'this is a message, todo: really implement this test'),
array('pass' => true, 'severity' => 'todo', 'message' => ''),
), $result);
$this->assertEquals(0, $parser->getTotalFailures());
}
public function testYamlDiagnostic()
{
// From https://phpunit.de/manual/current/en/logging.html#logging.tap
$content = <<<TAP
TAP version 13
not ok 1 - FOO
---
message: BAR
...
1..1
TAP;
$parser = new TapParser($content);
$result = $parser->parse();
$this->assertEquals(array(
array(
'pass' => false,
'severity' => 'fail',
'message' => 'FOO' . PHP_EOL . 'BAR',
),
), $result);
$this->assertEquals(1, $parser->getTotalFailures());
}
public function testFailureAndError()
{
// From https://phpunit.de/manual/current/en/logging.html#logging.tap
$content = <<<TAP
TAP version 13
not ok 1 - Failure: testFailure::FailureErrorTest
not ok 2 - Error: testError::FailureErrorTest
1..2
TAP;
$parser = new TapParser($content);
$result = $parser->parse();
$this->assertEquals(array(
array(
'pass' => false,
'severity' => 'fail',
'message' => 'Failure: testFailure::FailureErrorTest',
),
array(
'pass' => false,
'severity' => 'error',
'message' => 'Error: testError::FailureErrorTest',
)
), $result);
$this->assertEquals(2, $parser->getTotalFailures());
}
/**
* @expectedException \Exception
*/
public function testGarbage()
{
$content = "Garbage !";
$parser = new TapParser($content);
$parser->parse();
}
/**
* @expectedException \Exception
*/
public function testInvalidTestCount()
{
$content = <<<TAP
TAP version 13
ok 1 - SomeTest::testAnother
not ok
1..5
TAP;
$parser = new TapParser($content);
$parser->parse();
}
/**
* @expectedException \Exception
*/
public function testEndlessYaml()
{
$content = <<<TAP
TAP version 13
ok 1 - SomeTest::testAnother
---
1..1
TAP;
$parser = new TapParser($content);
$parser->parse();
}
public function testCodeception()
{
$content = <<< TAP
TAP version 13
ok 1 - try to access the dashboard as a guest (Auth/GuestAccessDashboardAndRedirectCept)
ok 2 - see the login page (Auth/SeeLoginCept)
ok 3 - click forgot password and see the email form (Auth/SeeLoginForgotPasswordCept)
ok 4 - see powered by runmybusiness branding (Auth/ShouldSeePoweredByBrandingCept)
ok 5 - submit invalid credentials (Auth/SubmitLoginAndFailCept)
ok 6 - submit valid credentials and see the dashboard (Auth/SubmitLoginAndSucceedCept)
1..6
TAP;
$parser = new TapParser($content);
$result = $parser->parse();
$this->assertEquals(
array(
array('pass' => true, 'severity' => 'success', 'message' => 'try to access the dashboard as a guest (Auth/GuestAccessDashboardAndRedirectCept)'),
array('pass' => true, 'severity' => 'success', 'message' => 'see the login page (Auth/SeeLoginCept)'),
array('pass' => true, 'severity' => 'success', 'message' => 'click forgot password and see the email form (Auth/SeeLoginForgotPasswordCept)'),
array('pass' => true, 'severity' => 'success', 'message' => 'see powered by runmybusiness branding (Auth/ShouldSeePoweredByBrandingCept)'),
array('pass' => true, 'severity' => 'success', 'message' => 'submit invalid credentials (Auth/SubmitLoginAndFailCept)'),
array('pass' => true, 'severity' => 'success', 'message' => 'submit valid credentials and see the dashboard (Auth/SubmitLoginAndSucceedCept)'),
),
$result
);
$this->assertEquals(0, $parser->getTotalFailures());
}
}

View file

@ -0,0 +1,17 @@
<?php
namespace Tests\PHPCI\ProcessControl;
use PHPCI\ProcessControl\PosixProcessControl;
class PosixProcessControlTest extends UnixProcessControlTest
{
protected function setUp()
{
$this->object = new PosixProcessControl();
}
public function testIsAvailable()
{
$this->assertEquals(function_exists('posix_kill'), PosixProcessControl::isAvailable());
}
}

View file

@ -0,0 +1,126 @@
<?php
namespace Tests\PHPCI\ProcessControl;
/**
* Some helpers to
*/
abstract class ProcessControlTest extends \PHPUnit_Framework_TestCase
{
/**
* @var type
*/
protected $process;
/**
* @var array
*/
protected $pipes;
/**
* @var \PHPCI\ProcessControl\ProcessControlInterface
*/
protected $object;
/** Starts a process.
*
* @return int The PID of the process.
*/
protected function startProcess()
{
$desc = array(array("pipe", "r"), array("pipe", "w"), array("pipe", "w"));
$this->pipes = array();
$this->process = proc_open($this->getTestCommand(), $desc, $this->pipes);
usleep(500);
$this->assertTrue(is_resource($this->process));
$this->assertTrue($this->isRunning());
$status = proc_get_status($this->process);
return $status['pid'];
}
/** End the running process.
*
* @return int
*/
protected function endProcess()
{
if (!is_resource($this->process)) {
return;
}
array_map('fclose', $this->pipes);
$exitCode = proc_close($this->process);
$this->assertFalse($this->isRunning());
$this->process = null;
return $exitCode;
}
/**
* @return bool
*/
protected function isRunning()
{
if (!is_resource($this->process)) {
return false;
}
$status = proc_get_status($this->process);
return $status['running'];
}
public function testIsRunning()
{
if (!$this->object->isAvailable()) {
$this->markTestSkipped();
}
$pid = $this->startProcess();
$this->assertTrue($this->object->isRunning($pid));
fwrite($this->pipes[0], PHP_EOL);
$exitCode = $this->endProcess();
$this->assertEquals(0, $exitCode);
$this->assertFalse($this->object->isRunning($pid));
}
public function testSoftKill()
{
if (!$this->object->isAvailable()) {
$this->markTestSkipped();
}
$pid = $this->startProcess();
$this->object->kill($pid);
usleep(500);
$this->assertFalse($this->isRunning());
}
public function testForcefullyKill()
{
if (!$this->object->isAvailable()) {
$this->markTestSkipped();
}
$pid = $this->startProcess();
$this->object->kill($pid, true);
usleep(500);
$this->assertFalse($this->isRunning());
}
abstract public function testIsAvailable();
abstract public function getTestCommand();
protected function tearDown()
{
parent::tearDown();
$this->endProcess();
}
}

View file

@ -0,0 +1,22 @@
<?php
namespace Tests\PHPCI\ProcessControl;
use PHPCI\ProcessControl\UnixProcessControl;
class UnixProcessControlTest extends ProcessControlTest
{
protected function setUp()
{
$this->object = new UnixProcessControl();
}
public function getTestCommand()
{
return "read SOMETHING";
}
public function testIsAvailable()
{
$this->assertEquals(DIRECTORY_SEPARATOR === '/', UnixProcessControl::isAvailable());
}
}

View file

@ -0,0 +1,22 @@
<?php
namespace Tests\PHPCI\ProcessControl;
use PHPCI\ProcessControl\WindowsProcessControl;
class WindowsProcessControlTest extends ProcessControlTest
{
protected function setUp()
{
$this->object = new WindowsProcessControl;
}
public function getTestCommand()
{
return "pause";
}
public function testIsAvailable()
{
$this->assertEquals(DIRECTORY_SEPARATOR === '\\', WindowsProcessControl::isAvailable());
}
}

View file

@ -0,0 +1,149 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2014, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace Tests\PHPCI\Service;
use PHPCI\Model\Build;
use PHPCI\Model\Project;
use PHPCI\Service\BuildService;
/**
* Unit tests for the ProjectService class.
* @author Dan Cryer <dan@block8.co.uk>
*/
class BuildServiceTest extends \PHPUnit_Framework_TestCase
{
/**
* @var BuildService $testedService
*/
protected $testedService;
/**
* @var \ $mockBuildStore
*/
protected $mockBuildStore;
public function setUp()
{
$this->mockBuildStore = $this->getMock('PHPCI\Store\BuildStore');
$this->mockBuildStore->expects($this->any())
->method('save')
->will($this->returnArgument(0));
$this->testedService = new BuildService($this->mockBuildStore);
}
/**
* @covers PHPUnit::execute
*/
public function testExecute_CreateBasicBuild()
{
$project = new Project();
$project->setType('github');
$project->setId(101);
$returnValue = $this->testedService->createBuild($project);
$this->assertEquals(101, $returnValue->getProjectId());
$this->assertEquals(Build::STATUS_NEW, $returnValue->getStatus());
$this->assertNull($returnValue->getStarted());
$this->assertNull($returnValue->getFinished());
$this->assertNull($returnValue->getLog());
$this->assertEquals(\PHPCI\Helper\Lang::get('manual_build'), $returnValue->getCommitMessage());
$this->assertNull($returnValue->getCommitterEmail());
$this->assertNull($returnValue->getExtra());
$this->assertEquals('master', $returnValue->getBranch());
$this->assertInstanceOf('DateTime', $returnValue->getCreated());
$this->assertEquals('Manual', $returnValue->getCommitId());
}
/**
* @covers PHPUnit::execute
*/
public function testExecute_CreateBuildWithOptions()
{
$project = new Project();
$project->setType('hg');
$project->setId(101);
$returnValue = $this->testedService->createBuild($project, '123', 'testbranch', 'test@example.com', 'test');
$this->assertEquals('testbranch', $returnValue->getBranch());
$this->assertEquals('123', $returnValue->getCommitId());
$this->assertEquals('test', $returnValue->getCommitMessage());
$this->assertEquals('test@example.com', $returnValue->getCommitterEmail());
}
/**
* @covers PHPUnit::execute
*/
public function testExecute_CreateBuildWithExtra()
{
$project = new Project();
$project->setType('bitbucket');
$project->setId(101);
$returnValue = $this->testedService->createBuild($project, null, null, null, null, array('item1' => 1001));
$this->assertEquals(1001, $returnValue->getExtra('item1'));
}
/**
* @covers PHPUnit::execute
*/
public function testExecute_CreateDuplicateBuild()
{
$build = new Build();
$build->setId(1);
$build->setProject(101);
$build->setCommitId('abcde');
$build->setStatus(Build::STATUS_FAILED);
$build->setLog('Test');
$build->setBranch('example_branch');
$build->setStarted(new \DateTime());
$build->setFinished(new \DateTime());
$build->setCommitMessage('test');
$build->setCommitterEmail('test@example.com');
$build->setExtra(json_encode(array('item1' => 1001)));
$returnValue = $this->testedService->createDuplicateBuild($build);
$this->assertNotEquals($build->getId(), $returnValue->getId());
$this->assertEquals($build->getProjectId(), $returnValue->getProjectId());
$this->assertEquals($build->getCommitId(), $returnValue->getCommitId());
$this->assertNotEquals($build->getStatus(), $returnValue->getStatus());
$this->assertEquals(Build::STATUS_NEW, $returnValue->getStatus());
$this->assertNull($returnValue->getLog());
$this->assertEquals($build->getBranch(), $returnValue->getBranch());
$this->assertNotEquals($build->getCreated(), $returnValue->getCreated());
$this->assertNull($returnValue->getStarted());
$this->assertNull($returnValue->getFinished());
$this->assertEquals('test', $returnValue->getCommitMessage());
$this->assertEquals('test@example.com', $returnValue->getCommitterEmail());
$this->assertEquals($build->getExtra('item1'), $returnValue->getExtra('item1'));
}
/**
* @covers PHPUnit::execute
*/
public function testExecute_DeleteBuild()
{
$store = $this->getMock('PHPCI\Store\BuildStore');
$store->expects($this->once())
->method('delete')
->will($this->returnValue(true));
$service = new BuildService($store);
$build = new Build();
$this->assertEquals(true, $service->deleteBuild($build));
}
}

View file

@ -0,0 +1,212 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2014, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link http://www.phptesting.org/
*/
namespace PHPCI\Service\Tests;
use PHPCI\Model\Build;
use PHPCI\Model\Project;
use PHPCI\Service\BuildService;
use PHPCI\Service\BuildStatusService;
/**
* Unit tests for the ProjectService class.
* @author Dan Cryer <dan@block8.co.uk>
*/
class BuildStatusServiceTest extends \PHPUnit_Framework_TestCase
{
const BRANCH = 'master';
/** @var Project */
protected $project;
protected $timezone;
public function setUp()
{
$project = new Project();
$project->setId(3);
$project->setBranch(self::BRANCH);
$project->setTitle('Test');
$this->project = $project;
$this->timezone = date_default_timezone_get();
date_default_timezone_set('UTC');
}
public function tearDown()
{
date_default_timezone_set($this->timezone);
}
/**
* @param $configId
* @param bool $setProject
* @return Build
*/
protected function getBuild($configId, $setProject = true)
{
$config = array(
'1' => array(
'status' => Build::STATUS_RUNNING,
'id' => 77,
'finishDateTime' => null,
'startedDate' => '2014-10-25 21:20:02',
'previousBuild' => null,
),
'2' => array(
'status' => Build::STATUS_RUNNING,
'id' => 78,
'finishDateTime' => null,
'startedDate' => '2014-10-25 21:20:02',
'previousBuild' => 4,
),
'3' => array(
'status' => Build::STATUS_SUCCESS,
'id' => 7,
'finishDateTime' => '2014-10-25 21:50:02',
'startedDate' => '2014-10-25 21:20:02',
'previousBuild' => null,
),
'4' => array(
'status' => Build::STATUS_FAILED,
'id' => 13,
'finishDateTime' => '2014-10-13 13:13:13',
'previousBuild' => null,
),
'5' => array(
'status' => Build::STATUS_NEW,
'id' => 1000,
'finishDateTime' => '2014-12-25 21:12:21',
'previousBuild' => 3,
)
);
$build = new Build();
$build->setId($config[$configId]['id']);
$build->setBranch(self::BRANCH);
$build->setStatus($config[$configId]['status']);
if ($config[$configId]['finishDateTime']) {
$build->setFinished(new \DateTime($config[$configId]['finishDateTime']));
}
if (!empty($config[$configId]['startedDate'])) {
$build->setStarted(new \DateTime('2014-10-25 21:20:02'));
}
$project = $this->getProjectMock($config[$configId]['previousBuild'], $setProject);
$build->setProjectObject($project);
return $build;
}
/**
* @param null|int $prevBuildId
* @param bool $setProject
* @return Project
*/
protected function getProjectMock($prevBuildId = null, $setProject = true) {
$project = $this->getMock('PHPCI\Model\Project', array('getLatestBuild'));
$prevBuild = ($prevBuildId) ? $this->getBuild($prevBuildId, false) : null;
$project->expects($this->any())
->method('getLatestBuild')
->will($this->returnValue($prevBuild));
/* @var $project Project */
$project->setId(3);
$project->setBranch(self::BRANCH);
$project->setTitle('Test');
if ($setProject) {
$this->project = $project;
}
return $project;
}
/**
* @dataProvider finishedProvider
*
* @param int $buildConfigId
* @param array $expectedResult
*/
public function testFinished($buildConfigId, array $expectedResult)
{
$build = $this->getBuild($buildConfigId);
$service = new BuildStatusService(self::BRANCH, $this->project, $build);
$service->setUrl('http://phpci.dev/');
$this->assertEquals($expectedResult, $service->toArray());
}
public function finishedProvider()
{
return array(
'buildingStatus' => array(
1,
array(
'name' => 'Test / master',
'activity' => 'Building',
'lastBuildLabel' => '',
'lastBuildStatus' => '',
'lastBuildTime' => '',
'webUrl' => 'http://phpci.dev/build/view/77',
)
),
'buildingStatusWithPrev' => array(
2,
array(
'name' => 'Test / master',
'activity' => 'Building',
'lastBuildLabel' => 13,
'lastBuildStatus' => 'Failure',
'lastBuildTime' => '2014-10-13T13:13:13+0000',
'webUrl' => 'http://phpci.dev/build/view/78',
)
),
'successStatus' => array(
3,
array(
'name' => 'Test / master',
'activity' => 'Sleeping',
'lastBuildLabel' => 7,
'lastBuildStatus' => 'Success',
'lastBuildTime' => '2014-10-25T21:50:02+0000',
'webUrl' => 'http://phpci.dev/build/view/7',
)
),
'failureStatus' => array(
4,
array(
'name' => 'Test / master',
'activity' => 'Sleeping',
'lastBuildLabel' => 13,
'lastBuildStatus' => 'Failure',
'lastBuildTime' => '2014-10-13T13:13:13+0000',
'webUrl' => 'http://phpci.dev/build/view/13',
)
),
'pending' => array(
5,
array(
'name' => 'Test / master',
'activity' => 'Pending',
'lastBuildLabel' => 7,
'lastBuildStatus' => 'Success',
'lastBuildTime' => '2014-10-25T21:50:02+0000',
'webUrl' => 'http://phpci.dev/build/view/1000',
)
),
);
}
}

View file

@ -0,0 +1,144 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2014, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace Tests\PHPCI\Service;
use PHPCI\Model\Project;
use PHPCI\Service\ProjectService;
/**
* Unit tests for the ProjectService class.
* @author Dan Cryer <dan@block8.co.uk>
*/
class ProjectServiceTest extends \PHPUnit_Framework_TestCase
{
/**
* @var ProjectService $testedService
*/
protected $testedService;
/**
* @var \ $mockProjectStore
*/
protected $mockProjectStore;
public function setUp()
{
$this->mockProjectStore = $this->getMock('PHPCI\Store\ProjectStore');
$this->mockProjectStore->expects($this->any())
->method('save')
->will($this->returnArgument(0));
$this->testedService = new ProjectService($this->mockProjectStore);
}
/**
* @covers PHPUnit::execute
*/
public function testExecute_CreateBasicProject()
{
$returnValue = $this->testedService->createProject('Test Project', 'github', 'block8/phpci');
$this->assertEquals('Test Project', $returnValue->getTitle());
$this->assertEquals('github', $returnValue->getType());
$this->assertEquals('block8/phpci', $returnValue->getReference());
$this->assertEquals('master', $returnValue->getBranch());
}
/**
* @covers PHPUnit::execute
*/
public function testExecute_CreateProjectWithOptions()
{
$options = array(
'ssh_private_key' => 'private',
'ssh_public_key' => 'public',
'allow_public_status' => 1,
'build_config' => 'config',
'branch' => 'testbranch',
);
$returnValue = $this->testedService->createProject('Test Project', 'github', 'block8/phpci', $options);
$this->assertEquals('private', $returnValue->getSshPrivateKey());
$this->assertEquals('public', $returnValue->getSshPublicKey());
$this->assertEquals('config', $returnValue->getBuildConfig());
$this->assertEquals('testbranch', $returnValue->getBranch());
$this->assertEquals(1, $returnValue->getAllowPublicStatus());
}
/**
* @link https://github.com/Block8/PHPCI/issues/484
* @covers PHPUnit::execute
*/
public function testExecute_CreateGitlabProjectWithoutPort()
{
$reference = 'git@gitlab.block8.net:block8/phpci.git';
$returnValue = $this->testedService->createProject('Gitlab', 'gitlab', $reference);
$this->assertEquals('git', $returnValue->getAccessInformation('user'));
$this->assertEquals('gitlab.block8.net', $returnValue->getAccessInformation('domain'));
$this->assertEquals('block8/phpci', $returnValue->getReference());
}
/**
* @covers PHPUnit::execute
*/
public function testExecute_UpdateExistingProject()
{
$project = new Project();
$project->setTitle('Before Title');
$project->setReference('Before Reference');
$project->setType('github');
$returnValue = $this->testedService->updateProject($project, 'After Title', 'bitbucket', 'After Reference');
$this->assertEquals('After Title', $returnValue->getTitle());
$this->assertEquals('After Reference', $returnValue->getReference());
$this->assertEquals('bitbucket', $returnValue->getType());
}
/**
* @covers PHPUnit::execute
*/
public function testExecute_EmptyPublicStatus()
{
$project = new Project();
$project->setAllowPublicStatus(1);
$options = array(
'ssh_private_key' => 'private',
'ssh_public_key' => 'public',
'build_config' => 'config',
);
$returnValue = $this->testedService->updateProject($project, 'Test Project', 'github', 'block8/phpci', $options);
$this->assertEquals(0, $returnValue->getAllowPublicStatus());
}
/**
* @covers PHPUnit::execute
*/
public function testExecute_DeleteProject()
{
$store = $this->getMock('PHPCI\Store\ProjectStore');
$store->expects($this->once())
->method('delete')
->will($this->returnValue(true));
$service = new ProjectService($store);
$project = new Project();
$this->assertEquals(true, $service->deleteProject($project));
}
}

View file

@ -0,0 +1,117 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2014, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace Tests\PHPCI\Service;
use PHPCI\Model\User;
use PHPCI\Service\UserService;
/**
* Unit tests for the ProjectService class.
* @author Dan Cryer <dan@block8.co.uk>
*/
class UserServiceTest extends \PHPUnit_Framework_TestCase
{
/**
* @var UserService $testedService
*/
protected $testedService;
/**
* @var \ $mockBuildStore
*/
protected $mockUserStore;
public function setUp()
{
$this->mockUserStore = $this->getMock('PHPCI\Store\UserStore');
$this->mockUserStore->expects($this->any())
->method('save')
->will($this->returnArgument(0));
$this->testedService = new UserService($this->mockUserStore);
}
/**
* @covers PHPUnit::execute
*/
public function testExecute_CreateNonAdminUser()
{
$user = $this->testedService->createUser('Test', 'test@example.com', 'testing', 0);
$this->assertEquals('Test', $user->getName());
$this->assertEquals('test@example.com', $user->getEmail());
$this->assertEquals(0, $user->getIsAdmin());
$this->assertTrue(password_verify('testing', $user->getHash()));
}
/**
* @covers PHPUnit::execute
*/
public function testExecute_CreateAdminUser()
{
$user = $this->testedService->createUser('Test', 'test@example.com', 'testing', 1);
$this->assertEquals(1, $user->getIsAdmin());
}
/**
* @covers PHPUnit::execute
*/
public function testExecute_RevokeAdminStatus()
{
$user = new User();
$user->setEmail('test@example.com');
$user->setName('Test');
$user->setIsAdmin(1);
$user = $this->testedService->updateUser($user, 'Test', 'test@example.com', 'testing', 0);
$this->assertEquals(0, $user->getIsAdmin());
}
/**
* @covers PHPUnit::execute
*/
public function testExecute_GrantAdminStatus()
{
$user = new User();
$user->setEmail('test@example.com');
$user->setName('Test');
$user->setIsAdmin(0);
$user = $this->testedService->updateUser($user, 'Test', 'test@example.com', 'testing', 1);
$this->assertEquals(1, $user->getIsAdmin());
}
/**
* @covers PHPUnit::execute
*/
public function testExecute_ChangesPasswordIfNotEmpty()
{
$user = new User();
$user->setHash(password_hash('testing', PASSWORD_DEFAULT));
$user = $this->testedService->updateUser($user, 'Test', 'test@example.com', 'newpassword', 0);
$this->assertFalse(password_verify('testing', $user->getHash()));
$this->assertTrue(password_verify('newpassword', $user->getHash()));
}
/**
* @covers PHPUnit::execute
*/
public function testExecute_DoesNotChangePasswordIfEmpty()
{
$user = new User();
$user->setHash(password_hash('testing', PASSWORD_DEFAULT));
$user = $this->testedService->updateUser($user, 'Test', 'test@example.com', '', 0);
$this->assertTrue(password_verify('testing', $user->getHash()));
}
}

43
tests/bootstrap.php Normal file
View file

@ -0,0 +1,43 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2013, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link http://www.phptesting.org/
*/
// Let PHP take a guess as to the default timezone, if the user hasn't set one:
date_default_timezone_set(@date_default_timezone_get());
// Load Composer autoloader:
require_once(dirname(__DIR__) . '/vendor/autoload.php');
// If the PHPCI config file is not where we expect it, try looking in
// env for an alternative config path.
$configFile = dirname(__FILE__) . '/../PHPCI/config.yml';
if (!file_exists($configFile)) {
$configEnv = getenv('phpci_config_file');
if (!empty($configEnv)) {
$configFile = $configEnv;
}
}
// Load configuration if present:
$conf = array();
$conf['b8']['app']['namespace'] = 'PHPCI';
$conf['b8']['app']['default_controller'] = 'Home';
$conf['b8']['view']['path'] = dirname(__DIR__) . '/PHPCI/View/';
$config = new b8\Config($conf);
if (file_exists($configFile)) {
$config->loadYaml($configFile);
}
require_once(dirname(__DIR__) . '/vars.php');
\PHPCI\Helper\Lang::init($config);
\PHPCI\Helper\Lang::setLanguage("en");

2
tests/temp/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
*
!.gitignore