1
0
Fork 0
Dieser Commit ist enthalten in:
DSB 2011-06-10 21:55:32 +00:00
Ursprung 2b21070b1a
Commit f7a7c71f86
1583 geänderte Dateien mit 454759 neuen und 0 gelöschten Zeilen

1
tests/.htaccess Normale Datei
Datei anzeigen

@ -0,0 +1 @@
Deny from all

106
tests/ControllerTestCase.php Normale Datei
Datei anzeigen

@ -0,0 +1,106 @@
<?php
require_once 'Zend/Test/PHPUnit/ControllerTestCase.php';
class ControllerTestCase extends Zend_Test_PHPUnit_ControllerTestCase
{
/**
* @var Zend_Application
*/
protected $_application;
public function setUp()
{
$this->bootstrap = array($this, 'appBootstrap');
parent::setUp();
$_SERVER['SERVER_NAME'] = 'localhost';
}
public function appBootstrap()
{
$this->_application= new Zend_Application(
APPLICATION_ENV,
APPLICATION_PATH . '/configs/application.ini'
);
$this->_application->bootstrap();
}
public function tearDown()
{
$this->resetRequest();
$this->resetResponse();
parent::tearDown();
}
public function loginUser($userName = 'tester', $userPass = 'test')
{
$this->getRequest()
->setMethod('POST')
->setParams(
array(
'user' => $userName,
'pass' => $userPass,
'autologin' => 0
)
);
$this->dispatch('/index/login');
// after successful login we should be redirected to the index page
$this->assertResponseCode('302');
$this->assertRedirectTo('/');
// clear request - so each test can use it's own dispatch
$this->clearRequest();
}
public function clearRequest()
{
// clear the request for further testing
$this->resetRequest()->resetResponse();
$this->request->setPost(array());
$this->request->setMethod('GET');
}
// You like to debug non working tests without useful messages?
// Here you go. ;)
public function showResponse()
{
$response = $this->getResponse();
echo "\n\nStatus Code: " . $response->getHttpResponseCode() . "\n\n";
foreach ($response->getHeaders() as $header) {
$replace = 'false';
if ($header['replace'] === true) {
$replace = 'true';
}
echo "\t {$header['name']} - {$header['value']} "
."(replace: {$replace})\n";
}
if ($response->isException()) {
echo "Exceptions:\n\n";
foreach ($response->getException() as $exception) {
echo "\t * Message: {$exception->getMessage()}\n";
echo "\t * File: {$exception->getFile()}\n";
echo "\t * Line: {$exception->getLine()}\n";
echo "\n";
}
}
$body = $response->getBody();
if ($body > '') {
echo str_repeat('-', 80) . "\n" . $body. str_repeat('-', 80);
}
// force output
die();
}
/**
* Read a fixture file from directory "tests/fixtures" and return content as string.
*
* @param string $fileName The filename to read
*
* @return string
*/
public function loadFixtureFile($fileName)
{
$fixturePath = realpath(dirname(__FILE__) . DS . 'fixtures');
$fullFileName = $fixturePath . DS . $fileName;
$content = file_get_contents($fullFileName);
return $content;
}
}

61
tests/Testhelper.php Normale Datei
Datei anzeigen

@ -0,0 +1,61 @@
<?php
class Testhelper
{
/**
* Prepare tests
*/
public static function setUp()
{
Testhelper::copyFile(
'users.ini', APPLICATION_PATH . DS . 'configs' . DS .'users.ini'
);
}
/**
* Copy a fixture to destination
*
* @param string $source Filename of source in fixture folder
* @param string $destination Filename of destination
* @throws Exception
* @return void
*/
public static function copyFile($source, $destination)
{
$fixturePath = realpath(dirname(__FILE__) . DS . 'fixtures');
$source = realpath($fixturePath . DS . $source);
// delete target file if it exists
if (file_exists($destination)) {
if (!unlink($destination)) {
throw new Exception(
'Error: Couldn\'t delete file "' . $destination .'"!'
);
}
}
if (!copy($source, $destination)) {
throw new Exception(
'Error: Couldn\'t copy file "' . $source . '" to "'
. $destination .'"!'
);
};
chmod($destination, 0755);
}
/**
* Remove a file
*
* @throws Exception
* @param string $file File to remove
* @return void
*/
public function removeFile($file)
{
if (!file_exists($file)) {
return;
}
if (!unlink($file)) {
throw new Exception(
'Error: Couldn\'t remove file "' . $file .'"'
);
}
}
}

10
tests/Zend.xml Normale Datei
Datei anzeigen

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8" ?>
<ruleset name="Zend">
<description>MySQLDumper2 coding standard</description>
<rule ref="Zend" />
<rule ref="Generic.Files.LineLength">
<properties>
<property name="lineLimit" value="120" />
</properties>
</rule>
</ruleset>

48
tests/bootstrap.php Normale Datei
Datei anzeigen

@ -0,0 +1,48 @@
<?php
// set up test environment
defined('DS') || define('DS', DIRECTORY_SEPARATOR);
defined('MSD_VERSION') || define('MSD_VERSION', ' 2.0.0');
defined('WORK_PATH') || define('WORK_PATH', realpath(dirname(__FILE__) . DS . '../'. DS . 'work'));
defined('CONFIG_PATH') || define('CONFIG_PATH', WORK_PATH . DS . 'config');
// Define path to application directory
defined('APPLICATION_PATH') || define(
'APPLICATION_PATH', realpath(
dirname(__FILE__) . DS . '..' . DS . 'application')
);
// Define path to test directory
defined('TEST_PATH') || define(
'TEST_PATH', realpath(dirname(__FILE__) . '/')
);
// Define application environment
if (!defined('APPLICATION_ENV')) {
define('APPLICATION_ENV', 'testing');
}
// Ensure library/ is on include_path
set_include_path(
implode(
PATH_SEPARATOR, array(
realpath(APPLICATION_PATH . '/../application'),
realpath(APPLICATION_PATH . '/../library'),
realpath(APPLICATION_PATH . '/views/helpers'),
get_include_path()
)
)
);
require_once 'Zend/Application.php';
require_once 'PHPUnit/Autoload.php';
require_once 'ControllerTestCase.php';
require_once 'Testhelper.php';
Testhelper::setUp();
$application = new Zend_Application(
APPLICATION_ENV,
APPLICATION_PATH . '/configs/application.ini'
);
$application->bootstrap();
clearstatcache();

73
tests/fixtures/mysqldumper.ini gevendort Normale Datei
Datei anzeigen

@ -0,0 +1,73 @@
[general]
title = "MySQLDumper"
mode = "easy"
logMaxsize = "1048576"
logUnit = "kb"
minspeed = "100"
maxspeed = "10000"
gzip = "y"
multipart = "n"
multipartSize = ""
optimize = "n"
errorHandling = "s"
dbDelete = "n"
[dbuser]
user = "root"
pass = ""
host = "localhost"
defaultDb = "information_schema"
port = ""
socket = ""
[autodelete]
Activated = "n"
PreserveBackups = ""
[email]
sendEmail = "n"
SenderAddress = ""
SenderName = ""
RecipientAddress = ""
RecipientName = ""
attachBackup = "n"
Maxsize = ""
SendmailCall = ""
SMTPHost = ""
SMTPPort = ""
SMTPUser = ""
SMTPPassword = ""
[ftp]
0.use = "n"
0.timeout = "10"
0.passiveMode = "y"
0.ssl = "n"
0.server = ""
0.port = "21"
0.user = ""
0.pass = ""
0.dir = "/"
[cronscript]
perlExtension = "pl"
perlPath = ""
perlTextOutput = "y"
perlTextOutputComplete = "y"
perlFileComment = ""
[interface]
language = "de"
theme = "msd"
notificationWindowPosition = "middleCenter"
showServerCaption = "y"
showTooltips = "y"
sqlboxHeight = "30"
recordsPerPage = "50"
sqlbrowserViewMode = "compact"
refreshProcesslist = "3"
[systemDatabases]
0 = "mysql"
1 = "information_schema"

72
tests/fixtures/mysqldumper2.ini gevendort Normale Datei
Datei anzeigen

@ -0,0 +1,72 @@
[general]
title = "MySQLDumper2"
mode = "easy"
logMaxsize = "1048576"
logUnit = "kb"
minspeed = "100"
maxspeed = "10000"
gzip = "y"
multipart = "n"
multipartSize = ""
optimize = "n"
errorHandling = "s"
dbDelete = "n"
[dbuser]
user = "root"
pass = ""
host = "localhost"
defaultDb = "test"
port = ""
socket = ""
[autodelete]
Activated = "n"
PreserveBackups = ""
[email]
sendEmail = "n"
SenderAddress = ""
SenderName = ""
RecipientAddress = ""
RecipientName = ""
attachBackup = "n"
Maxsize = ""
SendmailCall = ""
SMTPHost = ""
SMTPPort = ""
SMTPUser = ""
SMTPPassword = ""
[ftp]
0.use = "n"
0.timeout = "10"
0.passiveMode = "y"
0.ssl = "n"
0.server = ""
0.port = "21"
0.user = ""
0.pass = ""
0.dir = "/"
[cronscript]
perlExtension = "pl"
perlPath = ""
perlTextOutput = "y"
perlTextOutputComplete = "y"
perlFileComment = ""
[interface]
language = "de"
theme = "msd"
notificationWindowPosition = "middleCenter"
showServerCaption = "y"
showTooltips = "y"
sqlboxHeight = "30"
recordsPerPage = "50"
sqlbrowserViewMode = "compact"
refreshProcesslist = "3"
[systemDatabases]
0 = "mysql"
1 = "information_schema"

4
tests/fixtures/users.ini gevendort Normale Datei
Datei anzeigen

@ -0,0 +1,4 @@
[0]
name = "tester"
pass = "098f6bcd4621d373cade4e832627b4f6"

0
tests/fixtures/usersEmpty.ini gevendort Normale Datei
Datei anzeigen

Datei anzeigen

