Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

New unit tests

  • Loading branch information...
commit 68a4de7cf8a4579b1e47b64bd966670f5eb874a6 1 parent 3dbfd24
@kmontag kmontag authored
View
1  DependencyInjection/Configuration.php
@@ -47,6 +47,7 @@ public function getConfigTreeBuilder()
->defaultValue('js')
->end()
->scalarNode('base_directory')
+ ->cannotBeEmpty()
->defaultValue('@HearsayRequireJSBundle/Resources/scripts')
->end()
->arrayNode('namespaces')
View
17 DependencyInjection/HearsayRequireJSExtension.php
@@ -57,7 +57,7 @@ public function load(array $configs, ContainerBuilder $container)
$value = $settings['value'];
$container->getDefinition('hearsay_require_js.optimizer_filter')->addMethodCall('setOption', array($name, $value));
}
-
+
// Add the configured namespaces
foreach ($config['namespaces'] as $namespace => $settings) {
$this->addNamespaceMapping($settings['path'], $namespace, $container);
@@ -80,9 +80,11 @@ protected function addNamespaceMapping($path, $namespace, ContainerBuilder $cont
// Register the namespace with the configuration
$mapping = $container->getDefinition('hearsay_require_js.namespace_mapping');
$mapping->addMethodCall('registerNamespace', array($path, $namespace));
-
+
// And with the optimizer filter
- $container->getDefinition('hearsay_require_js.optimizer_filter')->addMethodCall('setOption', array('paths.' . $namespace, $path));
+ if ($namespace) {
+ $container->getDefinition('hearsay_require_js.optimizer_filter')->addMethodCall('setOption', array('paths.' . $namespace, $path));
+ }
// Create the assetic resource
$resource = new DefinitionDecorator('hearsay_require_js.directory_filename_resource');
@@ -101,11 +103,9 @@ protected function addNamespaceMapping($path, $namespace, ContainerBuilder $cont
*/
private function getRealPath($path, ContainerBuilder $container)
{
- // Get bundles so we can match up bundle notation
- $bundles = $container->getParameter('kernel.bundles');
-
// Expand bundle notation (snagged from the Assetic bundle)
if ($path[0] == '@' && strpos($path, '/') !== false) {
+
// Extract the bundle name and the directory within the bundle
$bundle = substr($path, 1);
$directory = '';
@@ -114,6 +114,9 @@ private function getRealPath($path, ContainerBuilder $container)
$bundle = substr($bundle, 0, $pos);
}
+ // Get loaded bundles
+ $bundles = $container->getParameter('kernel.bundles');
+
// Reconstruct the path
if (isset($bundles[$bundle])) {
$rc = new \ReflectionClass($bundles[$bundle]);
@@ -125,5 +128,5 @@ private function getRealPath($path, ContainerBuilder $container)
return $path;
}
-
+
}
View
25 Filter/RequireJSOptimizerFilter.php
@@ -52,13 +52,7 @@ class RequireJSOptimizerFilter implements FilterInterface
*/
protected $baseUrl = null;
/**
- * Plugin to apply when processing content.
- * @var string
- */
- protected $plugin = null;
- /**
- * Extension to add to temporary files for processing (generally dependent
- * on the plugin being used).
+ * Extension to add to temporary files for processing.
* @var string
*/
protected $extension = 'js';
@@ -86,18 +80,6 @@ public function setOption($name, $value)
}
/**
- * Set the plugin to apply to content before processing.
- * @param string $plugin The plugin module name, or null for no plugin.
- * @param string $extension The file extension to add to temporary files, to
- * enable them to be loaded by this plugin.
- */
- public function setPlugin($plugin, $extension)
- {
- $this->plugin = $plugin;
- $this->extension = $extension;
- }
-
- /**
* {@inheritdoc}
*/
public function filterLoad(AssetInterface $asset)
@@ -111,7 +93,8 @@ public function filterLoad(AssetInterface $asset)
public function filterDump(AssetInterface $asset)
{
$input = tempnam(sys_get_temp_dir(), 'assetic_requirejs');
- file_put_contents($input . '.' . $this->extension, $asset->getContent());
+ $inputFilename = $input . ($this->extension ? '.' . $this->extension : '');
+ file_put_contents($inputFilename, $asset->getContent());
$output = tempnam(sys_get_temp_dir(), 'assetic_requirejs');
@@ -124,7 +107,7 @@ public function filterDump(AssetInterface $asset)
->add('-o') // Optimize
// Configure the primary input
->add('paths.' . $name . '=' . $input)
- ->add('name=' . ($this->plugin ? $this->plugin . '!' : '') . $name)
+ ->add('name=' . $name)
// Configure the output
->add('out=' . $output)
View
27 HearsayRequireJSBundle.php
@@ -1,9 +1,36 @@
<?php
+/**
+ * Copyright (c) 2011 Hearsay News Products, Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
namespace Hearsay\RequireJSBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
+/**
+ * Bundle providing RequireJS integration.
+ * @author Kevin Montag <kevin@hearsay.it>
+ * @codeCoverageIgnore
+ */
class HearsayRequireJSBundle extends Bundle
{
}
View
3  Templating/Helper/RequireJSHelper.php
@@ -25,9 +25,8 @@
namespace Hearsay\RequireJSBundle\Templating\Helper;
use Hearsay\RequireJSBundle\Configuration\ConfigurationBuilder;
-use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
+use Symfony\Component\Templating\EngineInterface;
use Symfony\Component\Templating\Helper\Helper;
-use Symfony\Component\Translation\TranslatorInterface;
/**
* Templating helper for RequireJS inclusion.
View
50 Tests/Configuration/ConfigurationBuilderTest.php
@@ -0,0 +1,50 @@
+<?php
+
+/**
+ * Copyright (c) 2011 Hearsay News Products, Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+namespace Hearsay\RequireJSBundle\Tests\Configuration;
+
+use Hearsay\RequireJSBundle\Configuration\ConfigurationBuilder;
+
+/**
+ * Unit tests for the helper to generate RequireJS configuration.
+ * @author Kevin Montag <kevin@hearsay.it>
+ */
+class ConfigurationBuilderTest extends \PHPUnit_Framework_TestCase
+{
+ public function testConfigurationGenerated()
+ {
+ $translator = $this->getMock('Symfony\Component\Translation\TranslatorInterface');
+ $translator->expects($this->any())
+ ->method('getLocale')
+ ->will($this->returnValue('fr_FR'));
+ $builder = new ConfigurationBuilder($translator, 'js', array('option' => 'value'));
+
+ $expected = array(
+ 'locale' => 'fr_FR',
+ 'baseUrl' => 'js',
+ 'option' => 'value',
+ );
+ $this->assertEquals($expected, $builder->getConfiguration(), 'Unexpected configuration generated');
+ }
+}
View
67 Tests/Configuration/NamespaceMappingTest.php
@@ -0,0 +1,67 @@
+<?php
+
+/**
+ * Copyright (c) 2011 Hearsay News Products, Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+namespace Hearsay\RequireJSBundle\Tests\Configuration;
+
+use Hearsay\RequireJSBundle\Configuration\NamespaceMapping;
+
+/**
+ * Unit tests for the namespace mapping container.
+ * @author Kevin Montag <kevin@hearsay.it>
+ */
+class NamespaceMappingTest extends \PHPUnit_Framework_TestCase
+{
+
+ public function testFilesConvertedToModules()
+ {
+ $mapping = new NamespaceMapping('js');
+ $mapping->registerNamespace(__DIR__ . '/dir', 'modules');
+
+ $this->assertEquals('js/modules/file.js', $mapping->getModulePath(__DIR__ . '/dir/file.js'), 'Incorrect file-to-module conversion');
+ }
+
+ public function testExtraSlashesIgnored()
+ {
+ $mapping = new NamespaceMapping('js//');
+ $mapping->registerNamespace(__DIR__ . '/dir', '/modules/');
+
+ $this->assertEquals('js/modules/file.js', $mapping->getModulePath(__DIR__ . '/dir/file.js'), 'Incorrect file-to-module conversion');
+ }
+
+ public function testRelativePathsReduced()
+ {
+ $mapping = new NamespaceMapping('js');
+ $mapping->registerNamespace(__DIR__ . '/dir/../dir', 'modules');
+
+ $this->assertEquals('js/modules/file.js', $mapping->getModulePath(__DIR__ . '/../Configuration/dir/file.js'), 'Incorrect file-to-module conversion');
+ }
+
+ public function testNonexistentNamespaceReturnsFalse()
+ {
+ $mapping = new NamespaceMapping('js');
+
+ $this->assertFalse($mapping->getModulePath(__DIR__ . '/dir/file.js'), 'Non-existent module expected not to be converted');
+ }
+
+}
View
0  Tests/Configuration/dir/file.js
No changes.
View
131 Tests/DependencyInjection/HearsayRequireJSExtensionTest.php
@@ -0,0 +1,131 @@
+<?php
+
+/**
+ * Copyright (c) 2011 Hearsay News Products, Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+namespace Hearsay\RequireJSBundle\Tests\DependencyInjection;
+
+use Hearsay\RequireJSBundle\DependencyInjection\HearsayRequireJSExtension;
+use Symfony\Component\DependencyInjection\ContainerBuilder;
+
+/**
+ * Unit tests for the bundle loader.
+ * @author Kevin Montag <kevin@hearsay.it>
+ */
+class HearsayRequireJSExtensionTest extends \PHPUnit_Framework_TestCase
+{
+
+ public function testNamespacesMapped()
+ {
+ $config = array(
+ 'base_directory' => '/home/user/base',
+ 'namespaces' => array(
+ 'namespace' => '/home/user/path',
+ ),
+ );
+ $container = $this->getContainerBuilder();
+ $loader = new HearsayRequireJSExtension();
+
+ $loader->load(array($config), $container);
+
+ // Check the namespace mapping
+ $mapping = $container->getDefinition('hearsay_require_js.namespace_mapping');
+ $methods = $mapping->getMethodCalls();
+ $this->assertEquals(2, count($methods), 'Incorrect number of method calls on namespace mapping');
+ $this->assertContains(array(
+ 'registerNamespace', array('/home/user/path', 'namespace'),
+ ), $methods, 'Did not find expected method call');
+ $this->assertContains(array(
+ 'registerNamespace', array('/home/user/base', ''),
+ ), $methods, 'Did not find expected method call');
+
+ // Check the optimization filter
+ $filter = $container->getDefinition('hearsay_require_js.optimizer_filter');
+ $methods = $filter->getMethodCalls();
+ $this->assertEquals(1, count($methods), 'Incorrect number of method calls on optimizer filter');
+ $this->assertContains(array(
+ 'setOption', array('paths.namespace', '/home/user/path'),
+ ), $methods, 'Did not find expected method call');
+
+ // And the Assetic resources
+ foreach(array('/home/user/base', '/home/user/path') as $path) {
+ /* @var $resource \Symfony\Component\DependencyInjection\DefinitionDecorator */
+ $resource = $container->getDefinition('hearsay_require_js.directory_filename_resource.' . md5($path));
+ $this->assertInstanceOf('Symfony\Component\DependencyInjection\DefinitionDecorator', $resource);
+ $this->assertEquals(array($path), $resource->getArguments(), 'Incorrect constructor arguments for assetic resource');
+ $this->assertEquals('hearsay_require_js.directory_filename_resource', $resource->getParent(), 'Incorrect parent for assetic resource');
+
+ $tag = $resource->getTag('assetic.formula_resource');
+ $this->assertEquals(array(array('loader' => 'require_js')), $tag, 'Unexpected formula resource tag');
+ }
+ }
+
+ public function testOptimizerOptionsSet()
+ {
+ $config = array(
+ 'optimizer' => array(
+ 'options' => array(
+ 'option' => 'value',
+ ),
+ ),
+ );
+ $container = $this->getContainerBuilder();
+ $loader = new HearsayRequireJSExtension();
+
+ $loader->load(array($config), $container);
+
+ $optimizer = $container->getDefinition('hearsay_require_js.optimizer_filter');
+ $methods = $optimizer->getMethodCalls();
+ $this->assertEquals(1, count($methods), 'Incorrect number of method calls on optimizer');
+ $this->assertContains(array(
+ 'setOption', array('option', 'value'),
+ ), $methods, 'Did not find expected method call');
+ }
+
+ public function testExceptionOnUnrecognizedBundle()
+ {
+ $config = array(
+ 'base_directory' => '@UnknownBundle/Resources/scripts',
+ );
+ $container = $this->getContainerBuilder();
+ $loader = new HearsayRequireJSExtension();
+
+ $this->setExpectedException('InvalidArgumentException', 'Unrecognized bundle: "UnknownBundle"');
+ $loader->load(array($config), $container);
+ }
+
+ /**
+ * Helper to get a new container builder with necessary initialization
+ * performed.
+ * @return ContainerBuilder
+ */
+ protected function getContainerBuilder()
+ {
+ $container = new ContainerBuilder();
+ $bundles = array(
+ 'HearsayRequireJSBundle' => 'Hearsay\RequireJSBundle\HearsayRequireJSBundle',
+ );
+ $container->setParameter('kernel.bundles', $bundles);
+ return $container;
+ }
+
+}
View
31 Tests/Factory/Resource/DirectoryFilenameResourceTest.php
@@ -25,12 +25,13 @@
namespace Hearsay\RequireJSBundle\Tests\Factory\Resource;
use Hearsay\RequireJSBundle\Factory\Resource\DirectoryFilenameResource;
+use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
/**
* Unit tests for the filename resource.
* @author Kevin Montag <kevin@hearsay.it>
*/
-class DirectoryFilenameResourceTest extends \PHPUnit_Framework_TestCase
+class DirectoryFilenameResourceTest extends WebTestCase
{
public function testFilenamesRetrieved()
{
@@ -43,4 +44,32 @@ public function testFilenamesRetrieved()
$this->assertContains(__DIR__ . '/dir/file', $filenames, 'Did not find expected filename');
$this->assertContains(__DIR__ . '/dir/subdir/file', $filenames, 'Did not find expected filename');
}
+
+ public function testStringConversion()
+ {
+ $resource = new DirectoryFilenameResource(__DIR__);
+ $this->assertEquals(__DIR__, (string)$resource, 'Incorrect string conversion');
+ }
+
+ public function testFreshCheck()
+ {
+ $time = time() - 1;
+ $dir = $this->createKernel()->getCacheDir(); // Get a directory for temporary files
+
+ if (filemtime($dir) > $time) {
+ $this->markTestSkipped('Cache dir is too recently modified for testing');
+ }
+
+ $resource = new DirectoryFilenameResource($dir);
+ $this->assertTrue($resource->isFresh($time), 'Cache dir is not fresh');
+
+ $file = tempnam($dir, 'requirejs_test');
+ file_put_contents($file, 'temp');
+
+ $this->assertGreaterThan($time, filemtime($file), 'Sanity check failed; new file has outdated timestamp');
+ $this->assertFalse($resource->isFresh($time), sprintf('System temp dir is still fresh after adding a file (%d < %d', filemtime($dir), $time));
+
+ // Clean up
+ unlink($file);
+ }
}
View
6 Tests/Filter/RequireJSOptimizerFilterTest.php
@@ -42,7 +42,8 @@ public function testContentOptimized()
$filter->setOption('skipModuleInsertion', true);
$asset = new StringAsset('alert("Hi there!"); alert("Hi there again.");');
- $this->assertEquals('alert("Hi there!"),alert("Hi there again.")', $asset->dump($filter), 'Content was not properly optimized');
+ $asset->ensureFilter($filter);
+ $this->assertEquals('alert("Hi there!"),alert("Hi there again.")', $asset->dump(), 'Content was not properly optimized');
}
public function testBaseUrlModulesIncluded()
@@ -87,7 +88,6 @@ public function testOptionsPassed()
public function testErrorOnBadInput()
{
- // We use the current directory as the base URL
$filter = new RequireJSOptimizerFilter($this->getNodePath(), __DIR__ . '/../../Resources/scripts/r.js', __DIR__ . '/../../Resources/scripts');
// Try to load a nonexistent module
@@ -101,7 +101,7 @@ public function testErrorOnBadInput()
$this->setExpectedException('RuntimeException');
$asset->dump($filter);
}
-
+
/**
* Helper to fetch the path to node.js.
* @return string
View
11 Tests/Filter/modules/text.js
@@ -0,0 +1,11 @@
+/*
+ RequireJS text 0.26.0 Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
+ Available via the MIT or new BSD license.
+ see: http://github.com/jrburke/requirejs for details
+*/
+(function(){var j=["Msxml2.XMLHTTP","Microsoft.XMLHTTP","Msxml2.XMLHTTP.4.0"],l=/^\s*<\?xml(\s)+version=[\'\"](\d)*.(\d)*[\'\"](\s)*\?>/im,m=/<body[^>]*>\s*([\s\S]+)\s*<\/body>/im,n=typeof location!=="undefined"&&location.href,i=[];define(function(){var e,h,k;typeof window!=="undefined"&&window.navigator&&window.document?h=function(a,b){var c=e.createXhr();c.open("GET",a,!0);c.onreadystatechange=function(){c.readyState===4&&b(c.responseText)};c.send(null)}:typeof process!=="undefined"&&process.versions&&
+process.versions.node?(k=require.nodeRequire("fs"),h=function(a,b){b(k.readFileSync(a,"utf8"))}):typeof Packages!=="undefined"&&(h=function(a,b){var c=new java.io.File(a),g=java.lang.System.getProperty("line.separator"),c=new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(c),"utf-8")),d,f,e="";try{d=new java.lang.StringBuffer;(f=c.readLine())&&f.length()&&f.charAt(0)===65279&&(f=f.substring(1));for(d.append(f);(f=c.readLine())!==null;)d.append(g),d.append(f);e=String(d.toString())}finally{c.close()}b(e)});
+return e={version:"0.26.0",strip:function(a){if(a){var a=a.replace(l,""),b=a.match(m);b&&(a=b[1])}else a="";return a},jsEscape:function(a){return a.replace(/(['\\])/g,"\\$1").replace(/[\f]/g,"\\f").replace(/[\b]/g,"\\b").replace(/[\n]/g,"\\n").replace(/[\t]/g,"\\t").replace(/[\r]/g,"\\r")},createXhr:function(){var a,b,c;if(typeof XMLHttpRequest!=="undefined")return new XMLHttpRequest;else for(b=0;b<3;b++){c=j[b];try{a=new ActiveXObject(c)}catch(e){}if(a){j=[c];break}}if(!a)throw Error("createXhr(): XMLHttpRequest not available");
+return a},get:h,parseName:function(a){var b=!1,c=a.indexOf("."),e=a.substring(0,c),a=a.substring(c+1,a.length),c=a.indexOf("!");c!==-1&&(b=a.substring(c+1,a.length),b=b==="strip",a=a.substring(0,c));return{moduleName:e,ext:a,strip:b}},xdRegExp:/^((\w+)\:)?\/\/([^\/\\]+)/,canUseXhr:function(a,b,c,g){var d=e.xdRegExp.exec(a),f;if(!d)return!0;a=d[2];d=d[3];d=d.split(":");f=d[1];d=d[0];return(!a||a===b)&&(!d||d===c)&&(!f&&!d||f===g)},finishLoad:function(a,b,c,g,d){c=b?e.strip(c):c;d.isBuild&&d.inlineText&&
+(i[a]=c);g(c)},load:function(a,b,c,g){var d=e.parseName(a),f=d.moduleName+"."+d.ext,h=b.toUrl(f);!n||e.canUseXhr(h)?e.get(h,function(b){e.finishLoad(a,d.strip,b,c,g)}):b([f],function(a){e.finishLoad(d.moduleName+"."+d.ext,d.strip,a,c,g)})},write:function(a,b,c){if(b in i){var g=e.jsEscape(i[b]);c("define('"+a+"!"+b+"', function () { return '"+g+"';});\n")}},writeFile:function(a,b,c,g,d){var b=e.parseName(b),f=b.moduleName+"."+b.ext,h=c.toUrl(b.moduleName+"."+b.ext)+".js";e.load(f,c,function(){e.write(a,
+f,function(a){g(h,a)},d)},d)}}})})();
View
101 Tests/Templating/Helper/RequireJSHelperTest.php
@@ -0,0 +1,101 @@
+<?php
+
+/**
+ * Copyright (c) 2011 Hearsay News Products, Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+namespace Hearsay\RequireJSBundle\Tests\Templating\Helper;
+
+use Hearsay\RequireJSBundle\Templating\Helper\RequireJSHelper;
+
+/**
+ * Unit tests for the templating helper.
+ * @author Kevin Montag <kevin@hearsay.it>
+ */
+class RequireJSHelperTest extends \PHPUnit_Framework_TestCase
+{
+
+ public function testDefaultInitialization()
+ {
+ $engine = $this->getMock('Symfony\Component\Templating\EngineInterface');
+ $config = $this->getMockBuilder('Hearsay\RequireJSBundle\Configuration\ConfigurationBuilder')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $config->expects($this->once())
+ ->method('getConfiguration')
+ ->will($this->returnValue(array('option' => 'value')));
+
+ $engine->expects($this->once())
+ ->method('render')
+ ->with('HearsayRequireJSBundle::initialize.html.twig', array(
+ 'config' => array('option' => 'value'),
+ 'main' => null,
+ ))
+ ->will($this->returnValue('initialized'));
+
+ $helper = new RequireJSHelper($engine, $config);
+ $this->assertEquals('initialized', $helper->initialize(), 'Incorrect initialization rendered');
+ }
+
+ public function testConfigurationSuppressed()
+ {
+ $engine = $this->getMock('Symfony\Component\Templating\EngineInterface');
+ $config = $this->getMockBuilder('Hearsay\RequireJSBundle\Configuration\ConfigurationBuilder')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $config->expects($this->never())
+ ->method('getConfiguration');
+
+ $engine->expects($this->once())
+ ->method('render')
+ ->with('HearsayRequireJSBundle::initialize.html.twig', array(
+ 'config' => null,
+ 'main' => null,
+ ))
+ ->will($this->returnValue('initialized'));
+
+ $helper = new RequireJSHelper($engine, $config);
+ $this->assertEquals('initialized', $helper->initialize(array('configure' => false)), 'Incorrect initialization rendered');
+ }
+
+ public function testMainScriptIncluded()
+ {
+ $engine = $this->getMock('Symfony\Component\Templating\EngineInterface');
+ $config = $this->getMockBuilder('Hearsay\RequireJSBundle\Configuration\ConfigurationBuilder')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $config->expects($this->once())
+ ->method('getConfiguration')
+ ->will($this->returnValue(array('option' => 'value')));
+
+ $engine->expects($this->once())
+ ->method('render')
+ ->with('HearsayRequireJSBundle::initialize.html.twig', array(
+ 'config' => array('option' => 'value'),
+ 'main' => 'module',
+ ))
+ ->will($this->returnValue('initialized'));
+
+ $helper = new RequireJSHelper($engine, $config);
+ $this->assertEquals('initialized', $helper->initialize(array('main' => 'module')), 'Incorrect initialization rendered');
+ }
+
+}
Please sign in to comment.
Something went wrong with that request. Please try again.