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

View file

@ -1,79 +0,0 @@
<?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

@ -1,86 +0,0 @@
<?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

@ -1,280 +0,0 @@
<?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

@ -1,41 +0,0 @@
<?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

@ -1,35 +0,0 @@
<?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

@ -1,56 +0,0 @@
<?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

@ -1,83 +0,0 @@
<?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__ . "/");
}
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__ . "/" . $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

@ -1,35 +0,0 @@
<?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

@ -1,72 +0,0 @@
<?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

@ -1,114 +0,0 @@
<?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

@ -1,94 +0,0 @@
<?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

@ -1,86 +0,0 @@
<?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

@ -1,111 +0,0 @@
<?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

@ -1,408 +0,0 @@
<?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

@ -1,209 +0,0 @@
<?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

@ -1,59 +0,0 @@
<?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

@ -1,22 +0,0 @@
<?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

@ -1,165 +0,0 @@
<?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

@ -1,219 +0,0 @@
<?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

@ -1,36 +0,0 @@
<?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

@ -1,20 +0,0 @@
<?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

@ -1,26 +0,0 @@
<?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

@ -1,29 +0,0 @@
<?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

@ -1,29 +0,0 @@
<?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

@ -1,34 +0,0 @@
<?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

@ -1,303 +0,0 @@
<?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

@ -1,17 +0,0 @@
<?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

@ -1,126 +0,0 @@
<?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

@ -1,22 +0,0 @@
<?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

@ -1,22 +0,0 @@
<?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

@ -1,149 +0,0 @@
<?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

@ -1,212 +0,0 @@
<?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

@ -1,144 +0,0 @@
<?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

@ -1,117 +0,0 @@
<?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()));
}
}

View file

@ -1,43 +0,0 @@
<?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");

View file

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