@ -0,0 +1,27 @@
<?php
require_once 'PHPUnit/Framework/TestCase.php';
require_once APPLICATION_PATH . DS . implode(DS, array('models', 'Sqlbox.php'));
/**
* @group Models
*/
class SqlboxTest extends ControllerTestCase
{
public function testCanCreateTableSelectBox()
{
$model = new Application_Model_Sqlbox();
$config = Msd_Configuration::getInstance();
$config->set('dynamic.dbActual', 'information_schema');
$selectBox = $model->getTableSelectBox();
$tables = array('CHARACTER_SETS', 'COLLATIONS', 'COLLATION_CHARACTER_SET_APPLICABILITY',
'COLUMNS', 'COLUMN_PRIVILEGES', 'ENGINES'
);
$pattern = '<option value="%1$s">%1$s</option>';
foreach ($tables as $table) {
$val = sprintf($pattern, $table);
$this->assertTrue(strpos($selectBox, $val) !== false);
}
}
}

Datei anzeigen

@ -0,0 +1,38 @@
<?php
require_once 'PHPUnit/Framework/TestCase.php';
require_once APPLICATION_PATH . '/plugins/DeviceCheck.php';
//'DeviceCheck.php';
/**
* @group MsdPlugins
*/
class DeviceCheckerTest extends ControllerTestCase
{
protected $_deviceChecker = null;
protected $_ZendLayout = null;
public function setUp()
{
$this->_deviceChecker = new Application_Plugin_DeviceCheck();
$this->_ZendLayout = Zend_Layout::getMvcInstance();
}
public function testDispatchLoopStartupIsMobile()
{
$userAgentString = 'Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like
Mac OS X; en-us) AppleWebKit/528.18
(KHTML, like Gecko) Version/4.0 Mobile/7A341
Safari/528.16';
//Mock http_user_agent
$request = $this->getRequest()
->setHeader('user-agent', $userAgentString);
$this->_deviceChecker->dispatchLoopStartup($request);
$layout = $this->_ZendLayout->getLayout();
$expectedLayout = 'mobile';
$this->assertSame($layout, $expectedLayout);
}
}

Datei anzeigen

@ -0,0 +1,24 @@
<?php
require_once 'PHPUnit/Framework/TestCase.php';
require_once 'AbsoluteUrl.php';
/**
* @group MsdViewHelper
*/
class AbsoluteUrlTest extends ControllerTestCase
{
public function testCanGetAbsoluteUrl()
{
$_SERVER['HTTP_SCHEME'] = 'http';
$_SERVER['SERVER_PORT'] = 80;
$this->loginUser();
$viewHelper = new Msd_View_Helper_AbsoluteUrl();
$options = array('controller'=>'sql','action'=>'show.databases');
$res = $viewHelper->absoluteUrl($options);
$expected = 'http://localhost/sql/show.databases';
$this->assertEquals($expected, $res);
}
}

Datei anzeigen

@ -0,0 +1,34 @@
<?php
require_once 'PHPUnit/Framework/TestCase.php';
require_once 'AjaxLoad.php';
/**
* @group MsdViewHelper
*/
class AjaxLoadTest extends ControllerTestCase
{
public function testCanGetAbsoluteUrl()
{
$this->loginUser();
$viewHelper = new Msd_View_Helper_AjaxLoad();
$ajaxOptions = array('controller' => 'sql', 'action' => 'phpinfo');
$viewOptions = array(
'loadingMessage' => 'loading...',
'showThrober' => true
);
$res = $viewHelper->ajaxLoad($ajaxOptions, $viewOptions);
$this->assertTrue(is_string($res));
$checks = array(
'<span id="ajax-', // do we have our span?
'url: \'/sql/phpinfo', // did we get the correct Url?
'loading..', // loading message is in there?
);
foreach ($checks as $check) {
$this->assertTrue(strpos($res, $check) !== false,
'Not found in response: '.$check
);
}
}
}

Datei anzeigen

@ -0,0 +1,29 @@
<?php
require_once 'PHPUnit/Framework/TestCase.php';
require_once 'GetFreeDiskspace.php';
/**
* @group MsdViewHelper
*/
class GetFreeDiskspaceTest extends ControllerTestCase
{
public function setUp()
{
$this->view = new Zend_View();
$helperPath = APPLICATION_PATH . DIRECTORY_SEPARATOR
. 'views' . DIRECTORY_SEPARATOR . 'helpers';
$this->view->addHelperPath($helperPath, 'Msd_View_Helper');
$viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer();
$viewRenderer->setView($this->view);
Zend_Controller_Action_HelperBroker::addHelper($viewRenderer);
}
public function testGetFreeDiskspace()
{
$ret = $this->view->getFreeDiskspace();
$res = strpos($ret, '<span class="explain tooltip"')!== false ? true:false;
$this->assertEquals(true, $res);
}
}

Datei anzeigen

@ -0,0 +1,50 @@
<?php
require_once 'PHPUnit/Framework/TestCase.php';
require_once 'Menu.php';
/**
* @group MsdViewHelper
*/
class MenuTest extends ControllerTestCase
{
public function testWontRenderMenuAtLoginAction()
{
$this->dispatch('/index/login');
$this->assertQueryCount('form', 1);
$this->assertQueryCount('#user', 1);
$this->assertQueryCount('#pass', 1);
$this->assertQueryCount('#autologin', 1);
$this->assertQueryCount('#send', 1);
}
public function testCanRenderMenuWithInvalidActualDatabase()
{
$this->loginUser();
$config = Msd_Configuration::getInstance();
$config->set('dynamic.dbActual', -1);
$this->dispatch('/');
$this->assertQueryContentContains('#selectedDb', 'information_schema');
}
public function testCanFallbackToDefaultDbIfActualDbIsInvalid()
{
$this->loginUser();
$config = Msd_Configuration::getInstance();
$config->set('dynamic.dbActual', 'i_dont_exist');
$config->set('config.dbuser.defaultDb', 'information_schema');
$this->dispatch('/');
$this->assertQueryContentContains('#selectedDb', 'information_schema');
}
public function testCanFallbackToFirstDbIfActualAndDefaultDbsAreInvalid()
{
$this->loginUser();
$config = Msd_Configuration::getInstance();
$config->set('dynamic.dbActual', 'i_dont_exist');
$config->set('config.dbuser.defaultDb', 'I_dont_exist');
$this->dispatch('/');
$this->assertQueryContentContains('#selectedDb', 'information_schema');
}
}

Datei anzeigen

@ -0,0 +1,28 @@
<?php
/**
* @group MsdViewHelper
*/
class PopUpMessageTest extends ControllerTestCase
{
public function testcanAddPopUpMessage()
{
// force popUp by log in with wrong credentials
$this->getRequest()
->setMethod('POST')
->setParams(
array(
'user' => 'tester',
'pass' => 'wrongPassword',
'autologin' => 0
)
);
$this->dispatch('/index/login');
$this->assertNotRedirect();
// make sure we see the login error message
$this->assertQueryCount("//div[@id='login-message']", 1);
$msg = "Diese Kombination von Benutzername und Passwort ist unbekannt.";
$this->assertQueryContentContains('#login-message', $msg);
}
}

Datei anzeigen

@ -0,0 +1,17 @@
<?php
/**
* @group Error
*/
class Msd_Application_Controller_ErrorControllerTest
extends ControllerTestCase
{
public function testErrorControllerCatchesInvalidPageCalls()
{
$this->dispatch('/invalid/page');
$this->assertResponseCode(404);
$this->assertQueryContentContains('h2', 'Page not found');
$this->assertQueryContentContains('#controller', 'invalid');
$this->assertQueryContentContains('#action', 'page');
$this->assertQueryContentContains('#module', 'default');
}
}

Datei anzeigen

