Giter VIP home page Giter VIP logo

symfonyconfigtest's Introduction

SymfonyConfigTest

By Matthias Noback

Build Status

Writing configuration classes using the Symfony Config Component can be quite hard. To help you verify the validity of the resulting config node tree, this library provides a PHPUnit test case and some custom assertions.

Installation

Using Composer:

php composer.phar require --dev matthiasnoback/symfony-config-test

Usage

PHP 5.4 and up

Create a test case and use the trait from Matthias\SymfonyConfigTest\PhpUnit\ConfigurationTestCaseTrait. Then implement getConfiguration():

<?php

class ConfigurationTest extends \PHPUnit_Framework_TestCase
{
    use ConfigurationTestCaseTrait;

    protected function getConfiguration()
    {
        return new Configuration();
    }
}

PHP 5.3

Create a test case and extend from Matthias\SymfonyConfigTest\PhpUnit\AbstractConfigurationTestCase. Then implement getConfiguration():

<?php

class ConfigurationTest extends AbstractConfigurationTestCase
{
    protected function getConfiguration()
    {
        return new Configuration();
    }
}

Test invalid configuration values

Let's assume the Configuration class you want to test looks like this:

<?php

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

class ConfigurationWithRequiredValue implements ConfigurationInterface
{
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();

        $rootNode = $treeBuilder->root('root');
        $rootNode
            ->isRequired()
            ->children()
                ->scalarNode('required_value')
                    ->isRequired()
                ->end()
            ->end();

        return $treeBuilder;
    }
}

When you provide an empty array as the value for this configuration, you would expect an exception since the required_value node is required. You can assert that a given set of configuration values is invalid using the assertConfigurationIsInvalid() method:

<?php

class ConfigurationTest extends \PHPUnit_Framework_TestCase
{
    use ConfigurationTestCaseTrait;

    public function testValuesAreInvalidIfRequiredValueIsNotProvided()
    {
        $this->assertConfigurationIsInvalid(
            array(
                array() // no values at all
            ),
            'required_value' // (part of) the expected exception message - optional
        );
    }
}

Test processed configuration values

You may also want to verify that after processing an array of configuration values the result will be as expected:

<?php

class ConfigurationTest extends \PHPUnit_Framework_TestCase
{
    use ConfigurationTestCaseTrait;

    public function testProcessedValueContainsRequiredValue()
    {
        $this->assertProcessedConfigurationEquals(array(
            array('required_value' => 'first value'),
            array('required_value' => 'last value')
        ), array(
            'required_value'=> 'last value'
        ));
    }
}

Please note: the first argument of each of the assert* methods is an array of arrays. The extra nesting level allows you to test the merge process. See also the section Merging options of the Config Component documentation.

Test a subset of the configuration tree

Using this library it's possible to test just one branch of your configuration tree. Consider the following node tree definition, which contains the branches array_node_1 and array_node_2:

<?php

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

class ConfigurationWithTwoBranches implements ConfigurationInterface
{
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();

        $rootNode = $treeBuilder->root('root');
        $rootNode
            ->children()
                ->arrayNode('array_node_1')
                    ->isRequired()
                    ->children()
                        ->scalarNode('required_value_1')
                            ->isRequired()
                        ->end()
                    ->end()
                ->end()
                ->arrayNode('array_node_2')
                    ->isRequired()
                    ->children()
                        ->scalarNode('required_value_2')
                            ->isRequired()
                        ->end()
                    ->end()
                ->end()
            ->end();

        return $treeBuilder;
    }
}

If you want to test, for instance, only the array_node_1 branch from the example below, and ignore the array_node_2, provide array_node_1 as the argument for the $breadcrumbPath parameter of the test helper functions, for example:

/**
 * @test
 */
public function processed_configuration_for_array_node_1()
{
    $this->assertProcessedConfigurationEquals(
        array(
            array('array_node_1' => array('required_value_1' => 'original value'),
            array('array_node_1' => array('required_value_1' => 'final value')
        ),
        array(
            'array_node_1' => array(
                'required_value_1' => 'final value'
            )
        ),
        // the path of the nodes you want to focus on in this test:
        'array_node_1'
    );
}

This would trigger no validation errors for any value in the array_node_2 branch.

Note that the $breadcrumbPath can be even more specific, e.g. "doctrine.orm" (which would skip configuration processing for branch "doctrine.dbal", etc.).

Also note that you can only traverse over array nodes using the . in the breadcrumb path. The last part of the breadcrumb path can be any other type of node.

Test a subset of the prototyped configuration tree

You can traverse through prototype array nodes using * as its name in the breadcrumb path.

<?php

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

class PrototypedConfiguration implements ConfigurationInterface
{
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();

        $rootNode = $treeBuilder->root('root');
        $rootNode
            ->children()
                ->arrayNode('array_node')
                    ->useAttributeAsKey('name')
                    ->prototype('array')
                        ->children()
                            ->scalarNode('default_value')->cannotBeEmpty()->defaultValue('foobar')->end()
                            ->scalarNode('required_value')->isRequired()->end()
                        ->end()
                    ->end()
                ->end()
            ->end();

        return $treeBuilder;
    }
}

If you want to test whether default_value is set to foobar by default, but don't want the test to be affected by requirements on required_value node, you can define its path as array_node.*.default_value, for example:

/**
 * @test
 */
public function processed_configuration_for_array_node_1()
{
    $this->assertProcessedConfigurationEquals(
        array(
            array('array_node' => array('prototype_name' => null)),
        ),
        array(
            'array_node' => array(
                'prototype_name' => array(
                    'default_value' => 'foobar'
                )
            )
        ),
        // the path of the nodes you want to focus on in this test:
        'array_node.*.default_value'
    );
}

symfonyconfigtest's People

Contributors

matthiasnoback avatar soullivaneuh avatar h4cc avatar pamil avatar xabbuh avatar fvdb avatar helios-ag avatar emodric avatar javiereguiluz avatar wouterj avatar satahippy avatar

Watchers

Grégoire Paris avatar James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.