Merge branch 'feature/test-base-class-4608'

resolves #4608
This commit is contained in:
Matthias Jentsch 2013-08-27 18:01:23 +02:00
commit a9452d30e7
13 changed files with 1207 additions and 463 deletions

View File

@ -1,14 +1,13 @@
Testing guide # Testing guide
=============
## Testing controllers for compatibility with different monitoring datasources
Testing controllers for compatibility with different monitoring datasources
---------------------------------------------------------------------------
When it comes to writing controllers, it is important that your actions and queries work on every monitoring When it comes to writing controllers, it is important that your actions and queries work on every monitoring
datasource supported by icinga2 web. For this, the monitoring module provides a test library for controllers. datasource supported by icinga2 web. For this, the monitoring module provides a test library for controllers.
The database setup for every testcase ## The database setup for every testcase
--------------------------------------
When testing PostgreSQL and MySQL databases, the test library (normally) executes the following test procedure for every When testing PostgreSQL and MySQL databases, the test library (normally) executes the following test procedure for every
test case: test case:
@ -21,8 +20,7 @@ test case:
If anything goes wrong during this procedure, the test will be skipped (because maybe you don't have a pgsql database, but If anything goes wrong during this procedure, the test will be skipped (because maybe you don't have a pgsql database, but
want to test mysql, for example) want to test mysql, for example)
Setting up a test user and database in MySQL ## Setting up a test user and database in MySQL
--------------------------------------------
In MySQL, it's best to create a user icinga_unittest@localhost, a database icinga_unittest and grant all privileges on In MySQL, it's best to create a user icinga_unittest@localhost, a database icinga_unittest and grant all privileges on
this database: this database:
@ -34,8 +32,7 @@ this database:
mysql> FLUSH PRIVILEGES; mysql> FLUSH PRIVILEGES;
mysql> quit mysql> quit
Setting up a test user and database in PostgreSQL ## Setting up a test user and database in PostgreSQL
-------------------------------------------------
In PostgreSQL, you have to modify the pg_hba database if you don't have password authentication set up (which often is In PostgreSQL, you have to modify the pg_hba database if you don't have password authentication set up (which often is
the case). In this setup the icinga_unittest user is set to trust authentication on localhost, which means that no the case). In this setup the icinga_unittest user is set to trust authentication on localhost, which means that no
@ -48,9 +45,69 @@ password is queried when connecting from the local machine:
postgres=# \q postgres=# \q
bash$ createlang plpgsql icinga; bash$ createlang plpgsql icinga;
## Writing tests for icinga
Writing tests for controllers Icinga has it's own base test which lets you easily require libraries, testing database and form functionality. The class resides in
----------------------------- library/Icinga/Test. If you write a test, just subclass BaseTestCase.
### Default test header
Before writing a test you should include the base test first
// @codingStandardsIgnoreStart
require_once realpath(__DIR__ . '/../../../../../library/Icinga/Test/BaseTestCase.php');
// @codingStandardsIgnoreEnd
Now you can simply include dependencies with predefined properties:
require_once BaseTestCase::$libDir . '/Web/Form.php';
require_once BaseTestCase::$appDir . '/forms/Config/AuthenticationForm.php';
BaseTestCase provides static variables for every directory in the project.
### Writing database tests
The base test uses the PHPUnit dataProvider annotation system to create Zend Database Adapters. Typically a
database test looks like this:
/**
* @dataProvider mysqlDb
* @param Zend_Db_Adapter_PDO_Abstract $mysqlDb
*/
public function testSomethingWithMySql($mysqlDb)
{
$this->setupDbProvider($mysqlDb); // Drops everything from existing database
// Load a dump file into database
$this->loadSql($mysqlDb, BaseTestCase::$etcDir . '/etc/schema/mydump.mysql.sql');
// Test your code
}
Available data providers are: mysqlDb, pgsqlDb, oracleDb. The test will be skipped if a provider
could not be initialized.
### Write form tests
BaseTestCase holds method to require form libraries and create form classes based on class names.
public function testShowModifiedOrder()
{
$this->requireFormLibraries();
$form = $this->createForm(
'Icinga\Form\Config\AuthenticationForm',
array(
'priority' => 'test-ldap,test-db'
)
);
// Testing your code
}
The second parameter of createForm() can be omitted. You can set initial post request data as
an array if needed.
## Writing tests for controllers
When writing tests for controllers, you can subclass the MonitoringControllerTest class underneath monitoring/test/php/testlib: When writing tests for controllers, you can subclass the MonitoringControllerTest class underneath monitoring/test/php/testlib:

View File