@ -0,0 +1,268 @@
<?php
/**
* @group Index
*/
class Msd_Application_Controller_IndexControllerTest
extends ControllerTestCase
{
public static function setUpBeforeClass()
{
Testhelper::copyFile('mysqldumper2.ini', CONFIG_PATH . DS .'mysqldumper2.ini');
}
public static function tearDownAfterClass()
{
Testhelper::removeFile(CONFIG_PATH . DS . 'mysqldumper2.ini');
}
public function testRedirectsToLoginFormIfUserNotLoggedIn()
{
$this->dispatch('/index/phpinfo');
//we should be redirected to the log in page
$this->assertResponseCode('302');
$this->assertRedirectTo('/index/login');
}
public function testCanLoginUser()
{
$this->loginUser();
$this->dispatch('/');
//make sure we are not redirected to the log in page
$this->assertNotRedirect();
// make sure we are on the home page now
$this->assertQueryContentContains('h2', 'Home');
// we should have one div with id username
$this->assertQueryCount('#username', 1);
// which contains the username
$this->assertQueryContentContains('#username > p', 'tester');
// now lets check if we can access a page without being redirected
// to the log in page
$this->clearRequest();
$this->dispatch('/index/phpinfo');
$this->assertNotRedirect();
$this->assertQueryCount('#phpinfo', 1);
}
public function testWontLoginUserWithWrongCredentials()
{
$this->getRequest()
->setMethod('POST')
->setParams(
array(
'user' => 'tester',
'pass' => 'wrongPassword',
'autologin' => 0
)
);
$this->dispatch('/index/login');
$this->assertNotRedirect();
// make sure we see the login error message
$this->assertQueryCount("//div[@id='login-message']", 1);
$msg = "Diese Kombination von Benutzername und Passwort ist unbekannt.";
$this->assertQueryContentContains('#login-message', $msg);
}
public function testCanRedirectToInstallIfUserFileIsBroken()
{
$path= APPLICATION_PATH . '/configs/';
rename($path.'users.ini', $path.'users.bak');
$this->getRequest()
->setMethod('POST')
->setParams(
array(
'user' => 'tester',
'pass' => 'test',
'autologin' => 0
)
);
$this->dispatch('/index/login');
$this->assertResponseCode('302');
rename($path.'users.bak', $path.'users.ini');
$this->assertRedirect();
$this->assertRedirectTo('/install');
}
/**
* @depends testCanLoginUser
*/
public function testCanLogoutUser()
{
$_COOKIE['msd_autologin'] =
'ZC5UZ1xNHTfnaQN2FqIOCuA--:1ef26361573f7032cebe97cec16f0bd0';
$this->dispatch('/index/logout');
// now we should be redirected to login page
$this->assertRedirectTo('/index/login');
$this->assertResponseCode('302');
$this->assertRedirect();
}
public function testCanAutoLoginUserByCookie()
{
$_COOKIE['msd_autologin'] =
'ZC5UZ1xNHTfnaQN2FqIOCuA--:1ef26361573f7032cebe97cec16f0bd0';
$this->dispatch('/index/phpinfo');
$this->assertNotRedirect();
// dom id #phpinfo is only shown on phpinfo page, so let's look for it
$this->assertQueryCount('#phpinfo', 1);
}
/**
* @outputBuffering enabled
*/
public function testCanLoginWithAutoLogin()
{
$this->dispatch('/index/logout');
$this->clearRequest();
$this->getRequest()
->setMethod('POST')
->setParams(
array(
'user' => 'tester',
'pass' => 'test',
'autologin' => 1
)
);
$this->dispatch('/index/login');
// after successful login we should be redirected to the index page
$this->assertResponseCode('302');
$this->assertRedirectTo('/');
$this->clearRequest();
}
public function testCanShowIndex()
{
$this->loginUser();
$this->dispatch('/');
$this->assertNotRedirect();
// we are there if button PHP-Info is shown
$this->assertQueryContentContains('#content', 'PHP-Info');
}
public function testCanShowPhpinfo()
{
$this->loginUser();
$this->dispatch('/index/phpinfo');
$this->assertNotRedirect();
// dom id #phpinfo is only shown on phpinfo page, so let's look for it
$this->assertQueryCount('#phpinfo', 1);
}
public function testCanRefreshDbListAndRedirectsToOldAction()
{
$this->loginUser();
$this->getRequest()
->setMethod('POST')
->setParams(
array(
'lastAction' => 'phpinfo',
'lastController' => 'index'
)
);
$this->dispatch('/index/dbrefresh');
$this->assertRedirectTo('/index/phpinfo');
}
public function testCanRefreshDbListWithInvalidActiveDb()
{
$this->loginUser();
$this->getRequest()
->setMethod('POST')
->setParams(
array(
'lastAction' => 'phpinfo',
'lastController' => 'index'
)
);
$config = Msd_Configuration::getInstance();
$config->set('dynamic.dbActual', -1);
$this->dispatch('/index/dbrefresh');
$this->assertRedirectTo('/index/phpinfo');
}
public function testCanSelectDb()
{
$this->loginUser();
$config = Msd_Configuration::getInstance();
// set invalid active db
$config->set('dynamic.dbActual', -1);
$this->getRequest()
->setMethod('POST')
->setParams(
array(
'lastAction' => 'phpinfo',
'lastController' => 'index',
'selectedDb' => base64_encode('information_schema')
)
);
$this->dispatch('/index/selectdb');
$this->assertRedirectTo('/index/phpinfo');
// check if actual db was switched
$this->assertEquals(
'information_schema',
$config->get('dynamic.dbActual')
);
}
public function testCanToggleMenuStatus()
{
$this->dispatch('index/ajax.Toggle.Menu');
$menu = new Zend_Session_Namespace('menu');
$this->assertEquals(1, $menu->showMenu);
$this->dispatch('index/ajax.Toggle.Menu');
$this->assertEquals(0, $menu->showMenu);
}
public function testCanSwitchConfiguration()
{
$this->loginUser();
$this->getRequest()
->setMethod('POST')
->setParams(
array(
'lastAction' => 'phpinfo',
'lastController' => 'index',
'selectedConfig' => base64_encode('mysqldumper')
)
);
$this->dispatch('/index/switchconfig');
$config = Msd_Configuration::getInstance();
$this->assertEquals('mysqldumper', $config->get('dynamic.configFile'));
// are we still on the phpinfo page?
$this->assertQueryCount('#phpinfo', 1);
// now lets switch to another configuration
$this->clearRequest();
$this->getRequest()
->setMethod('POST')
->setParams(
array(
'lastAction' => 'phpinfo',
'lastController' => 'index',
'selectedConfig' => base64_encode('mysqldumper2')
)
);
$this->dispatch('/index/switchconfig');
$config = Msd_Configuration::getInstance();
$this->assertEquals('mysqldumper2', $config->get('dynamic.configFile'));
// are we still on the phpinfo page?
$this->assertQueryCount('#phpinfo', 1);
}
public function testCanLoadConfigFromSession()
{
$_SESSION = unserialize($this->loadFixtureFile('sessions/sessionTester.txt'));
$reflection = new ReflectionClass('Msd_Configuration');
$property = $reflection->getProperty('_instance');
$property->setAccessible(true);
$oldInstance = $property->getValue(null);
$property->setValue(null, null);
Msd_Configuration::getInstance();
$property->setValue(null, $oldInstance);
$this->loginUser();
$this->assertTrue(true);
}
}

Datei anzeigen

@ -0,0 +1,15 @@
<?php
/**
* @group Error
*/
class Msd_Application_Controller_InstallControllerTest
extends ControllerTestCase
{
public function testCanDispatchInstallPage()
{
$_GET['language'] = 'de';
$this->dispatch('/install/index');
$this->assertQueryContentContains('h3', 'Schritt 1: Sprache wählen (de)');
$this->assertQueryCount('input[@id="lang-de"]', 1);
}
}

Datei anzeigen

@ -0,0 +1,54 @@
<?php
/**
* @group Sql
*/
class Msd_Application_Controller_SqlControllerTest
extends ControllerTestCase
{
public function testCanShowDatabaseList()
{
$this->loginUser();
$this->dispatch('sql');
// make sure headline of db list is shown with correct user
$expected = "Datenbanken des Benutzers 'root'@'localhost'";
$this->assertQueryContentContains('h2', $expected);
// make sure we see the "show tables" link for db information_schema
$expected = base64_encode("information_schema");
$this->assertXpath("//a[contains(@href, '" . $expected ."')]");
}
public function testCanShowTableList()
{
$this->loginUser();
$this->dispatch('sql/show.tables/dbName/bXlzcWw%3D');
// make sure headline shows the selected database
$expected = 'Tabellen der Datenbank `mysql`';
$this->assertQueryContentContains('h2', $expected);
// make sure we see the detail link for table `mysql`.`db`
$expected = 'columns_priv';
$this->assertQueryContentContains('table > tr > td > label', $expected);
}
public function testCanShowTableData()
{
$this->loginUser();
$this->dispatch('sql/show.table.data/dbName/bXlzcWw%3D/tableName/dXNlcg%3D%3D');
// make sure headline shows the selected table
$expected = 'Datensätze der Tabelle `mysql`.`user`';
$this->assertQueryContentContains('h2', $expected);
// make sure user root@localhost is shown
$expected = 'localhost ';
$this->assertQueryContentContains('table > tr > td', $expected);
$expected = 'root ';
$this->assertQueryContentContains('table > tr > td', $expected);
}
public function testCanFallbackToShowingDataOfFirstTableOnIncorrectTable()
{
$this->loginUser();
$this->dispatch('sql/show.table.data/dbName/bXlzcWw%3D/tableName/iDontExits');
// we excpect a fall back to the first found table in db `mysql`
$expected = 'Datensätze der Tabelle `mysql`.`columns_priv`';
$this->assertQueryContentContains('h2', $expected);
}
}

Datei anzeigen

@ -0,0 +1,58 @@
<?php
/**
* @group login
*/
class Msd_UserTest extends ControllerTestCase
{
public function testCanLoginUserByCookie()
{
$_COOKIE['msd_autologin'] =
'ZC5UZ1xNHTfnaQN2FqIOCuA--:1ef26361573f7032cebe97cec16f0bd0';
$request = Zend_Controller_Front::getInstance()->getRequest();
$request->setParam('msd_autologin', $_COOKIE['msd_autologin']);
$user = new Msd_User();
$this->assertTrue($user->isLoggedIn());
// make sure auth session is set after log in
$this->assertEquals(
'tester',
$_SESSION['Zend_Auth']['storage']['name']
);
}
public function testCanDetectInvalidLoginCookie()
{
$_COOKIE['msd_autologin'] =
'C5UZ1xNHTfnaQN2FqIOCuA--:1ef26361573f7032cebe97cec16f0bd0';
$request = Zend_Controller_Front::getInstance()->getRequest();
$request->setParam('msd_autologin', $_COOKIE['msd_autologin']);
$user = new Msd_User();
$this->assertFalse($user->isLoggedIn());
}
public function testCanDetectNonExistantUsersFile()
{
Testhelper::removeFile(
APPLICATION_PATH . DS . 'configs' . DS . 'users.ini'
);
$user = new Msd_User();
$loginResult = $user->login('tester', 'test');
$this->assertEquals(Msd_User::NO_USER_FILE, $loginResult);
Testhelper::copyFile(
'users.ini', APPLICATION_PATH . DS . 'configs' . DS .'users.ini');
}
public function testCanDetectEmptyUsersFile()
{
// overwrite users.ini with en empty file
Testhelper::copyFile('usersEmpty.ini',
APPLICATION_PATH . DS . 'configs' . DS .'users.ini');
$user = new Msd_User();
$loginResult = $user->login('tester', 'test');
$this->assertEquals(Msd_User::NO_VALID_USER, $loginResult);
// restore users.ini file
Testhelper::copyFile(
'users.ini', APPLICATION_PATH . DS . 'configs' . DS .'users.ini');
}
}

41
tests/phpunit.vm.xml Normale Datei
Datei anzeigen

@ -0,0 +1,41 @@
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="./bootstrap.php"
colors="false"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false"
testSuiteLoaderClass="PHPUnit_Runner_StandardTestSuiteLoader"
verbose="true"
strict="true">
<testsuites>
<testsuite name="MySQLDumper2TestSuite">
<directory>unit/</directory>
<directory>functional</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">../application/</directory>
<directory suffix=".php">../library/Msd</directory>
<exclude>
<directory suffix=".phtml">../application/</directory>
<directory>../application/language</directory>
<file>../application/Bootstrap.php</file>
</exclude>
</whitelist>
</filter>
<logging>
<log type="junit" target="./../../build/logs/junit.xml" />
<log type="coverage-html" target="./../../build/coverage" charset="UTF-8"
yui="true" highlight="true"
lowUpperBound="50" highLowerBound="80"/>
<log type="coverage-clover" target="./../../build/logs/coverage-clover.xml" charset="UTF-8"
highlight="true" lowUpperBound="50" highLowerBound="80"/>
</logging>
</phpunit>

