4 * This file is part of Twig.
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 use PHPUnit\Framework\TestCase;
15 * Integration test helper.
17 * @author Fabien Potencier <fabien@symfony.com>
18 * @author Karma Dordrak <drak@zikula.org>
20 abstract class Twig_Test_IntegrationTestCase extends TestCase
25 abstract protected function getFixturesDir();
28 * @return Twig_RuntimeLoaderInterface[]
30 protected function getRuntimeLoaders()
36 * @return Twig_ExtensionInterface[]
38 protected function getExtensions()
44 * @return Twig_SimpleFilter[]
46 protected function getTwigFilters()
52 * @return Twig_SimpleFunction[]
54 protected function getTwigFunctions()
60 * @return Twig_SimpleTest[]
62 protected function getTwigTests()
68 * @dataProvider getTests
70 public function testIntegration($file, $message, $condition, $templates, $exception, $outputs)
72 $this->doIntegrationTest($file, $message, $condition, $templates, $exception, $outputs);
76 * @dataProvider getLegacyTests
79 public function testLegacyIntegration($file, $message, $condition, $templates, $exception, $outputs)
81 $this->doIntegrationTest($file, $message, $condition, $templates, $exception, $outputs);
84 public function getTests($name, $legacyTests = false)
86 $fixturesDir = realpath($this->getFixturesDir());
89 foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($fixturesDir), RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
90 if (!preg_match('/\.test$/', $file)) {
94 if ($legacyTests xor false !== strpos($file->getRealpath(), '.legacy.test')) {
98 $test = file_get_contents($file->getRealpath());
100 if (preg_match('/--TEST--\s*(.*?)\s*(?:--CONDITION--\s*(.*))?\s*((?:--TEMPLATE(?:\(.*?\))?--(?:.*?))+)\s*(?:--DATA--\s*(.*))?\s*--EXCEPTION--\s*(.*)/sx', $test, $match)) {
101 $message = $match[1];
102 $condition = $match[2];
103 $templates = self::parseTemplates($match[3]);
104 $exception = $match[5];
105 $outputs = array(array(null, $match[4], null, ''));
106 } elseif (preg_match('/--TEST--\s*(.*?)\s*(?:--CONDITION--\s*(.*))?\s*((?:--TEMPLATE(?:\(.*?\))?--(?:.*?))+)--DATA--.*?--EXPECT--.*/s', $test, $match)) {
107 $message = $match[1];
108 $condition = $match[2];
109 $templates = self::parseTemplates($match[3]);
111 preg_match_all('/--DATA--(.*?)(?:--CONFIG--(.*?))?--EXPECT--(.*?)(?=\-\-DATA\-\-|$)/s', $test, $outputs, PREG_SET_ORDER);
113 throw new InvalidArgumentException(sprintf('Test "%s" is not valid.', str_replace($fixturesDir.'/', '', $file)));
116 $tests[] = array(str_replace($fixturesDir.'/', '', $file), $message, $condition, $templates, $exception, $outputs);
119 if ($legacyTests && empty($tests)) {
120 // add a dummy test to avoid a PHPUnit message
121 return array(array('not', '-', '', array(), '', array()));
127 public function getLegacyTests()
129 return $this->getTests('testLegacyIntegration', true);
132 protected function doIntegrationTest($file, $message, $condition, $templates, $exception, $outputs)
135 $this->markTestSkipped('no tests to run');
139 eval('$ret = '.$condition.';');
141 $this->markTestSkipped($condition);
145 $loader = new Twig_Loader_Array($templates);
147 foreach ($outputs as $i => $match) {
148 $config = array_merge(array(
150 'strict_variables' => true,
151 ), $match[2] ? eval($match[2].';') : array());
152 $twig = new Twig_Environment($loader, $config);
153 $twig->addGlobal('global', 'global');
154 foreach ($this->getRuntimeLoaders() as $runtimeLoader) {
155 $twig->addRuntimeLoader($runtimeLoader);
158 foreach ($this->getExtensions() as $extension) {
159 $twig->addExtension($extension);
162 foreach ($this->getTwigFilters() as $filter) {
163 $twig->addFilter($filter);
166 foreach ($this->getTwigTests() as $test) {
167 $twig->addTest($test);
170 foreach ($this->getTwigFunctions() as $function) {
171 $twig->addFunction($function);
174 // avoid using the same PHP class name for different cases
176 if (PHP_VERSION_ID >= 50300) {
177 $p = new ReflectionProperty($twig, 'templateClassPrefix');
178 $p->setAccessible(true);
179 $p->setValue($twig, '__TwigTemplate_'.hash('sha256', uniqid(mt_rand(), true), false).'_');
183 $template = $twig->loadTemplate('index.twig');
184 } catch (Exception $e) {
185 if (false !== $exception) {
186 $message = $e->getMessage();
187 $this->assertSame(trim($exception), trim(sprintf('%s: %s', get_class($e), $message)));
188 $last = substr($message, strlen($message) - 1);
189 $this->assertTrue('.' === $last || '?' === $last, $message, 'Exception message must end with a dot or a question mark.');
194 throw new Twig_Error(sprintf('%s: %s', get_class($e), $e->getMessage()), -1, $file, $e);
198 $output = trim($template->render(eval($match[1].';')), "\n ");
199 } catch (Exception $e) {
200 if (false !== $exception) {
201 $this->assertSame(trim($exception), trim(sprintf('%s: %s', get_class($e), $e->getMessage())));
206 $e = new Twig_Error(sprintf('%s: %s', get_class($e), $e->getMessage()), -1, $file, $e);
208 $output = trim(sprintf('%s: %s', get_class($e), $e->getMessage()));
211 if (false !== $exception) {
212 list($class) = explode(':', $exception);
213 $constraintClass = class_exists('PHPUnit\Framework\Constraint\Exception') ? 'PHPUnit\Framework\Constraint\Exception' : 'PHPUnit_Framework_Constraint_Exception';
214 $this->assertThat(null, new $constraintClass($class));
217 $expected = trim($match[3], "\n ");
219 if ($expected !== $output) {
220 printf("Compiled templates that failed on case %d:\n", $i + 1);
222 foreach (array_keys($templates) as $name) {
223 echo "Template: $name\n";
224 $loader = $twig->getLoader();
225 if (!$loader instanceof Twig_SourceContextLoaderInterface) {
226 $source = new Twig_Source($loader->getSource($name), $name);
228 $source = $loader->getSourceContext($name);
230 echo $twig->compile($twig->parse($twig->tokenize($source)));
233 $this->assertEquals($expected, $output, $message.' (in '.$file.')');
237 protected static function parseTemplates($test)
239 $templates = array();
240 preg_match_all('/--TEMPLATE(?:\((.*?)\))?--(.*?)(?=\-\-TEMPLATE|$)/s', $test, $matches, PREG_SET_ORDER);
241 foreach ($matches as $match) {
242 $templates[($match[1] ? $match[1] : 'index.twig')] = $match[2];
249 class_alias('Twig_Test_IntegrationTestCase', 'Twig\Test\IntegrationTestCase', false);