Abstract.php 9.38 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
<?php
/**
 * PHP Unit test suite for Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 *
 * @category   EcomDev
 * @package    EcomDev_PHPUnit
14
 * @copyright  Copyright (c) 2013 EcomDev BV (http://www.ecomdev.org)
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
 * @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 * @author     Ivan Chepurnyi <ivan.chepurnyi@ecomdev.org>
 */

/**
 * Abstract constraint for EcomDev_PHPUnit constraints
 * Contains flexible constaint types implementation
 *
 */
abstract class EcomDev_PHPUnit_Constraint_Abstract
    extends PHPUnit_Framework_Constraint
{
    /**
     * List of valiadation rules for expected value
     * It is an associative array with key as type and value
     * as an array of rules.
     *
     * First item of the rule array is mandatory indicator,
     * second is function name for checking the type,
     * third one is the type that will be displayed in invalid argument expception
     * each of them can be ommited or if it between other ones just by specifying null value
     *
     * @var array
     */
    protected $_expectedValueValidation = array();

    /**
     * List of types that will use diff for displaying fail result
     *
     * @var array
     */
    protected $_typesWithDiff = array();

    /**
     * Comparisment type defined in the constructor
     *
     * @var string
     */
    protected $_type = null;

    /**
     * Expected value defined in the constructor
     *
     * @var mixed
     */
    protected $_expectedValue = null;

    /**
     * Custom actual value
     *
     * @var mixed
     */
    protected $_actualValue = null;

    /**
     * Flag for using of actual value in failure description
     *
     * @var boolean
     */
    protected $_useActualValue = false;

76 77 78 79 80 81 82
    /**
     * Comparison failure for nice failure messages
     *
     * @var PHPUnit_Framework_ComparisonFailure
     */
    protected $_comparisonFailure = null;

83 84 85 86 87
    /**
     * Abstract cnstraint constructor,
     * provides unified interface for working with multiple types of evalation
     *
     * @param string $type
88 89 90
     * @param mixed  $expectedValue
     *
     * @throws PHPUnit_Framework_Exception
91 92 93
     */
    public function __construct($type, $expectedValue = null)
    {
94
        $reflection = EcomDev_Utils_Reflection::getReflection(get_class($this));
95 96 97 98 99 100 101 102 103 104 105 106 107 108
        $types = array();
        foreach ($reflection->getConstants() as $name => $constant) {
            if (strpos($name, 'TYPE_') === 0) {
                $types[] = $constant;
            }
        }

        if (empty($type) || !is_string($type) || !in_array($type, $types)) {
            throw PHPUnit_Util_InvalidArgumentHelper::factory(1, 'string', $type);
        }


        if (isset($this->_expectedValueValidation[$type])) {
            $expectedValueType = (isset($this->_expectedValueValidation[$type][2]) ?
109
                                  $this->_expectedValueValidation[$type][2] :
110 111 112 113 114 115 116 117 118 119 120
                                  '');

            // Mandatory check
            if (isset($this->_expectedValueValidation[$type][0])
                && $this->_expectedValueValidation[$type][0]
                && $expectedValue === null) {
                throw PHPUnit_Util_InvalidArgumentHelper::factory(2, $expectedValueType, $expectedValue);
            }

            // Type check
            if (isset($this->_expectedValueValidation[$type][1])
121
                && $expectedValue !== null
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
                && !$this->_expectedValueValidation[$type][1]($expectedValue)) {
                throw PHPUnit_Util_InvalidArgumentHelper::factory(2, $expectedValueType, $expectedValue);
            }
        }

        $this->_type = $type;
        $this->_expectedValue = $expectedValue;
    }

    /**
     * Set actual value that will be used in the fail message
     *
     * @param mixed $actual
     * @return EcomDev_PHPUnit_Constraint_Abstract
     */
    protected function setActualValue($actual)
    {
        $this->_useActualValue = true;
        $this->_actualValue = $actual;
        return $this;
    }


    /**
     * Calls internal protected method by defined constraint type
     * Also can be passed a single argument
     *
     * @param string $prefix
     * @return mixed
     */
    protected function callProtectedByType($prefix, $argument = null)
    {
        $camelizedType = uc_words($this->_type, '');
        $methodName = $prefix . $camelizedType;
        return $this->$methodName($argument);
    }

    /**
     * Evaluates value by type.
161
     *
162
     * @see PHPUnit_Framework_Constraint::evaluate()
163 164 165 166 167
     *
     * @param  mixed $other Value or object to evaluate.
     * @param  string $description Additional information about the test
     * @param  bool $returnResult Whether to return a result or throw an exception
     * @return mixed
168
     */
169
    public function evaluate($other, $description = '', $returnResult = false)
170
    {
171 172 173 174 175 176 177 178 179 180 181 182 183
        $success = false;

        if ($this->callProtectedByType('evaluate', $other)) {
            $success = true;
        }

        if ($returnResult) {
            return $success;
        }

        if (!$success) {
            $this->fail($other, $description);
        }
184 185 186 187 188 189 190 191
    }

    /**
     * Generates a failure exception based on exception type
     *
     * (non-PHPdoc)
     * @see PHPUnit_Framework_Constraint::fail()
     */
192
    public function fail($other, $description, PHPUnit_Framework_ComparisonFailure $comparisonFailure = NULL)
193
    {
194
        $failureDescription = sprintf('Failed asserting that %s', $this->failureDescription($other));
195 196 197 198

        if (in_array($this->_type, $this->_typesWithDiff)) {
            throw new EcomDev_PHPUnit_Constraint_Exception(
                $failureDescription,
199
                $this->getComparisonFailure($this->getExpectedValue(), $this->getActualValue($other)),
200 201 202 203 204 205 206 207 208
                $description
            );
        } else {
            throw new EcomDev_PHPUnit_Constraint_Exception(
                $failureDescription, $this->getActualValue($other), $description
            );
        }
    }

209 210 211 212 213 214 215 216
    /**
     * Adds compatibility to PHPUnit 3.6
     *
     * @param mixed $other
     * @param mixed $description (custom description)
     * @param boolean $not
     * @return string
     */
217
    protected function failureDescription($other)
218 219
    {
        if (method_exists($this, 'customFailureDescription')) {
220
            return $this->customFailureDescription($other);
221 222
        }

223
        return parent::failureDescription($other);
224 225
    }

226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
    /**
     * Returns a scalar representation of actual value,
     * Returns $other if internal acutal value is not set
     *
     * @param Varien_Simplexml_Element $other
     * @return scalar
     */
    protected function getActualValue($other = null)
    {
        if ($this->_useActualValue) {
            return $this->_actualValue;
        }

        return $other;
    }

    /**
     * Returns a scalar representation of expected value
     *
245
     * @return scalar
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
     */
    protected function getExpectedValue()
    {
        return $this->_expectedValue;
    }

    /**
     * Text reperesentation of constraint
     * (non-PHPdoc)
     * @see PHPUnit_Framework_SelfDescribing::toString()
     */
    public function toString()
    {
        return $this->callProtectedByType('text');
    }
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280

    /**
     * Exports value as string
     *
     * @param mixed $value
     * @return string
     */
    public function exportAsString($value)
    {
        if (is_array($value) && preg_match('/^\d+$/', implode('', array_keys($value)))) {
            $stringValue = '';
            foreach ($value as $val) {
                $stringValue .= (is_string($val) ? $val : PHPUnit_Util_Type::export($val)) . "\n";
            }

            return $stringValue;
        } else {
            return PHPUnit_Util_Type::export($value);
        }
    }
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336

    /**
     * Compares two values by using correct comparator for two types
     *
     * @param mixed $expectedValue
     * @param mixed $actualValue
     * @return bool
     */
    public function compareValues($expectedValue, $actualValue)
    {
        $comparatorFactory = PHPUnit_Framework_ComparatorFactory::getDefaultInstance();

        try {
            $comparator = $comparatorFactory->getComparatorFor(
                $expectedValue, $actualValue
            );

            $comparator->assertEquals(
                $expectedValue,
                $actualValue
            );
        }

        catch (PHPUnit_Framework_ComparisonFailure $f) {
            $this->_comparisonFailure = $f;
            return false;
        }

        return true;
    }

    /**
     * Retrieve comparison failure exception.
     *
     * Is used for generation of the failure messages
     *
     * @param mixed $actualValue
     * @param mixed $expectedValue
     *
     * @return PHPUnit_Framework_ComparisonFailure
     */
    public function getComparisonFailure($actualValue, $expectedValue)
    {
        if ($this->_comparisonFailure !== null) {
            $failure = $this->_comparisonFailure;
            $this->_comparisonFailure = null;
            return $failure;
        }

        return new PHPUnit_Framework_ComparisonFailure(
            $expectedValue,
            $actualValue,
            $this->exportAsString($expectedValue),
            $this->exportAsString($actualValue)
        );
    }
337
}