33
tests/phpunit.xml Normale Datei
Datei anzeigen

@ -0,0 +1,33 @@
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="./bootstrap.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false"
testSuiteLoaderClass="PHPUnit_Runner_StandardTestSuiteLoader"
verbose="true"
strict="true">
<testsuites>
<testsuite name="MySQLDumper2TestSuite">
<directory>unit/</directory>
<directory>functional</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">../application/</directory>
<directory suffix=".php">../library/Msd</directory>
<exclude>
<directory suffix=".phtml">../application/</directory>
<directory>../application/language</directory>
<file>../application/Bootstrap.php</file>
<file>./unit/library/Msd/Validate/File/AccessibleTest.php</file>
</exclude>
</whitelist>
</filter>
</phpunit>

Datei anzeigen

@ -0,0 +1,35 @@
<?php
require_once 'PHPUnit/Framework/TestCase.php';
require_once 'ByteOutput.php';
/**
* @group MsdViewHelper
*/
class ByteOutputTest extends PHPUnit_Framework_TestCase
{
public function testByteOutputWithoutHtml()
{
$expected='1.00 KB';
$viewHelper = new Msd_View_Helper_ByteOutput();
$res = $viewHelper->byteOutput(1024, 2, false);
$this->assertEquals($expected, $res);
}
public function testByteOutputWithHtml()
{
$expected = '1.00 <span class="explain tooltip" title="KiloBytes">KB</span>';
$viewHelper = new Msd_View_Helper_ByteOutput();
$res = $viewHelper->byteOutput(1024, 2, true);
$this->assertEquals($expected, $res);
}
public function testByteOutputWithNonNumericValue()
{
$expected = 'I am not a number';
$viewHelper = new Msd_View_Helper_ByteOutput();
$res = $viewHelper->byteOutput($expected, 2, true);
$this->assertEquals($expected, $res);
}
}

Datei anzeigen

@ -0,0 +1,29 @@
<?php
require_once 'PHPUnit/Framework/TestCase.php';
require_once 'Filesize.php';
/**
* @group MsdViewHelper
*/
class FilesizeTest extends PHPUnit_Framework_TestCase
{
public function testFilesize()
{
$expected='14.00 <span class="explain tooltip" title="Bytes">B</span>';
//setup view and helper path to Msd_View_Helper
// needed because the filesize-helper calls the byteOupt-Helper
$view = new Zend_View();
$helperPath = APPLICATION_PATH . DIRECTORY_SEPARATOR
. 'views' . DIRECTORY_SEPARATOR . 'helpers';
$view->addHelperPath($helperPath, 'Msd_View_Helper');
$viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer();
$viewRenderer->setView($view);
Zend_Controller_Action_HelperBroker::addHelper($viewRenderer);
$res = $view->filesize(
APPLICATION_PATH . '/.htaccess'
);
$this->assertEquals($expected, $res);
}
}

Datei anzeigen

@ -0,0 +1,34 @@
<?php
require_once 'PHPUnit/Framework/TestCase.php';
require_once('GetConfigTitle.php');
/**
* @group MsdViewHelper
*/
class GetConfigTitleTest extends PHPUnit_Framework_TestCase
{
public function testCanReadConfigTitleFromConfigFile()
{
$expected='MySQLDumper';
$viewHelper = new Msd_View_Helper_GetConfigTitle();
$res = $viewHelper->getConfigTitle('mysqldumper');
$this->assertEquals(true, is_string($res));
$this->assertEquals($expected, $res);
}
public function testWillThrowExceptionOnInvalidConfigFile()
{
$viewHelper = new Msd_View_Helper_GetConfigTitle();
try {
$viewHelper->getConfigTitle('i_dont_exist');
} catch (Msd_Exception $e) {
$this->assertInstanceof('Msd_Exception', $e);
$expected = 'Couldn\'t read configuration file';
$this->assertEquals($expected, substr($e->getMessage(), 0, 32));
return;
}
$this->fail('An expected exception has not been raised.');
}
}

Datei anzeigen

@ -0,0 +1,37 @@
<?php
require_once 'PHPUnit/Framework/TestCase.php';
require_once 'GetIconSrc.php';
/**
* @group MsdViewHelper
*/
class GetIconSrcTest extends PHPUnit_Framework_TestCase
{
public function testGetIconSrcForIconWithoutSize()
{
$expected = '/css/msd/icons/openfile.gif';
$viewHelper = new Msd_View_Helper_GetIconSrc();
$res = $viewHelper->getIconSrc('openFile');
$this->assertEquals(true, is_string($res));
$this->assertEquals($expected, $res);
}
public function testGetIconSrcForIconWithSize()
{
$expected = '/css/msd/icons/16x16/Edit.png';
$viewHelper = new Msd_View_Helper_GetIconSrc();
$res = $viewHelper->getIconSrc('Edit', 16);
$this->assertEquals(true, is_string($res));
$this->assertEquals($expected, $res);
}
/**
* @expectedException Msd_Exception
*/
public function testFailGetNonExistantIcon()
{
$viewHelper = new Msd_View_Helper_GetIconSrc();
$res = $viewHelper->getIconSrc('nonExistantIcon', 16);
}
}

Datei anzeigen

@ -0,0 +1,64 @@
<?php
require_once 'PHPUnit/Framework/TestCase.php';
require_once 'GetIcon.php';
/**
* @group MsdViewHelper
*/
class GetIconTest extends PHPUnit_Framework_TestCase
{
public function testGetIconEdit()
{
$expected = '<img src="/css/msd/icons/16x16/Edit.png" '
.'alt="" title="" />';
$viewHelper = new Msd_View_Helper_GetIcon();
$res = $viewHelper->getIcon('Edit', '', 16);
$this->assertEquals($expected, $res);
}
public function testGetIconEditWithTitle()
{
$expected = '<img src="/css/msd/icons/16x16/Edit.png" alt="Titletest" '
.'title="Titletest" />';
$viewHelper = new Msd_View_Helper_GetIcon();
$res = $viewHelper->getIcon('Edit', 'Titletest', 16);
$this->assertEquals($expected, $res);
}
public function testGetIconInfoSize16()
{
$expected = '<img src="/css/msd/icons/16x16/Info.png" '
. 'alt="" title="" />';
$viewHelper = new Msd_View_Helper_GetIcon();
$res = $viewHelper->getIcon('Info', '', 16);
$this->assertEquals($expected, $res);
}
public function testGetIconInfoSize20()
{
$expected = '<img src="/css/msd/icons/20x20/Info.png" '
. 'alt="" title="" />';
$viewHelper = new Msd_View_Helper_GetIcon();
$res = $viewHelper->getIcon('Info', '', 20);
$this->assertEquals($expected, $res);
}
/**
* @expectedException Msd_Exception
*/
public function testFailGetNonExistantIcon()
{
$viewHelper = new Msd_View_Helper_GetIcon();
$viewHelper->getIcon('nonExistantIcon');
}
public function testGetIconWithoutSize()
{
$expected = '<img src="/css/msd/icons/minus.gif" '
. 'alt="" title="" />';
$viewHelper = new Msd_View_Helper_GetIcon();
$res = $viewHelper->getIcon('minus');
$this->assertEquals($expected, $res);
}
}

Datei anzeigen

@ -0,0 +1,29 @@
<?php
require_once 'PHPUnit/Framework/TestCase.php';
require_once 'GetServerProtocol.php';
/**
* @group MsdViewHelper
*/
class GetServerProtocolTest extends PHPUnit_Framework_TestCase
{
public function testGetServerProtocolHTTP()
{
$expected='http://';
$_SERVER['HTTPS'] = 'Off';
$viewHelper = new Msd_View_Helper_GetServerProtocol();
$res = $viewHelper->getServerProtocol();
$this->assertEquals($expected, $res);
}
public function testGetServerProtocolHTTPS()
{
$expected='https://';
$_SERVER['HTTPS'] = 'On';
$viewHelper = new Msd_View_Helper_GetServerProtocol();
$res = $viewHelper->getServerProtocol();
$this->assertEquals($expected, $res);
}
}

Datei anzeigen

@ -0,0 +1,30 @@
<?php
require_once 'PHPUnit/Framework/TestCase.php';
require_once 'IsTableOptimizable.php';
/**
* @group MsdViewHelper
*/
class IsTableOptimizableTest extends PHPUnit_Framework_TestCase
{
/**
* Tests if helper returns true for MyIsam-Engine
*/
public function testIsTableOptimizable()
{
$viewHelper = new Msd_View_Helper_IsTableOptimizable();
$res = $viewHelper->isTableOptimizable('MyISAM');
$this->assertEquals(true, $res);
}
/**
* Tests if helper returns false for CSV-Engine
*/
public function testFailIsTableOptimizable()
{
$viewHelper = new Msd_View_Helper_IsTableOptimizable();
$res = $viewHelper->isTableOptimizable('CSV');
$this->assertEquals(false, $res);
}
}

Datei anzeigen

@ -0,0 +1,18 @@
<?php
require_once 'PHPUnit/Framework/TestCase.php';
require_once 'JsEscape.php';
/**
* @group MsdViewHelper
*/
class JsEscapeTest extends PHPUnit_Framework_TestCase
{
public function testJsEscapeWithQuotes()
{
$expected = "test\'with\'quotes\'";
$viewHelper = new Msd_View_Helper_JsEscape();
$res = $viewHelper->jsEscape("test'with'quotes'");
$this->assertEquals($expected, $res);
}
}

Datei anzeigen

@ -0,0 +1,31 @@
<?php
require_once 'PHPUnit/Framework/TestCase.php';
require_once 'NumberFormat.php';
/**
* @group MsdViewHelper
*/
class NumberFormatTest extends PHPUnit_Framework_TestCase
{
public function testFormatNumberWithoutPrecision()
{
$viewHelper = new Msd_View_Helper_NumberFormat();
$res = $viewHelper->numberFormat(24.123456);
$this->assertEquals('24', $res);
}
public function testFormatNumberWithPrecision()
{
$viewHelper = new Msd_View_Helper_NumberFormat();
$res = $viewHelper->numberFormat(24.12356789, 3);
$this->assertEquals('24,124', $res);
}
public function testFailFormatNumberConversionToFloat()
{
$viewHelper = new Msd_View_Helper_NumberFormat();
$res = $viewHelper->numberFormat('AAA', 3);
$this->assertEquals('0,000', $res);
}
}

