Refactor ResourceForm tests

refs #6011
This commit is contained in:
Johannes Meyer 2014-04-16 16:41:23 +02:00
parent 3d44c45eb8
commit 21b949758f
7 changed files with 509 additions and 159 deletions

View File

@ -89,7 +89,7 @@ class LdapBackendForm extends BaseBackendForm
array(
'required' => true,
'allowEmpty' => false,
'label' => t('LDAP resource'),
'label' => t('LDAP Resource'),
'helptext' => t('The resource to use for authenticating with this provider'),
'value' => $this->getBackend()->get('resource'),
'multiOptions' => $this->getResources()

View File

@ -29,40 +29,41 @@
namespace Icinga\Form\Config\Resource;
use \Zend_Config;
use Exception;
use Zend_Config;
use Zend_Form_Element_Checkbox;
use Icinga\Web\Form;
use Icinga\Logger\Logger;
use Icinga\Web\Form\Decorator\HelpText;
use Icinga\Data\ResourceFactory;
use Icinga\Web\Form\Element\Number;
use Icinga\Web\Form\Decorator\HelpText;
/**
* Form for modifying a monitoring backend
*/
class ResourceForm extends Form
{
/**
* The currently edited resource.
* The resource
*
* @var Zend_Config
*/
private $resource;
protected $resource;
/**
* The (new) name of the resource
*
* @var string
*/
private $name = '';
protected $name;
/**
* The old name of the resource
*
* @var string
*/
private $oldName = '';
protected $oldName;
/**
* Return the current resource name.
* Set the current resource name
*
* @param string $name
*
* @return void|\Zend_Form
* @param string $name The name to set
*/
public function setName($name)
{
@ -70,18 +71,24 @@ class ResourceForm extends Form
}
/**
* Get the current resource name
*
* @return null|string
*/
public function getName()
{
return $this->getValue('resource_all_name');
$name = $this->getValue('resource_all_name');
if (!$name) {
return $this->name;
}
return $name;
}
/**
* Set the original name of the resource. This value is persisted using
* a hidden field.
* Set the original name of the resource
*
* @param $name
* @param string $name The name to set
*/
public function setOldName($name)
{
@ -89,182 +96,24 @@ class ResourceForm extends Form
}
/**
* Get the resource name that was initially set.
* Get the resource name that was initially set
*
* @return null|string
*/
public function getOldName()
{
return $this->getValue('resource_all_name_old');
$oldName = $this->getValue('resource_all_name_old');
if (!$oldName) {
return $this->oldName;
}
private function addDbForm()
{
$this->addElement(
'select',
'resource_db_db',
array(
'label' => 'Database Type',
'value' => $this->getResource()->get('db', 'mysql'),
'required' => true,
'helptext' => 'The type of SQL database you want to create.',
'multiOptions' => array(
'mysql' => 'MySQL',
'pgsql' => 'PostgreSQL'
//'oracle' => 'Oracle'
)
)
);
$this->addElement(
'text',
'resource_db_host',
array (
'label' => 'Host',
'value' => $this->getResource()->get('host', 'localhost'),
'required' => true,
'helptext' => 'The hostname of the database.'
)
);
$this->addElement(
'text',
'resource_db_port',
array(
'label' => 'Port',
'value' => $this->getResource()->get('port', 3306),
'required' => true,
'validators' => array(
array('regex', false, '/^[0-9]+$/')
),
'helptext' => 'The port number to use.'
)
);
$this->addElement(
'text',
'resource_db_dbname',
array(
'label' => 'Database Name',
'value' => $this->getResource()->get('dbname', ''),
'required' => true,
'helptext' => 'The name of the database to use'
)
);
$this->addElement(
'text',
'resource_db_username',
array (
'label' => 'Username',
'value' => $this->getResource()->get('username', ''),
'required' => true,
'helptext' => 'The user name to use for authentication.'
)
);
$this->addElement(
'password',
'resource_db_password',
array(
'label' => 'Password',
'renderPassword' => true,
'value' => $this->getResource()->get('password', ''),
'helptext' => 'The password to use for authentication',
'required' => true
)
);
}
private function addStatusdatForm()
{
$this->addElement(
'text',
'resource_statusdat_status_file',
array(
'label' => 'Status.dat File',
'value' => $this->getResource()->get('status_file', '/usr/local/icinga/var/status.dat'),
'required' => true,
'helptext' => 'Location of your icinga status.dat file'
)
);
$this->addElement(
'text',
'resource_statusdat_object_file',
array(
'label' => 'Objects.cache File',
'value' => $this->getResource()->get('status_file', '/usr/local/icinga/var/objects.cache'),
'required' => true,
'helptext' => 'Location of your icinga objects.cache file'
)
);
}
private function addLivestatusForm()
{
$this->addElement(
'text',
'resource_livestatus_socket',
array(
'label' => 'Livestatus Socket Location',
'required' => true,
'helptext' => 'The path to your livestatus socket used for querying monitoring data',
'value' => $this->getResource()->socket,
)
);
}
private function addLdapForm()
{
$this->addElement(
'text',
'resource_ldap_hostname',
array(
'label' => 'LDAP Server Host',
'allowEmpty' => false,
'value' => $this->getResource()->get('hostname', 'localhost'),
'helptext' => 'The hostname or address of the LDAP server to use for authentication',
'required' => true
)
);
$this->addElement(
'text',
'resource_ldap_root_dn',
array(
'label' => 'LDAP Root DN',
'value' => $this->getResource()->get('root_dn', 'ou=people,dc=icinga,dc=org'),
'helptext' => 'The path where users can be found on the ldap server',
'required' => true
)
);
$this->addElement(
'text',
'resource_ldap_bind_dn',
array(
'label' => 'LDAP Bind DN',
'value' => $this->getResource()->get('bind_dn', 'cn=admin,cn=config'),
'helptext' => 'The user dn to use for querying the ldap server',
'required' => true
)
);
$this->addElement(
'password',
'resource_ldap_bind_pw',
array(
'label' => 'LDAP Bind Password',
'renderPassword' => true,
'value' => $this->getResource()->get('bind_pw', ''),
'helptext' => 'The password to use for querying the ldap server',
'required' => true
)
);
return $oldName;
}
/**
* Set the resource configuration to edit.
*
* @param Zend_Config $resource
* @param Zend_Config $resource The config to set
*/
public function setResource(Zend_Config $resource)
{
@ -279,50 +128,234 @@ class ResourceForm extends Form
public function getResource()
{
if (!isset($this->resource)) {
// Init empty resource
$this->resource = new Zend_Config(
array('type' => 'db')
);
$this->resource = new Zend_Config(array('type' => 'db'));
}
return $this->resource;
}
/**
* Add a field to change the resource name and one hidden field
* to save the previous resource name.
*/
private function addNameFields()
protected function addDbForm()
{
$this->addElement(
'select',
'resource_db_db',
array(
'required' => true,
'label' => t('Database Type'),
'helptext' => t('The type of SQL database you want to create.'),
'value' => $this->getResource()->get('db', 'mysql'),
'multiOptions' => array(
'mysql' => 'MySQL',
'pgsql' => 'PostgreSQL'
//'oracle' => 'Oracle'
)
)
);
$this->addElement(
'text',
'resource_db_host',
array (
'required' => true,
'label' => t('Host'),
'helptext' => t('The hostname of the database.'),
'value' => $this->getResource()->get('host', 'localhost')
)
);
$this->addElement(
new Number(
array(
'name' => 'resource_db_port',
'required' => true,
'label' => t('Port'),
'helptext' => t('The port to use.'),
'value' => $this->getResource()->get('port', 3306)
)
)
);
$this->addElement(
'text',
'resource_db_dbname',
array(
'required' => true,
'label' => t('Database Name'),
'helptext' => t('The name of the database to use'),
'value' => $this->getResource()->get('dbname', '')
)
);
$this->addElement(
'text',
'resource_db_username',
array (
'required' => true,
'label' => t('Username'),
'helptext' => t('The user name to use for authentication.'),
'value' => $this->getResource()->get('username', '')
)
);
$this->addElement(
'password',
'resource_db_password',
array(
'required' => true,
'renderPassword' => true,
'label' => t('Password'),
'helptext' => t('The password to use for authentication'),
'value' => $this->getResource()->get('password', '')
)
);
}
protected function addStatusdatForm()
{
$this->addElement(
'text',
'resource_statusdat_status_file',
array(
'required' => true,
'label' => t('Filepath'),
'helptext' => t('Location of your icinga status.dat file'),
'value' => $this->getResource()->get('status_file', '/usr/local/icinga/var/status.dat')
)
);
$this->addElement(
'text',
'resource_statusdat_object_file',
array(
'required' => true,
'label' => t('Filepath'),
'helptext' => t('Location of your icinga objects.cache file'),
'value' => $this->getResource()->get('status_file', '/usr/local/icinga/var/objects.cache')
)
);
}
protected function addLivestatusForm()
{
$this->addElement(
'text',
'resource_livestatus_socket',
array(
'required' => true,
'label' => t('Socket'),
'helptext' => t('The path to your livestatus socket used for querying monitoring data'),
'value' => $this->getResource()->get('socket', '/usr/local/icinga/var/rw/livestatus')
)
);
}
protected function addLdapForm()
{
$this->addElement(
'text',
'resource_ldap_hostname',
array(
'required' => true,
'allowEmpty' => false,
'label' => t('Host'),
'helptext' => t('The hostname or address of the LDAP server to use for authentication'),
'value' => $this->getResource()->get('hostname', 'localhost')
)
);
$this->addElement(
'text',
'resource_ldap_root_dn',
array(
'required' => true,
'label' => t('Root DN'),
'helptext' => t('The path where users can be found on the ldap server'),
'value' => $this->getResource()->get('root_dn', 'ou=people,dc=icinga,dc=org')
)
);
$this->addElement(
'text',
'resource_ldap_bind_dn',
array(
'required' => true,
'label' => t('Bind DN'),
'helptext' => t('The user dn to use for querying the ldap server'),
'value' => $this->getResource()->get('bind_dn', 'cn=admin,cn=config')
)
);
$this->addElement(
'password',
'resource_ldap_bind_pw',
array(
'required' => true,
'renderPassword' => true,
'label' => t('Bind Password'),
'helptext' => t('The password to use for querying the ldap server'),
'value' => $this->getResource()->get('bind_pw', '')
)
);
}
protected function addFileForm()
{
$this->addElement(
'text',
'resource_file_filename',
array(
'required' => true,
'label' => t('Filepath'),
'helptext' => t('The filename to fetch information from'),
'value' => $this->getResource()->get('filename', '')
)
);
$this->addElement(
'text',
'resource_file_fields',
array(
'required' => true,
'label' => t('Pattern'),
'helptext' => t('The regular expression by which to identify columns'),
'value' => $this->getResource()->get('fields', '')
)
);
}
protected function addNameFields()
{
$this->addElement(
'text',
'resource_all_name',
array(
'label' => 'Resource Name',
'value' => $this->name,
'helptext' => 'The unique name of this resource',
'required' => true
'required' => true,
'label' => t('Resource Name'),
'helptext' => t('The unique name of this resource'),
'value' => $this->getName()
)
);
$this->addElement(
'hidden',
'resource_all_name_old',
array(
'value' => $this->oldName
'value' => $this->getOldName()
)
);
}
/**
* Add checkbox at the beginning of the form which allows to skip logic connection validation
* Add checkbox at the beginning of the form which allows to skip connection validation
*/
private function addForceCreationCheckbox()
protected function addForceCreationCheckbox()
{
$checkbox = new \Zend_Form_Element_Checkbox(
$checkbox = new Zend_Form_Element_Checkbox(
array(
'name' => 'backend_force_creation',
'label' => 'Force Changes',
'helptext' => 'Check this box to enforce changes without connectivity validation',
'order' => 0
'order' => 0,
'name' => 'resource_force_creation',
'label' => t('Force Changes'),
'helptext' => t('Check this box to enforce changes without connectivity validation')
)
);
$checkbox->addDecorator(new HelpText());
@ -332,21 +365,22 @@ class ResourceForm extends Form
/**
* Add a select box for choosing the type to use for this backend
*/
private function addTypeSelectionBox()
protected function addTypeSelectionBox()
{
$this->addElement(
'select',
'resource_type',
array(
'label' => 'Resource Type',
'value' => $this->getResource()->type,
'required' => true,
'helptext' => 'The type of resource.',
'label' => t('Resource Type'),
'helptext' => t('The type of resource'),
'value' => $this->getResource()->type,
'multiOptions' => array(
'db' => 'SQL Database',
'ldap' => 'Ldap',
'db' => t('SQL Database'),
'ldap' => 'LDAP',
'statusdat' => 'Status.dat',
'livestatus' => 'Livestatus'
'livestatus' => 'Livestatus',
'file' => t('File')
)
)
);
@ -354,10 +388,10 @@ class ResourceForm extends Form
}
/**
* Validate this form with the Zend validation mechanism and perform a validation of the connection.
* Validate this form with the Zend validation mechanism and perform a validation of the connection
*
* If validation fails, the 'backend_force_creation' checkbox is prepended to the form to allow users to
* skip the logic connection validation.
* If validation fails, the 'resource_force_creation' checkbox is prepended to the form to allow users to
* skip the connection validation
*
* @param array $data The form input to validate
*
@ -368,7 +402,7 @@ class ResourceForm extends Form
if (!parent::isValid($data)) {
return false;
}
if ($this->getRequest()->getPost('backend_force_creation')) {
if (isset($data['resource_force_creation']) && $data['resource_force_creation']) {
return true;
}
if (!$this->isValidResource()) {
@ -380,14 +414,15 @@ class ResourceForm extends Form
/**
* Test if the changed resource is a valid resource, by instantiating it and
* checking if connection is possible.
* checking if a connection is possible
*
* @return bool True when connection to the resource is possible.
* @return bool True when a connection to the resource is possible
*/
private function isValidResource()
public function isValidResource()
{
try {
$config = $this->getConfig();
try {
switch ($config->type) {
case 'db':
$resource = ResourceFactory::createResource($config);
@ -396,23 +431,33 @@ class ResourceForm extends Form
case 'statusdat':
if (!file_exists($config->object_file) || !file_exists($config->status_file)) {
$this->addErrorMessage(
'Connectivity validation failed, the provided file or socket does not exist.'
t('Connectivity validation failed, the provided file does not exist.')
);
return false;
}
break;
case 'livestatus':
// TODO: Implement check
$resource = ResourceFactory::createResource($config);
$resource->connect()->disconnect();
break;
case 'ldap':
$resource = ResourceFactory::createResource($config);
$resource->connect();
break;
}
} catch (\Exception $exc) {
$this->addErrorMessage('Connectivity validation failed, connection to the given resource not possible.');
case 'file':
if (!file_exists($config->filename)) {
$this->addErrorMessage(
t('Connectivity validation failed, the provided file does not exist.')
);
return false;
}
break;
}
} catch (Exception $e) {
$this->addErrorMessage(t('Connectivity validation failed, connection to the given resource not possible.'));
return false;
}
return true;
}
@ -420,6 +465,7 @@ class ResourceForm extends Form
{
$this->addNameFields();
$this->addTypeSelectionBox();
switch ($this->getRequest()->getParam('resource_type', $this->getResource()->type)) {
case 'db':
$this->addDbForm();
@ -433,7 +479,11 @@ class ResourceForm extends Form
case 'ldap':
$this->addLdapForm();
break;
case 'file':
$this->addFileForm();
break;
}
$this->setSubmitLabel('{{SAVE_ICON}} Save Changes');
}
@ -445,18 +495,17 @@ class ResourceForm extends Form
public function getConfig()
{
$values = $this->getValues();
$type = $values['resource_type'];
$result = array('type' => $type);
$result = array('type' => $values['resource_type']);
foreach ($values as $key => $value) {
if ($key !== 'resource_type' && $key !== 'resource_all_name' && $key !== 'resource_all_name_old') {
$configKey = explode('_', $key, 3);
if (sizeof($configKey) < 3) {
Logger::warning('EditResourceForm: invalid form key "' . $key . '" was ignored.');
continue;
}
if (count($configKey) === 3) {
$result[$configKey[2]] = $value;
}
}
}
return new Zend_Config($result);
}
}

View File

@ -273,6 +273,15 @@ class Connection
}
}
public function connect()
{
if (!$this->connection) {
$this->getConnection();
}
return $this;
}
public function disconnect()
{
if ($this->connection) {

View File

@ -29,16 +29,38 @@
namespace Icinga\Web\Form\Element;
use Zend_Form_Element_Xhtml;
/**
* Number form element
*
* @TODO: The given label for this element is not displayed. (Reason unknown)
*/
class Number extends \Zend_Form_Element_Xhtml
class Number extends Zend_Form_Element_Xhtml
{
/**
* Default form view helper to use for rendering
*
* @var string
*/
public $helper = "formNumber";
/**
* Check whether $value is of type integer
*
* @param string $value The value to check
* @param mixed $context Context to use
*
* @return bool
*/
public function isValid($value, $context = null)
{
if (parent::isValid($value, $context)) {
if (is_numeric($value)) {
return true;
}
$this->addError(t('Please enter a number.'));
}
return false;
}
}

View File

@ -4,12 +4,18 @@
namespace Tests\Icinga\Form\Config\Authentication;
use \Mockery;
use Mockery;
use Icinga\Test\BaseTestCase;
use Icinga\Form\Config\Authentication\DbBackendForm;
class DbBackendFormTest extends BaseTestCase
{
public function tearDown()
{
parent::tearDown();
Mockery::close(); // Necessary because some tests run in a separate process
}
/**
* @runInSeparateProcess
*/

View File

@ -4,12 +4,18 @@
namespace Tests\Icinga\Form\Config\Authentication;
use \Mockery;
use Mockery;
use Icinga\Test\BaseTestCase;
use Icinga\Form\Config\Authentication\LdapBackendForm;
class LdapBackendFormTest extends BaseTestCase
{
public function tearDown()
{
parent::tearDown();
Mockery::close(); // Necessary because some tests run in a separate process
}
/**
* @runInSeparateProcess
*/

View File

@ -0,0 +1,258 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Tests\Icinga\Form\Config\Resource;
use Mockery;
use Zend_Config;
use Icinga\Test\BaseTestCase;
use Icinga\Form\Config\Resource\ResourceForm;
class TestResourceForm extends ResourceForm
{
public $is_valid;
public function isValidResource()
{
return $this->is_valid;
}
}
class ResourceFormTest extends BaseTestCase
{
public function tearDown()
{
parent::tearDown();
Mockery::close(); // Necessary because some tests run in a separate process
}
public function testIsForceCreationCheckboxBeingAdded()
{
$form = new TestResourceForm();
$form->is_valid = false;
$this->assertFalse($form->isValid(array()));
$this->assertNotNull(
$form->getElement('resource_force_creation'),
'Checkbox to force the creation of a resource is not being added though the resource is invalid'
);
}
public function testIsForceCreationCheckboxNotBeingAdded()
{
$form = new TestResourceForm();
$form->is_valid = true;
$this->assertTrue($form->isValid(array()));
$this->assertNull(
$form->getElement('resource_force_creation'),
'Checkbox to force the creation of a resource is being added though the resource is valid'
);
}
public function testIsTheFormValidIfForceCreationTrue()
{
$form = new TestResourceForm();
$form->is_valid = false;
$this->assertTrue(
$form->isValid(array('resource_force_creation' => 1)),
'ResourceForm with invalid resource is not valid though force creation is set'
);
}
/**
* @runInSeparateProcess
*/
public function testValidDbResourceIsValid()
{
$this->setUpResourceFactoryMock(
Mockery::mock()->shouldReceive('getConnection')->atMost()->twice()->andReturn(Mockery::self())->getMock()
);
$form = $this->buildResourceForm(new Zend_Config(array('type' => 'db')));
$this->assertTrue(
$form->isValidResource(),
'ResourceForm claims that a valid db resource is not valid'
);
}
/**
* @runInSeparateProcess
*/
public function testInvalidDbResourceIsNotValid()
{
$this->setUpResourceFactoryMock(
Mockery::mock()->shouldReceive('getConnection')->once()->andThrow('\Exception')->getMock()
);
$form = $this->buildResourceForm(new Zend_Config(array('type' => 'db')));
$this->assertFalse(
$form->isValidResource(),
'ResourceForm claims that an invalid db resource is valid'
);
}
/**
* @runInSeparateProcess
*/
public function testValidLdapResourceIsValid()
{
$this->setUpResourceFactoryMock(
Mockery::mock()->shouldReceive('connect')->getMock()
);
$form = $this->buildResourceForm(new Zend_Config(array('type' => 'ldap')));
$this->assertTrue(
$form->isValidResource(),
'ResourceForm claims that a valid ldap resource is not valid'
);
}
/**
* @runInSeparateProcess
*/
public function testInvalidLdapResourceIsNotValid()
{
$this->setUpResourceFactoryMock(
Mockery::mock()->shouldReceive('connect')->once()->andThrow('\Exception')->getMock()
);
$form = $this->buildResourceForm(new Zend_Config(array('type' => 'ldap')));
$this->assertFalse(
$form->isValidResource(),
'ResourceForm claims that an invalid ldap resource is valid'
);
}
/**
* @runInSeparateProcess
*/
public function testValidLivestatusResourceIsValid()
{
$this->setUpResourceFactoryMock(
Mockery::mock()->shouldReceive('connect')->andReturn(Mockery::self())
->shouldReceive('disconnect')->getMock()
);
$form = $this->buildResourceForm(new Zend_Config(array('type' => 'livestatus')));
$this->assertTrue(
$form->isValidResource(),
'ResourceForm claims that a valid livestatus resource is not valid'
);
}
/**
* @runInSeparateProcess
*/
public function testInvalidLivestatusResourceIsNotValid()
{
$this->setUpResourceFactoryMock(
Mockery::mock()->shouldReceive('connect')->once()->andThrow('\Exception')->getMock()
);
$form = $this->buildResourceForm(new Zend_Config(array('type' => 'livestatus')));
$this->assertFalse(
$form->isValidResource(),
'ResourceForm claims that an invalid livestatus resource is valid'
);
}
public function testValidFileResourceIsValid()
{
$form = $this->buildResourceForm(
new Zend_Config(
array(
'type' => 'file',
'filename' => BaseTestCase::$testDir . '/res/status/icinga.status.dat'
)
)
);
$this->assertTrue(
$form->isValidResource(),
'ResourceForm claims that a valid file resource is not valid'
);
}
public function testInvalidFileResourceIsNotValid()
{
$form = $this->buildResourceForm(
new Zend_Config(
array(
'type' => 'file',
'filename' => 'not_existing'
)
)
);
$this->assertFalse(
$form->isValidResource(),
'ResourceForm claims that an invalid file resource is valid'
);
}
public function testValidStatusdatResourceIsValid()
{
$form = $this->buildResourceForm(
new Zend_Config(
array(
'type' => 'statusdat',
'status_file' => BaseTestCase::$testDir . '/res/status/icinga.status.dat',
'object_file' => BaseTestCase::$testDir . '/res/status/icinga.objects.cache',
)
)
);
$this->assertTrue(
$form->isValidResource(),
'ResourceForm claims that a valid statusdat resource is not valid'
);
}
public function testInvalidStatusdatResourceIsNotValid()
{
$form = $this->buildResourceForm(
new Zend_Config(
array(
'type' => 'statusdat',
'status_file' => 'not_existing',
'object_file' => 'not_existing'
)
)
);
$this->assertFalse(
$form->isValidResource(),
'ResourceForm claims that an invalid statusdat resource is valid'
);
}
protected function buildResourceForm($resourceConfig)
{
$form = new ResourceForm();
$form->setRequest($this->getRequestMock());
$form->setResource($resourceConfig);
$form->create();
return $form;
}
protected function getRequestMock()
{
return Mockery::mock('\Zend_Controller_Request_Abstract')
->shouldReceive('getParam')
->with(Mockery::type('string'), Mockery::type('string'))
->andReturnUsing(function ($name, $default) { return $default; })
->getMock();
}
protected function setUpResourceFactoryMock($resourceMock)
{
Mockery::mock('alias:Icinga\Data\ResourceFactory')
->shouldReceive('createResource')
->with(Mockery::type('\Zend_Config'))
->andReturn($resourceMock);
}
}