@ -196,14 +196,12 @@ class DbAdapterFactory implements ConfigAwareFactory
/** /**
* Create the Db_Adapter for the given configuration section * Create the Db_Adapter for the given configuration section
* *
* @param mixed $config The configuration section containing the * @param Zend_Config $config The configuration section containing the db information
* db information
* *
* @return Zend_Db_Adapter_Abstract The created Zend_Db_Adapter * @return Zend_Db_Adapter_Abstract The created Zend_Db_Adapter
* * @throws ConfigurationError When the specified db type is invalid
* @throws ConfigurationError When the specified db type is invalid
*/ */
private static function createDbAdapter($config) public static function createDbAdapter(Zend_Config $config)
{ {
if ($config->type !== 'db') { if ($config->type !== 'db') {
$msg = 'Resource type must be "db" but is "' . $config->type . '"'; $msg = 'Resource type must be "db" but is "' . $config->type . '"';

View File

@ -0,0 +1,394 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
/**
* This file is part of Icinga 2 Web.
*
* Icinga 2 Web - Head for multiple monitoring backends.
* Copyright (C) 2013 Icinga Development Team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* @copyright 2013 Icinga Development Team <info@icinga.org>
* @license http://www.gnu.org/licenses/gpl-2.0.txt GPL, version 2
* @author Icinga Development Team <info@icinga.org>
*/
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Test;
// @codingStandardsIgnoreStart
require_once 'Zend/Test/PHPUnit/ControllerTestCase.php';
require_once 'Zend/Db/Adapter/Pdo/Abstract.php';
require_once 'DbTest.php';
require_once 'FormTest.php';
// @codingStandardsIgnoreEnd
use \Exception;
use \RuntimeException;
use \Zend_Test_PHPUnit_ControllerTestCase;
use \Zend_Config;
use \Zend_Db_Adapter_Pdo_Abstract;
use \Zend_Db_Adapter_Pdo_Mysql;
use \Zend_Db_Adapter_Pdo_Pgsql;
use \Zend_Db_Adapter_Pdo_Oci;
use \Icinga\Application\DbAdapterFactory;
use \Icinga\Web\Form;
/**
* Class BaseTestCase
*/
class BaseTestCase extends Zend_Test_PHPUnit_ControllerTestCase implements DbTest, FormTest
{
/**
* Path to application/
*
* @var string
*/
public static $appDir;
/**
* Path to library/Icinga
*
* @var string
*/
public static $libDir;
/**
* Path to etc/
*
* @var
*/
public static $etcDir;
/**
* Path to test/php/
*
* @var string
*/
public static $testDir;
/**
* Path to share/icinga2-web
*
* @var string
*/
public static $shareDir;
/**
* Path to modules/
*
* @var string
*/
public static $moduleDir;
/**
* DbAdapterFactory configuration for different database types
*
* @var array
*/
private static $dbConfiguration = array(
'mysql' => array(
'type' => 'db',
'db' => 'mysql',
'host' => '127.0.0.1',
'port' => 3306,
'dbname' => 'icinga_unittest',
'username' => 'icinga_unittest',
'password' => 'icinga_unittest'
),
'pgsql' => array(
'type' => 'db',
'db' => 'pgsql',
'host' => '127.0.0.1',
'port' => 5432,
'dbname' => 'icinga_unittest',
'username' => 'icinga_unittest',
'password' => 'icinga_unittest'
),
);
/**
* Constructs a test case with the given name.
*
* @param string $name
* @param array $data
* @param string $dataName
* @see PHPUnit_Framework_TestCase::__construct
*/
public function __construct($name = null, array $data = array(), $dataName = '')
{
parent::__construct($name, $data, $dataName);
$tz = @date_default_timezone_get();
date_default_timezone_set('UTC');
}
/**
* Setup test path environment
*
* @throws RuntimeException
*/
public static function setupDirectories()
{
static $initialized = false;
if ($initialized === true) {
return;
}
$baseDir = realpath(__DIR__ . '/../../../');
if ($baseDir === false) {
throw new RuntimeException('Application base dir not found');
}
self::$appDir = $baseDir . '/application';
self::$libDir = $baseDir . '/library/Icinga';
self::$etcDir = $baseDir . '/etc';
self::$testDir = $baseDir . '/test/php';
self::$shareDir = $baseDir . '/share/icinga2-web';
self::$moduleDir = $baseDir . '/modules';
$initialized = true;
}
/**
* Create Zend_Config for database configuration
*
* @param string $name
*
* @return Zend_Config
* @throws RuntimeException
*/
private function createDbConfigFor($name)
{
if (array_key_exists($name, self::$dbConfiguration)) {
return new Zend_Config(self::$dbConfiguration[$name]);
}
throw new RuntimeException('Configuration for database type not available: ' . $name);
}
/**
* Creates an array of Zend Database Adapter
*
* @param string $name
*
* @return array
*/
private function createDbAdapterFor($name)
{
$this->requireDbLibraries();
try {
$adapter = DbAdapterFactory::createDbAdapter($this->createDbConfigFor($name));
} catch (Exception $e) {
$adapter = $e->getMessage();
}
return array(
array($adapter)
);
}
/**
* PHPUnit provider for mysql
*
* @return Zend_Db_Adapter_Pdo_Mysql
*/
public function mysqlDb()
{
return $this->createDbAdapterFor('mysql');
}
/**
* PHPUnit provider for pgsql
*
* @return Zend_Db_Adapter_Pdo_Pgsql
*/
public function pgsqlDb()
{
return $this->createDbAdapterFor('pgsql');
}
/**
* PHPUnit provider for oracle
*
* @return Zend_Db_Adapter_Pdo_Oci
*/
public function oracleDb()
{
return $this->createDbAdapterFor('oracle');
}
/**
* Executes sql file on PDO object
*
* @param Zend_Db_Adapter_Pdo_Abstract $resource
* @param string $filename
*
* @return boolean Operational success flag
* @throws RuntimeException
*/
public function loadSql(Zend_Db_Adapter_Pdo_Abstract $resource, $filename)
{
if (!is_file($filename)) {
throw new RuntimeException(
'Sql file not found: ' . $filename . ' (test=' . $this->getName() . ')'
);
}
$sqlData = file_get_contents($filename);
if (!$sqlData) {
throw new RuntimeException(
'Sql file is empty: ' . $filename . ' (test=' . $this->getName() . ')'
);
}
$resource->exec($sqlData);
}
/**
* Setup provider for testcase
*
* @param string|Zend_Db_Adapter_PDO_Abstract|null $resource
*/
public function setupDbProvider($resource)
{
if (!$resource instanceof Zend_Db_Adapter_Pdo_Abstract) {
if (is_string($resource)) {
$this->markTestSkipped('Could not initialize provider: ' . $resource);
} else {
$this->markTestSkipped('Could not initialize provider');
}
return;
}
try {
$resource->getConnection();
} catch (Exception $e) {
$this->markTestSkipped('Could not connect to provider: '. $e->getMessage());
}
$tables = $resource->listTables();
foreach ($tables as $table) {
$resource->exec('DROP TABLE ' . $table . ';');
}
}
/**
* Instantiate a new form object
*
* @param string $formClass Form class to instantiate
* @param array $requestData Request data for the form
*
* @return Form
* @throws RuntimeException
*/
public function createForm($formClass, array $requestData = array())
{
$this->requireFormLibraries();
$classParts = explode('\\', $formClass);
$identifier = array_shift($classParts);
array_shift($classParts); // Throw away
$fixedPathComponent = '/forms';
if (strtolower($identifier) == 'icinga') {
$startPathComponent = self::$appDir . $fixedPathComponent;
} else {
$startPathComponent = self::$moduleDir
. '/'
. strtolower($identifier)
. '/application'
.$fixedPathComponent;
}
$classFile = $startPathComponent . '/' . implode('/', $classParts) . '.php';
if (!file_exists($classFile)) {
throw new RuntimeException('Class file for form "' . $formClass . '" not found');
}
require_once $classFile;
$form = new $formClass();
$request = $this->getRequest();
$request->setMethod('POST');
$request->setPost($requestData);
$form->setRequest($request);
return $form;
}
/**
* Require all libraries to instantiate forms
*/
public function requireFormLibraries()
{
// @codingStandardsIgnoreStart
require_once 'Zend/Form/Decorator/Abstract.php';
require_once 'Zend/Validate/Abstract.php';
require_once 'Zend/Form/Element/Xhtml.php';
require_once 'Zend/Form/Element/Text.php';
require_once 'Zend/Form/Element/Submit.php';
require_once 'Zend/Form.php';
require_once 'Zend/View.php';
require_once self::$libDir . '/Web/Form/InvalidCSRFTokenException.php';
require_once self::$libDir . '/Web/Form/Element/DateTimePicker.php';
require_once self::$libDir . '/Web/Form/Element/Note.php';
require_once self::$libDir . '/Web/Form/Element/Number.php';
require_once self::$libDir . '/Web/Form/Decorator/ConditionalHidden.php';
require_once self::$libDir . '/Web/Form/Decorator/HelpText.php';
require_once self::$libDir . '/Web/Form/Validator/DateFormatValidator.php';
require_once self::$libDir . '/Web/Form/Validator/TimeFormatValidator.php';
require_once self::$libDir . '/Web/Form/Validator/WritablePathValidator.php';
require_once self::$libDir . '/Web/Form.php';
// @codingStandardsIgnoreEnd
}
/**
* Require all classes for database adapter creation
*/
public function requireDbLibraries()
{
// @codingStandardsIgnoreStart
require_once 'Zend/Config.php';
require_once 'Zend/Db.php';
require_once 'Zend/Log.php';
require_once realpath(self::$libDir . '/Exception/ConfigurationError.php');
require_once realpath(self::$libDir . '/Util/ConfigAwareFactory.php');
require_once realpath(self::$libDir . '/Application/DbAdapterFactory.php');
require_once realpath(self::$libDir . '/Application/Logger.php');
// @codingStandardsIgnoreEnd
}
}
// @codingStandardsIgnoreStart
BaseTestCase::setupDirectories();
// @codingStandardsIgnoreEnd

View File

@ -0,0 +1,75 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
/**
* This file is part of Icinga 2 Web.
*
* Icinga 2 Web - Head for multiple monitoring backends.
* Copyright (C) 2013 Icinga Development Team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* @copyright 2013 Icinga Development Team <info@icinga.org>
* @license http://www.gnu.org/licenses/gpl-2.0.txt GPL, version 2
* @author Icinga Development Team <info@icinga.org>
*/
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Test;
use \Zend_Db_Adapter_Pdo_Abstract;
use \Zend_Db_Adapter_Pdo_Mysql;
use \Zend_Db_Adapter_Pdo_Pgsql;
use \Zend_Db_Adapter_Pdo_Oci;
interface DbTest
{
/**
* PHPUnit provider for mysql
*
* @return Zend_Db_Adapter_Pdo_Mysql
*/
public function mysqlDb();
/**
* PHPUnit provider for pgsql
*
* @return Zend_Db_Adapter_Pdo_Pgsql
*/
public function pgsqlDb();
/**
* PHPUnit provider for oracle
*
* @return Zend_Db_Adapter_Pdo_Oci
*/
public function oracleDb();
/**
* Executes sql file on PDO object
*
* @param Zend_Db_Adapter_PDO_Abstract $resource
* @param string $filename
*
* @return boolean Operational success flag
*/
public function loadSql(Zend_Db_Adapter_PDO_Abstract $resource, $filename);
/**
* Setup provider for testcase
*
* @param string|Zend_Db_Adapter_PDO_Abstract|null $resource
*/
public function setupDbProvider($resource);
}

View File

@ -0,0 +1,52 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
/**
* This file is part of Icinga 2 Web.
*
* Icinga 2 Web - Head for multiple monitoring backends.
* Copyright (C) 2013 Icinga Development Team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* @copyright 2013 Icinga Development Team <info@icinga.org>
* @license http://www.gnu.org/licenses/gpl-2.0.txt GPL, version 2
* @author Icinga Development Team <info@icinga.org>
*/
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Test;
use Icinga\Web\Form;
/**
* Interface to test form objects
*/
interface FormTest
{
/**
* Instantiate a new form object
*
* @param string $formClass Form class to instantiate
* @param array $requestData Request data for the form
*
* @return Form
*/
public function createForm($formClass, array $requestData = array());
/**
* Require all libraries to instantiate forms
*/
public function requireFormLibraries();
}

View File

@ -28,16 +28,23 @@
namespace Test\Icinga\Form\Config; namespace Test\Icinga\Form\Config;
// @codingStandardsIgnoreStart
require_once realpath(__DIR__ . '/../../../../../library/Icinga/Test/BaseTestCase.php');
// @codingStandardsIgnoreEnd
require_once('Zend/Config.php'); use Icinga\Test\BaseTestCase;
require_once('Zend/Config/Ini.php');
require_once(realpath('library/Icinga/Web/Form/BaseFormTest.php')); // @codingStandardsIgnoreStart
require_once(realpath('../../application/forms/Config/AuthenticationForm.php')); require_once 'Zend/Form.php';
require_once(realpath('../../application/forms/Config/Authentication/BaseBackendForm.php')); require_once 'Zend/Config.php';
require_once(realpath('../../application/forms/Config/Authentication/DbBackendForm.php')); require_once 'Zend/Config/Ini.php';
require_once(realpath('../../application/forms/Config/Authentication/LdapBackendForm.php')); require_once BaseTestCase::$libDir . '/Web/Form.php';
require_once BaseTestCase::$appDir . '/forms/Config/AuthenticationForm.php';
require_once BaseTestCase::$appDir . '/forms/Config/Authentication/BaseBackendForm.php';
require_once BaseTestCase::$appDir . '/forms/Config/Authentication/DbBackendForm.php';
require_once BaseTestCase::$appDir . '/forms/Config/Authentication/LdapBackendForm.php';
// @codingStandardsIgnoreEnd
use \Test\Icinga\Web\Form\BaseFormTest;
use \Icinga\Web\Form; use \Icinga\Web\Form;
use \DOMDocument; use \DOMDocument;
use \Zend_Config; use \Zend_Config;
@ -47,7 +54,7 @@ use \Zend_View;
* Test for the authentication provider form * Test for the authentication provider form
* *
*/ */
class AuthenticationFormTest extends \Test\Icinga\Web\Form\BaseFormTest class AuthenticationFormTest extends BaseTestCase
{ {
/** /**
@ -84,8 +91,8 @@ class AuthenticationFormTest extends \Test\Icinga\Web\Form\BaseFormTest
*/ */
public function testLdapProvider() public function testLdapProvider()
{ {
date_default_timezone_set('UTC'); $this->requireFormLibraries();
$form = $this->getRequestForm(array(), 'Icinga\Form\Config\AuthenticationForm'); $form = $this->createForm('Icinga\Form\Config\AuthenticationForm');
$config = new Zend_Config( $config = new Zend_Config(
array( array(
'test-ldap' => array( 'test-ldap' => array(
@ -121,9 +128,10 @@ class AuthenticationFormTest extends \Test\Icinga\Web\Form\BaseFormTest
* Test the database provider form population from config * Test the database provider form population from config
* *
*/ */
public function testDbProvider() { public function testDbProvider()
date_default_timezone_set('UTC'); {
$form = $this->getRequestForm(array(), 'Icinga\Form\Config\AuthenticationForm'); $this->requireFormLibraries();
$form = $this->createForm('Icinga\Form\Config\AuthenticationForm');
$config = new Zend_Config( $config = new Zend_Config(
array( array(
'test-db' => array( 'test-db' => array(
@ -164,10 +172,12 @@ class AuthenticationFormTest extends \Test\Icinga\Web\Form\BaseFormTest
*/ */
public function testShowModifiedOrder() public function testShowModifiedOrder()
{ {
date_default_timezone_set('UTC'); $this->requireFormLibraries();
$form = $this->getRequestForm( $form = $this->createForm(
array('priority' => 'test-ldap,test-db'), 'Icinga\Form\Config\AuthenticationForm',
'Icinga\Form\Config\AuthenticationForm' array(
'priority' => 'test-ldap,test-db'
)
); );
$config = $this->getTestConfig(); $config = $this->getTestConfig();
$form->setResources( $form->setResources(
@ -192,8 +202,9 @@ class AuthenticationFormTest extends \Test\Icinga\Web\Form\BaseFormTest
*/ */
public function testConfigurationCreation() public function testConfigurationCreation()
{ {
date_default_timezone_set('UTC'); $this->requireFormLibraries();
$form = $this->getRequestForm( $form = $this->createForm(
'Icinga\Form\Config\AuthenticationForm',
array( array(
'priority' => 'test-ldap,test-db', 'priority' => 'test-ldap,test-db',
'backend_testdb_resource' => 'db_resource_2', 'backend_testdb_resource' => 'db_resource_2',
@ -202,10 +213,8 @@ class AuthenticationFormTest extends \Test\Icinga\Web\Form\BaseFormTest
'backend_testldap_bind_dn' => 'modified_bind_dn', 'backend_testldap_bind_dn' => 'modified_bind_dn',
'backend_testldap_bind_pw' => 'modified_bind_pw', 'backend_testldap_bind_pw' => 'modified_bind_pw',
'backend_testldap_user_class' => 'modified_user_class', 'backend_testldap_user_class' => 'modified_user_class',
'backend_testldap_user_name_attribute' => 'modified_user_name_attribute', 'backend_testldap_user_name_attribute' => 'modified_user_name_attribute'
'backend_testdb_resource' => 'db_resource_2' )
),
'Icinga\Form\Config\AuthenticationForm'
); );
$form->setResources( $form->setResources(
@ -282,8 +291,9 @@ class AuthenticationFormTest extends \Test\Icinga\Web\Form\BaseFormTest
*/ */
public function testBackendRemoval() public function testBackendRemoval()
{ {
date_default_timezone_set('UTC'); $this->requireFormLibraries();
$form = $this->getRequestForm( $form = $this->createForm(
'Icinga\Form\Config\AuthenticationForm',
array( array(
'priority' => 'test-ldap,test-db', 'priority' => 'test-ldap,test-db',
'backend_testdb_resource' => 'db_resource_2', 'backend_testdb_resource' => 'db_resource_2',
@ -293,10 +303,8 @@ class AuthenticationFormTest extends \Test\Icinga\Web\Form\BaseFormTest
'backend_testldap_bind_dn' => 'modified_bind_dn', 'backend_testldap_bind_dn' => 'modified_bind_dn',
'backend_testldap_bind_pw' => 'modified_bind_pw', 'backend_testldap_bind_pw' => 'modified_bind_pw',
'backend_testldap_user_class' => 'modified_user_class', 'backend_testldap_user_class' => 'modified_user_class',
'backend_testldap_user_name_attribute' => 'modified_user_name_attribute', 'backend_testldap_user_name_attribute' => 'modified_user_name_attribute'
'backend_testdb_resource' => 'db_resource_2' )
),
'Icinga\Form\Config\AuthenticationForm'
); );
$form->setResources( $form->setResources(

View File

@ -28,29 +28,34 @@
namespace Test\Icinga\Form\Config; namespace Test\Icinga\Form\Config;
// @codingStandardsIgnoreStart
require_once realpath(__DIR__ . '/../../../../../library/Icinga/Test/BaseTestCase.php');
// @codingStandardsIgnoreEnd
require_once('Zend/Config.php'); use Icinga\Test\BaseTestCase;
require_once('Zend/Config/Ini.php'); // @codingStandardsIgnoreStart
require_once(realpath('library/Icinga/Web/Form/BaseFormTest.php')); require_once 'Zend/Form.php';
require_once(realpath('../../application/forms/Config/GeneralForm.php')); require_once 'Zend/Config.php';
require_once 'Zend/Config/Ini.php';
require_once BaseTestCase::$libDir . '/Web/Form.php';
require_once BaseTestCase::$appDir . '/forms/Config/GeneralForm.php';
// @codingStandardsIgnoreEnd
use Test\Icinga\Web\Form\BaseFormTest;
use \Icinga\Web\Form; use \Icinga\Web\Form;
use \DOMDocument; use \DOMDocument;
use \Zend_Config; use \Zend_Config;
use \Zend_View; use \Zend_View;
class GeneralFormTest extends \Test\Icinga\Web\Form\BaseFormTest class GeneralFormTest extends BaseTestCase
{ {
private function isHiddenElement($value, $htmlString) private function isHiddenElement($value, $htmlString)
{ {
$html = new DOMDocument(); $html = new DOMDocument();
$html->loadHTML($htmlString); $html->loadHTML($htmlString);
$hidden = $html->getElementsByTagName('noscript'); $hidden = $html->getElementsByTagName('noscript');
foreach($hidden as $node) { foreach ($hidden as $node) {
foreach($node->childNodes as $child) { foreach ($node->childNodes as $child) {
if ($child->hasAttributes() === false) { if ($child->hasAttributes() === false) {
continue; continue;
} }
@ -66,8 +71,8 @@ class GeneralFormTest extends \Test\Icinga\Web\Form\BaseFormTest
*/ */
public function testCorrectFieldPopulation() public function testCorrectFieldPopulation()
{ {
date_default_timezone_set('UTC'); $this->requireFormLibraries();
$form = $this->getRequestForm(array(), 'Icinga\Form\Config\GeneralForm'); $form = $this->createForm('Icinga\Form\Config\GeneralForm');
$form->setConfiguration( $form->setConfiguration(
new Zend_Config( new Zend_Config(
array( array(
@ -95,23 +100,54 @@ class GeneralFormTest extends \Test\Icinga\Web\Form\BaseFormTest
) )
); );
$form->setConfigDir('/tmp'); $form->setConfigDir('/tmp');
$view = new Zend_View();
$form->create(); $form->create();
$this->assertEquals(1, $form->getValue('environment'), 'Asserting the checkbox for devlopment being set to true'); $this->assertEquals(
$this->assertEquals('Europe/Berlin', $form->getValue('timezone'), 'Asserting the correct timezone to be displayed'); 1,
$this->assertEquals('/my/module/path', $form->getValue('module_folder'), 'Asserting the correct module folder to be set'); $form->getValue('environment'),
$this->assertEquals('d-m/Y', $form->getValue('date_format'), 'Asserting the correct data format to be set'); 'Asserting the checkbox for devlopment being set to true'
$this->assertEquals('A:i', $form->getValue('time_format'), 'Asserting the correct time to be set'); );
$this->assertEquals('ini', $form->getValue('preferences_type'), 'Asserting the correct preference type to be set'); $this->assertEquals(
$this->assertEquals('./my/path', $form->getValue('preferences_ini_path'), 'Asserting the correct ini path to be set'); 'Europe/Berlin',
$this->assertEquals('', $form->getValue('preferences_db_resource'), 'Asserting the database resource not to be set'); $form->getValue('timezone'),
'Asserting the correct timezone to be displayed'
);
$this->assertEquals(
'/my/module/path',
$form->getValue('module_folder'),
'Asserting the correct module folder to be set'
);
$this->assertEquals(
'd-m/Y',
$form->getValue('date_format'),
'Asserting the correct data format to be set'
);
$this->assertEquals(
'A:i',
$form->getValue('time_format'),
'Asserting the correct time to be set'
);
$this->assertEquals(
'ini',
$form->getValue('preferences_type'),
'Asserting the correct preference type to be set'
);
$this->assertEquals(
'./my/path',
$form->getValue('preferences_ini_path'),
'Asserting the correct ini path to be set'
);
$this->assertEquals(
'',
$form->getValue('preferences_db_resource'),
'Asserting the database resource not to be set'
);
} }
public function testCorrectConditionalIniFieldRendering() public function testCorrectConditionalIniFieldRendering()
{ {
date_default_timezone_set('UTC'); $this->requireFormLibraries();
$form = $this->getRequestForm(array(), 'Icinga\Form\Config\GeneralForm'); $form = $this->createForm('Icinga\Form\Config\GeneralForm');
$form->setConfiguration( $form->setConfiguration(
new Zend_Config( new Zend_Config(
array( array(
@ -146,8 +182,8 @@ class GeneralFormTest extends \Test\Icinga\Web\Form\BaseFormTest
public function testCorrectConditionalDbFieldRendering() public function testCorrectConditionalDbFieldRendering()
{ {
date_default_timezone_set('UTC'); $this->requireFormLibraries();
$form = $this->getRequestForm(array(), 'Icinga\Form\Config\GeneralForm'); $form = $this->createForm('Icinga\Form\Config\GeneralForm');
$form->setConfiguration( $form->setConfiguration(
new Zend_Config( new Zend_Config(
array( array(

View File

@ -28,13 +28,19 @@
namespace Test\Icinga\Form\Config; namespace Test\Icinga\Form\Config;
require_once('Zend/Config.php'); // @codingStandardsIgnoreStart
require_once('Zend/Config/Ini.php'); require_once realpath(__DIR__ . '/../../../../../library/Icinga/Test/BaseTestCase.php');
require_once(realpath('library/Icinga/Web/Form/BaseFormTest.php')); // @codingStandardsIgnoreEnd
require_once(realpath('../../application/forms/Config/LoggingForm.php'));
require_once(realpath('../../library/Icinga/Application/Icinga.php')); use Icinga\Test\BaseTestCase;
// @codingStandardsIgnoreStart
require_once 'Zend/Form.php';
require_once 'Zend/Config.php';
require_once 'Zend/Config/Ini.php';
require_once BaseTestCase::$libDir . '/Web/Form.php';
require_once BaseTestCase::$appDir . '/forms/Config/GeneralForm.php';
// @codingStandardsIgnoreEnd
use \Test\Icinga\Web\Form\BaseFormTest;
use \Icinga\Web\Form; use \Icinga\Web\Form;
use \Zend_Config; use \Zend_Config;
@ -42,7 +48,7 @@ use \Zend_Config;
* Test for the authentication provider form * Test for the authentication provider form
* *
*/ */
class LoggingFormTest extends BaseFormTest class LoggingFormTest extends BaseTestCase
{ {
/** /**
@ -51,8 +57,8 @@ class LoggingFormTest extends BaseFormTest
*/ */
public function testLoggingFormPopulation() public function testLoggingFormPopulation()
{ {
date_default_timezone_set('UTC'); $this->requireFormLibraries();
$form = $this->getRequestForm(array(), 'Icinga\Form\Config\LoggingForm'); $form = $this->createForm('Icinga\Form\Config\LoggingForm');
$config = new Zend_Config( $config = new Zend_Config(
array( array(
'logging' => array( 'logging' => array(
@ -76,9 +82,12 @@ class LoggingFormTest extends BaseFormTest
'0', '0',
$form->getValue('logging_app_verbose'), $form->getValue('logging_app_verbose'),
'Asserting the logging verbose tick not to be set' 'Asserting the logging verbose tick not to be set'
); );
$this->assertEquals('/some/path', $form->getValue('logging_app_target'), 'Asserting the logging path to be set'); $this->assertEquals(
'/some/path',
$form->getValue('logging_app_target'),
'Asserting the logging path to be set'
);
$this->assertEquals( $this->assertEquals(
1, 1,
$form->getValue('logging_debug_enable'), $form->getValue('logging_debug_enable'),
@ -97,16 +106,16 @@ class LoggingFormTest extends BaseFormTest
*/ */
public function testCorrectConfigCreation() public function testCorrectConfigCreation()
{ {
date_default_timezone_set('UTC'); $this->requireFormLibraries();
$form = $this->getRequestForm( $form = $this->createForm(
'Icinga\Form\Config\LoggingForm',
array( array(
'logging_enable' => 1, 'logging_enable' => 1,
'logging_app_target' => 'some/new/target', 'logging_app_target' => 'some/new/target',
'logging_app_verbose' => 1, 'logging_app_verbose' => 1,
'logging_debug_enable' => 0, 'logging_debug_enable' => 0,
'logging_debug_target' => 'a/new/target' 'logging_debug_target' => 'a/new/target'
), )
'Icinga\Form\Config\LoggingForm'
); );
$baseConfig = new Zend_Config( $baseConfig = new Zend_Config(
array( array(

View File

@ -28,26 +28,30 @@
namespace Test\Icinga\Form\Preference; namespace Test\Icinga\Form\Preference;
// @codingStandardsIgnoreStart
require_once realpath(__DIR__ . '/../../../../../library/Icinga/Test/BaseTestCase.php');
// @codingStandardsIgnoreEnd
require_once('Zend/Config.php'); use Icinga\Test\BaseTestCase;
require_once('Zend/Config/Ini.php');
require_once('Zend/Form/Element/Select.php'); // @codingStandardsIgnoreStart
require_once(realpath('library/Icinga/Web/Form/BaseFormTest.php')); require_once 'Zend/Config.php';
require_once(realpath('../../application/forms/Preference/GeneralForm.php')); require_once 'Zend/Config/Ini.php';
require_once(realpath('../../library/Icinga/User/Preferences/ChangeSet.php')); require_once 'Zend/Form/Element/Select.php';
require_once(realpath('../../library/Icinga/User/Preferences.php')); require_once BaseTestCase::$libDir . '/User/Preferences.php';
require_once BaseTestCase::$libDir . '/Web/Form.php';
require_once BaseTestCase::$appDir . '/forms/Preference/GeneralForm.php';
require_once BaseTestCase::$libDir . '/User/Preferences/ChangeSet.php';
// @codingStandardsIgnoreEnd
use Test\Icinga\Web\Form\BaseFormTest;
use \Icinga\Web\Form; use \Icinga\Web\Form;
use \DOMDocument;
use \Zend_Config; use \Zend_Config;
use \Zend_View;
use Icinga\User\Preferences; use Icinga\User\Preferences;
/** /**
* Test for general form, mainly testing enable/disable behaviour * Test for general form, mainly testing enable/disable behaviour
*/ */
class GeneralFormTest extends \Test\Icinga\Web\Form\BaseFormTest class GeneralFormTest extends BaseTestCase
{ {
/** /**
@ -56,8 +60,8 @@ class GeneralFormTest extends \Test\Icinga\Web\Form\BaseFormTest
*/ */
public function testDisableFormIfUsingDefault() public function testDisableFormIfUsingDefault()
{ {
date_default_timezone_set('UTC'); $this->requireFormLibraries();
$form = $this->getRequestForm(array(), 'Icinga\Form\Preference\GeneralForm'); $form = $this->createForm('Icinga\Form\Preference\GeneralForm');
$form->setRequest($this->getRequest()); $form->setRequest($this->getRequest());
$form->setConfiguration( $form->setConfiguration(
new Zend_Config( new Zend_Config(
@ -85,8 +89,8 @@ class GeneralFormTest extends \Test\Icinga\Web\Form\BaseFormTest
*/ */
public function testEnsableFormIfUsingPreference() public function testEnsableFormIfUsingPreference()
{ {
date_default_timezone_set('UTC'); $this->requireFormLibraries();
$form = $this->getRequestForm(array(), 'Icinga\Form\Preference\GeneralForm'); $form = $this->createForm('Icinga\Form\Preference\GeneralForm');
$form->setRequest($this->getRequest()); $form->setRequest($this->getRequest());
$form->setConfiguration( $form->setConfiguration(
new Zend_Config( new Zend_Config(
@ -109,5 +113,4 @@ class GeneralFormTest extends \Test\Icinga\Web\Form\BaseFormTest
'Asserting form elements to be disabled when not set in a preference' 'Asserting form elements to be disabled when not set in a preference'
); );
} }
} }

View File

@ -29,38 +29,43 @@
namespace Tests\Icinga\Authentication; namespace Tests\Icinga\Authentication;
require_once('Zend/Config.php'); // @codingStandardsIgnoreStart
require_once('Zend/Config/Ini.php'); require_once realpath(__DIR__ . '/../../../../../library/Icinga/Test/BaseTestCase.php');
require_once('Zend/Db/Adapter/Abstract.php'); // @codingStandardsIgnoreEnd
require_once('Zend/Db.php');
require_once('Zend/Log.php');
require_once('../../library/Icinga/Util/ConfigAwareFactory.php');
require_once('../../library/Icinga/Authentication/UserBackend.php');
require_once('../../library/Icinga/Protocol/Ldap/Exception.php');
require_once('../../library/Icinga/Application/DbAdapterFactory.php');
require_once('../../library/Icinga/Application/Config.php');
require_once('../../library/Icinga/Authentication/Credentials.php');
require_once('../../library/Icinga/Authentication/Backend/DbUserBackend.php');
require_once('../../library/Icinga/User.php');
require_once('../../library/Icinga/Application/Logger.php');
use Zend_Config; use \Icinga\Test\BaseTestCase;
use Zend_Db_Adapter_Abstract;
use Icinga\Authentication\Backend\DbUserBackend; // @codingStandardsIgnoreStart
use Icinga\Application\DbAdapterFactory; require_once 'Zend/Config.php';
use Icinga\Util\Crypto; require_once 'Zend/Config/Ini.php';
use Icinga\Authentication\Credentials; require_once 'Zend/Db/Adapter/Abstract.php';
use Icinga\User; require_once 'Zend/Db.php';
require_once 'Zend/Log.php';
require_once BaseTestCase::$libDir . '/Util/ConfigAwareFactory.php';
require_once BaseTestCase::$libDir . '/Authentication/UserBackend.php';
require_once BaseTestCase::$libDir . '/Protocol/Ldap/Exception.php';
require_once BaseTestCase::$libDir . '/Application/DbAdapterFactory.php';
require_once BaseTestCase::$libDir . '/Application/Config.php';
require_once BaseTestCase::$libDir . '/Authentication/Credentials.php';
require_once BaseTestCase::$libDir . '/Authentication/Backend/DbUserBackend.php';
require_once BaseTestCase::$libDir . '/User.php';
require_once BaseTestCase::$libDir . '/Application/Logger.php';
// @codingStandardsIgnoreEnd
use \PDO;
use \Zend_Db_Adapter_Pdo_Abstract;
use \Zend_Config;
use \Icinga\Authentication\Backend\DbUserBackend;
use \Icinga\Application\DbAdapterFactory;
use \Icinga\Authentication\Credentials;
use \Icinga\User;
use \Icinga\Application\Config; use \Icinga\Application\Config;
/** /**
* Test Class fpr DbUserBackend * Test Class fpr DbUserBackend
*/ */
class DbUserBackendTest extends \PHPUnit_Framework_TestCase { class DbUserBackendTest extends BaseTestCase
{
/*
* Mapping of columns
*/
const USER_NAME_COLUMN = 'username'; const USER_NAME_COLUMN = 'username';
const SALT_COLUMN = 'salt'; const SALT_COLUMN = 'salt';
@ -76,263 +81,157 @@ class DbUserBackendTest extends \PHPUnit_Framework_TestCase {
*/ */
private $testTable = 'account'; private $testTable = 'account';
/**
* The database that is used to store the authentication data
*
* @var string
*/
private $testDatabase = 'icinga_unittest';
/** /**
* Example users * Example users
* *
* @var array * @var array
*/ */
private $users; private $userData = array(
array(
/** self::USER_NAME_COLUMN => 'user1',
* The DbUserBackend configured to use MySQL self::PASSWORD_COLUMN => 'secret1',
* self::SALT_COLUMN => '8a7487a539c5d1d6766639d04d1ed1e6',
* @var DbUserBackend self::ACTIVE_COLUMN => 1
*/ ),
private $mysql; array(
self::USER_NAME_COLUMN => 'user2',
self::PASSWORD_COLUMN => 'secret2',
/** self::SALT_COLUMN => '04b5521ddd761b5a5b633be83faa494d',
* The DbUserBackend configured to use PostgreSQL self::ACTIVE_COLUMN => 1
* ),
* @var DbUserBackend array(
*/ self::USER_NAME_COLUMN => 'user3',
private $pgsql; self::PASSWORD_COLUMN => 'secret3',
self::SALT_COLUMN => '08bb94ba3120338ae56db80ef551d324',
/** self::ACTIVE_COLUMN => 0
* Contains the PDO names used for the different SQL databases. )
*
* @var array
*/
private $dbTypeMap = Array(
'mysql' => 'PDO_MYSQL',
'pgsql' => 'PDO_PGSQL'
); );
/**
* Create a preset configuration that can be used to access the database
* with the icinga_unittest account.
*
* @param String $dbType The database type as a string, like 'mysql' or 'pgsql'.
*
* @return Zend_Config The created resource configuration
*/
private function getResourceConfig($dbType)
{
return new Zend_Config(
array(
'type' => 'db',
'db' => $dbType,
'host' => 'localhost',
'username' => 'icinga_unittest',
'password' => 'icinga_unittest',
'dbname' => $this->testDatabase,
'table' => $this->testTable
)
);
}
/**
* Create a backend with the given database type
*
* @param String $dbType The database type as a string, like 'mysql' or 'pgsql'.
*
* @return DbUserBackend|null
*/
private function createBackend($dbType)
{
try {
$db = $this->createDb($this->getResourceConfig($dbType));
$this->setUpDb($db,$dbType);
return new DbUserBackend($db);
} catch(\Exception $e) {
echo 'CREATE_BACKEND_ERROR:'.$e->getMessage();
return null;
}
}
/**
* Create the db adapter
*
* @param $config The configuration to use
*
* @return Zend_Db_Adapter_Abstract The created adabter
*/
private function createDb($config)
{
return DbAdapterFactory::createDbAdapterFromConfig($config);
}
/**
* Create the backends and fill it with sample-data
*/
protected function setUp()
{
DbAdapterFactory::resetConfig();
$this->users = Array(
0 => Array(
self::USER_NAME_COLUMN => 'user1',
self::PASSWORD_COLUMN => 'secret1',
self::SALT_COLUMN => '8a7487a539c5d1d6766639d04d1ed1e6',
self::ACTIVE_COLUMN => 1
),
1 => Array(
self::USER_NAME_COLUMN => 'user2',
self::PASSWORD_COLUMN => 'secret2',
self::SALT_COLUMN => '04b5521ddd761b5a5b633be83faa494d',
self::ACTIVE_COLUMN => 1
),
2 => Array(
self::USER_NAME_COLUMN => 'user3',
self::PASSWORD_COLUMN => 'secret3',
self::SALT_COLUMN => '08bb94ba3120338ae56db80ef551d324',
self::ACTIVE_COLUMN => 0
)
);
$this->mysql = $this->createBackend('mysql');
$this->pgsql = $this->createBackend('pgsql');
}
/** /**
* Test the authentication functions of the DbUserBackend using PostgreSQL as backend. * Test the authentication functions of the DbUserBackend using PostgreSQL as backend.
*
* @dataProvider pgsqlDb
*/ */
public function testCorrectUserLoginForPgsql() public function testCorrectUserLoginForPgsql($db)
{ {
if (!empty($this->pgsql)) { $this->setupDbProvider($db);
$this->runBackendAuthentication($this->pgsql); $backend = new DbUserBackend($db);
$this->runBackendUsername($this->pgsql); $this->runBackendAuthentication($backend);
} $this->runBackendUsername($backend);
else {
$this->markTestSkipped();
}
} }
/** /**
* Test the authentication functions of the DbUserBackend using MySQL as backend. * Test the authentication functions of the DbUserBackend using MySQL as backend.
*/
public function testCorrectUserLoginForMySQL()
{
if(!empty($this->mysql)){
$this->runBackendAuthentication($this->mysql);
$this->runBackendUsername($this->mysql);
}
else{
$this->markTestSkipped();
}
}
/**
* Try to drop all databases that may eventually be present
*/
public function tearDown()
{
try{
$db = $this->createDb($this->getResourceConfig('mysql'));
$this->tearDownDb($db);
} catch(\Exception $e) { }
try {
$db = $this->createDb($this->getResourceConfig('pgsql'));
$this->tearDownDb($db);
} catch(\Exception $e) { }
}
/**
* Drop the test database in the given db
* *
* @param $db * @dataProvider mysqlDb
*/ */
private function tearDownDb($db) public function testCorrectUserLoginForMySQL($db)
{ {
$db->exec('DROP TABLE '.$this->testTable); $this->setupDbProvider($db);
$backend = new DbUserBackend($db);
$this->runBackendAuthentication($backend);
$this->runBackendUsername($backend);
} }
/** /**
* Fill the given database with the sample-data provided in users * @param Zend_Db_Adapter_Pdo_Abstract $resource
*
* @param $db Zend_Db_Adapter_Abstract The database to set up
* @param $type String The database type as a string: 'mysql'|'pgsql'
*/ */
private function setUpDb($db,$type) public function setupDbProvider($resource)
{ {
try { parent::setupDbProvider($resource);
$this->tearDownDb($db);
} catch (\Exception $e) {}
$setupScript = file_get_contents('../../etc/schema/accounts.' . $type . '.sql'); $type = $resource->getConnection()->getAttribute(PDO::ATTR_DRIVER_NAME);
$db->exec($setupScript);
for ($i = 0; $i < count($this->users); $i++) { $dumpFile = BaseTestCase::$etcDir . '/schema/accounts.' . $type . '.sql';
$usr = $this->users[$i];
$data = Array( $this->assertFileExists($dumpFile);
self::USER_NAME_COLUMN => $usr[self::USER_NAME_COLUMN],
self::PASSWORD_COLUMN => hash_hmac('sha256', $this->loadSql($resource, $dumpFile);
for ($i = 0; $i < count($this->userData); $i++) {
$usr = $this->userData[$i];
$data = array(
self::USER_NAME_COLUMN => $usr[self::USER_NAME_COLUMN],
self::PASSWORD_COLUMN => hash_hmac(
'sha256',
$usr[self::SALT_COLUMN], $usr[self::SALT_COLUMN],
$usr[self::PASSWORD_COLUMN] $usr[self::PASSWORD_COLUMN]
), ),
self::ACTIVE_COLUMN => $usr[self::ACTIVE_COLUMN], self::ACTIVE_COLUMN => $usr[self::ACTIVE_COLUMN],
self::SALT_COLUMN => $usr[self::SALT_COLUMN] self::SALT_COLUMN => $usr[self::SALT_COLUMN]
); );
$db->insert($this->testTable,$data); $resource->insert($this->testTable, $data);
} }
} }
/** /**
* Run the hasUsername test against an instance of DbUserBackend * Run the hasUsername test against an instance of DbUserBackend
* *
* @param $backend The backend that will be tested. * @param DbUserBackend $backend The backend that will be tested.
*/ */
private function runBackendUsername($backend) private function runBackendUsername($backend)
{ {
// Known user // Known user
$this->assertTrue($backend->hasUsername( $this->assertTrue(
new Credentials( $backend->hasUsername(
$this->users[0][self::USER_NAME_COLUMN], new Credentials(
$this->users[0][self::PASSWORD_COLUMN]) $this->userData[0][self::USER_NAME_COLUMN],
), 'Assert that the user is known by the backend'); $this->userData[0][self::PASSWORD_COLUMN]
)
),
'Assert that the user is known by the backend'
);
// Unknown user // Unknown user
$this->assertFalse($backend->hasUsername( $this->assertFalse(
new Credentials( $backend->hasUsername(
'unknown user', new Credentials(
'secret') 'unknown user',
), 'Assert that the user is not known by the backend'); 'secret'
)
),
'Assert that the user is not known by the backend'
);
// Inactive user // Inactive user
$this->assertFalse($backend->hasUsername( $this->assertFalse(
new Credentials( $backend->hasUsername(
$this->users[2][self::USER_NAME_COLUMN], new Credentials(
$this->users[2][self::PASSWORD_COLUMN]) $this->userData[2][self::USER_NAME_COLUMN],
), 'Assert that the user is inactive and therefore not known by the backend'); $this->userData[2][self::PASSWORD_COLUMN]
)
),
'Assert that the user is inactive and therefore not known by the backend'
);
} }
/** /**
* Run the authentication test against an instance of DbUserBackend * Run the authentication test against an instance of DbUserBackend
* *
* @param $backend The backend that will be tested. * @param DbUserBackend $backend The backend that will be tested.
*/ */
private function runBackendAuthentication($backend) private function runBackendAuthentication($backend)
{ {
// Known user // Known user
$this->assertNotNull($backend->authenticate( $this->assertNotNull(
new Credentials( $backend->authenticate(
$this->users[0][self::USER_NAME_COLUMN], new Credentials(
$this->users[0][self::PASSWORD_COLUMN]) $this->userData[0][self::USER_NAME_COLUMN],
), 'Assert that an existing, active user with the right credentials can authenticate.'); $this->userData[0][self::PASSWORD_COLUMN]
)
),
'Assert that an existing, active user with the right credentials can authenticate.'
);
// Wrong password // Wrong password
$this->assertNull( $this->assertNull(
$backend->authenticate( $backend->authenticate(
new Credentials( new Credentials(
$this->users[1][self::USER_NAME_COLUMN], $this->userData[1][self::USER_NAME_COLUMN],
'wrongpassword') 'wrongpassword'
), 'Assert that an existing user with an invalid password cannot authenticate' )
),
'Assert that an existing user with an invalid password cannot authenticate'
); );
// Nonexisting user // Nonexisting user
@ -340,16 +239,21 @@ class DbUserBackendTest extends \PHPUnit_Framework_TestCase {
$backend->authenticate( $backend->authenticate(
new Credentials( new Credentials(
'nonexisting user', 'nonexisting user',
$this->users[1][self::PASSWORD_COLUMN]) $this->userData[1][self::PASSWORD_COLUMN]
), 'Assert that a non-existing user cannot authenticate.' )
),
'Assert that a non-existing user cannot authenticate.'
); );
// Inactive user // Inactive user
$this->assertNull( $this->assertNull(
$backend->authenticate( $backend->authenticate(
new Credentials( new Credentials(
$this->users[2][self::USER_NAME_COLUMN], $this->userData[2][self::USER_NAME_COLUMN],
$this->users[2][self::PASSWORD_COLUMN]) $this->userData[2][self::PASSWORD_COLUMN]
), 'Assert that an inactive user cannot authenticate.'); )
),
'Assert that an inactive user cannot authenticate.'
);
} }
} }

View File

@ -0,0 +1,199 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
/**
* This file is part of Icinga 2 Web.
*
* Icinga 2 Web - Head for multiple monitoring backends.
* Copyright (C) 2013 Icinga Development Team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* @copyright 2013 Icinga Development Team <info@icinga.org>
* @license http://www.gnu.org/licenses/gpl-2.0.txt GPL, version 2
* @author Icinga Development Team <info@icinga.org>
*/
// {{{ICINGA_LICENSE_HEADER}}}
namespace Tests\Icinga\Test;
require_once 'Zend/Db/Adapter/Pdo/Mysql.php';
require_once 'Zend/Db/Adapter/Pdo/Pgsql.php';
require_once realpath(__DIR__ . '/../../../../../library/Icinga/Test/BaseTestCase.php');
use \PDO;
use \RuntimeException;
use Icinga\Test\BaseTestCase;
class BaseTestCaseDbTest extends BaseTestCase
{
private $emptySqlDumpFile;
protected function tearDown()
{
if ($this->emptySqlDumpFile) {
unlink($this->emptySqlDumpFile);
}
}
public function testExistingTestDirectories()
{
$this->assertFileExists(self::$appDir);
$this->assertFileExists(self::$libDir);
$this->assertFileExists(self::$etcDir);
$this->assertFileExists(self::$testDir);
$this->assertFileExists(self::$moduleDir);
// $this->assertFileExists(self::$shareDir);
}
/**
* @dataProvider mysqlDb
*/
public function testMySqlProviderAnnotation($resource)
{
$this->setupDbProvider($resource);
$this->assertInstanceOf('Zend_Db_Adapter_Pdo_Mysql', $resource);
}
/**
* @dataProvider mysqlDb
*/
public function testMySqlCreateTablePart1($resource)
{
$this->setupDbProvider($resource);
/** @var \Zend_Db_Adapter_Pdo_Abstract $resource **/
$resource->exec('CREATE TABLE test(uid INT NOT NULL PRIMARY KEY);');
$tables = $resource->listTables();
$this->assertCount(1, $tables);
}
/**
* @dataProvider mysqlDb
*/
public function testMySqlCreateTablePart2($resource)
{
$this->setupDbProvider($resource);
$tables = $resource->listTables();
$this->assertCount(0, $tables);
}
private function dbAdapterSqlLoadTable($resource)
{
/** @var $resource \Zend_Db_Adapter_Pdo_Abstract **/
$this->setupDbProvider($resource);
$sqlContent = array();
$sqlContent[] = 'CREATE TABLE dummyData(value VARCHAR(50) NOT NULL PRIMARY KEY);';
for ($i=0; $i<20; $i++) {
$sqlContent[] = 'INSERT INTO dummyData VALUES(\'' . uniqid(). '\');';
}
$tempFile = tempnam(sys_get_temp_dir(), 'icinga2-web-test-load-sql');
file_put_contents($tempFile, implode(chr(10), $sqlContent));
$this->loadSql($resource, $tempFile);
$count = (int)$resource->fetchOne('SELECT COUNT(*) as cntX from dummyData;');
$this->assertSame(20, $count);
$this->assertTrue(unlink($tempFile));
}
/**
* @dataProvider mysqlDb
*/
public function testMySqlLoadTable($resource)
{
$this->dbAdapterSqlLoadTable($resource);
}
/**
* @dataProvider pgsqlDb
*/
public function testPgSqlProviderAnnotation($resource)
{
$this->setupDbProvider($resource);
$this->assertInstanceOf('Zend_Db_Adapter_Pdo_Pgsql', $resource);
}
/**
* @dataProvider pgsqlDb
*/
public function testPgSqlCreateTablePart1($resource)
{
$this->setupDbProvider($resource);
/** @var \Zend_Db_Adapter_Pdo_Abstract $resource **/
$resource->exec('CREATE TABLE test(uid INT NOT NULL PRIMARY KEY);');
$tables = $resource->listTables();
$this->assertCount(1, $tables);
}
/**
* @dataProvider pgsqlDb
*/
public function testPgSqlCreateTablePart2($resource)
{
$this->setupDbProvider($resource);
$tables = $resource->listTables();
$this->assertCount(0, $tables);
}
/**
* @dataProvider pgsqlDb
*/
public function testPgSqlLoadTable($resource)
{
$this->dbAdapterSqlLoadTable($resource);
}
/**
* @dataProvider mysqlDb
*/
public function testNotExistSqlDumpFile($resource)
{
$this->setupDbProvider($resource);
$this->setExpectedException(
'RuntimeException',
'Sql file not found: /does/not/exist1238837 (test=testNotExistSqlDumpFile with data set #0)'
);
$this->loadSql($resource, '/does/not/exist1238837');
}
/**
* @dataProvider mysqlDb
*/
public function testDumpFileIsEmpty($resource)
{
$this->setupDbProvider($resource);
$this->emptySqlDumpFile = tempnam(sys_get_temp_dir(), 'icinga2-web-db-test-empty');
$this->assertFileExists($this->emptySqlDumpFile);
$expectedMessage = 'Sql file is empty: '
. $this->emptySqlDumpFile
. ' (test=testDumpFileIsEmpty with data set #0)';
$this->setExpectedException(
'RuntimeException',
$expectedMessage
);
$this->loadSql($resource, $this->emptySqlDumpFile);
}
}

View File

@ -0,0 +1,44 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
/**
* This file is part of Icinga 2 Web.
*
* Icinga 2 Web - Head for multiple monitoring backends.
* Copyright (C) 2013 Icinga Development Team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* @copyright 2013 Icinga Development Team <info@icinga.org>
* @license http://www.gnu.org/licenses/gpl-2.0.txt GPL, version 2
* @author Icinga Development Team <info@icinga.org>
*/
// {{{ICINGA_LICENSE_HEADER}}}
namespace Tests\Icinga\Test;
require_once realpath(__DIR__ . '/../../../../../library/Icinga/Test/BaseTestCase.php');
use Icinga\Test\BaseTestCase;
class BaseTestCaseFormTest extends BaseTestCase
{
public function testFormCreation()
{
$form1 = $this->createForm('Icinga\Form\Authentication\LoginForm');
$this->assertInstanceOf('Icinga\Web\Form', $form1);
$form2 = $this->createForm('Monitoring\Form\Config\ConfirmRemovalForm');
$this->assertInstanceOf('Icinga\Web\Form', $form2);
}
}

View File

@ -1,108 +1,59 @@
<?php <?php
// {{{ICINGA_LICENSE_HEADER}}}
/**
* This file is part of Icinga 2 Web.
*
* Icinga 2 Web - Head for multiple monitoring backends.
* Copyright (C) 2013 Icinga Development Team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* @copyright 2013 Icinga Development Team <info@icinga.org>
* @license http://www.gnu.org/licenses/gpl-2.0.txt GPL, version 2
* @author Icinga Development Team <info@icinga.org>
*/
// {{{ICINGA_LICENSE_HEADER}}}
namespace Tests\Icinga\User\Preferences; namespace Tests\Icinga\User\Preferences;
require_once __DIR__ . '/../../../../../../library/Icinga/Exception/ConfigurationError.php'; // @codingStandardsIgnoreStart
require_once __DIR__ . '/../../../../../../library/Icinga/Util/ConfigAwareFactory.php'; require_once realpath(__DIR__. '/../../../../../../library/Icinga/Test/BaseTestCase.php');
require_once __DIR__ . '/../../../../../../library/Icinga/Application/DbAdapterFactory.php'; // @codingStandardsIgnoreEnd
require_once __DIR__ . '/../../../../../../library/Icinga/User.php';
require_once __DIR__ . '/../../../../../../library/Icinga/User/Preferences.php';
require_once __DIR__ . '/../../../../../../library/Icinga/User/Preferences/ChangeSet.php';
require_once __DIR__ . '/../../../../../../library/Icinga/User/Preferences/LoadInterface.php';
require_once __DIR__ . '/../../../../../../library/Icinga/User/Preferences/FlushObserverInterface.php';
require_once __DIR__ . '/../../../../../../library/Icinga/User/Preferences/DbStore.php';
use Icinga\Test\BaseTestCase;
// @codingStandardsIgnoreStart
require_once 'Zend/Db.php'; require_once 'Zend/Db.php';
require_once 'Zend/Config.php';
require_once 'Zend/Db/Adapter/Abstract.php'; require_once 'Zend/Db/Adapter/Abstract.php';
require_once BaseTestCase::$libDir . '/Exception/ConfigurationError.php';
require_once BaseTestCase::$libDir . '/User.php';
require_once BaseTestCase::$libDir . '/User/Preferences.php';
require_once BaseTestCase::$libDir . '/User/Preferences/LoadInterface.php';
require_once BaseTestCase::$libDir . '/User/Preferences/FlushObserverInterface.php';
require_once BaseTestCase::$libDir . '/User/Preferences/DbStore.php';
// @codingStandardsIgnoreEnd
use Icinga\Application\DbAdapterFactory; use \Zend_Db_Adapter_PDO_Abstract;
use Icinga\User; use Icinga\User;
use Icinga\User\Preferences\DbStore; use Icinga\User\Preferences\DbStore;
use Icinga\User\Preferences; use Icinga\User\Preferences;
use \PHPUnit_Framework_TestCase;
use \Zend_Config;
use \Zend_Db;
use \Zend_Db_Adapter_Abstract;
use \PDOException;
use \Exception;
class DbStoreTest extends PHPUnit_Framework_TestCase class DbStoreTest extends BaseTestCase
{ {
const TYPE_MYSQL = 'mysql';
const TYPE_PGSQL = 'pgsql'; private function createDbStore(Zend_Db_Adapter_PDO_Abstract $db)
private $table = 'preference';
private $databaseConfig = array(
'type' => 'db',
'host' => '127.0.0.1',
'username' => 'icinga_unittest',
'password' => 'icinga_unittest',
'dbname' => 'icinga_unittest'
);
/**
* @var Zend_Db_Adapter_Abstract
*/
private $dbMysql;
/**
* @var Zend_Db_Adapter_Abstract
*/
private $dbPgsql;
private function createDb($type)
{
$this->databaseConfig['db'] = $type;
$db = DbAdapterFactory::createDbAdapterFromConfig(
new Zend_Config($this->databaseConfig)
);
try {
$db->getConnection();
$dumpFile = realpath(__DIR__ . '/../../../../../../etc/schema/preferences.' . strtolower($type) . '.sql');
if (!$dumpFile) {
throw new Exception('Dumpfile for db type not found: ' . $type);
}
try {
$db->getConnection()->exec(file_get_contents($dumpFile));
} catch (PDOException $e) {
// PASS
}
} catch (\Zend_Db_Adapter_Exception $e) {
return null;
} catch (PDOException $e) {
return null;
}
return $db;
}
protected function setUp()
{
$this->dbMysql = $this->createDb(self::TYPE_MYSQL);
$this->dbPgsql = $this->createDb(self::TYPE_PGSQL);
}
protected function tearDown()
{
if ($this->dbMysql) {
$this->dbMysql->getConnection()->exec('DROP TABLE ' . $this->table);
}
if ($this->dbPgsql) {
$this->dbPgsql->getConnection()->exec('DROP TABLE ' . $this->table);
}
}
private function createDbStore(Zend_Db_Adapter_Abstract $db)
{ {
$user = new User('jdoe'); $user = new User('jdoe');
@ -113,53 +64,67 @@ class DbStoreTest extends PHPUnit_Framework_TestCase
return $store; return $store;
} }
public function testCreateUpdateDeletePreferenceValuesMySQL() /**
* @dataProvider mysqlDb
* @param Zend_Db_Adapter_PDO_Abstract $mysqlDb
*/
public function testCreateUpdateDeletePreferenceValuesMySQL($mysqlDb)
{ {
if ($this->dbMysql) { $this->setupDbProvider($mysqlDb);
$store = $this->createDbStore($this->dbMysql);
$preferences = new Preferences(array()); $this->loadSql(
$preferences->attach($store); $mysqlDb,
$sqlDumpFile = BaseTestCase::$etcDir . '/schema/preferences.mysql.sql'
);
$preferences->set('test.key1', 'OK1'); $store = $this->createDbStore($mysqlDb);
$preferences->set('test.key2', 'OK2');
$preferences->set('test.key3', 'OK2');
$preferences->remove('test.key2'); $preferences = new Preferences(array());
$preferences->attach($store);
$preferences->set('test.key3', 'OKOK333'); $preferences->set('test.key1', 'OK1');
$preferences->set('test.key2', 'OK2');
$preferences->set('test.key3', 'OK2');
$preferencesTest = new Preferences($store->load()); $preferences->remove('test.key2');
$this->assertEquals('OK1', $preferencesTest->get('test.key1'));
$this->assertNull($preferencesTest->get('test.key2')); $preferences->set('test.key3', 'OKOK333');
$this->assertEquals('OKOK333', $preferencesTest->get('test.key3'));
} else { $preferencesTest = new Preferences($store->load());
$this->markTestSkipped('MySQL test environment is not configured'); $this->assertEquals('OK1', $preferencesTest->get('test.key1'));
} $this->assertNull($preferencesTest->get('test.key2'));
$this->assertEquals('OKOK333', $preferencesTest->get('test.key3'));
} }
public function testCreateUpdateDeletePreferenceValuesPgSQL() /**
* @dataProvider pgsqlDb
* @param Zend_Db_Adapter_PDO_Abstract $pgsqlDb
*/
public function testCreateUpdateDeletePreferenceValuesPgSQL($pgsqlDb)
{ {
if ($this->dbPgsql) { $this->setupDbProvider($pgsqlDb);
$store = $this->createDbStore($this->dbPgsql);
$preferences = new Preferences(array()); $this->loadSql(
$preferences->attach($store); $pgsqlDb,
$sqlDumpFile = BaseTestCase::$etcDir . '/schema/preferences.pgsql.sql'
);
$preferences->set('test.key1', 'OK1'); $store = $this->createDbStore($pgsqlDb);
$preferences->set('test.key2', 'OK2');
$preferences->set('test.key3', 'OK2');
$preferences->remove('test.key2'); $preferences = new Preferences(array());
$preferences->attach($store);
$preferences->set('test.key3', 'OKOK333'); $preferences->set('test.key1', 'OK1');
$preferences->set('test.key2', 'OK2');
$preferences->set('test.key3', 'OK2');
$preferencesTest = new Preferences($store->load()); $preferences->remove('test.key2');
$this->assertEquals('OK1', $preferencesTest->get('test.key1'));
$this->assertNull($preferencesTest->get('test.key2')); $preferences->set('test.key3', 'OKOK333');
$this->assertEquals('OKOK333', $preferencesTest->get('test.key3'));
} else { $preferencesTest = new Preferences($store->load());
$this->markTestSkipped('PgSQL test environment is not configured'); $this->assertEquals('OK1', $preferencesTest->get('test.key1'));
} $this->assertNull($preferencesTest->get('test.key2'));
$this->assertEquals('OKOK333', $preferencesTest->get('test.key3'));
} }
} }