Datei anzeigen

@ -0,0 +1,42 @@
<?php
require_once 'PHPUnit/Framework/TestCase.php';
require_once 'Out.php';
/**
* @group MsdViewHelper
*/
class OutTest extends PHPUnit_Framework_TestCase
{
public function setUp()
{
$this->view = new Zend_View();
$helperPath = APPLICATION_PATH . DIRECTORY_SEPARATOR
. 'views' . DIRECTORY_SEPARATOR . 'helpers';
$this->view->addHelperPath($helperPath, 'Msd_View_Helper');
$viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer();
$viewRenderer->setView($this->view);
Zend_Controller_Action_HelperBroker::addHelper($viewRenderer);
}
public function testCanReturnOriginalValue()
{
$expected='test';
$res = $this->view->out('test');
$this->assertEquals($expected, $res);
}
public function testCanConvertNullValue()
{
$expected='NULL';
$res = $this->view->out(null, true);
$this->assertEquals($expected, $res);
}
public function testCanDecorateValue()
{
$expected='<i>NULL</i>';
$res = $this->view->out(null, true, 'i');
$this->assertEquals($expected, $res);
}
}

Datei anzeigen

@ -0,0 +1,203 @@
<?php
require_once 'PHPUnit/Framework/TestCase.php';
require_once 'Paginator.php';
/**
* @group MsdViewHelper
*/
class PaginatorTest extends PHPUnit_Framework_TestCase
{
/**
* @var Zend_View
*/
public $view = null;
public function setUp()
{
$this->view = new Zend_View();
$helperPath = implode(DIRECTORY_SEPARATOR, array(APPLICATION_PATH, 'views', 'helpers'));
$scriptPath = implode(DIRECTORY_SEPARATOR, array(APPLICATION_PATH, 'views', 'scripts'));
$this->view->addHelperPath($helperPath, 'Msd_View_Helper');
$this->view->setScriptPath($scriptPath);
$viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer();
$viewRenderer->setView($this->view);
Zend_Controller_Action_HelperBroker::addHelper($viewRenderer);
}
public function testOnChangeReturnsValidJavascriptCode()
{
$paginator = new Msd_View_Helper_Paginator();
$reflection = new ReflectionClass($paginator);
$method = $reflection->getMethod('_getOnChange');
$method->setAccessible(true);
$onChange = $method->invokeArgs($paginator, array('form'));
$this->assertEquals('$(this).parent().parent()[0].submit();', $onChange);
$onChange = $method->invokeArgs($paginator, array('url', '/sql/index/', 'pageNumber'));
$this->assertEquals("window.location.href = '/sql/index/pageNumber/' + this.value + '/';", $onChange);
$onChange = $method->invokeArgs($paginator, array('js', 'changePage(this.value);'));
$this->assertEquals('changePage(this.value);', $onChange);
}
public function testGetButtonClickReturnsValidJavascriptCode()
{
$paginator = new Msd_View_Helper_Paginator();
$reflection = new ReflectionClass($paginator);
$method = $reflection->getMethod('_getButtonClick');
$method->setAccessible(true);
$onChange = $method->invokeArgs(
$paginator,
array(
'form',
array('targetPage' => 2)
)
);
$this->assertEquals("$(this).parent().children('select').val(2); $(this).parent().parent()[0].submit();", $onChange);
$onChange = $method->invokeArgs(
$paginator,
array(
'url',
array('baseUrl' => '/sql/index/', 'urlParam' => 'pageNumber', 'targetPage' => 2)
)
);
$this->assertEquals("window.location.href = '/sql/index/pageNumber/2/';", $onChange);
$onChange = $method->invokeArgs(
$paginator,
array(
'js',
array('targetPage' => 2, 'onClick' => 'PHPUnitTest(:PAGE:);')
)
);
$this->assertEquals('PHPUnitTest(2);', $onChange);
}
public function testGetButtonInfoReturnsInformationForTheButtonState()
{
$paginator = new Msd_View_Helper_Paginator();
$reflection = new ReflectionClass($paginator);
$method = $reflection->getMethod('_getButtonInfo');
$method->setAccessible(true);
$buttonInfo = $method->invoke($paginator, false);
$this->assertArrayHasKey('icon', $buttonInfo);
$this->assertEmpty($buttonInfo['icon']);
$this->assertArrayHasKey('disabled', $buttonInfo);
$this->assertEmpty($buttonInfo['disabled']);
$buttonInfo = $method->invoke($paginator, true);
$this->assertArrayHasKey('icon', $buttonInfo);
$this->assertEquals('Disabled', $buttonInfo['icon']);
$this->assertArrayHasKey('disabled', $buttonInfo);
$this->assertEquals(' disabled="disabled"', $buttonInfo['disabled']);
}
public function testCanBuildAPaginatorWhichUsesJavascriptForPageSwitch()
{
$options = array(
'currentPage' => 1,
'pageCount' => 10,
'urlParam' => 'pageNr',
'baseUrl' => '/php/unit/test/',
'mode' => 'js',
'actions' => array(
'first' => 'first(:PAGE:);',
'prev' => 'prev(:PAGE:);',
'next' => 'next(:PAGE:);',
'last' => 'last(:PAGE:);',
'change' => 'change(this.value);',
),
);
$paginator = new Msd_View_Helper_Paginator();
$paginator->setView($this->view);
$result = $paginator->paginator($options);
$button = strpos($result, '<button class="Formbutton first" type="button" onclick="first(1);" accesskey="c" disabled="disabled">');
$this->assertNotEquals(false, $button);
$button = strpos($result, '<button class="Formbutton paginator prev" type="button" onclick="prev(0);" accesskey="v" disabled="disabled">');
$this->assertNotEquals(false, $button);
$button = strpos($result, '<select id="combobox" name="pageNr" onchange="change(this.value);" accesskey="b">');
$this->assertNotEquals(false, $button);
$button = strpos($result, '<button class="Formbutton next" type="button" onclick="next(2);" accesskey="n">');
$this->assertNotEquals(false, $button);
$button = strpos($result, '<button class="Formbutton last" type="button" onclick="last(10);" accesskey="m">');
$this->assertNotEquals(false, $button);
$button = strpos($result, '$("#combobox").combobox();');
$this->assertNotEquals(false, $button);
}
public function testCanBuildAPaginatorWhichUsesFormForPageSwitch()
{
$options = array(
'currentPage' => 1,
'pageCount' => 10,
'urlParam' => 'pageNr',
'baseUrl' => '/php/unit/test/',
'mode' => 'form',
);
$paginator = new Msd_View_Helper_Paginator();
$paginator->setView($this->view);
$result = $paginator->paginator($options);
$button = strpos($result, '<button class="Formbutton first" type="submit" onclick="$(this).parent().children(\'select\').val(1); $(this).parent().parent()[0].submit();" accesskey="c" disabled="disabled">');
$this->assertNotEquals(false, $button);
$button = strpos($result, '<button class="Formbutton paginator prev" type="submit" onclick="$(this).parent().children(\'select\').val(0); $(this).parent().parent()[0].submit();" accesskey="v" disabled="disabled">');
$this->assertNotEquals(false, $button);
$button = strpos($result, '<select id="combobox" name="pageNr" onchange="$(this).parent().parent()[0].submit();" accesskey="b">');
$this->assertNotEquals(false, $button);
$button = strpos($result, '<button class="Formbutton next" type="submit" onclick="$(this).parent().children(\'select\').val(2); $(this).parent().parent()[0].submit();" accesskey="n">');
$this->assertNotEquals(false, $button);
$button = strpos($result, '<button class="Formbutton last" type="submit" onclick="$(this).parent().children(\'select\').val(10); $(this).parent().parent()[0].submit();" accesskey="m">');
$this->assertNotEquals(false, $button);
$button = strpos($result, '$("#combobox").combobox();');
$this->assertNotEquals(false, $button);
}
public function testCanBuildAPaginatorWhichUsesUrlsForPageSwitch()
{
$options = array(
'currentPage' => 1,
'pageCount' => 10,
'urlParam' => 'pageNr',
'baseUrl' => '/php/unit/test/',
'mode' => 'url',
);
$paginator = new Msd_View_Helper_Paginator();
$paginator->setView($this->view);
$result = $paginator->paginator($options);
$button = strpos($result, '<button class="Formbutton first" type="button" onclick="window.location.href = \'/php/unit/test/pageNr/1/\';" accesskey="c" disabled="disabled">');
$this->assertNotEquals(false, $button);
$button = strpos($result, '<button class="Formbutton paginator prev" type="button" onclick="window.location.href = \'/php/unit/test/pageNr/0/\';" accesskey="v" disabled="disabled">');
$this->assertNotEquals(false, $button);
$button = strpos($result, '<select id="combobox" name="pageNr" onchange="window.location.href = \'/php/unit/test/pageNr/\' + this.value + \'/\';" accesskey="b">');
$this->assertNotEquals(false, $button);
$button = strpos($result, '<button class="Formbutton next" type="button" onclick="window.location.href = \'/php/unit/test/pageNr/2/\';" accesskey="n">');
$this->assertNotEquals(false, $button);
$button = strpos($result, '<button class="Formbutton last" type="button" onclick="window.location.href = \'/php/unit/test/pageNr/10/\';" accesskey="m">');
$this->assertNotEquals(false, $button);
$button = strpos($result, '$("#combobox").combobox();');
$this->assertNotEquals(false, $button);
}
}

Datei anzeigen

@ -0,0 +1,27 @@
<?php
require_once 'PHPUnit/Framework/TestCase.php';
require_once 'TimeToDate.php';
/**
* @group MsdViewHelper
*/
class TimeToDateTest extends PHPUnit_Framework_TestCase
{
public function testTimeToDate()
{
$expected='27.08.2010 00:49:48';
$viewHelper = new Msd_View_Helper_TimeToDate();
$res = $viewHelper->timeToDate('2010-08-27T00:49:48+02:00');
$this->assertEquals($expected, $res);
}
public function testInvalidTimeToDate()
{
$viewHelper = new Msd_View_Helper_TimeToDate();
$res = $viewHelper->timeToDate('an invalid date timestamp');
$this->assertEquals(
'No date part in \'an invalid date timestamp\' found.', $res
);
}
}

