MustacheTest.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. <?php
  2. require_once '../Mustache.php';
  3. /**
  4. * A PHPUnit test case for Mustache.php.
  5. *
  6. * This is a very basic, very rudimentary unit test case. It's probably more important to have tests
  7. * than to have elegant tests, so let's bear with it for a bit.
  8. *
  9. * This class assumes an example directory exists at `../examples` with the following structure:
  10. *
  11. * @code
  12. * examples
  13. * foo
  14. * Foo.php
  15. * foo.mustache
  16. * foo.txt
  17. * bar
  18. * Bar.php
  19. * bar.mustache
  20. * bar.txt
  21. * @endcode
  22. *
  23. * To use this test:
  24. *
  25. * 1. {@link http://www.phpunit.de/manual/current/en/installation.html Install PHPUnit}
  26. * 2. run phpunit from the `test` directory:
  27. * `phpunit MustacheTest`
  28. * 3. Fix bugs. Lather, rinse, repeat.
  29. *
  30. * @extends PHPUnit_Framework_TestCase
  31. */
  32. class MustacheTest extends PHPUnit_Framework_TestCase {
  33. const TEST_CLASS = 'Mustache';
  34. protected $knownIssues = array(
  35. // Just the whitespace ones...
  36. );
  37. /**
  38. * Test Mustache constructor.
  39. *
  40. * @access public
  41. * @return void
  42. */
  43. public function test__construct() {
  44. $template = '{{#mustaches}}{{#last}}and {{/last}}{{type}}{{^last}}, {{/last}}{{/mustaches}}';
  45. $data = array(
  46. 'mustaches' => array(
  47. array('type' => 'Natural'),
  48. array('type' => 'Hungarian'),
  49. array('type' => 'Dali'),
  50. array('type' => 'English'),
  51. array('type' => 'Imperial'),
  52. array('type' => 'Freestyle', 'last' => 'true'),
  53. )
  54. );
  55. $output = 'Natural, Hungarian, Dali, English, Imperial, and Freestyle';
  56. $m1 = new Mustache();
  57. $this->assertEquals($output, $m1->render($template, $data));
  58. $m2 = new Mustache($template);
  59. $this->assertEquals($output, $m2->render(null, $data));
  60. $m3 = new Mustache($template, $data);
  61. $this->assertEquals($output, $m3->render());
  62. $m4 = new Mustache(null, $data);
  63. $this->assertEquals($output, $m4->render($template));
  64. }
  65. /**
  66. * @dataProvider constructorOptions
  67. */
  68. public function testConstructorOptions($options, $charset, $delimiters, $pragmas) {
  69. $mustache = new MustacheExposedOptionsStub(null, null, null, $options);
  70. $this->assertEquals($charset, $mustache->getCharset());
  71. $this->assertEquals($delimiters, $mustache->getDelimiters());
  72. $this->assertEquals($pragmas, $mustache->getPragmas());
  73. }
  74. public function constructorOptions() {
  75. return array(
  76. array(
  77. array(),
  78. 'UTF-8',
  79. array('{{', '}}'),
  80. array(),
  81. ),
  82. array(
  83. array(
  84. 'charset' => 'UTF-8',
  85. 'delimiters' => '<< >>',
  86. 'pragmas' => array(Mustache::PRAGMA_UNESCAPED)
  87. ),
  88. 'UTF-8',
  89. array('<<', '>>'),
  90. array(Mustache::PRAGMA_UNESCAPED),
  91. ),
  92. array(
  93. array(
  94. 'charset' => 'cp866',
  95. 'delimiters' => array('[[[[', ']]]]'),
  96. 'pragmas' => array(Mustache::PRAGMA_UNESCAPED)
  97. ),
  98. 'cp866',
  99. array('[[[[', ']]]]'),
  100. array(Mustache::PRAGMA_UNESCAPED),
  101. ),
  102. );
  103. }
  104. /**
  105. * @expectedException MustacheException
  106. */
  107. public function testConstructorInvalidPragmaOptionsThrowExceptions() {
  108. $mustache = new Mustache(null, null, null, array('pragmas' => array('banana phone')));
  109. }
  110. /**
  111. * Test __toString() function.
  112. *
  113. * @access public
  114. * @return void
  115. */
  116. public function test__toString() {
  117. $m = new Mustache('{{first_name}} {{last_name}}', array('first_name' => 'Karl', 'last_name' => 'Marx'));
  118. $this->assertEquals('Karl Marx', $m->__toString());
  119. $this->assertEquals('Karl Marx', (string) $m);
  120. $m2 = $this->getMock(self::TEST_CLASS, array('render'), array());
  121. $m2->expects($this->once())
  122. ->method('render')
  123. ->will($this->returnValue('foo'));
  124. $this->assertEquals('foo', $m2->render());
  125. }
  126. public function test__toStringException() {
  127. $m = $this->getMock(self::TEST_CLASS, array('render'), array());
  128. $m->expects($this->once())
  129. ->method('render')
  130. ->will($this->throwException(new Exception));
  131. try {
  132. $out = (string) $m;
  133. } catch (Exception $e) {
  134. $this->fail('__toString should catch all exceptions');
  135. }
  136. }
  137. /**
  138. * Test render().
  139. *
  140. * @access public
  141. * @return void
  142. */
  143. public function testRender() {
  144. $m = new Mustache();
  145. $this->assertEquals('', $m->render(''));
  146. $this->assertEquals('foo', $m->render('foo'));
  147. $this->assertEquals('', $m->render(null));
  148. $m2 = new Mustache('foo');
  149. $this->assertEquals('foo', $m2->render());
  150. $m3 = new Mustache('');
  151. $this->assertEquals('', $m3->render());
  152. $m3 = new Mustache();
  153. $this->assertEquals('', $m3->render(null));
  154. }
  155. /**
  156. * Test render() with data.
  157. *
  158. * @group interpolation
  159. */
  160. public function testRenderWithData() {
  161. $m = new Mustache('{{first_name}} {{last_name}}');
  162. $this->assertEquals('Charlie Chaplin', $m->render(null, array('first_name' => 'Charlie', 'last_name' => 'Chaplin')));
  163. $this->assertEquals('Zappa, Frank', $m->render('{{last_name}}, {{first_name}}', array('first_name' => 'Frank', 'last_name' => 'Zappa')));
  164. }
  165. /**
  166. * @group partials
  167. */
  168. public function testRenderWithPartials() {
  169. $m = new Mustache('{{>stache}}', null, array('stache' => '{{first_name}} {{last_name}}'));
  170. $this->assertEquals('Charlie Chaplin', $m->render(null, array('first_name' => 'Charlie', 'last_name' => 'Chaplin')));
  171. $this->assertEquals('Zappa, Frank', $m->render('{{last_name}}, {{first_name}}', array('first_name' => 'Frank', 'last_name' => 'Zappa')));
  172. }
  173. /**
  174. * @group interpolation
  175. * @dataProvider interpolationData
  176. */
  177. public function testDoubleRenderMustacheTags($template, $context, $expected) {
  178. $m = new Mustache($template, $context);
  179. $this->assertEquals($expected, $m->render());
  180. }
  181. public function interpolationData() {
  182. return array(
  183. array(
  184. '{{#a}}{{=<% %>=}}{{b}} c<%={{ }}=%>{{/a}}',
  185. array('a' => array(array('b' => 'Do Not Render'))),
  186. '{{b}} c'
  187. ),
  188. array(
  189. '{{#a}}{{b}}{{/a}}',
  190. array('a' => array('b' => '{{c}}'), 'c' => 'FAIL'),
  191. '{{c}}'
  192. ),
  193. );
  194. }
  195. /**
  196. * Mustache should allow newlines (and other whitespace) in comments and all other tags.
  197. *
  198. * @group comments
  199. */
  200. public function testNewlinesInComments() {
  201. $m = new Mustache("{{! comment \n \t still a comment... }}");
  202. $this->assertEquals('', $m->render());
  203. }
  204. /**
  205. * Mustache should return the same thing when invoked multiple times.
  206. */
  207. public function testMultipleInvocations() {
  208. $m = new Mustache('x');
  209. $first = $m->render();
  210. $second = $m->render();
  211. $this->assertEquals('x', $first);
  212. $this->assertEquals($first, $second);
  213. }
  214. /**
  215. * Mustache should return the same thing when invoked multiple times.
  216. *
  217. * @group interpolation
  218. */
  219. public function testMultipleInvocationsWithTags() {
  220. $m = new Mustache('{{one}} {{two}}', array('one' => 'foo', 'two' => 'bar'));
  221. $first = $m->render();
  222. $second = $m->render();
  223. $this->assertEquals('foo bar', $first);
  224. $this->assertEquals($first, $second);
  225. }
  226. /**
  227. * Mustache should not use templates passed to the render() method for subsequent invocations.
  228. */
  229. public function testResetTemplateForMultipleInvocations() {
  230. $m = new Mustache('Sirve.');
  231. $this->assertEquals('No sirve.', $m->render('No sirve.'));
  232. $this->assertEquals('Sirve.', $m->render());
  233. $m2 = new Mustache();
  234. $this->assertEquals('No sirve.', $m2->render('No sirve.'));
  235. $this->assertEquals('', $m2->render());
  236. }
  237. /**
  238. * Test the __clone() magic function.
  239. *
  240. * @group examples
  241. * @dataProvider getExamples
  242. *
  243. * @param string $class
  244. * @param string $template
  245. * @param string $output
  246. */
  247. public function test__clone($class, $template, $output) {
  248. if (isset($this->knownIssues[$class])) {
  249. return $this->markTestSkipped($this->knownIssues[$class]);
  250. }
  251. $m = new $class;
  252. $n = clone $m;
  253. $n_output = $n->render($template);
  254. $o = clone $n;
  255. $this->assertEquals($m->render($template), $n_output);
  256. $this->assertEquals($n_output, $o->render($template));
  257. $this->assertNotSame($m, $n);
  258. $this->assertNotSame($n, $o);
  259. $this->assertNotSame($m, $o);
  260. }
  261. /**
  262. * Test everything in the `examples` directory.
  263. *
  264. * @group examples
  265. * @dataProvider getExamples
  266. *
  267. * @param string $class
  268. * @param string $template
  269. * @param string $output
  270. */
  271. public function testExamples($class, $template, $output) {
  272. if (isset($this->knownIssues[$class])) {
  273. return $this->markTestSkipped($this->knownIssues[$class]);
  274. }
  275. $m = new $class;
  276. $this->assertEquals($output, $m->render($template));
  277. }
  278. /**
  279. * Data provider for testExamples method.
  280. *
  281. * Assumes that an `examples` directory exists inside parent directory.
  282. * This examples directory should contain any number of subdirectories, each of which contains
  283. * three files: one Mustache class (.php), one Mustache template (.mustache), and one output file
  284. * (.txt).
  285. *
  286. * This whole mess will be refined later to be more intuitive and less prescriptive, but it'll
  287. * do for now. Especially since it means we can have unit tests :)
  288. *
  289. * @return array
  290. */
  291. public function getExamples() {
  292. $basedir = dirname(__FILE__) . '/../examples/';
  293. $ret = array();
  294. $files = new RecursiveDirectoryIterator($basedir);
  295. while ($files->valid()) {
  296. if ($files->hasChildren() && $children = $files->getChildren()) {
  297. $example = $files->getSubPathname();
  298. $class = null;
  299. $template = null;
  300. $output = null;
  301. foreach ($children as $file) {
  302. if (!$file->isFile()) continue;
  303. $filename = $file->getPathname();
  304. $info = pathinfo($filename);
  305. if (isset($info['extension'])) {
  306. switch($info['extension']) {
  307. case 'php':
  308. $class = $info['filename'];
  309. include_once($filename);
  310. break;
  311. case 'mustache':
  312. $template = file_get_contents($filename);
  313. break;
  314. case 'txt':
  315. $output = file_get_contents($filename);
  316. break;
  317. }
  318. }
  319. }
  320. if (!empty($class)) {
  321. $ret[$example] = array($class, $template, $output);
  322. }
  323. }
  324. $files->next();
  325. }
  326. return $ret;
  327. }
  328. /**
  329. * @group delimiters
  330. */
  331. public function testCrazyDelimiters() {
  332. $m = new Mustache(null, array('result' => 'success'));
  333. $this->assertEquals('success', $m->render('{{=[[ ]]=}}[[ result ]]'));
  334. $this->assertEquals('success', $m->render('{{=(( ))=}}(( result ))'));
  335. $this->assertEquals('success', $m->render('{{={$ $}=}}{$ result $}'));
  336. $this->assertEquals('success', $m->render('{{=<.. ..>=}}<.. result ..>'));
  337. $this->assertEquals('success', $m->render('{{=^^ ^^}}^^ result ^^'));
  338. $this->assertEquals('success', $m->render('{{=// \\\\}}// result \\\\'));
  339. }
  340. /**
  341. * @group delimiters
  342. */
  343. public function testResetDelimiters() {
  344. $m = new Mustache(null, array('result' => 'success'));
  345. $this->assertEquals('success', $m->render('{{=[[ ]]=}}[[ result ]]'));
  346. $this->assertEquals('success', $m->render('{{=<< >>=}}<< result >>'));
  347. $this->assertEquals('success', $m->render('{{=<% %>=}}<% result %>'));
  348. }
  349. /**
  350. * @group delimiters
  351. */
  352. public function testStickyDelimiters() {
  353. $m = new Mustache(null, array('result' => 'FAIL'));
  354. $this->assertEquals('{{ result }}', $m->render('{{=[[ ]]=}}{{ result }}[[={{ }}=]]'));
  355. $this->assertEquals('{{ result }}', $m->render('{{=[[ ]]=}}[[#result]]{{ result }}[[/result]]'));
  356. $this->assertEquals('{{ result }}', $m->render('{{=[[ ]]=}}[[#result]]{{ result }}[[/result]][[={{ }}=]]'));
  357. $this->assertEquals('{{ result }}', $m->render('{{#result}}{{=[[ ]]=}}{{ result }}[[/result]][[^result]][[={{ }}=]][[ result ]]{{/result}}'));
  358. }
  359. /**
  360. * @group sections
  361. * @dataProvider poorlyNestedSections
  362. * @expectedException MustacheException
  363. */
  364. public function testPoorlyNestedSections($template) {
  365. $m = new Mustache($template);
  366. $m->render();
  367. }
  368. public function poorlyNestedSections() {
  369. return array(
  370. array('{{#foo}}'),
  371. array('{{#foo}}{{/bar}}'),
  372. array('{{#foo}}{{#bar}}{{/foo}}'),
  373. array('{{#foo}}{{#bar}}{{/foo}}{{/bar}}'),
  374. array('{{#foo}}{{/bar}}{{/foo}}'),
  375. );
  376. }
  377. /**
  378. * Ensure that Mustache doesn't double-render sections (allowing mustache injection).
  379. *
  380. * @group sections
  381. */
  382. public function testMustacheInjection() {
  383. $template = '{{#foo}}{{bar}}{{/foo}}';
  384. $view = array(
  385. 'foo' => true,
  386. 'bar' => '{{win}}',
  387. 'win' => 'FAIL',
  388. );
  389. $m = new Mustache($template, $view);
  390. $this->assertEquals('{{win}}', $m->render());
  391. }
  392. }
  393. class MustacheExposedOptionsStub extends Mustache {
  394. public function getPragmas() {
  395. return $this->_pragmas;
  396. }
  397. public function getCharset() {
  398. return $this->_charset;
  399. }
  400. public function getDelimiters() {
  401. return array($this->_otag, $this->_ctag);
  402. }
  403. }