Datei anzeigen

@ -0,0 +1,53 @@
<?php
/**
* @group Auth
*/
class Msd_Auth_Adapter_IniTest extends PHPUnit_Framework_TestCase
{
public $iniPath = null;
public $userIni = null;
public function setUp()
{
$this->iniPath = APPLICATION_PATH . DS .'configs';
$this->userIni = $this->iniPath . DS . 'users.ini';
}
public function testThrowsExceptionIfInvokedWithNonExistantIniFile()
{
try {
new Msd_Auth_Adapter_Ini(
$this->iniPath . '/I_dont_exist.ini'
);
} catch (Msd_Exception $e) {
$res = 'INI file with authentication information doesn\'t exists!';
$this->assertEquals($res, $e->getMessage());
return;
}
$this->fail('An expected exception has not been raised.');
}
public function testThrowsExceptionIfUsernameIsNull()
{
$authAdapter = new Msd_Auth_Adapter_Ini($this->userIni);
$authAdapter->setUsername(null);
try {
$authAdapter->authenticate();
} catch (Msd_Exception $e) {
$res = 'You must set the username and password first!';
$this->assertEquals($res, $e->getMessage());
return;
}
$this->fail('An expected exception has not been raised.');
}
public function testCanFailAuthIfCredentialsAreWrong()
{
$authAdapter = new Msd_Auth_Adapter_Ini($this->userIni);
$authAdapter->setUsername('iDontExist');
$authAdapter->setPassword('iAmWrong');
$authResult = $authAdapter->authenticate();
$res = $authResult->getCode();
$this->assertEquals($res, Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID);
}
}

Datei anzeigen

@ -0,0 +1,23 @@
<?php
/**
* @group configuration
*/
class Msd_ConfigurationPhpValuesTest extends PHPUnit_Framework_TestCase
{
public function testCanFallbackTo30SecondsExecutionTime()
{
ini_set('max_execution_time', 31);
$dynamicValues = Msd_ConfigurationPhpValues::getDynamicValues();
$this->assertEquals(30, $dynamicValues->maxExecutionTime);
}
public function testCanFallbackTo16MbRam()
{
$activeValue = ini_get('memory_limit');
ini_set('memory_limit', '15M');
$dynamicValues = Msd_ConfigurationPhpValues::getDynamicValues();
// reset value to not break tests
ini_set('memory_limit', $activeValue);
$this->assertEquals(16, $dynamicValues->phpRam);
}
}

Datei anzeigen

@ -0,0 +1,237 @@
<?php
/**
* @group configuration
*/
class Msd_ConfigurationTest extends ControllerTestCase
{
public static function setUpBeforeClass()
{
Testhelper::copyFile('mysqldumper.ini', CONFIG_PATH . DS .'mysqldumper.ini');
Testhelper::copyFile('mysqldumper2.ini', CONFIG_PATH . DS .'mysqldumper2.ini');
}
public static function tearDownAfterClass()
{
Testhelper::removeFile(CONFIG_PATH . DS . 'mysqldumper2.ini');
}
public function setUp()
{
$this->loginUser();
}
public function testThrowsExceptionOnCloning()
{
$config = Msd_Configuration::getInstance();
try {
clone($config);
} catch (Exception $e) {
$this->assertInstanceof('Msd_Exception', $e);
return;
}
$this->fail('An expected exception has not been raised.');
}
public function testCanSetValues()
{
$config = Msd_Configuration::getInstance();
$config->set('config.testval', 999);
$this->assertEquals(999, $config->get('config.testval'));
$config->set('config.interface.testval2', 999);
$this->assertEquals(999, $config->get('config.interface.testval2'));
}
/**
* @expectedException Msd_Exception
*/
public function testCanThrowExceptionOnSettingIllegalValue()
{
$config = Msd_Configuration::getInstance();
$config->set('config.t.r.t.v', 999);
}
public function testCanReloadConfig()
{
$config = Msd_Configuration::getInstance();
$config->set('config.general.dbDelete', 'y'); //defaults to 'n'
$this->assertEquals('y', $config->get('config.general.dbDelete'));
$config->reloadConfig();
$this->assertEquals('n', $config->get('config.general.dbDelete'));
}
public function testCanGetValuesFromConfiguration()
{
$config = Msd_Configuration::getInstance();
// get complete config-array
$values = $config->get('config');
$this->assertArrayHasKey('interface', $values);
$this->assertArrayHasKey('dbuser', $values);
$this->assertArrayHasKey('cronscript', $values);
$this->assertArrayHasKey('cronscript', $values);
$this->assertArrayHasKey('ftp', $values);
$this->assertArrayHasKey('email', $values);
$this->assertArrayHasKey('autodelete', $values);
$this->assertArrayHasKey('general', $values);
//check some nested keys in different levels
$values = $config->get('config.general');
$this->assertArrayHasKey('mode', $values);
$this->assertArrayHasKey('title', $values);
$this->assertArrayHasKey('optimize', $values);
$value = $config->get('config.general.dbDelete');
$this->assertEquals('n', $value);
$values = $config->get('config.ftp.0');
$this->assertArrayHasKey('use', $values);
$this->assertArrayHasKey('server', $values);
$this->assertArrayHasKey('user', $values);
$value = $config->get('config.ftp.0.timeout');
$this->assertEquals(10, $value);
}
public function testCanReturnNullOnNonExistantConfigKey()
{
$config = Msd_Configuration::getInstance();
$value = $config->get('config.IDont.Exist');
$this->assertEquals(null, $value);
}
public function testCanThrowExceptionOnSettingIncorrectValue()
{
$config = Msd_Configuration::getInstance();
try {
$config->set('testval', 999);
} catch (Exception $e) {
$this->assertInstanceof('Msd_Exception', $e);
return;
}
$this->fail('An expected exception has not been raised.');
}
public function testCanThrowExceptionOnGettingIncorrectValue()
{
$config = Msd_Configuration::getInstance();
try {
$config->get('testval', 999);
} catch (Exception $e) {
$this->assertInstanceof('Msd_Exception', $e);
return;
}
$this->fail('An expected exception has not been raised.');
}
public function testCanLoadConfigFromSessionOnSameRequest()
{
$config = Msd_Configuration::getInstance();
$config->set('config.testval', 888);
$config->saveConfigToSession();
unset($config);
$config = Msd_Configuration::getInstance();
$config->loadConfigFromSession();
$this->assertEquals(888, $config->get('config.testval'));
// test constructor; should get filename and data from session
Msd_Configuration::getInstance();
}
public function testCanLoadConfiguration()
{
$config = Msd_Configuration::getInstance('mysqldumper', true);
$this->assertEquals('mysqldumper', $config->get('dynamic.configFile'));
// load another configuration and set values to actual session
$config->loadConfiguration('mysqldumper2', true);
$this->assertEquals('mysqldumper2', $config->get('dynamic.configFile'));
}
public function testCanLoadConfigWithoutApplying()
{
$config = Msd_Configuration::getInstance('mysqldumper', true);
$this->assertEquals('mysqldumper', $config->get('dynamic.configFile'));
// load data from another config file but without using it
$configData = $config->loadConfiguration('mysqldumper2', false);
$this->assertInstanceOf('Zend_Config_Ini', $configData);
$this->assertEquals(
'MySQLDumper2',
$configData->general->title
);
$this->assertEquals(
'pl',
$configData->cronscript->perlExtension
);
// make sure the actual config didn't change
$this->assertEquals('mysqldumper', $config->get('dynamic.configFile'));
}
public function testThrowsExceptionOnLoadNonExistantConfigfile()
{
$config = Msd_Configuration::getInstance();
try {
$config->loadConfiguration('IDontExist');
} catch (Exception $e) {
$this->assertInstanceof('Msd_Exception', $e);
return;
}
$this->fail('An expected exception has not been raised.');
}
public function testCanGetConfigTitle()
{
$config = Msd_Configuration::getInstance();
$config->loadConfiguration('mysqldumper');
$title = $config->getTitle();
$this->assertEquals('MySQLDumper', $title);
$config->loadConfiguration('mysqldumper2');
$title = $config->getTitle();
$this->assertEquals('MySQLDumper2', $title);
}
/**
* @depends testCanLoadConfiguration
*/
public function testCanSaveConfiguration()
{
$config = Msd_Configuration::getInstance();
$config->loadConfiguration('mysqldumper2');
// change a value
$config->set('config.cronscript.Path', 'IAmAPath');
$config->save('mysqldumper2');
// reload it and check changed val
$config->loadConfiguration('mysqldumper2');
$this->assertEquals('IAmAPath', $config->get('config.cronscript.Path'));
// change val again
$config->set('config.cronscript.Path', 'IDiffer');
// now save without giving the filename; should be taken from session
$config->save();
// reload it and again check changed val
$config->loadConfiguration('mysqldumper2');
$this->assertEquals('IDiffer', $config->get('config.cronscript.Path'));
// reset val for further tests
$config->set('config.cronscript.Path', '');
$config->save();
}
/**
* @depends testCanSaveConfiguration
*/
public function testCanSaveConfigFromArray()
{
$config = Msd_Configuration::getInstance();
$config->loadConfiguration('mysqldumper2');
// change title and save as new file
$config->set('config.general.title', 'MySQLDumper3');
$configData =$config->get('config');
$this->assertTrue(is_array($configData));
$config->save('mysqldumper3', $configData);
$configFile = $config->get('paths.config').'/mysqldumper3.ini';
$this->assertFileExists($configFile);
$config->loadConfiguration('mysqldumper3');
$title = $config->get('config.general.title');
$this->assertEquals('MySQLDumper3', $title);
Testhelper::removeFile(CONFIG_PATH . DS . 'mysqldumper3.ini');
}
}

Datei anzeigen

@ -0,0 +1,36 @@
<?php
/**
* @group database
*/
class Msd_DbTest extends ControllerTestCase
{
public function setUp()
{
$this->loginUser();
}
public function testCanGetMysqliInstance()
{
$dbo = Msd_Db::getAdapter();
$this->assertInstanceOf('Msd_Db_Mysqli', $dbo);
}
public function testCanGetMysqlInstance()
{
$dbo = Msd_Db::getAdapter(null, true);
$this->assertInstanceOf('Msd_Db_Mysql', $dbo);
}
public function testThrowsExceptionOnInvalidQuery()
{
$dbo = Msd_Db::getAdapter();
try {
$dbo->query('I am not a valid query');
} catch (Exception $e) {
$this->assertInstanceOf('Msd_Exception', $e);
$this->assertEquals(1064, $e->getCode());
return;
}
$this->fail('An expected exception has not been raised.');
}
}

Datei anzeigen

@ -0,0 +1,32 @@
<?php
/**
* @group Files
*/
class Msd_FileTest extends PHPUnit_Framework_TestCase
{
public function testCanGetChmodValueOfFile()
{
$valid = array('0644', '664', '666', '0755', '0777');
$res = Msd_File::getChmod(CONFIG_PATH . '/mysqldumper.ini');
$this->assertTrue(in_array($res, $valid));
}
public function testCanGetConfigurationNames()
{
$configNames = Msd_File::getConfigNames();
$this->assertNotEmpty($configNames);
$this->assertTrue(in_array('mysqldumper', $configNames));
}
public function testRetrunsEmptyArrayIfPathIsNotReadable()
{
$config = Msd_Configuration::getInstance();
$oldPath = $config->get('paths.config');
$config->set('paths.config', '/I/Dont/Exist');
$configNames = Msd_File::getConfigNames();
$config->set('paths.config', $oldPath);
$this->assertTrue(is_array($configNames));
$this->assertEmpty($configNames);
}
}

Datei anzeigen

@ -0,0 +1,86 @@
<?php
/**
* @group html
*/
class Msd_HtmlTest extends PHPUnit_Framework_TestCase
{
public function testCanConvertNewLines()
{
$expected = 'alert("hello");\nalert("hello2");';
$res = Msd_Html::getJsQuote("alert(\"hello\");\nalert(\"hello2\");", false);
$this->assertEquals($expected, $res);
}
public function testCanBuildJsQuotedStringAndEscapesSlashes()
{
$expected = 'alert(\"hello\/\");';
$res = Msd_Html::getJsQuote('alert("hello/");', true);
$this->assertEquals($expected, $res);
}
public function testCanCreatePrefixArray()
{
$array = array(
'name_one' => 1,
'name_two' => 1,
'name_three' => 1,
'name2_one' => 1,
'name2_two' => 1,
'name2_three' => 1,
'name3' => 1,
'name4_one' => 1,
'name4_two' => 1
);
$res = Msd_Html::getPrefixArray($array);
$expected = array(
'name' => 'name',
'name2' => 'name2',
'name4' => 'name4'
);
$this->assertSame($expected, $res);
}
public function testCanBuildHtmlOptions()
{
$options = array(
'first' => 0,
'second' => 1,
'third' => 2
);
$res = Msd_Html::getHtmlOptions($options, '', false);
$expected = "<option value=\"first\">0</option>\n"
. "<option value=\"second\">1</option>\n"
."<option value=\"third\">2</option>\n";
$this->assertSame($expected, $res);
}
public function testCanBuildHtmlOptionsWithSeletedOption()
{
$options = array(
'first' => 0,
'second' => 1,
'third' => 2
);
$res = Msd_Html::getHtmlOptions($options, 'second', false);
$expected = "<option value=\"first\">0</option>\n"
. "<option value=\"second\" selected=\"selected\">1</option>\n"
. "<option value=\"third\">2</option>\n";
$this->assertSame($expected, $res);
}
public function testCanBuildHtmlOptionsAndShowAllOption()
{
$options = array(
'first' => 0,
'second' => 1,
'third' => 2
);
$res = Msd_Html::getHtmlOptions($options, 'second', true);
$expected = "<option value=\"\">---</option>\n"
. "<option value=\"first\">0</option>\n"
. "<option value=\"second\" selected=\"selected\">1</option>\n"
. "<option value=\"third\">2</option>\n";
$this->assertSame($expected, $res);
}
}

Datei anzeigen

@ -0,0 +1,121 @@
<?php
/**
* @group language
*/
class Msd_LanguageTest extends ControllerTestCase
{
private $_lang = null;
private $_translator = null;
private $_languages = array();
public function setUp()
{
$this->_lang = Msd_Language::getInstance();
$this->_translator = $this->_lang->getTranslator();
$this->_languages = $this->_lang->getAvailableLanguages();
}
public function testCanGetInstance()
{
$this->assertInstanceOf('Msd_Language', $this->_lang);
}
public function testCanGetTranslator()
{
$this->assertInstanceOf('Zend_Translate', $this->_translator);
}
public function testCanLoadLanguageEn()
{
$this->_lang->loadLanguage('en');
$this->assertEquals('yes', $this->_translator->translate('L_YES'));
}
public function testCanLoadLanguageDe()
{
$this->_lang->loadLanguage('de');
$this->assertEquals('ja', $this->_translator->translate('L_YES'));
}
public function testCanLoadAndTranslateAllLanguageFiles()
{
$languages = array_keys($this->_languages);
foreach ($languages as $language) {
$this->_lang->loadLanguage($language);
$this->assertNotEquals(
'L_YES',
$this->_translator->translate('L_YES')
);
}
}
public function testCanUseMagicGetter()
{
$this->_lang->loadLanguage('de');
$this->assertEquals('ja', $this->_lang->L_YES);
}
public function testCanLoadLanguageList()
{
$isArray = is_array($this->_languages);
$this->assertEquals(true, $isArray);
}
public function testLanguageKeyExists()
{
$languages = array('ar', 'bg_BG', 'cs', 'da', 'de', 'de_CH', 'de_LU',
'el', 'en', 'es', 'fa', 'fr', 'it', 'nl', 'pl', 'pt_BR', 'ro', 'ru',
'sk', 'sl', 'sv_SE', 'tr', 'vi_VN'
);
foreach ($languages as $language) {
$this->assertArrayHasKey($language, $this->_languages);
}
}
public function testReturnsOriginalInputForUnsetValues()
{
$this->assertEquals(
'No Translation',
$this->_translator->translate('No Translation')
);
}
public function testCanTranslateZendIds()
{
$this->_lang->loadLanguage("de");
$zendmessageId = 'emailAddressInvalidFormat';
$translation = $this->_lang->translateZendId($zendmessageId);
$this->assertEquals(
"Das Format der E-Mail-Adresse ist ungültig.",
$translation
);
}
public function testWontTranslateAlreadyTranslatedZendIds()
{
$this->_lang->loadLanguage("de");
$zendmessageId = 'accessFilter';
$translation = $this->_lang->translateZendId($zendmessageId, 'accessFilter');
$this->assertEquals("accessFilter", $translation
);
}
public function testReturnsUntranslatedStringWithoutPrefixIfMessageIsUnknown()
{
$this->_lang->loadLanguage("de");
$res = $this->_lang->L_IDONTEXIST;
$this->assertEquals("IDONTEXIST", $res);
}
public function testForbidsCloning()
{
try {
clone($this->_lang);
} catch (Msd_Exception $e) {
$res = 'Cloning of Msd_Language is not allowed!';
$this->assertEquals($res, $e->getMessage());
return;
}
$this->fail('An expected exception has not been raised.');
}
}

Datei anzeigen

@ -0,0 +1,71 @@
<?php
/**
* @group Log
*/
class Msd_LogTest extends PHPUnit_Framework_TestCase
{
public function testCanGetLogger()
{
$logger = new Msd_Log();
$this->assertInstanceof('Msd_Log', $logger);
}
public function testCanGetFilePathOfLoggerType()
{
$logger = new Msd_Log();
$this->assertInstanceof('Msd_Log', $logger);
$logPath = $logger->getFile(Msd_Log::PHP);
$this->assertEquals(WORK_PATH . '/log/php.log', $logPath);
$logPath = $logger->getFile(Msd_Log::PERL);
$this->assertEquals(WORK_PATH . '/log/perl.log', $logPath);
$logPath = $logger->getFile(Msd_Log::PERL_COMPLETE);
$this->assertEquals(WORK_PATH . '/log/perlComplete.log', $logPath);
$logPath = $logger->getFile(Msd_Log::ERROR);
$this->assertEquals(WORK_PATH . '/log/phpError.log', $logPath);
}
public function testCanGetLoggerOfGivenType()
{
$logger = new Msd_Log();
$this->assertInstanceof('Msd_Log', $logger);
$loggerTypes = array(
Msd_Log::PHP => WORK_PATH . '/log/php.log',
Msd_Log::PERL => WORK_PATH . '/log/perl.log',
Msd_Log::PERL_COMPLETE => WORK_PATH . '/log/perlComplete.log',
Msd_Log::ERROR => WORK_PATH . '/log/phpError.log',
);
foreach ($loggerTypes as $logType => $logPath) {
$this->assertInstanceof('Zend_Log', $logger->getLogInstance($logType));
$this->assertEquals($logger->getFile($logType), $logPath);
}
}
public function testClosesFileHandlesOnDestroy()
{
$logger = new Msd_Log();
$this->assertInstanceof('Msd_Log', $logger);
$loggerTypes = array(
Msd_Log::PHP => WORK_PATH . '/log/php.log',
Msd_Log::PERL => WORK_PATH . '/log/perl.log',
Msd_Log::PERL_COMPLETE => WORK_PATH . '/log/perlComplete.log',
Msd_Log::ERROR => WORK_PATH . '/log/phpError.log',
);
foreach ($loggerTypes as $logType => $logPath) {
$this->assertInstanceof('Zend_Log', $logger->getLogInstance($logType));
$this->assertEquals($logger->getFile($logType), $logPath);
}
unset($logger);
}
public function testCanWriteToLogFile()
{
$res = Msd_Log::write(Msd_Log::PHP, 'test message');
print_r($res);
}
}

Datei anzeigen

@ -0,0 +1,68 @@
<?php
if (get_current_user() != 'root') {
include_once(TEST_PATH . '/unit/library/Msd/Validate/File/AccessibleTest.php');
// Exclude this test if called via cli.
// phpunit seems to always run as user "root", no matter how we call it.
// If we call phpunti from Jenkins (which has its own user) via Ant phpunit
// is executed as root. If we call it from the shell as user "msd", phpunit is
// run as root. I didn't find a way to let phpunit run as another user.
//
// Of course the user root can always set chmod values, so these tests
// wouldn't make sense. To get rid of the nasty "skipped test"
// messages if working in the shell, I only let phpunit execute these tests
// if it is not running as root.
// After excluding and/or blacklisting this file in phpunit.xml didn't work either
// I am upset and simply want to get rid of this.
// S. Bergmann, you have taken away hours of my time because things
// doesn't work the way they are described in your documentation.
// Better hope we will not meet again in real life. ;)
class Msd_Validate_File_NonRootAccessibleTest extends Msd_Validate_File_AccessibleTest
{
public function testCanDetectIfFileIsNotReadable()
{
if (get_current_user() == 'root') {
$this->markTestIncomplete('This test can not be run as user root.');
return;
}
$this->chmod(0100);
$this->validator->setOptions(array('accessTypes' => "read"));
$this->assertEquals(false, $this->validator->isValid($this->_testFile));
}
public function testCanDetectIfFileIsNotWritable()
{
if (get_current_user() == 'root') {
$this->markTestIncomplete('This test can not be run as user root.');
return;
}
$this->chmod(0400);
$this->validator->setOptions(array('accessTypes' => "write"));
$this->assertEquals(false, $this->validator->isValid($this->_testFile));
}
public function testCanDetectIfDirIsNotReadable()
{
if (get_current_user() == 'root') {
$this->markTestIncomplete('This test can not be run as user root.');
return;
}
$this->chmod(0100, $this->_testDir);
$this->validator->setOptions(array('accessTypes' => "dir,read"));
$this->assertEquals(false, $this->validator->isValid($this->_testDir));
$this->chmod(0700, $this->_testDir);
}
public function testCanDetectIfDirIsNotWritable()
{
if (get_current_user() == 'root') {
$this->markTestIncomplete('This test can not be run as user root.');
return;
}
$this->chmod(0400, $this->_testDir);
$this->validator->setOptions(array('accessTypes' => "dir,write"));
$this->assertEquals(false, $this->validator->isValid($this->_testDir));
$this->chmod(0700, $this->_testDir);
}
}
}

Datei anzeigen

@ -0,0 +1,236 @@
<?php
/**
* @group validate
*/
class Msd_Validate_File_AccessibleTest extends PHPUnit_Framework_TestCase
{
/**
* @var string Path to test files
*/
protected $_testFile = '';
/**
* @var string Path to test files
*/
protected $_testDir = '';
/**
* @var Msd_Validate_File_Accessible
*/
protected $validator = null;
public function setUp()
{
parent::setUp();
$this->_testDir = TEST_PATH . DS . 'fixtures' . DS . 'tmp';
if (!file_exists($this->_testDir)) {
mkdir($this->_testDir, 0777);
$this->chmod(0777, $this->_testDir);
}
$this->_testFile = $this->_testDir . '/testFile.sh';
if (!file_exists($this->_testFile)) {
file_put_contents($this->_testFile, "#!/bin/sh\necho 'Executed'\n");
$this->chmod(0777);
}
$this->validator = new Msd_Validate_File_Accessible();
}
/**
* Chmod _testFile to given value
*
* @param string $rights Octal rights
* @param bool $file FileName
* @return void
*/
public function chmod($rights, $file = false)
{
if ($file === false) {
$file = $this->_testFile;
}
$chmod = chmod($file, $rights);
clearstatcache();
if ($chmod === false) {
$this->fail('Couldn\'t chmod ' . $file . ' to ' . $rights);
}
}
public function testCanDetectIfFileExists()
{
$this->chmod(0400);
$this->assertEquals(true, $this->validator->isValid($this->_testFile));
}
public function testCanDetectIfFileDoesNotExists()
{
$file = $this->_testDir . '/IDontExist.txt';
$this->assertEquals(false, $this->validator->isValid($file));
}
public function testCanDetectIfFileIsReadable()
{
$this->chmod(0400);
$this->validator->setOptions(array('accessTypes' => "read"));
$this->assertEquals(true, $this->validator->isValid($this->_testFile));
}
public function testCanDetectIfFileIsWritable()
{
$this->chmod(0200);
$this->validator->setOptions(array('accessTypes' => "write"));
$this->assertEquals(true, $this->validator->isValid($this->_testFile));
}
public function testCanDetectIfFileIsExecutable()
{
$this->chmod(0100);
$this->validator->setOptions(array('accessTypes' => "execute"));
$this->assertEquals(true, $this->validator->isValid($this->_testFile));
}
public function testCanDetectIfFileIsNotExecutable()
{
$this->chmod(0400);
$this->validator->setOptions(array('accessTypes' => "execute"));
$this->assertEquals(false, $this->validator->isValid($this->_testFile));
}
public function testCanDetectIfFileIsDir()
{
$this->chmod(0777, $this->_testDir);
$this->validator->setOptions(array('accessTypes' => "dir"));
$this->assertEquals(true, $this->validator->isValid($this->_testDir));
}
public function testCanDetectIfFileIsNotDir()
{
$this->validator->setOptions(array('accessTypes' => "dir"));
$this->assertEquals(false, $this->validator->isValid($this->_testFile));
}
public function testCanDetectIfFileIsFile()
{
$this->chmod(0700);
$this->validator->setOptions(array('accessTypes' => "file"));
$this->assertEquals(true, $this->validator->isValid($this->_testFile));
}
public function testCanDetectIfFileIsNotAFile()
{
$this->chmod(0700, $this->_testDir);
$this->validator->setOptions(array('accessTypes' => "file"));
$this->assertEquals(false, $this->validator->isValid($this->_testDir));
}
public function testCanDetectIfFileIsNotUploaded()
{
$this->chmod(0700);
$this->validator->setOptions(array('accessTypes' => "uploaded"));
$this->assertEquals(false, $this->validator->isValid($this->_testFile));
}
public function testCanDetectIfDirIsReadable()
{
$this->chmod(0400, $this->_testDir);
$this->validator->setOptions(array('accessTypes' => "dir,read"));
$this->assertEquals(true, $this->validator->isValid($this->_testDir));
$this->chmod(0700, $this->_testDir);
}
public function testCanDetectIfDirIsWritable()
{
$this->chmod(0200, $this->_testDir);
$this->validator->setOptions(array('accessTypes' => "dir,write"));
$this->assertEquals(true, $this->validator->isValid($this->_testDir));
$this->chmod(0700, $this->_testDir);
}
public function testCanSetOptionsWithAccessTypesAsString()
{
$this->validator->setOptions(
array(
'pathPrefix' => './',
'accessTypes' => 'read,write'
)
);
$options = $this->validator->getOptions();
$this->assertInternalType('array', $options);
$this->assertArrayHasKey('pathPrefix', $options);
$this->assertEquals('./', $options['pathPrefix']);
$this->assertInternalType('array', $options['accessTypes']);
$this->assertTrue($options['accessTypes']['read']);
$this->assertTrue($options['accessTypes']['write']);
}
public function testCanSetOptionsWithAccessTypesAsZendConfig()
{
$this->validator->setOptions(
array(
'pathPrefix' => './',
'accessTypes' => new Zend_Config(array('read', 'write')),
)
);
$options = $this->validator->getOptions();
$this->assertInternalType('array', $options);
$this->assertArrayHasKey('pathPrefix', $options);
$this->assertEquals('./', $options['pathPrefix']);
$this->assertInternalType('array', $options['accessTypes']);
$this->assertTrue($options['accessTypes']['read']);
$this->assertTrue($options['accessTypes']['write']);
}
public function testCanSetOptionsWithAccessTypesAsArray()
{
$this->validator->setOptions(
array(
'pathPrefix' => './',
'accessTypes' => array('read', 'write'),
)
);
$options = $this->validator->getOptions();
$this->assertInternalType('array', $options);
$this->assertArrayHasKey('pathPrefix', $options);
$this->assertEquals('./', $options['pathPrefix']);
$this->assertInternalType('array', $options['accessTypes']);
$this->assertTrue($options['accessTypes']['read']);
$this->assertTrue($options['accessTypes']['write']);
}
public function testClassConstructorSetsOptions()
{
$validator = new Msd_Validate_File_Accessible(
array(
'pathPrefix' => './',
'accessTypes' => array('read', 'write'),
)
);
$options = $validator->getOptions();
$this->assertInternalType('array', $options);
$this->assertArrayHasKey('pathPrefix', $options);
$this->assertEquals('./', $options['pathPrefix']);
$this->assertInternalType('array', $options['accessTypes']);
$this->assertTrue($options['accessTypes']['read']);
$this->assertTrue($options['accessTypes']['write']);
}
/**
* @expectedException Msd_Validate_Exception
*/
public function testThrowsExceptionIfOptionsArgumentIsNotAnArray()
{
$this->validator->setOptions('Go test and throw the exception.');
}
/**
* @expectedException Msd_Validate_Exception
*/
public function testThrowsExceptionIfAccessTypesOptionIsAnInvalidVariableType()
{
$this->validator->setOptions(array('accessTypes' => new stdClass()));
}
}

Datei anzeigen

@ -0,0 +1,38 @@
<?php
/**
* @group configuration
*/
class Msd_VersionTest extends PHPUnit_Framework_TestCase
{
public $version = null;
public function setUp()
{
$this->version = new Msd_Version();
$options = array(
'requiredPhpVersion' => '99.99.99',
'requiredMysqlVersion' => '99.99.99'
);
$this->oldVersion = new Msd_Version($options);
}
public function testCanGetRequiredPhpVersion()
{
$this->assertEquals('5.2.0', $this->version->getRequiredPhpVersion());
}
public function testCanDetectOldPhpVersion()
{
$this->assertEquals(false, $this->oldVersion->checkPhpVersion());
}
public function testCanGetRequiredMysqlVersion()
{
$this->assertEquals('4.1.2', $this->version->getRequiredMysqlVersion());
}
public function testCanDetectOldMysqlVersion()
{
$this->assertEquals(false, $this->oldVersion->checkMysqlVersion());
}
}