This commit is contained in:
Uwe Tews
2015-05-04 03:00:52 +02:00
parent 1834622d94
commit 0dea9f271c
366 changed files with 19007 additions and 1 deletions

32
tests/Bootstrap.php Normal file
View File

@@ -0,0 +1,32 @@
<?php
/*
* This file is part of the Smarty PHPUnit tests.
*
*/
/*
* Smarty PHPUnit Bootstrap
*/
// Locate SmartyBC class and load it
if (is_file(__DIR__ . '/../smarty/libs/SmartyBC.class.php')) {
require_once __DIR__ . '/../smarty/libs/SmartyBC.class.php';
} elseif (is_file(__DIR__ . '/../libs/SmartyBC.class.php')) {
require_once __DIR__ . '/../libs/SmartyBC.class.php';
} else {
throw new Exception('can not locate Smarty distribution');
}
if (!defined('SMARTY_COMPOSER_INSTALL')) {
foreach (array(__DIR__ . '/../../autoload.php', __DIR__ . '/../vendor/autoload.php', __DIR__ . '/vendor/autoload.php') as $file) {
if (file_exists($file)) {
define('SMARTY_COMPOSER_INSTALL', $file);
break;
}
}
unset($file);
}
if (!class_exists('PHPUnit_Framework_TestCase')) {
require_once SMARTY_COMPOSER_INSTALL;
}
require_once 'PHPUnit_Smarty.php';
ini_set('date.timezone', 'UTC');

606
tests/PHPUnit_Smarty.php Normal file
View File

@@ -0,0 +1,606 @@
<?php
/*
* This file is part of the Smarty PHPUnit tests.
*
*/
/**
* Smarty Test Case Fixture
*/
class PHPUnit_Smarty extends PHPUnit_Framework_TestCase
{
/**
* Smarty object
*
* @var SmartyBC
*/
public $smartyBC = null;
/**
* SmartyBC object
*
* @var Smarty
*/
public $smarty = null;
/**
* Flag if test is using the Smarty object
*
* @var bool
*/
public $loadSmarty = true;
/**
* Flag if test is using the SmartyBC object
*
* @var bool
*/
public $loadSmartyBC = false;
/**
* Flag for initialization at first test
*
* @var bool
*/
public static $init = true;
/**
* Configuration data from config.xml
*
* @var array
*/
public static $config = null;
/**
* Saved current working directory
*
* @var null
*/
public static $cwd = null;
/**
* PDO object for Mysql tests
*
* @var PDO
*/
public static $pdo = null;
/**
* Default blacklist
*
* @var array
*/
protected $backupStaticAttributesBlacklist = array(
'PHPUnit_Smarty' => array('config', 'pdo', 'init'),
);
/**
* This method is called before the first test of this test class is run.
*
*/
public static function setUpBeforeClass()
{
error_reporting(E_ALL | E_STRICT);
self::$init = true;
self::$pdo = null;
if (self::$config == null) {
$xml = simplexml_load_file(__DIR__ . '/config.xml');
$json_string = json_encode($xml);
self::$config = json_decode($json_string, true);
if (empty(self::$config['mysql']['DB_PASSWD'])) {
self::$config['mysql']['DB_PASSWD'] = null;
}
}
}
/**
* This method is called after the last test of this test class is run.
*
*/
public static function tearDownAfterClass()
{
self::$pdo = null;
}
/**
* Constructs a test case with the given name.
*
* @param string $name
* @param array $data
* @param string $dataName
*/
public function __construct($name = null, array $data = array(), $dataName = '')
{
parent::__construct($name, $data, $dataName);
$this->backupStaticAttributesBlacklist[get_class($this)] = array('init', 'config', 'pdo');
}
/**
* Setup Smarty instance called for each test
*
* @param null $dir working directory
*/
public function setUpSmarty($dir = null)
{
// set up current working directory
chdir($dir);
self::$cwd = getcwd();
// create missing folders for test
if (self::$init) {
if (!is_dir($dir . '/templates')) {
mkdir($dir . '/templates');
}
if (!is_dir($dir . '/configs')) {
mkdir($dir . '/configs');
}
if (self::$config['individualFolders'] != 'true') {
$dir = __DIR__;
}
if (!is_dir($dir . '/templates_c')) {
mkdir($dir . '/templates_c');
chmod($dir . '/templates_c', 0775);
}
if (!is_dir($dir . '/cache')) {
mkdir($dir . '/cache');
chmod($dir . '/cache', 0775);
}
self::$init = false;
}
clearstatcache();
// instance Smarty class
if ($this->loadSmarty) {
$this->smarty = new Smarty;
if (self::$config['individualFolders'] != 'true') {
$this->smarty->setCompileDir(__DIR__ . '/templates_c');
$this->smarty->setCacheDir(__DIR__ . '/cache');
}
}
// instance SmartyBC class
if ($this->loadSmartyBC) {
$this->smartyBC = new SmartyBC;
if (self::$config['individualFolders'] != 'true') {
$this->smartyBC->setCompileDir(__DIR__ . '/templates_c');
$this->smartyBC->setCacheDir(__DIR__ . '/cache');
}
}
}
/**
* Create Mysql PDO object
*
*/
final public function getConnection()
{
if (self::$pdo == null) {
try {
self::$pdo = new PDO(self::$config['mysql']['DB_DSN'], self::$config['mysql']['DB_USER'], self::$config['mysql']['DB_PASSWD']);
}
catch (PDOException $e) {
throw new SmartyException('Mysql Resource failed: ' . $e->getMessage());
}
$timezone = date_default_timezone_get();
self::$pdo->exec("SET time_zone = '{$timezone}';");
}
}
/**
* Create table for Mysql resource
*
*/
public function initMysqlResource()
{
$this->getConnection();
self::$pdo->exec("DROP TABLE `templates`");
self::$pdo->exec("CREATE TABLE IF NOT EXISTS `templates` (
`name` varchar(100) NOT NULL,
`modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`source` text,
PRIMARY KEY (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8");
}
/**
* Create table for Mysql cache resource
*
*/
public function initMysqlCache()
{
$this->getConnection();
self::$pdo->exec("DROP TABLE `output_cache`");
self::$pdo->exec("CREATE TABLE IF NOT EXISTS `output_cache` (
`id` char(40) NOT NULL COMMENT 'sha1 hash',
`name` varchar(250) NOT NULL,
`cache_id` varchar(250) DEFAULT NULL,
`compile_id` varchar(250) DEFAULT NULL,
`modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`expire` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`content` mediumblob NOT NULL,
PRIMARY KEY (`id`),
KEY `name` (`name`),
KEY `cache_id` (`cache_id`),
KEY `compile_id` (`compile_id`),
KEY `modified` (`modified`),
KEY `expire` (`expire`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8");
}
/**
* Delete files in templates_c and cache folders
*
*/
public function cleanDirs()
{
$this->cleanCompileDir();
$this->cleanCacheDir();
}
/**
* Delete files in templates_c folder
*
*/
public function cleanCompileDir()
{
if (isset($this->smarty)) {
$this->cleanDir($this->smarty->getCompileDir());
} elseif (isset($this->smartyBC)) {
$this->cleanDir($this->smartyBC->getCompileDir());
}
}
/**
* Delete files in cache folder
*
*/
public function cleanCacheDir()
{
if (isset($this->smarty)) {
$this->cleanDir($this->smarty->getCacheDir());
} elseif (isset($this->smartyBC)) {
$this->cleanDir($this->smartyBC->getCacheDir());
}
}
/**
* Delete files and sub folders
*
* @param string $dir
*/
public function cleanDir($dir)
{
$di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
$ri = new RecursiveIteratorIterator($di, RecursiveIteratorIterator::CHILD_FIRST);
foreach ($ri as $file) {
$file->isDir() ? rmdir($file) : unlink($file);
}
}
/**
* Get PDO object
*
* @return null|PDO
*/
final public function getPDO()
{
return self::$pdo;
}
/**
* Remove "\r" and replace "\t" with spaces
*
* @param string $in
*
* @return mixed
*/
public function normalizeString($in)
{
if (is_string($in)) {
$in = str_replace("\r", '', $in);
$in = str_replace("\t", ' ', $in);
}
return $in;
}
/**
* Return source path
*
* @param Smarty_Internal_TemplateBase $tpl template object
* @param null|string $name optional template name
* @param null|string $type optional template type
* @param null|string $dir optional template folder
*
* @return string
* @throws \Exception
*/
public function buildSourcePath($tpl, $name = null, $type = null, $dir = null)
{
$name = isset($name) ? $name : $tpl->source->name;
$type = isset($type) ? $type : $tpl->source->type;
$dir = isset($dir) ? $dir : $this->smarty->getTemplateDir(0);
switch ($type) {
case 'file':
case 'php':
return $this->normalizePath($dir . $name, true);
case 'mysqltest':
case 'mysql':
return sha1($type . ':' . $name);
case 'string':
return sha1($name);
default:
throw new Exception("Unhandled source resource type '{$type}'");
}
}
/**
* Build template uid
*
* @param Smarty_Internal_TemplateBase $tpl template object
* @param null|string $value
* @param null|string $name optional template name
* @param null|string $type optional template type
*
* @return string
* @throws \Exception
*/
public function buildUid($tpl, $value = null, $name = null, $type = null)
{
$type = isset($type) ? $type : $tpl->source->type;
$name = isset($name) ? $name : $tpl->source->name;
switch ($type) {
case 'file':
if ($tpl instanceof Smarty) {
return sha1($this->normalizePath($this->smarty->getTemplateDir(0) . $name, true));
}
return sha1($tpl->source->filepath);
case 'php':
return sha1($tpl->source->filepath);
case 'mysqltest':
case 'mysql':
return sha1($type . ':' . $name);
case 'string':
return sha1($name);
default:
throw new Exception("Unhandled source resource type '{$type}'");
}
}
/**
* Normalize file path
*
* @param string $path input path
* @param bool $ds if true use system directory separator
*
* @return string
*/
public function normalizePath($path, $ds = false)
{
$path = str_replace(array('\\', '/./'), '/', $path);
while ($path !== $new = preg_replace('#[^\.\/]+/\.\./#', '', $path)) {
$path = $new;
}
if (DS !== '/' && $ds) {
$path = str_replace('/', DS, $path);
}
return $path;
}
/**
* Return base name
*
* @param \Smarty_Internal_Template|\Smarty_Internal_TemplateBase $tpl template object
* @param null|string $name optional template name
* @param null|string $type optional template type
*
* @return null|string
*/
public function getBasename(Smarty_Internal_Template $tpl, $name = null, $type = null)
{
$name = isset($name) ? $name : $tpl->source->name;
$type = isset($type) ? $type : $tpl->source->type;
switch ($type) {
case 'file':
if (($_pos = strpos($name, ']')) !== false) {
$name = substr($name, $_pos + 1);
}
return basename($name);
case 'mysqltest':
case 'mysql':
return $name;
case 'string':
return '';
default:
return null;
}
}
/**
* Return compiled file path
*
* @param \Smarty_Internal_Template|\Smarty_Internal_TemplateBase $tpl template object
* @param bool $sub use sub directory flag
* @param bool $caching caching flag
* @param null|string $compile_id optional compile id
* @param null|string $name optional template name
* @param null|string $type optional template type
* @param null|string $dir optional template folder
*
* @return string
* @throws \Exception
*/
public function buildCompiledPath(Smarty_Internal_Template $tpl, $sub = true, $caching = false, $compile_id = null, $name = null, $type = null, $dir = null)
{
$sep = DS;
$_compile_id = isset($compile_id) ? preg_replace('![^\w\|]+!', '_', $compile_id) : null;
$sp = $this->buildSourcePath($tpl, $name, $type, $dir);
$uid = $this->buildUid($tpl, $sp, $name, $type);
$_flag = '';
$_filepath = $uid . $_flag;
// if use_sub_dirs, break file into directories
if ($sub) {
$_filepath = substr($_filepath, 0, 2) . $sep
. substr($_filepath, 2, 2) . $sep
. substr($_filepath, 4, 2) . $sep
. $_filepath;
}
$_compile_dir_sep = $sub ? $sep : '^';
if (isset($_compile_id)) {
$_filepath = $_compile_id . $_compile_dir_sep . $_filepath;
}
// caching token
if ($caching) {
$_cache = '.cache';
} else {
$_cache = '';
}
$_compile_dir = $tpl->smarty->getCompileDir();
// set basename if not specified
$_basename = $this->getBasename($tpl, $name, $type);
if ($_basename === null) {
$_basename = basename(preg_replace('![^\w\/]+!', '_', $name));
}
// separate (optional) basename by dot
if ($_basename) {
$_basename = '.' . $_basename;
}
return $_compile_dir . $_filepath . '.' . $type . $_basename . $_cache . '.php';
}
/**
* Return cache file path
*
* @param Smarty_Internal_TemplateBase $tpl template object
* @param bool $sub use sub directory flag
* @param null|string $cache_id optional cache id
* @param null|string $compile_id optional compile id
* @param null|string $name optional template name
* @param null|string $type optional template type
* @param null|string $dir optional template folder
* @param null|string $cacheType optional cache resource type
*
* @return string
* @throws \Exception
*/
public function buildCachedPath($tpl, $sub = true, $cache_id = null, $compile_id = null, $name = null, $type = null, $dir = null, $cacheType = null)
{
$cacheType = isset($cacheType) ? $cacheType : $tpl->smarty->caching_type;
switch ($cacheType) {
case 'file':$sep = DS;
$_compile_id = isset($compile_id) ? preg_replace('![^\w\|]+!', '_', $compile_id) : null;
$_cache_id = isset($cache_id) ? preg_replace('![^\w\|]+!', '_', $cache_id) : null;
$sp = $this->buildSourcePath($tpl, $name, $type, $dir);
$uid = $this->buildUid($tpl, $sp, $name, $type);
$_filepath = $uid;
// if use_sub_dirs, break file into directories
if ($sub) {
$_filepath = substr($_filepath, 0, 2) . $sep
. substr($_filepath, 2, 2) . $sep
. substr($_filepath, 4, 2) . $sep
. $_filepath;
}
$_compile_dir_sep = $sub ? $sep : '^';
if (isset($_cache_id)) {
$_cache_id = str_replace('|', $_compile_dir_sep, $_cache_id) . $_compile_dir_sep;
} else {
$_cache_id = '';
}
if (isset($_compile_id)) {
$_compile_id = $_compile_id . $_compile_dir_sep;
} else {
$_compile_id = '';
}
$smarty = isset($tpl->smarty) ? $tpl->smarty : $tpl;
$_cache_dir = $smarty->getCacheDir();
return $_cache_dir . $_cache_id . $_compile_id . $_filepath . '.' . basename($sp) . '.php';
case 'mysql':
case 'mysqltest':
case 'pdo':
case 'foobar':
$sp = $this->buildSourcePath($tpl, $name, $type, $dir);
$_compile_id = isset($compile_id) ? preg_replace('![^\w\|]+!', '_', $compile_id) : null;
$_cache_id = isset($cache_id) ? preg_replace('![^\w\|]+!', '_', $cache_id) : null;
return sha1($sp . $_cache_id . $_compile_id);
default:
throw new Exception("Unhandled cache resource type '{$cacheType}'");
}
}
/**
* Prefilter to remove \r from template source
*
* @param string $tpl_source
* @param $template
*
* @return mixed
*/
function remove_cr($tpl_source, $template)
{
return str_replace(array("\r\n", "\r"), "\n", $tpl_source);
}
/**
* Remove Smarty object from cached resources
*
*/
public function clearResourceCache()
{
if (class_exists('Smarty_Resource', false)) {
if (isset(Smarty_Resource::$sources) && !empty(Smarty_Resource::$sources)) {
foreach (Smarty_Resource::$sources as $obj) {
if (isset($obj->smarty)) {
$obj->smarty = null;
}
}
Smarty_Resource::$sources = array();
}
if (isset(Smarty_Resource::$compileds) && !empty(Smarty_Resource::$compileds)) {
foreach (Smarty_Resource::$compileds as $obj) {
if (isset($obj->smarty)) {
$obj->smarty = null;
}
}
Smarty_Resource::$compileds = array();
}
if (isset(Smarty_Resource::$resources) && !empty(Smarty_Resource::$resources)) {
foreach (Smarty_Resource::$resources as $obj) {
if (isset($obj->smarty)) {
$obj->smarty = null;
}
}
Smarty_Resource::$resources = array();
}
}
if (class_exists('Smarty_CacheResource', false)) {
if (isset(Smarty_CacheResource::$resources) && !empty(Smarty_CacheResource::$resources)) {
foreach (Smarty_CacheResource::$resources as $obj) {
if (isset($obj->smarty)) {
$obj->smarty = null;
}
}
Smarty_CacheResource::$resources = array();
}
}
}
/**
* Tears down the fixture
* This method is called after a test is executed.
*
*/
protected function tearDown()
{
$this->clearResourceCache();
if (isset($this->smarty->smarty)) {
$this->smarty->smarty = null;
}
if (isset($this->smarty)) {
$this->smarty = null;
}
if (isset($this->smartyBC->smarty)) {
$this->smartyBC->smarty = null;
}
if (isset($this->smartyBC)) {
$this->smartyBC = null;
}
}
}

View File

@@ -1 +1,17 @@
# phpunit #Smarty 3 template engine
##PHPUnit repository
For installing the PHPUnit test by composer use the following:
"require-dev": {
"smarty/smarty-phpunit": "3.1.12"
}
Replace 3.1.12 with the installed Smarty version number.
Starting with Smarty version 3.1.22 the "require-dev" section will be added
to the composer.json file of the Smarty distribution.
The tests for the custom template and cache resources Mysql, Memcache and APC can
be enabled in config.xml.

View File

@@ -0,0 +1,144 @@
<?php
/**
* Smarty PHPunit tests for cache resource file
*
* @package PHPunit
* @author Uwe Tews
*/
/**
* class for cache resource file tests
*
* @backupStaticAttributes enabled
*/
class HttpModifiedSinceTest extends PHPUnit_Smarty
{
public function setUp()
{
$this->setUpSmarty(__DIR__);
}
public function testInit()
{
$this->cleanDirs();
}
/**
*
*/
public function testDisabled()
{
$_SERVER['SMARTY_PHPUNIT_DISABLE_HEADERS'] = true;
$_SERVER['SMARTY_PHPUNIT_HEADERS'] = array();
$this->smarty->setCacheModifiedCheck(false);
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 20;
ob_start();
$this->smarty->display('helloworld.tpl');
$output = ob_get_contents();
ob_end_clean();
$this->assertEquals('hello world', $output);
$this->assertEquals('', join("\r\n", $_SERVER['SMARTY_PHPUNIT_HEADERS']));
unset($_SERVER['HTTP_IF_MODIFIED_SINCE']);
unset($_SERVER['SMARTY_PHPUNIT_HEADERS']);
unset($_SERVER['SMARTY_PHPUNIT_DISABLE_HEADERS']);
}
/**
*
*/
public function testEnabledUncached()
{
$_SERVER['SMARTY_PHPUNIT_DISABLE_HEADERS'] = true;
$_SERVER['SMARTY_PHPUNIT_HEADERS'] = array();
$this->smarty->setCacheModifiedCheck(true);
$this->smarty->caching = false;
$this->smarty->cache_lifetime = 20;
ob_start();
$this->smarty->display('helloworld.tpl');
$output = ob_get_contents();
ob_end_clean();
$this->assertEquals('hello world', $output);
$this->assertEquals('', join("\r\n", $_SERVER['SMARTY_PHPUNIT_HEADERS']));
unset($_SERVER['HTTP_IF_MODIFIED_SINCE']);
unset($_SERVER['SMARTY_PHPUNIT_HEADERS']);
unset($_SERVER['SMARTY_PHPUNIT_DISABLE_HEADERS']);
}
/**
*
*/
public function testEnabledCached()
{
$_SERVER['SMARTY_PHPUNIT_DISABLE_HEADERS'] = true;
$_SERVER['SMARTY_PHPUNIT_HEADERS'] = array();
$this->smarty->setCacheModifiedCheck(true);
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 20;
ob_start();
$l1 = ob_get_level();
$this->smarty->display('helloworld.tpl');
$l2 = ob_get_level();
$output = ob_get_contents();
ob_end_clean();
$this->assertEquals('hello world', $output);
$t1 = time();
$t2 = strtotime(substr( $_SERVER['SMARTY_PHPUNIT_HEADERS'][0],15));
$this->assertTrue(($t2-$t1) <= 1);
}
/**
*
*/
public function testEnabledCached2()
{
$_SERVER['SMARTY_PHPUNIT_HEADERS'] = array();
$_SERVER['HTTP_IF_MODIFIED_SINCE'] = gmdate('D, d M Y H:i:s', time() - 3600) . ' GMT';
$this->smarty->setCacheModifiedCheck(true);
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 20;
ob_start();
$l3 = ob_get_level();
$this->smarty->display('helloworld.tpl');
$l4 = ob_get_level();
$output = ob_get_contents();
ob_end_clean();
$this->assertEquals('hello world', $output);
$t1 = time();
$t2 = strtotime(substr( $_SERVER['SMARTY_PHPUNIT_HEADERS'][0],15));
$this->assertTrue(($t2-$t1) <= 1);
}
/**
*
*/
public function testEnabledCached3()
{
$_SERVER['SMARTY_PHPUNIT_HEADERS'] = array();
$_SERVER['HTTP_IF_MODIFIED_SINCE'] = gmdate('D, d M Y H:i:s', time() + 10) . ' GMT';
$this->smarty->setCacheModifiedCheck(true);
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 20;
ob_start();
$l5 = ob_get_level();
$this->smarty->display('helloworld.tpl');
$l6 = ob_get_level();
$output = ob_get_contents();
ob_end_clean();
$this->assertEquals('', $output);
$this->assertEquals('304 Not Modified', join("\r\n", $_SERVER['SMARTY_PHPUNIT_HEADERS']));
unset($_SERVER['HTTP_IF_MODIFIED_SINCE']);
unset($_SERVER['SMARTY_PHPUNIT_HEADERS']);
unset($_SERVER['SMARTY_PHPUNIT_DISABLE_HEADERS']);
}
}

View File

@@ -0,0 +1 @@
hello world

View File

@@ -0,0 +1,31 @@
<?php
/**
* Smarty PHPunit tests for cache resource file
*
* @package PHPunit
* @author Uwe Tews
*/
include_once __DIR__ . '/../Memcache/CacheResourceCustomMemcacheTest.php';
/**
* class for cache resource file tests
*
* @backupStaticAttributes enabled
*/
class CacheResourceCustomApcTest extends CacheResourceCustomMemcacheTest
{
public function setUp()
{
if (self::$config['cacheResource']['ApcEnable'] != 'true') {
$this->markTestSkipped('Apc tests are disabled');
} else {
if (!function_exists('apc_cache_info') || ini_get('apc.enable_cli')) {
$this->markTestSkipped('APC cache not available');
}
}
$this->setUpSmarty(__DIR__);
parent::setUp();
$this->smarty->addPluginsDir(SMARTY_DIR . '../demo/plugins/');
}
}

View File

@@ -0,0 +1,379 @@
<?php
/**
* Smarty PHPunit tests for cache resource file
*
* @package PHPunit
* @author Uwe Tews
*/
include_once __DIR__ . '/../_shared/CacheResourceTestCommon.php';
/**
* class for cache resource file tests
*
* @backupStaticAttributes enabled
*/
class CacheResourceFileTest extends CacheResourceTestCommon
{
public function setUp()
{
$this->setUpSmarty(__DIR__);
parent::setUp();
}
public function testInit()
{
$this->cleanDirs();
}
/**
* test getCachedFilepath with configuration['useSubDirs'] enabled
*/
public function testGetCachedFilepathSubDirs()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$this->smarty->setUseSubDirs(true);
$tpl = $this->smarty->createTemplate('helloworld.tpl');
$this->assertEquals($this->buildCachedPath($tpl, true, null, null, 'helloworld.tpl', $type = 'file', $this->smarty->getTemplateDir(0), 'file')
, $tpl->cached->filepath);
}
/**
* test getCachedFilepath with cache_id
*/
public function testGetCachedFilepathCacheId()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$this->smarty->setUseSubDirs(true);
$tpl = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar');
$this->assertEquals($this->buildCachedPath($tpl, true, 'foo|bar', null, 'helloworld.tpl', $type = 'file', $this->smarty->getTemplateDir(0), 'file')
, $tpl->cached->filepath);
}
/**
* test getCachedFilepath with compile_id
*/
public function testGetCachedFilepathCompileId()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$this->smarty->setUseSubDirs(true);
$tpl = $this->smarty->createTemplate('helloworld.tpl', null, 'blar');
$this->assertEquals($this->buildCachedPath($tpl, true, null, 'blar', 'helloworld.tpl', $type = 'file', $this->smarty->getTemplateDir(0), 'file')
, $tpl->cached->filepath);
}
/**
* test getCachedFilepath with cache_id and compile_id
*/
public function testGetCachedFilepathCacheIdCompileId()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$this->smarty->setUseSubDirs(true);
$tpl = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar', 'blar');
$this->assertEquals($this->buildCachedPath($tpl, true, 'foo|bar', 'blar', 'helloworld.tpl', $type = 'file', $this->smarty->getTemplateDir(0), 'file')
, $tpl->cached->filepath);
}
/**
* test cache->clear_all with cache_id and compile_id
*/
public function testClearCacheAllCacheIdCompileId()
{
$this->cleanCacheDir();
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$this->smarty->setUseSubDirs(true);
$tpl = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar', 'blar');
$this->writeCachedContent($tpl);
$this->assertTrue(file_exists($tpl->cached->filepath));
$this->assertEquals(1, $this->smarty->clearAllCache());
}
/**
* test cache->clear with cache_id and compile_id
*/
public function testClearCacheCacheIdCompileId()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$this->cleanCacheDir();
$this->smarty->setUseSubDirs(false);
$tpl = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar', 'blar');
$this->writeCachedContent($tpl);
$tpl2 = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar2', 'blar');
$this->writeCachedContent($tpl2);
$tpl3 = $this->smarty->createTemplate('helloworld2.tpl', 'foo|bar', 'blar');
$this->writeCachedContent($tpl3);
$this->assertTrue(file_exists($tpl->cached->filepath));
$this->assertTrue(file_exists($tpl2->cached->filepath));
$this->assertTrue(file_exists($tpl3->cached->filepath));
$this->assertEquals(2, $this->smarty->clearCache(null, 'foo|bar'));
$this->assertFalse(file_exists($tpl->cached->filepath));
$this->assertTrue(file_exists($tpl2->cached->filepath));
$this->assertFalse(file_exists($tpl3->cached->filepath));
}
public function testClearCacheCacheIdCompileId2()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$this->smarty->setUseSubDirs(false);
$this->cleanCacheDir();
$tpl = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar', 'blar');
$this->writeCachedContent($tpl);
$tpl2 = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar2', 'blar');
$this->writeCachedContent($tpl2);
$tpl3 = $this->smarty->createTemplate('helloworld2.tpl', 'foo|bar', 'blar');
$this->writeCachedContent($tpl3);
$this->assertTrue(file_exists($tpl->cached->filepath));
$this->assertTrue(file_exists($tpl2->cached->filepath));
$this->assertTrue(file_exists($tpl3->cached->filepath));
$this->assertEquals(2, $this->smarty->clearCache('helloworld.tpl'));
$this->assertFalse(file_exists($tpl->cached->filepath));
$this->assertFalse(file_exists($tpl2->cached->filepath));
$this->assertTrue(file_exists($tpl3->cached->filepath));
}
public function testClearCacheCacheIdCompileId2Sub()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$this->smarty->setUseSubDirs(true);
$this->cleanCacheDir();
$tpl = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar', 'blar');
$this->writeCachedContent($tpl);
$tpl2 = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar2', 'blar');
$this->writeCachedContent($tpl2);
$tpl3 = $this->smarty->createTemplate('helloworld2.tpl', 'foo|bar', 'blar');
$this->writeCachedContent($tpl3);
$this->assertTrue(file_exists($tpl->cached->filepath));
$this->assertTrue(file_exists($tpl2->cached->filepath));
$this->assertTrue(file_exists($tpl3->cached->filepath));
$this->assertEquals(2, $this->smarty->clearCache('helloworld.tpl'));
$this->assertFalse(file_exists($tpl->cached->filepath));
$this->assertFalse(file_exists($tpl2->cached->filepath));
$this->assertTrue(file_exists($tpl3->cached->filepath));
}
public function testClearCacheCacheIdCompileId3()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$this->cleanCacheDir();
$this->smarty->setUseSubDirs(false);
$tpl = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar', 'blar');
$this->writeCachedContent($tpl);
$tpl2 = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar', 'blar2');
$this->writeCachedContent($tpl2);
$tpl3 = $this->smarty->createTemplate('helloworld2.tpl', 'foo|bar', 'blar');
$this->writeCachedContent($tpl3);
$this->assertTrue(file_exists($tpl->cached->filepath));
$this->assertTrue(file_exists($tpl2->cached->filepath));
$this->assertTrue(file_exists($tpl3->cached->filepath));
$this->assertEquals(1, $this->smarty->clearCache('helloworld.tpl', null, 'blar2'));
$this->assertTrue(file_exists($tpl->cached->filepath));
$this->assertFalse(file_exists($tpl2->cached->filepath));
$this->assertTrue(file_exists($tpl3->cached->filepath));
}
public function testClearCacheCacheIdCompileId3Sub()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$this->cleanCacheDir();
$this->smarty->setUseSubDirs(true);
$tpl = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar', 'blar');
$this->writeCachedContent($tpl);
$tpl2 = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar', 'blar2');
$this->writeCachedContent($tpl2);
$tpl3 = $this->smarty->createTemplate('helloworld2.tpl', 'foo|bar', 'blar');
$this->writeCachedContent($tpl3);
$this->assertTrue(file_exists($tpl->cached->filepath));
$this->assertTrue(file_exists($tpl2->cached->filepath));
$this->assertTrue(file_exists($tpl3->cached->filepath));
$this->assertEquals(1, $this->smarty->clearCache('helloworld.tpl', null, 'blar2'));
$this->assertTrue(file_exists($tpl->cached->filepath));
$this->assertFalse(file_exists($tpl2->cached->filepath));
$this->assertTrue(file_exists($tpl3->cached->filepath));
}
public function testClearCacheCacheIdCompileId4()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$this->smarty->setUseSubDirs(false);
$this->cleanCacheDir();
$tpl = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar', 'blar');
$this->writeCachedContent($tpl);
$tpl2 = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar', 'blar2');
$this->writeCachedContent($tpl2);
$tpl3 = $this->smarty->createTemplate('helloworld2.tpl', 'foo|bar', 'blar');
$this->writeCachedContent($tpl3);
$this->assertTrue(file_exists($tpl->cached->filepath));
$this->assertTrue(file_exists($tpl2->cached->filepath));
$this->assertTrue(file_exists($tpl3->cached->filepath));
$this->assertEquals(1, $this->smarty->clearCache('helloworld.tpl', null, 'blar2'));
$this->assertTrue(file_exists($tpl->cached->filepath));
$this->assertFalse(file_exists($tpl2->cached->filepath));
$this->assertTrue(file_exists($tpl3->cached->filepath));
}
public function testClearCacheCacheIdCompileId4Sub()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$this->smarty->setUseSubDirs(true);
$this->cleanCacheDir();
$tpl = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar', 'blar');
$this->writeCachedContent($tpl);
$tpl2 = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar', 'blar2');
$this->writeCachedContent($tpl2);
$tpl3 = $this->smarty->createTemplate('helloworld2.tpl', 'foo|bar', 'blar');
$this->writeCachedContent($tpl3);
$this->assertTrue(file_exists($tpl->cached->filepath));
$this->assertTrue(file_exists($tpl2->cached->filepath));
$this->assertTrue(file_exists($tpl3->cached->filepath));
$this->assertEquals(1, $this->smarty->clearCache('helloworld.tpl', null, 'blar2'));
$this->assertTrue(file_exists($tpl->cached->filepath));
$this->assertFalse(file_exists($tpl2->cached->filepath));
$this->assertTrue(file_exists($tpl3->cached->filepath));
}
public function testClearCacheCacheIdCompileId5()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$this->smarty->setUseSubDirs(false);
$this->cleanCacheDir();
$tpl = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar', 'blar');
$this->writeCachedContent($tpl);
$tpl2 = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar', 'blar2');
$this->writeCachedContent($tpl2);
$tpl3 = $this->smarty->createTemplate('helloworld2.tpl', 'foo|bar', 'blar');
$this->writeCachedContent($tpl3);
$this->assertTrue(file_exists($tpl->cached->filepath));
$this->assertTrue(file_exists($tpl2->cached->filepath));
$this->assertTrue(file_exists($tpl3->cached->filepath));
$this->assertEquals(2, $this->smarty->clearCache(null, null, 'blar'));
$this->assertFalse(file_exists($tpl->cached->filepath));
$this->assertTrue(file_exists($tpl2->cached->filepath));
$this->assertFalse(file_exists($tpl3->cached->filepath));
}
public function testClearCacheCacheIdCompileId5Sub()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$this->smarty->setUseSubDirs(true);
$this->cleanCacheDir();
$tpl = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar', 'blar');
$this->writeCachedContent($tpl);
$tpl2 = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar', 'blar2');
$this->writeCachedContent($tpl2);
$tpl3 = $this->smarty->createTemplate('helloworld2.tpl', 'foo|bar', 'blar');
$this->writeCachedContent($tpl3);
$this->assertTrue(file_exists($tpl->cached->filepath));
$this->assertTrue(file_exists($tpl2->cached->filepath));
$this->assertTrue(file_exists($tpl3->cached->filepath));
$this->assertEquals(2, $this->smarty->clearCache(null, null, 'blar'));
$this->assertFalse(file_exists($tpl->cached->filepath));
$this->assertTrue(file_exists($tpl2->cached->filepath));
$this->assertFalse(file_exists($tpl3->cached->filepath));
}
public function testClearCacheCacheFile()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$this->smarty->setUseSubDirs(false);
$this->cleanCacheDir();
$tpl = $this->smarty->createTemplate('helloworld.tpl');
$this->writeCachedContent($tpl);
$tpl2 = $this->smarty->createTemplate('helloworld.tpl', null, 'bar');
$this->writeCachedContent($tpl2);
$tpl3 = $this->smarty->createTemplate('helloworld.tpl', 'buh|blar');
$this->writeCachedContent($tpl3);
$tpl4 = $this->smarty->createTemplate('helloworld2.tpl');
$this->writeCachedContent($tpl4);
$this->assertTrue(file_exists($tpl->cached->filepath));
$this->assertTrue(file_exists($tpl2->cached->filepath));
$this->assertTrue(file_exists($tpl3->cached->filepath));
$this->assertTrue(file_exists($tpl4->cached->filepath));
$this->assertEquals(3, $this->smarty->clearCache('helloworld.tpl'));
$this->assertFalse(file_exists($tpl->cached->filepath));
$this->assertFalse(file_exists($tpl2->cached->filepath));
$this->assertFalse(file_exists($tpl3->cached->filepath));
$this->assertTrue(file_exists($tpl4->cached->filepath));
}
public function testClearCacheCacheFileSub()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$this->smarty->setUseSubDirs(true);
$this->cleanCacheDir();
$tpl = $this->smarty->createTemplate('helloworld.tpl');
$this->writeCachedContent($tpl);
$tpl2 = $this->smarty->createTemplate('helloworld.tpl', null, 'bar');
$this->writeCachedContent($tpl2);
$tpl3 = $this->smarty->createTemplate('helloworld.tpl', 'buh|blar');
$this->writeCachedContent($tpl3);
$tpl4 = $this->smarty->createTemplate('helloworld2.tpl');
$this->writeCachedContent($tpl4);
$this->assertTrue(file_exists($tpl->cached->filepath));
$this->assertTrue(file_exists($tpl2->cached->filepath));
$this->assertTrue(file_exists($tpl3->cached->filepath));
$this->assertTrue(file_exists($tpl4->cached->filepath));
$this->assertEquals(3, $this->smarty->clearCache('helloworld.tpl'));
$this->assertFalse(file_exists($tpl->cached->filepath));
$this->assertFalse(file_exists($tpl2->cached->filepath));
$this->assertFalse(file_exists($tpl3->cached->filepath));
$this->assertTrue(file_exists($tpl4->cached->filepath));
}
/**
* test cache->clear_all method
*/
public function testClearCacheAll()
{
$this->cleanCacheDir();
file_put_contents($this->smarty->getCacheDir() . 'dummy.php', 'test');
$this->assertEquals(1, $this->smarty->clearAllCache());
}
/**
* test cache->clear_all method not expired
*/
public function testClearCacheAllNotExpired()
{
$this->cleanCacheDir();
file_put_contents($this->smarty->getCacheDir() . 'dummy.php', 'test');
touch($this->smarty->getCacheDir() . 'dummy.php', time() - 1000);
clearstatcache();
$this->assertEquals(0, $this->smarty->clearAllCache(2000));
}
/**
* test cache->clear_all method expired
*/
public function testClearCacheAllExpired()
{
$this->cleanCacheDir();
file_put_contents($this->smarty->getCacheDir() . 'dummy.php', 'test');
touch($this->smarty->getCacheDir() . 'dummy.php', time() - 1000);
clearstatcache();
$this->assertEquals(1, $this->smarty->clearAllCache(500));
}
private function writeCachedContent($tpl)
{
$tpl->writeCachedContent("echo 'hello world';\n");
}
}

View File

@@ -0,0 +1,92 @@
<?php
/**
* Smarty PHPunit tests for cache resource memcache
*
* @package PHPunit
* @author Uwe Tews
*/
include_once __DIR__ . '/../_shared/CacheResourceTestCommon.php';
/**
* class for cache resource memcache tests
*
* @backupStaticAttributes enabled
*/
class CacheResourceCustomMemcacheTest extends CacheResourceTestCommon
{
/**
* Sets up the fixture
* This method is called before a test is executed.
*
*/
public function setUp()
{
if (self::$config['cacheResource']['MemcacheEnable'] != 'true') {
$this->markTestSkipped('Memcache tests are disabled');
} else {
if (!class_exists('Memcache')) {
$this->markTestSkipped('Memcache not available');
}
}
$this->setUpSmarty(__DIR__);
parent::setUp();
$this->smarty->setCachingType('memcachetest');
}
public function testInit()
{
$this->cleanDirs();
}
protected function doClearCacheAssertion($a, $b)
{
$this->assertEquals(- 1, $b);
}
public function testGetCachedFilepathSubDirs()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$tpl = $this->smarty->createTemplate('helloworld.tpl');
$sha1 = $tpl->source->uid . '#helloworld_tpl##';
$this->assertEquals($sha1, $tpl->cached->filepath);
}
/**
* test getCachedFilepath with cache_id
*/
public function testGetCachedFilepathCacheId()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$tpl = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar');
$sha1 = $tpl->source->uid . '#helloworld_tpl#foo|bar#';
$this->assertEquals($sha1, $tpl->cached->filepath);
}
/**
* test getCachedFilepath with compile_id
*/
public function testGetCachedFilepathCompileId()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$tpl = $this->smarty->createTemplate('helloworld.tpl', null, 'blar');
$sha1 = $tpl->source->uid . '#helloworld_tpl##blar';
$this->assertEquals($sha1, $tpl->cached->filepath);
}
/**
* test getCachedFilepath with cache_id and compile_id
*/
public function testGetCachedFilepathCacheIdCompileId()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$tpl = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar', 'blar');
$sha1 = $tpl->source->uid . '#helloworld_tpl#foo|bar#blar';
$this->assertEquals($sha1, $tpl->cached->filepath);
}
}

View File

@@ -0,0 +1,36 @@
<?php
/**
* Smarty PHPunit tests for cache resource file
*
* @package PHPunit
* @author Uwe Tews
*/
include_once __DIR__ . '/../_shared/CacheResourceTestCommon.php';
/**
* class for cache resource file tests
*
* @backupStaticAttributes enabled
*/
class CacheResourceCustomMysqlTest extends CacheResourceTestCommon
{
public function setUp()
{
if (self::$config['cacheResource']['MysqlEnable'] != 'true') {
$this->markTestSkipped('mysql tests are disabled');
}
if (self::$init) {
$this->getConnection();
}
$this->setUpSmarty(__DIR__);
parent::setUp();
$this->smarty->setCachingType('mysqltest');
}
public function testInit()
{
$this->cleanDirs();
$this->initMysqlCache();
}
}

View File

@@ -0,0 +1,39 @@
<?php
/**
* Smarty PHPunit tests for cache resource file
*
* @package PHPunit
* @author Uwe Tews
*/
include_once __DIR__ . '/../_shared/CacheResourceTestCommon.php';
/**
* class for cache resource file tests
*
* @backupStaticAttributes enabled
*/
class CacheResourceCustomRegisteredTest extends CacheResourceTestCommon
{
public function setUp()
{
if (self::$config['cacheResource']['MysqlEnable'] != 'true') {
$this->markTestSkipped('mysql tests are disabled');
}
if (self::$init) {
$this->getConnection();
}
$this->setUpSmarty(__DIR__);
parent::setUp();
if (!class_exists('Smarty_CacheResource_Mysqltest', false)) {
require_once(__DIR__ . "/../_shared/PHPunitplugins/cacheresource.mysqltest.php");
}
$this->smarty->setCachingType('foobar');
$this->smarty->registerCacheResource('foobar', new Smarty_CacheResource_Mysqltest());
}
public function testInit()
{
$this->cleanDirs();
$this->initMysqlCache();
}
}

View File

@@ -0,0 +1,522 @@
<?php
/**
* Smarty PHPunit tests for cache resource file
*
* @package PHPunit
* @author Uwe Tews
*/
/**
* class for cache resource file tests
*
* @backupStaticAttributes enabled
*/
class CacheResourceTestCommon extends PHPUnit_Smarty
{
public static $touchResource = null;
public function setUp()
{
$this->smarty->setTemplateDir(__DIR__ . '/../_shared/templates');
$this->smarty->addPluginsDir(__DIR__ . '/../_shared/PHPunitplugins');
$this->smarty->registerFilter('pre', array($this, 'compiledPrefilter'));
}
protected function doClearCacheAssertion($a, $b)
{
$this->assertEquals($a, $b);
}
public function compiledPrefilter($text, Smarty_Internal_Template $tpl)
{
return str_replace('#', $tpl->getVariable('test'), $text);
}
/**
* test getCachedFilepath with configuration['useSubDirs'] enabled
*/
public function testGetCachedFilepathSubDirs()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$this->smarty->setUseSubDirs(true);
$tpl = $this->smarty->createTemplate('helloworld.tpl');
$this->assertEquals($this->buildCachedPath($tpl), $tpl->cached->filepath);
}
/**
* test getCachedFilepath with cache_id
*/
public function testGetCachedFilepathCacheId()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$tpl = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar');
$this->assertEquals($this->buildCachedPath($tpl, true, 'foo|bar'), $tpl->cached->filepath);
}
/**
* test getCachedFilepath with compile_id
*/
public function testGetCachedFilepathCompileId()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$tpl = $this->smarty->createTemplate('helloworld.tpl', null, 'blar');
$this->assertEquals($this->buildCachedPath($tpl, true, null, 'blar'), $tpl->cached->filepath);
}
/**
* test getCachedFilepath with cache_id and compile_id
*/
public function testGetCachedFilepathCacheIdCompileId()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$tpl = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar', 'blar');
$this->assertEquals($this->buildCachedPath($tpl, true, 'foo|bar', 'blar'), $tpl->cached->filepath);
}
/**
* test cache->clear_all with cache_id and compile_id
*/
public function testClearCacheAllCacheIdCompileId()
{
$this->smarty->clearAllCache();
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$tpl = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar', 'blar');
$tpl->writeCachedContent('hello world');
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl));
// Custom CacheResources may return -1 if they can't tell the number of deleted elements
$this->assertEquals(-1, $this->smarty->clearAllCache());
}
/**
* test cache->clear with cache_id and compile_id
*/
public function testClearCacheCacheIdCompileId()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$this->smarty->clearAllCache();
// create and cache templates
$tpl = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar', 'blar');
$tpl->writeCachedContent('hello world 1');
$tpl2 = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar2', 'blar');
$tpl2->writeCachedContent('hello world 2');
$tpl3 = $this->smarty->createTemplate('helloworld2.tpl', 'foo|bar', 'blar');
$tpl3->writeCachedContent('hello world 3');
// test cached content
$this->assertEquals('hello world 1', $tpl->cached->handler->getCachedContent($tpl));
$this->assertEquals('hello world 2', $tpl->cached->handler->getCachedContent($tpl2));
$this->assertEquals('hello world 3', $tpl->cached->handler->getCachedContent($tpl3));
// test number of deleted caches
$this->doClearCacheAssertion(2, $this->smarty->clearCache(null, 'foo|bar'));
// test that caches are deleted properly
$this->assertNull($tpl->cached->handler->getCachedContent($tpl));
$this->assertEquals('hello world 2', $tpl->cached->handler->getCachedContent($tpl2));
$this->assertNull($tpl->cached->handler->getCachedContent($tpl3));
}
public function testClearCacheCacheIdCompileId2()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$this->smarty->clearAllCache();
// create and cache templates
$tpl = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar', 'blar');
$tpl->writeCachedContent('hello world');
$tpl2 = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar2', 'blar');
$tpl2->writeCachedContent('hello world');
$tpl3 = $this->smarty->createTemplate('helloworld2.tpl', 'foo|bar', 'blar');
$tpl3->writeCachedContent('hello world');
// test cached content
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl));
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl2));
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl3));
// test number of deleted caches
$this->doClearCacheAssertion(2, $this->smarty->clearCache('helloworld.tpl'));
// test that caches are deleted properly
$this->assertNull($tpl->cached->handler->getCachedContent($tpl));
$this->assertNull($tpl->cached->handler->getCachedContent($tpl2));
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl3));
}
public function testClearCacheCacheIdCompileId2Sub()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$this->smarty->clearAllCache();
// create and cache templates
$tpl = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar', 'blar');
$tpl->writeCachedContent('hello world');
$tpl2 = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar2', 'blar');
$tpl2->writeCachedContent('hello world');
$tpl3 = $this->smarty->createTemplate('helloworld2.tpl', 'foo|bar', 'blar');
$tpl3->writeCachedContent('hello world');
// test cached content
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl));
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl2));
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl3));
// test number of deleted caches
$this->doClearCacheAssertion(2, $this->smarty->clearCache('helloworld.tpl'));
// test that caches are deleted properly
$this->assertNull($tpl->cached->handler->getCachedContent($tpl));
$this->assertNull($tpl->cached->handler->getCachedContent($tpl2));
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl3));
}
public function testClearCacheCacheIdCompileId3()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$this->smarty->clearAllCache();
// create and cache templates
$tpl = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar', 'blar');
$tpl->writeCachedContent('hello world');
$tpl2 = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar', 'blar2');
$tpl2->writeCachedContent('hello world');
$tpl3 = $this->smarty->createTemplate('helloworld2.tpl', 'foo|bar', 'blar');
$tpl3->writeCachedContent('hello world');
// test cached content
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl));
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl2));
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl3));
// test number of deleted caches
$this->doClearCacheAssertion(1, $this->smarty->clearCache('helloworld.tpl', null, 'blar2'));
// test that caches are deleted properly
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl));
$this->assertNull($tpl->cached->handler->getCachedContent($tpl2));
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl3));
}
public function testClearCacheCacheIdCompileId3Sub()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$this->smarty->clearAllCache();
// create and cache templates
$tpl = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar', 'blar');
$tpl->writeCachedContent('hello world');
$tpl2 = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar', 'blar2');
$tpl2->writeCachedContent('hello world');
$tpl3 = $this->smarty->createTemplate('helloworld2.tpl', 'foo|bar', 'blar');
$tpl3->writeCachedContent('hello world');
// test cached content
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl));
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl2));
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl3));
// test number of deleted caches
$this->doClearCacheAssertion(1, $this->smarty->clearCache('helloworld.tpl', null, 'blar2'));
// test that caches are deleted properly
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl));
$this->assertNull($tpl->cached->handler->getCachedContent($tpl2));
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl3));
}
public function testClearCacheCacheIdCompileId4()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$this->smarty->clearAllCache();
// create and cache templates
$tpl = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar', 'blar');
$tpl->writeCachedContent('hello world');
$tpl2 = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar', 'blar2');
$tpl2->writeCachedContent('hello world');
$tpl3 = $this->smarty->createTemplate('helloworld2.tpl', 'foo|bar', 'blar');
$tpl3->writeCachedContent('hello world');
// test cached content
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl));
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl2));
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl3));
// test number of deleted caches
$this->doClearCacheAssertion(1, $this->smarty->clearCache('helloworld.tpl', null, 'blar2'));
// test that caches are deleted properly
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl));
$this->assertNull($tpl->cached->handler->getCachedContent($tpl2));
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl3));
}
public function testClearCacheCacheIdCompileId4Sub()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$this->smarty->clearAllCache();
// create and cache templates
$tpl = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar', 'blar');
$tpl->writeCachedContent('hello world');
$tpl2 = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar', 'blar2');
$tpl2->writeCachedContent('hello world');
$tpl3 = $this->smarty->createTemplate('helloworld2.tpl', 'foo|bar', 'blar');
$tpl3->writeCachedContent('hello world');
// test cached content
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl));
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl2));
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl3));
// test number of deleted caches
$this->doClearCacheAssertion(1, $this->smarty->clearCache('helloworld.tpl', null, 'blar2'));
// test that caches are deleted properly
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl));
$this->assertNull($tpl->cached->handler->getCachedContent($tpl2));
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl3));
}
public function testClearCacheCacheIdCompileId5()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$this->smarty->clearAllCache();
// create and cache templates
$tpl = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar', 'blar');
$tpl->writeCachedContent('hello world');
$tpl2 = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar', 'blar2');
$tpl2->writeCachedContent('hello world');
$tpl3 = $this->smarty->createTemplate('helloworld2.tpl', 'foo|bar', 'blar');
$tpl3->writeCachedContent('hello world');
// test cached content
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl));
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl2));
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl3));
// test number of deleted caches
$this->doClearCacheAssertion(2, $this->smarty->clearCache(null, null, 'blar'));
// test that caches are deleted properly
$this->assertNull($tpl->cached->handler->getCachedContent($tpl));
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl2));
$this->assertNull($tpl->cached->handler->getCachedContent($tpl3));
}
public function testClearCacheCacheIdCompileId5Sub()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$this->smarty->clearAllCache();
// create and cache templates
$tpl = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar', 'blar');
$tpl->writeCachedContent('hello world');
$tpl2 = $this->smarty->createTemplate('helloworld.tpl', 'foo|bar', 'blar2');
$tpl2->writeCachedContent('hello world');
$tpl3 = $this->smarty->createTemplate('helloworld2.tpl', 'foo|bar', 'blar');
$tpl3->writeCachedContent('hello world');
// test cached content
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl));
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl2));
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl3));
// test number of deleted caches
$this->doClearCacheAssertion(2, $this->smarty->clearCache(null, null, 'blar'));
// test that caches are deleted properly
$this->assertNull($tpl->cached->handler->getCachedContent($tpl));
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl2));
$this->assertNull($tpl->cached->handler->getCachedContent($tpl3));
}
public function testClearCacheCacheFile()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$this->smarty->clearAllCache();
// create and cache templates
$tpl = $this->smarty->createTemplate('helloworld.tpl');
$tpl->writeCachedContent('hello world');
$tpl2 = $this->smarty->createTemplate('helloworld.tpl', null, 'bar');
$tpl2->writeCachedContent('hello world');
$tpl3 = $this->smarty->createTemplate('helloworld.tpl', 'buh|blar');
$tpl3->writeCachedContent('hello world');
$tpl4 = $this->smarty->createTemplate('helloworld2.tpl');
$tpl4->writeCachedContent('hello world');
// test cached content
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl));
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl2));
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl3));
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl4));
// test number of deleted caches
$this->doClearCacheAssertion(3, $this->smarty->clearCache('helloworld.tpl'));
// test that caches are deleted properly
$this->assertNull($tpl->cached->handler->getCachedContent($tpl));
$this->assertNull($tpl->cached->handler->getCachedContent($tpl2));
$this->assertNull($tpl->cached->handler->getCachedContent($tpl3));
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl4));
}
public function testClearCacheCacheFileSub()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$this->smarty->clearAllCache();
// create and cache templates
$tpl = $this->smarty->createTemplate('helloworld.tpl');
$tpl->writeCachedContent('hello world');
$tpl2 = $this->smarty->createTemplate('helloworld.tpl', null, 'bar');
$tpl2->writeCachedContent('hello world');
$tpl3 = $this->smarty->createTemplate('helloworld.tpl', 'buh|blar');
$tpl3->writeCachedContent('hello world');
$tpl4 = $this->smarty->createTemplate('helloworld2.tpl');
$tpl4->writeCachedContent('hello world');
// test cached content
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl));
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl2));
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl3));
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl4));
// test number of deleted caches
$this->doClearCacheAssertion(3, $this->smarty->clearCache('helloworld.tpl'));
// test that caches are deleted properly
$this->assertNull($tpl->cached->handler->getCachedContent($tpl));
$this->assertNull($tpl->cached->handler->getCachedContent($tpl2));
$this->assertNull($tpl->cached->handler->getCachedContent($tpl3));
$this->assertEquals('hello world', $tpl->cached->handler->getCachedContent($tpl4));
}
/**
*
* @run InSeparateProcess
* @preserveGlobalState disabled
*
*/
public function testIsCachedPrepare()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$this->smarty->assign('test', 1);
// compile and cache
$this->assertEquals('cache resource test:1 compiled:1 rendered:1', $this->smarty->fetch('cacheresource.tpl'));
}
/**
*
* @run InSeparateProcess
* @preserveGlobalState disabled
*
*/
public function testIsCached()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$this->smarty->assign('test', 2);
$tpl = $this->smarty->createTemplate('cacheresource.tpl', $this->smarty);
$this->assertTrue($tpl->isCached());
$this->assertEquals('cache resource test:2 compiled:1 rendered:1', $this->smarty->fetch($tpl));
}
/**
*
* @run InSeparateProcess
* @preserveGlobalState disabled
*
*/
public function testIsCachedCachingDisabled()
{
$this->smarty->assign('test', 3);
$tpl = $this->smarty->createTemplate('cacheresource.tpl', $this->smarty);
$this->assertFalse($tpl->isCached());
$this->assertEquals('cache resource test:3 compiled:3 rendered:3', $this->smarty->fetch($tpl));
}
/**
*
* @run InSeparateProcess
* @preserveGlobalState disabled
*
*/
public function testForceCache()
{
$this->smarty->caching = true;
$this->smarty->setForceCache(true);
$this->smarty->cache_lifetime = 1000;
$this->smarty->assign('test', 4);
$tpl = $this->smarty->createTemplate('cacheresource.tpl', $this->smarty);
$this->assertFalse($tpl->isCached(), 'isCached() must be false at forceCache');
$this->assertEquals('cache resource test:4 compiled:1 rendered:4', $this->smarty->fetch($tpl));
}
/**
*
* @run InSeparateProcess
* @preserveGlobalState disabled
*
*/
public function testIsCachedAftertestForceCache()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$this->smarty->assign('test', 5);
$tpl = $this->smarty->createTemplate('cacheresource.tpl', $this->smarty);
$this->assertTrue($tpl->isCached(), 'isCached() must be true after forceCache');
$this->assertEquals('cache resource test:5 compiled:1 rendered:4', $this->smarty->fetch($tpl));
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*
*/
public function testIsCachedTouchedSource()
{
sleep(2);
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$this->smarty->assign('test', 6);
$filepath = $this->buildSourcePath(null, 'cacheresource.tpl', 'file');
touch($filepath);
sleep(2);
clearstatcache();
$tpl = $this->smarty->createTemplate('cacheresource.tpl', $this->smarty);
$isCached = $tpl->isCached();
$mustCompile = $tpl->mustCompile();
$this->assertFalse($isCached, 'isCached() must be false after touch of source');
$this->assertTrue($mustCompile, 'mustCompile() must be true after touch of source');
$this->assertEquals('cache resource test:6 compiled:6 rendered:6', $this->smarty->fetch($tpl), 'recompile failed');
$this->assertFalse($isCached, 'isCached() must be false after touch of source');
$this->assertTrue($mustCompile, 'mustCompile() must be true after touch of source');
}
/**
*
* @run InSeparateProcess
* @preserveGlobalState disabled
*
*/
public function testIsCachedAfterTouch()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$this->smarty->assign('test', 7);
$tpl = $this->smarty->createTemplate('cacheresource.tpl', $this->smarty);
$this->assertTrue($tpl->isCached(), 'isCached() must be true after recompilation');
$this->assertEquals('cache resource test:7 compiled:6 rendered:6', $this->smarty->fetch($tpl));
}
/**
*
* @run InSeparateProcess
* @preserveGlobalState disabled
*
*/
public function testIsCachedForceCompile()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$this->smarty->setForceCompile(true);
$this->smarty->assign('test', 8);
$tpl = $this->smarty->createTemplate('cacheresource.tpl', $this->smarty);
$this->assertFalse($tpl->isCached(), 'isCached() must be false at force compile');
$this->assertEquals('cache resource test:8 compiled:8 rendered:8', $this->smarty->fetch($tpl));
}
/**
*
* @run InSeparateProcess
* @preserveGlobalState disabled
*
*/
public function testIsCachedAfterForceCompile()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$this->smarty->assign('test', 9);
$tpl = $this->smarty->createTemplate('cacheresource.tpl', $this->smarty);
$this->assertTrue($tpl->isCached(), 'isCached() must be true after recompilation');
$this->assertEquals('cache resource test:9 compiled:8 rendered:8', $this->smarty->fetch($tpl));
}
}

View File

@@ -0,0 +1,25 @@
<?php
require_once SMARTY_DIR . '../demo/plugins/cacheresource.apc.php';
class Smarty_CacheResource_Apctest extends Smarty_CacheResource_Apc
{
public function get(Smarty_Internal_Template $_template)
{
$this->contents = array();
$this->timestamps = array();
$t = $this->getContent($_template);
return $t ? $t : null;
}
public function __sleep()
{
return array();
}
public function __wakeup()
{
$this->__construct();
}
}

View File

@@ -0,0 +1,25 @@
<?php
require_once SMARTY_DIR . '../demo/plugins/cacheresource.memcache.php';
class Smarty_CacheResource_Memcachetest extends Smarty_CacheResource_Memcache
{
public function get(Smarty_Internal_Template $_template)
{
$this->contents = array();
$this->timestamps = array();
$t = $this->getContent($_template);
return $t ? $t : null;
}
public function __sleep()
{
return array();
}
public function __wakeup()
{
$this->__construct();
}
}

View File

@@ -0,0 +1,18 @@
<?php
require_once SMARTY_DIR . '../demo/plugins/cacheresource.mysql.php';
class Smarty_CacheResource_Mysqltest extends Smarty_CacheResource_Mysql
{
public function __construct() {
try {
$this->db = PHPUnit_Smarty::$pdo;
} catch (PDOException $e) {
throw new SmartyException('Mysql Resource failed: ' . $e->getMessage());
}
$this->fetch = $this->db->prepare('SELECT modified, content FROM output_cache WHERE id = :id');
$this->fetchTimestamp = $this->db->prepare('SELECT modified FROM output_cache WHERE id = :id');
$this->save = $this->db->prepare('REPLACE INTO output_cache (id, name, cache_id, compile_id, content)
VALUES (:id, :name, :cache_id, :compile_id, :content)');
}
}

View File

@@ -0,0 +1,22 @@
<?php
class Smarty_Resource_Filetest extends Smarty_Internal_Resource_File
{
/**
* populate Source Object with meta data from Resource
*
* @param Smarty_Template_Source $source source object
* @param Smarty_Internal_Template $_template template object
*/
public function populate(Smarty_Template_Source $source, Smarty_Internal_Template $_template = null)
{
parent::populate($source, $_template);
if ($source->exists) {
if (isset(CacheResourceTestCommon::$touchResource[$source->filepath])) {
$source->timestamp = CacheResourceTestCommon::$touchResource[$source->filepath];
}
}
}
}

View File

@@ -0,0 +1 @@
cache resource test:{$test nocache} compiled:# rendered:{$test}

View File

@@ -0,0 +1 @@
hello world

View File

@@ -0,0 +1 @@
hello world

View File

@@ -0,0 +1,40 @@
<?php
/**
* Smarty PHPunit tests compilation of compiler plugins
*
* @package PHPunit
* @author Uwe Tews
*/
/**
* class for compiler plugin tests
*
* @backupStaticAttributes enabled
*/
class CompileCompilerPluginTest extends PHPUnit_Smarty
{
public function setUp()
{
$this->setUpSmarty(__DIR__);
}
public function testInit()
{
$this->cleanDirs();
}
/**
* test compiler plugin tag in template file
*/
public function testCompilerPlugin()
{
$this->smarty->registerPlugin(Smarty::PLUGIN_COMPILER, 'compilerplugin', 'mycompilerplugin');
$tpl = $this->smarty->createTemplate('compilerplugintest.tpl');
$this->assertEquals("Hello World", $this->smarty->fetch($tpl));
}
}
function mycompilerplugin($params, $compiler)
{
return '<?php echo \'Hello World\';?>';
}

View File

@@ -0,0 +1 @@
{compilerplugin}

View File

@@ -0,0 +1,70 @@
<?php
/**
* Smarty PHPunit tests of delimiter
*
* @package PHPunit
* @author Uwe Tews
*/
/**
* class for delimiter tests
*
* @backupStaticAttributes enabled
*/
class DelimiterTest extends PHPUnit_Smarty
{
public function setUp()
{
$this->setUpSmarty(__DIR__);
}
public function testInit()
{
$this->cleanDirs();
}
/**
* test <{ }> delimiter
*/
public function testDelimiter1()
{
$this->smarty->left_delimiter = '<{';
$this->smarty->right_delimiter = '}>';
$tpl = $this->smarty->createTemplate('eval:<{* comment *}><{if true}><{"hello world"}><{/if}>');
$this->assertEquals("hello world", $this->smarty->fetch($tpl));
}
/**
* test <-{ }-> delimiter
*/
public function testDelimiter2()
{
$this->smarty->left_delimiter = '<-{';
$this->smarty->right_delimiter = '}->';
$tpl = $this->smarty->createTemplate('eval:<-{* comment *}-><-{if true}-><-{"hello world"}-><-{/if}->');
$this->assertEquals("hello world", $this->smarty->fetch($tpl));
}
/**
* test <--{ }--> delimiter
*/
public function testDelimiter3()
{
$this->smarty->left_delimiter = '<--{';
$this->smarty->right_delimiter = '}-->';
$tpl = $this->smarty->createTemplate('eval:<--{* comment *}--><--{if true}--><--{"hello world"}--><--{/if}-->');
$this->assertEquals("hello world", $this->smarty->fetch($tpl));
}
/**
* test {{ }} delimiter
*/
public function testDelimiter4()
{
$this->smarty->left_delimiter = '{{';
$this->smarty->right_delimiter = '}}';
$tpl = $this->smarty->createTemplate('eval:{{* comment *}}{{if true}}{{"hello world"}}{{/if}}');
$this->assertEquals("hello world", $this->smarty->fetch($tpl));
}
}

View File

@@ -0,0 +1,379 @@
<?php
/**
* Smarty PHPunit tests of config variables
*
* @package PHPunit
* @author Uwe Tews
*/
/**
* class for config variable tests
*
* @b ackupStaticAttributes enabled
*/
class ConfigVarTest extends PHPUnit_Smarty
{
/**
* Sets up the fixture
* This method is called before a test is executed.
*
*/
public function setUp()
{
$this->setUpSmarty(__DIR__);
}
/**
* empty templat_c and cache folders
*/
public function testInit()
{
$this->cleanDirs();
}
/**
* test number config variable
*/
public function testConfigNumber()
{
$this->smarty->configLoad('test.conf');
$this->assertEquals("123.4", $this->smarty->fetch('eval:{#Number#}'));
}
/**
* @run InSeparateProcess
* @preserveGlobalState disabled
*
* test string config variable
*/
public function testConfigText()
{
$this->smarty->configLoad('test.conf');
$this->assertEquals("123bvc", $this->smarty->fetch('eval:{#text#}'));
}
/**
* @run InSeparateProcess
* @preserveGlobalState disabled
*
* test line string config variable
*/
public function testConfigLine()
{
$this->smarty->configLoad('test.conf');
$this->assertEquals("123 This is a line", $this->smarty->fetch('eval:{#line#}'));
}
/**
* @run InSeparateProcess
* @preserveGlobalState disabled
*
* test config variables in global sections
*/
public function testConfigVariableGlobalSections()
{
$this->smarty->configLoad('test.conf');
$this->assertEquals("Welcome to Smarty! Global Section1 Global Section2", $this->smarty->fetch('eval:{#title#} {#sec1#} {#sec2#}'));
}
/**
* @run InSeparateProcess
* @preserveGlobalState disabled
*
* test config variables loading section2
*/
public function testConfigVariableSection2()
{
$this->smarty->configLoad('test.conf', 'section2');
$this->assertEquals("Welcome to Smarty! Global Section1 Hello Section2", $this->smarty->fetch('eval:{#title#} {#sec1#} {#sec2#}'));
}
/**
* @run InSeparateProcess
* @preserveGlobalState disabled
*
* test config variables loading section special char
*/
public function testConfigVariableSectionSpecialChar()
{
$this->smarty->configLoad('test.conf', '/');
$this->assertEquals("Welcome to Smarty! special char", $this->smarty->fetch('eval:{#title#} {#sec#}'));
}
/**
* @run InSeparateProcess
* @preserveGlobalState disabled
*
* test config variables loading section foo/bar
*/
public function testConfigVariableSectionFooBar()
{
$this->smarty->configLoad('test.conf', 'foo/bar');
$this->assertEquals("Welcome to Smarty! section foo/bar", $this->smarty->fetch('eval:{#title#} {#sec#}'));
}
/**
* @run InSeparateProcess
* @preserveGlobalState disabled
*
* test config variables loaded in different scopes from different sections (Smarty and template)
*/
public function testConfigDifferentScope()
{
$this->smarty->configLoad('test.conf', 'section2');
$tpl = $this->smarty->createTemplate('eval:{#title#} {#sec1#} {#sec2#}');
$tpl->configLoad('test.conf', 'section1');
$this->assertEquals("Welcome to Smarty! Global Section1 Hello Section2", $this->smarty->fetch('eval:{#title#} {#sec1#} {#sec2#}'));
$this->assertEquals("Welcome to Smarty! Hello Section1 Global Section2", $this->smarty->fetch($tpl));
}
/**
* test config variables of hidden sections
* shall display variables from hidden section
*
* @run InSeparateProcess
* @preserveGlobalState disabled
*/
public function testConfigVariableHidden()
{
$this->smarty->config_read_hidden = true;
$this->smarty->configLoad('test.conf', 'hidden');
$this->assertEquals("Welcome to Smarty!Hidden Section", $this->smarty->fetch('eval:{#title#}{#hiddentext#}'));
}
/**
* test config variables of disabled hidden sections
* shall display not variables from hidden section
*
* @run InSeparateProcess
* @preserveGlobalState disabled
*/
public function testConfigVariableHiddenDisable()
{
$this->smarty->setErrorReporting(error_reporting() & ~(E_NOTICE | E_USER_NOTICE));
$this->smarty->config_read_hidden = false;
$this->smarty->configLoad('test.conf', 'hidden');
$this->assertEquals("Welcome to Smarty!", $this->smarty->fetch('eval:{#title#}{#hiddentext#}'));
}
/**
* test getConfigVars
*
* @run InSeparateProcess
* @preserveGlobalState disabled
*/
public function testConfigGetSingleConfigVar()
{
$this->smarty->configLoad('test.conf');
$this->assertEquals("Welcome to Smarty!", $this->smarty->getConfigVars('title'));
}
/**
* test getConfigVars return all variables
*
* @run InSeparateProcess
* @preserveGlobalState disabled
*/
public function testConfigGetAllConfigVars()
{
$this->smarty->configLoad('test.conf');
$vars = $this->smarty->getConfigVars();
$this->assertTrue(is_array($vars));
$this->assertEquals("Welcome to Smarty!", $vars['title']);
$this->assertEquals("Global Section1", $vars['sec1']);
}
/**
* test clearConfig for single variable
*
* @run InSeparateProcess
* @preserveGlobalState disabled
*/
public function testConfigClearSingleConfigVar()
{
$this->smarty->configLoad('test.conf');
$this->smarty->clearConfig('title');
$this->assertEquals("", $this->smarty->getConfigVars('title'));
}
/**
* test clearConfig for all variables
*
* @run InSeparateProcess
* @preserveGlobalState disabled
*/
public function testConfigClearConfigAll()
{
$this->smarty->configLoad('test.conf');
$this->smarty->clearConfig();
$vars = $this->smarty->getConfigVars();
$this->assertTrue(is_array($vars));
$this->assertTrue(empty($vars));
}
/**
* test config vars on data object
*
* @run InSeparateProcess
* @preserveGlobalState disabled
*/
public function testConfigTextData()
{
$data = $this->smarty->createData();
$data->configLoad('test.conf');
$this->assertEquals("123bvc", $this->smarty->fetch('eval:{#text#}', $data));
}
/**
* test getConfigVars on data object
*
* @run InSeparateProcess
* @preserveGlobalState disabled
*/
public function testConfigGetSingleConfigVarData()
{
$data = $this->smarty->createData();
$data->configLoad('test.conf');
$this->assertEquals("Welcome to Smarty!", $data->getConfigVars('title'));
}
/**
* test getConfigVars return all variables on data object
*
* @run InSeparateProcess
* @preserveGlobalState disabled
*/
public function testConfigGetAllConfigVarsData()
{
$data = $this->smarty->createData();
$data->configLoad('test.conf');
$vars = $data->getConfigVars();
$this->assertTrue(is_array($vars));
$this->assertEquals("Welcome to Smarty!", $vars['title']);
$this->assertEquals("Global Section1", $vars['sec1']);
}
/**
* test clearConfig for single variable on data object
*
* @run InSeparateProcess
* @preserveGlobalState disabled
*/
public function testConfigClearSingleConfigVarData()
{
$data = $this->smarty->createData();
$data->configLoad('test.conf');
$data->clearConfig('title');
$this->assertEquals("", $data->getConfigVars('title'));
$this->assertEquals("Global Section1", $data->getConfigVars('sec1'));
}
/**
* test clearConfig for all variables on data object
*
* @run InSeparateProcess
* @preserveGlobalState disabled
*/
public function testConfigClearConfigAllData()
{
$data = $this->smarty->createData();
$data->configLoad('test.conf');
$data->clearConfig();
$vars = $data->getConfigVars();
$this->assertTrue(is_array($vars));
$this->assertTrue(empty($vars));
}
/**
* test config vars on template object
*
* @run InSeparateProcess
* @preserveGlobalState disabled
*/
public function testConfigTextTemplate()
{
$tpl = $this->smarty->createTemplate('eval:{#text#}');
$tpl->configLoad('test.conf');
$this->assertEquals("123bvc", $this->smarty->fetch($tpl));
}
/**
* test getConfigVars on template object
*
* @run InSeparateProcess
* @preserveGlobalState disabled
*/
public function testConfigGetSingleConfigVarTemplate()
{
$tpl = $this->smarty->createTemplate('eval:{#text#}');
$tpl->configLoad('test.conf');
$this->assertEquals("Welcome to Smarty!", $tpl->getConfigVars('title'));
}
/**
* test getConfigVars return all variables on template object
*
* @run InSeparateProcess
* @preserveGlobalState disabled
*/
public function testConfigGetAllConfigVarsTemplate()
{
$tpl = $this->smarty->createTemplate('eval:{#text#}');
$tpl->configLoad('test.conf');
$vars = $tpl->getConfigVars();
$this->assertTrue(is_array($vars));
$this->assertEquals("Welcome to Smarty!", $vars['title']);
$this->assertEquals("Global Section1", $vars['sec1']);
}
/**
* test clearConfig for single variable on template object
*
* @run InSeparateProcess
* @preserveGlobalState disabled
*/
public function testConfigClearSingleConfigVarTemplate()
{
$tpl = $this->smarty->createTemplate('eval:{#text#}');
$tpl->configLoad('test.conf');
$tpl->clearConfig('title');
$this->assertEquals("", $tpl->getConfigVars('title'));
$this->assertEquals("Global Section1", $tpl->getConfigVars('sec1'));
}
/**
* test clearConfig for all variables on template object
*
* @run InSeparateProcess
* @preserveGlobalState disabled
*/
public function testConfigClearConfigAllTemplate()
{
$tpl = $this->smarty->createTemplate('eval:{#text#}');
$tpl->configLoad('test.conf');
$tpl->clearConfig();
$vars = $tpl->getConfigVars();
$this->assertTrue(is_array($vars));
$this->assertTrue(empty($vars));
}
/**
* test config variables loading from absolute file path
*
* @run InSeparateProcess
* @preserveGlobalState disabled
*/
public function testConfigAbsolutePath()
{
$file = realpath($this->smarty->getConfigDir(0) . 'test.conf');
$this->smarty->configLoad($file);
$this->assertEquals("123.4", $this->smarty->fetch('eval:{#Number#}'));
}
public function testConfigResourceDb4()
{
$this->smarty->addPluginsDir(dirname(__FILE__) . "/PHPunitplugins/");
$this->smarty->configLoad('db4:foo.conf');
$this->assertEquals("bar", $this->smarty->fetch('eval:{#foo#}'));
}
}

View File

@@ -0,0 +1,143 @@
<?php
/**
* Smarty PHPUnit tests default config handler
*
* @package PHPunit
* @author Uwe Tews
*/
/**
* class for default config handler test
*
* @backupStaticAttributes enabled
*/
class DefaultConfigHandlerTest extends PHPUnit_Smarty
{
/**
* Sets up the fixture
* This method is called before a test is executed.
*
*/
public function setUp()
{
$this->setUpSmarty(__DIR__);
$this->smarty->setForceCompile(true);
}
/**
* @expectedException SmartyException
* @expectedExceptionMessage Unable to read
* @expectedExceptionMessage file 'foo.conf'
*
* test unknown config file
*/
public function testUnknownConfigFile()
{
$this->smarty->configLoad('foo.conf');
}
/**
* @expectedException SmartyException
* @expectedExceptionMessage Default config handler
* @expectedExceptionMessage not callable
*
* test register unknown default config handler
*
*/
public function testRegisterUnknownDefaultConfigHandler()
{
$this->smarty->registerDefaultConfigHandler('foo');
}
/**
* test default config handler replacement (config data)
*
* @throws \Exception
* @throws \SmartyException
*/
public function testDefaultConfigHandlerReplacement()
{
$this->smarty->registerDefaultConfigHandler('configHandlerData');
$this->smarty->configLoad('foo.conf');
$this->assertEquals("bar", $this->smarty->fetch('eval:{#foo#}'));
}
/**
* test default config handler replacement (other config file)
*
* @throws \Exception
* @throws \SmartyException
*/
public function testDefaultConfigHandlerReplacementByConfigFile()
{
$this->smarty->registerDefaultConfigHandler('configHandlerFile');
$this->smarty->configLoad('foo.conf');
$this->assertEquals("123.4", $this->smarty->fetch('eval:{#Number#}'));
}
/**
* @expectedException SmartyException
* @expectedExceptionMessage Unable to read
* @expectedExceptionMessage file 'foo.conf'
*
* test default config handler replacement (return false)
*
*/
public function testDefaultConfigHandlerReplacementReturningFalse()
{
$this->smarty->configLoad('foo.conf');
}
}
/**
* config handler returning config data
*
* @param $resource_type
* @param $resource_name
* @param $config_source
* @param $config_timestamp
* @param \Smarty $smarty
*
* @return bool
*/
function configHandlerData($resource_type, $resource_name, &$config_source, &$config_timestamp, Smarty $smarty)
{
$output = "foo = 'bar'\n";
$config_source = $output;
$config_timestamp = time();
return true;
}
/**
* config handler returning config file
*
* @param $resource_type
* @param $resource_name
* @param $config_source
* @param $config_timestamp
* @param \Smarty $smarty
*
* @return string
*/
function configHandlerFile($resource_type, $resource_name, &$config_source, &$config_timestamp, Smarty $smarty)
{
return $smarty->getConfigDir(0) . 'test.conf';
}
/**
* config handler returning false
*
* @param $resource_type
* @param $resource_name
* @param $config_source
* @param $config_timestamp
* @param \Smarty $smarty
*
* @return bool
*/
function configHandlerFalse($resource_type, $resource_name, &$config_source, &$config_timestamp, Smarty $smarty)
{
return false;
}

View File

@@ -0,0 +1,27 @@
<?php
/*
* Smarty plugin
* -------------------------------------------------------------
* File: resource.db3.php
* Type: resource
* Name: db
* Purpose: Fetches templates from a database
* -------------------------------------------------------------
*/
class Smarty_Resource_Db4 extends Smarty_Resource
{
public function populate(Smarty_Template_Source $source, Smarty_Internal_Template $_template = null)
{
$source->filepath = 'db4:';
$source->uid = sha1($source->resource);
$source->timestamp = 0;
$source->exists = true;
}
public function getContent(Smarty_Template_Source $source)
{
return "foo = 'bar'\n";
}
}

View File

@@ -0,0 +1,49 @@
title = Welcome to Smarty!
overwrite = Overwrite1
overwrite = Overwrite2
booleanon = on
Intro = """This is a value that spans more
than one line. you must enclose
it in triple quotes."""
Number = 123.4
text = 123bvc
line = 123 This is a line
sec1 = Global Section1
sec2 = Global Section2
sec = Global char
[/]
sec = special char
[foo/bar]
sec = section foo/bar
[section1]
sec1 = Hello Section1
[section2]
sec2 = 'Hello Section2'
[.hidden]
hiddentext = Hidden Section
#Comment
# Comment with a space first line first
#Comment line starting with space
# Space before and after #
#The line below only contains a #
#
#
# title = This is not the correct title
#[section1]
#sec1 = Wrong text

View File

@@ -0,0 +1,119 @@
<?php
/**
* Smarty PHPunit tests for File resources
*
* @package PHPunit
* @author Uwe Tews
*/
/**
* class for file resource tests
*
* @backupStaticAttributes enabled
*/
class CustomResourceAmbiguousTest extends PHPUnit_Smarty
{
public $_resource = null;
public function setUp()
{
$this->setUpSmarty(__DIR__);
require_once dirname(__FILE__) . '/PHPunitplugins/resource.ambiguous.php';
// empty the template dir
$this->smarty->setTemplateDir(array());
// kill cache for unit test
// Smarty::$_resource_cache = array();
}
public function testInit()
{
$this->cleanDirs();
}
protected function relative($path)
{
$path = str_replace(dirname(__FILE__), '.', $path);
if (DS == "\\") {
$path = str_replace("\\", "/", $path);
}
return $path;
}
public function testNone()
{
$resource_handler = new Smarty_Resource_Ambiguous(dirname(__FILE__) . '/templates/ambiguous/');
$this->smarty->registerResource('ambiguous', $resource_handler);
$this->smarty->setDefaultResourceType('ambiguous');
$this->smarty->setAllowAmbiguousResources(true);
$tpl = $this->smarty->createTemplate('foobar.tpl');
$this->assertFalse($tpl->source->exists);
}
/**
*
* @run InSeparateProcess
* @preserveGlobalState disabled
*
*/
public function testCase1()
{
$resource_handler = new Smarty_Resource_Ambiguous(dirname(__FILE__) . '/templates/ambiguous/');
$this->smarty->registerResource('ambiguous', $resource_handler);
$this->smarty->setDefaultResourceType('ambiguous');
$this->smarty->setAllowAmbiguousResources(true);
$resource_handler->setSegment('case1');
$tpl = $this->smarty->createTemplate('foobar.tpl');
$this->assertTrue($tpl->source->exists);
$this->assertEquals('case1', $tpl->source->content);
}
/**
*
* @run InSeparateProcess
* @preserveGlobalState disabled
*
*/
public function testCase2()
{
$resource_handler = new Smarty_Resource_Ambiguous(dirname(__FILE__) . '/templates/ambiguous/');
$this->smarty->registerResource('ambiguous', $resource_handler);
$this->smarty->setDefaultResourceType('ambiguous');
$this->smarty->setAllowAmbiguousResources(true);
$resource_handler->setSegment('case2');
$tpl = $this->smarty->createTemplate('foobar.tpl');
$this->assertTrue($tpl->source->exists);
$this->assertEquals('case2', $tpl->source->content);
}
/**
*
* @run InSeparateProcess
* @preserveGlobalState disabled
*
*/
public function testCaseSwitching()
{
$resource_handler = new Smarty_Resource_Ambiguous(dirname(__FILE__) . '/templates/ambiguous/');
$this->smarty->registerResource('ambiguous', $resource_handler);
$this->smarty->setDefaultResourceType('ambiguous');
$this->smarty->setAllowAmbiguousResources(true);
$resource_handler->setSegment('case1');
$tpl = $this->smarty->createTemplate('foobar.tpl');
$this->assertTrue($tpl->source->exists);
$this->assertEquals('case1', $tpl->source->content);
$resource_handler->setSegment('case2');
$tpl = $this->smarty->createTemplate('foobar.tpl');
$this->assertTrue($tpl->source->exists);
$this->assertEquals('case2', $tpl->source->content);
}
}

View File

@@ -0,0 +1,58 @@
<?php
/**
* Ambiguous Filename Custom Resource Example
*
* @package Resource-examples
* @author Rodney Rehm
*/
class Smarty_Resource_Ambiguous extends Smarty_Internal_Resource_File
{
protected $directory;
protected $segment;
public function __construct($directory)
{
$this->directory = rtrim($directory, "/\\") . DS;
// parent::__construct();
}
public function setSegment($segment)
{
$this->segment = $segment;
}
/**
* modify resource_name according to resource handlers specifications
*
* @param Smarty $smarty Smarty instance
* @param string $resource_name resource_name to make unique
*
* @return string unique resource name
*/
public function buildUniqueResourceName(Smarty $smarty, $resource_name, $isConfig = false)
{
return get_class($this) . '#' . $this->segment . '#' . $resource_name;
}
/**
* populate Source Object with meta data from Resource
*
* @param Smarty_Template_Source $source source object
* @param Smarty_Internal_Template $_template template object
*/
public function populate(Smarty_Template_Source $source, Smarty_Internal_Template $_template = null)
{
$segment = '';
if ($this->segment) {
$segment = rtrim($this->segment, "/\\") . DS;
}
$source->filepath = $this->directory . $segment . $source->name;
$source->uid = sha1($source->filepath);
if ($_template->smarty->getCompileCheck() && !isset($source->timestamp)) {
$source->timestamp = @filemtime($source->filepath);
$source->exists = !!$source->timestamp;
}
}
}

View File

@@ -0,0 +1,54 @@
<?php
/**
* Smarty PHPUnit tests demo resource plugin extendaall
*
* @package PHPunit
* @author Uwe Tews
*/
/**
* class for demo resource plugin extendaall tests
*
* @backupStaticAttributes enabled
*/
class ResourceExtendsAllPluginTest extends PHPUnit_Smarty
{
public function setUp()
{
$this->setUpSmarty(__DIR__);
}
public function testInit()
{
$this->cleanDirs();
}
public function testResourcePluginExtendsall()
{
$this->smarty->addPluginsDir(SMARTY_DIR . "../demo/plugins/");
$this->smarty->setTemplateDir(array(
'root' => './templates',
'./templates_2',
'./templates_3',
'./templates_4',
));
$expected = "templates\n\n templates_3\n templates\n\ntemplates_4";
$this->assertEquals($expected, $this->smarty->fetch('extendsall:extendsall.tpl'));
}
public function testResourcePluginExtendsallOne()
{
$this->smarty->addPluginsDir(SMARTY_DIR . "../demo/plugins/");
$this->smarty->setTemplateDir(array(
'root' => './templates',
'./templates_2',
'./templates_3',
'./templates_4',
));
$expected = "templates\ntemplates";
$this->assertEquals($expected, $this->smarty->fetch('extendsall:extendsall2.tpl'));
}
}

View File

@@ -0,0 +1,2 @@
{block name="alpha"}templates{/block}
{block name="bravo_2"}templates{/block}

View File

@@ -0,0 +1,2 @@
{block name="alpha"}templates{/block}
{block name="bravo_2"}templates{/block}

View File

@@ -0,0 +1 @@
php hello world

View File

@@ -0,0 +1,5 @@
{block name="alpha"}templates_3{/block}
{block name="bravo"}
{block name="bravo_1"}templates_3{/block}
{block name="bravo_2"}templates_3{/block}
{/block}

View File

@@ -0,0 +1,3 @@
{block name="alpha"}templates_4{/block}
{block name="bravo"}templates_4{/block}
{block name="charlie"}templates_4{/block}

View File

@@ -0,0 +1,18 @@
<?php
require_once SMARTY_DIR . '../demo/plugins/resource.mysqls.php';
class Smarty_Resource_Mysqlstest extends Smarty_Resource_Mysqls
{
public function __construct()
{
try {
$this->db = PHPUnit_Smarty::$pdo;
}
catch
(PDOException $e) {
throw new SmartyException('Mysql Resource failed: ' . $e->getMessage());
}
$this->fetch = $this->db->prepare('SELECT modified, source FROM templates WHERE name = :name');
}
}

View File

@@ -0,0 +1,19 @@
<?php
require_once SMARTY_DIR . '../demo/plugins/resource.mysql.php';
class Smarty_Resource_Mysqltest extends Smarty_Resource_Mysql
{
public function __construct()
{
try {
$this->db = PHPUnit_Smarty::$pdo;
}
catch
(PDOException $e) {
throw new SmartyException('Mysql Resource failed: ' . $e->getMessage());
}
$this->fetch = $this->db->prepare('SELECT modified, source FROM templates WHERE name = :name');
$this->mtime = $this->db->prepare('SELECT modified FROM templates WHERE name = :name');
}
}

View File

@@ -0,0 +1,93 @@
<?php
/**
* Smarty PHPunit tests resource plugins
*
* @package PHPunit
* @author Uwe Tews
*/
/**
* class for resource plugins tests
*
* @backupStaticAttributes enabled
*/
class ResourceMysqlPluginTest extends PHPUnit_Smarty
{
public function setUp()
{
if (self::$config['resource']['MysqlEnable'] != 'true') {
$this->markTestSkipped('mysql tests are disabled');
}
if (self::$init) {
$this->getConnection();
}
$this->setUpSmarty(__DIR__);
}
public function testInit()
{
$this->cleanDirs();
$this->initMysqlResource();
PHPUnit_Smarty::$pdo->exec("REPLACE INTO templates VALUES ('test.tpl', '2010-12-25 22:00:00', '{\$x = \'hello world\'}{\$x}' )");
}
/**
* test resource plugin rendering of a custom resource
*/
public function testResourcePluginMysql()
{
//$this->smarty->addPluginsDir(SMARTY_DIR . "../demo/plugins/");
$this->smarty->addPluginsDir("./PHPunitplugins/");
$this->assertEquals('hello world', $this->smarty->fetch('mysqltest:test.tpl'));
}
/**
* test resource plugin timestamp of a custom resource
*/
public function testResourcePluginMysqlTimestamp()
{
// $this->smarty->addPluginsDir(SMARTY_DIR . "../demo/plugins/");
$this->smarty->addPluginsDir("./PHPunitplugins/");
$tpl = $this->smarty->createTemplate('mysqltest:test.tpl');
$this->assertEquals(strtotime("2010-12-25 22:00:00"), $tpl->source->timestamp);
}
/**
* test resource plugin compiledFilepath of a custom resource
*/
public function testResourcePluginMysqlCompiledFilepath()
{
// $this->smarty->addPluginsDir(SMARTY_DIR . "../demo/plugins/");
$this->smarty->addPluginsDir("./PHPunitplugins/");
$tpl = $this->smarty->createTemplate('mysqltest:test.tpl');
$this->assertEquals($this->buildCompiledPath($tpl, false, false, null, 'test.tpl', 'mysqltest', $this->smarty->getTemplateDir(0))
, $tpl->compiled->filepath
);
}
public function testResourcePluginMysqlCompiledFilepathCache()
{
//$this->smarty->addPluginsDir(SMARTY_DIR . "../demo/plugins/");
$this->smarty->addPluginsDir("./PHPunitplugins/");
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$this->smarty->setForceCompile(true);
$this->smarty->fetch('mysqltest:test.tpl');
$tpl = $this->smarty->createTemplate('mysqltest:test.tpl');
$this->assertEquals($this->buildCompiledPath($tpl, false, true, null, 'test.tpl', 'mysqltest', $this->smarty->getTemplateDir(0))
, $tpl->compiled->filepath
);
$this->smarty->caching = false;
}
/**
* test resource plugin timestamp of a custom resource with only fetch() implemented
*/
public function testResourcePluginMysqlTimestampWithoutFetchTimestamp()
{
// $this->smarty->addPluginsDir(SMARTY_DIR . "../demo/plugins/");
$this->smarty->addPluginsDir("./PHPunitplugins/");
$tpl = $this->smarty->createTemplate('mysqlstest:test.tpl');
$this->assertEquals(strtotime("2010-12-25 22:00:00"), $tpl->source->timestamp);
}
}

View File

@@ -0,0 +1,2 @@
{block name="alpha"}templates{/block}
{block name="bravo_2"}templates{/block}

View File

@@ -0,0 +1,2 @@
{block name="alpha"}templates{/block}
{block name="bravo_2"}templates{/block}

View File

@@ -0,0 +1,111 @@
<?php
/**
* Smarty PHPunit tests deault template handler
*
* @package PHPunit
* @author Uwe Tews
*/
/**
* class for block plugin tests
*
* @backupStaticAttributes enabled
*/
class DefaultTemplateHandlerTest extends PHPUnit_Smarty
{
public function setUp()
{
$this->setUpSmarty(__DIR__);
$this->smarty->setForceCompile(true);
$this->smarty->disableSecurity();
}
public function testInit()
{
$this->cleanDirs();
}
/**
* test error on unknow template
*/
public function testUnknownTemplate()
{
try {
$this->smarty->fetch('foo.tpl');
}
catch (Exception $e) {
$this->assertContains('Unable to load template', $e->getMessage());
return;
}
$this->fail('Exception for none existing template has not been raised.');
}
/**
* test error on registration on none existent handler function.
*/
public function testRegisterNoneExistentHandlerFunction()
{
try {
$this->smarty->registerDefaultTemplateHandler('foo');
}
catch (Exception $e) {
$this->assertContains("Default template handler", $e->getMessage());
$this->assertContains("not callable", $e->getMessage());
return;
}
$this->fail('Exception for none callable function has not been raised.');
}
/**
* test replacement by default template handler
*/
/**
* public function testDefaultTemplateHandlerReplacement()
* {
* $this->smarty->register->defaultTemplateHandler('my_template_handler');
* $this->assertEquals("Recsource foo.tpl of type file not found", $this->smarty->fetch('foo.tpl'));
* }
*/
public function testDefaultTemplateHandlerReplacementByTemplateFile()
{
$this->smarty->registerDefaultTemplateHandler('my_template_handler_file');
$this->assertEquals("hello world", $this->smarty->fetch('foo.tpl'));
}
/**
* test default template handler returning fals
*/
public function testDefaultTemplateHandlerReturningFalse()
{
$this->smarty->registerDefaultTemplateHandler('my_false');
try {
$this->smarty->fetch('foo.tpl');
}
catch (Exception $e) {
$this->assertContains('Unable to load template', $e->getMessage());
return;
}
$this->fail('Exception for none existing template has not been raised.');
}
}
function my_template_handler($resource_type, $resource_name, &$template_source, &$template_timestamp, Smarty $smarty)
{
$output = "Recsource $resource_name of type $resource_type not found";
$template_source = $output;
$template_timestamp = time();
return true;
}
function my_template_handler_file($resource_type, $resource_name, &$template_source, &$template_timestamp, Smarty $smarty)
{
return $smarty->getTemplateDir(0) . 'helloworld.tpl';
}
function my_false($resource_type, $resource_name, &$template_source, &$template_timestamp, Smarty $smarty)
{
return false;
}

View File

@@ -0,0 +1 @@
hello world

View File

@@ -0,0 +1,177 @@
<?php
/**
* Smarty PHPunit tests for eval resources
*
* @package PHPunit
* @author Uwe Tews
*/
/**
* class for eval resource tests
*
* @backupStaticAttributes enabled
*/
class EvalResourceTest extends PHPUnit_Smarty
{
public function setUp()
{
$this->setUpSmarty(__DIR__);
}
public function testInit()
{
$this->cleanDirs();
}
/**
* test template eval exits
*/
public function testTemplateEvalExists1()
{
$tpl = $this->smarty->createTemplate('eval:{$foo}');
$this->assertTrue($tpl->source->exists);
}
public function testTemplateEvalExists2()
{
$this->assertTrue($this->smarty->templateExists('eval:{$foo}'));
}
/**
* test getTemplateFilepath
*/
public function testGetTemplateFilepath()
{
$tpl = $this->smarty->createTemplate('eval:hello world');
$this->assertEquals('2aae6c35c94fcfb415dbe95f408b9ce91ee846ed', $tpl->source->filepath);
}
/**
* test getTemplateTimestamp
*/
public function testGetTemplateTimestamp()
{
$tpl = $this->smarty->createTemplate('eval:hello world');
$this->assertFalse($tpl->source->timestamp);
}
/**
* test getTemplateSource
*/
public function testGetTemplateSource()
{
$tpl = $this->smarty->createTemplate('eval:hello world{$foo}');
$this->assertEquals('hello world{$foo}', $tpl->source->content);
}
/**
* test empty templates
*/
public function testEmptyTemplate()
{
$tpl = $this->smarty->createTemplate('eval:');
$this->assertEquals('', $this->smarty->fetch($tpl));
}
/**
* test usesCompiler
*/
public function testUsesCompiler()
{
$tpl = $this->smarty->createTemplate('eval:hello world');
$this->assertFalse($tpl->source->uncompiled);
}
/**
* test isEvaluated
*/
public function testIsEvaluated()
{
$tpl = $this->smarty->createTemplate('eval:hello world');
$this->assertTrue($tpl->source->recompiled);
}
/**
* test mustCompile
*/
public function testMustCompile()
{
$tpl = $this->smarty->createTemplate('eval:hello world');
$this->assertTrue($tpl->mustCompile());
}
/**
* test getCompiledFilepath
*/
public function testGetCompiledFilepath()
{
$tpl = $this->smarty->createTemplate('eval:hello world');
$this->assertFalse($tpl->compiled->filepath);
}
/**
* test getCompiledTimestamp
*/
public function testGetCompiledTimestamp()
{
$tpl = $this->smarty->createTemplate('eval:hello world');
$this->assertFalse($tpl->compiled->timestamp);
}
/**
* test isCached
*/
public function testIsCached()
{
$tpl = $this->smarty->createTemplate('eval:hello world');
$this->assertFalse($tpl->isCached());
}
/**
* test getRenderedTemplate
*/
public function testGetRenderedTemplate()
{
$tpl = $this->smarty->createTemplate('eval:hello world');
$this->assertEquals('hello world', $tpl->fetch());
}
/**
* test that no complied template and cache file was produced
*/
public function testNoFiles()
{
$this->cleanDir($this->smarty->getCacheDir());
$this->cleanDir($this->smarty->getCompileDir());
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 20;
$tpl = $this->smarty->createTemplate('eval:hello world');
$this->assertEquals('hello world', $this->smarty->fetch($tpl));
$this->assertEquals(0, $this->smarty->clearAllCache());
$this->assertEquals(0, $this->smarty->clearCompiledTemplate());
}
/**
* test $smarty->is_cached
*/
public function testSmartyIsCached()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 20;
$tpl = $this->smarty->createTemplate('eval:hello world');
$this->assertEquals('hello world', $this->smarty->fetch($tpl));
$this->assertFalse($this->smarty->isCached($tpl));
}
public function testUrlencodeTemplate()
{
$tpl = $this->smarty->createTemplate('eval:urlencode:%7B%22foobar%22%7Cescape%7D');
$this->assertEquals('foobar', $tpl->fetch());
}
public function testBase64Template()
{
$tpl = $this->smarty->createTemplate('eval:base64:eyJmb29iYXIifGVzY2FwZX0=');
$this->assertEquals('foobar', $tpl->fetch());
}
}

View File

@@ -0,0 +1,45 @@
<?php
/**
* Smarty PHPunit tests for Extendsresource
*
* @package PHPunit
* @author Uwe Tews
*/
/**
* class for extends resource tests
*
* @backupStaticAttributes enabled
*/
class ExtendsResourceTest extends PHPUnit_Smarty
{
public function setUp()
{
$this->setUpSmarty(__DIR__);
}
public function testInit()
{
$this->cleanDirs();
}
/**
* test child/parent template chain with prepend
*/
public function testCompileBlockChildPrepend_003()
{
$result = $this->smarty->fetch('extends:003_parent.tpl|003_child_prepend.tpl');
$this->assertContains("prepend - Default Title", $result);
}
/**
* test child/parent template chain with apppend
*/
public function testCompileBlockChildAppend_004()
{
$this->smarty->merge_compiled_includes = true;
$result = $this->smarty->fetch('extends:004_parent.tpl|004_child_append.tpl');
$this->assertContains("Default Title - append", $result);
}
}

View File

@@ -0,0 +1 @@
{block name='title' prepend}prepend - {/block}

View File

@@ -0,0 +1 @@
{block name='title'}Default Title{/block}

View File

@@ -0,0 +1 @@
{block name='title' append} - append{/block}

View File

@@ -0,0 +1 @@
{block name='title'}Default Title{/block}

View File

@@ -0,0 +1 @@
{$foo = 'bar'}

View File

@@ -0,0 +1 @@
{block name='test'}-{$foo}-{/block}

View File

@@ -0,0 +1,277 @@
<?php
/**
* Smarty PHPunit tests for File resources
*
* @package PHPunit
* @author Uwe Tews
*/
/**
* class for file resource tests
*
* @backupStaticAttributes enabled
*/
class FileResourceTest extends PHPUnit_Smarty
{
public function setUp()
{
$this->setUpSmarty(__DIR__);
}
public function testInit()
{
$this->cleanDirs();
}
protected function relative($path)
{
$path = str_replace(str_replace("\\", "/", dirname(__FILE__)), '.', str_replace("\\", "/", $path));
return $path;
}
/**
*
*/
public function testGetTemplateFilepath()
{
$tpl = $this->smarty->createTemplate('helloworld.tpl');
$this->assertEquals("./templates/helloworld.tpl", str_replace('\\', '/', $tpl->source->filepath));
}
public function testTemplateFileExists1()
{
$tpl = $this->smarty->createTemplate('helloworld.tpl');
$this->assertTrue($tpl->source->exists);
}
public function testTemplateFileExists2()
{
$this->assertTrue($this->smarty->templateExists('helloworld.tpl'));
}
public function testTemplateFileNotExists1()
{
$tpl = $this->smarty->createTemplate('notthere.tpl');
$this->assertFalse($tpl->source->exists);
}
public function testTemplateFileNotExists2()
{
$this->assertFalse($this->smarty->templateExists('notthere.tpl'));
}
public function testTemplateFileNotExists3()
{
try {
$result = $this->smarty->fetch('notthere.tpl');
}
catch (Exception $e) {
$this->assertContains('Unable to load template file \'notthere.tpl\'', $e->getMessage());
return;
}
$this->fail('Exception for not existing template is missing');
}
public function testGetTemplateTimestamp()
{
$tpl = $this->smarty->createTemplate('helloworld.tpl');
$this->assertTrue(is_integer($tpl->source->timestamp));
$this->assertEquals(10, strlen($tpl->source->timestamp));
}
public function testGetTemplateSource()
{
$tpl = $this->smarty->createTemplate('helloworld.tpl');
$this->assertEquals('hello world', $tpl->source->content);
}
public function testUsesCompiler()
{
$tpl = $this->smarty->createTemplate('helloworld.tpl');
$this->assertFalse($tpl->source->uncompiled);
}
public function testIsEvaluated()
{
$tpl = $this->smarty->createTemplate('helloworld.tpl');
$this->assertFalse($tpl->source->recompiled);
}
public function testGetCompiledFilepath()
{
$tpl = $this->smarty->createTemplate('helloworld.tpl');
$this->assertEquals($this->buildCompiledPath($tpl, false, false, null, 'helloworld.tpl', 'file', $this->smarty->getTemplateDir(0))
, $tpl->compiled->filepath
);
}
public function testGetCompiledTimestampPrepare()
{
$tpl = $this->smarty->createTemplate('helloworld.tpl');
// create dummy compiled file
file_put_contents($tpl->compiled->filepath, '<?php ?>');
touch($tpl->compiled->filepath, $tpl->source->timestamp);
}
/**
*
*/
public function testGetCompiledTimestamp()
{
$tpl = $this->smarty->createTemplate('helloworld.tpl');
$this->assertTrue(is_integer($tpl->compiled->timestamp));
$this->assertEquals(10, strlen($tpl->compiled->timestamp));
$this->assertEquals($tpl->compiled->timestamp, $tpl->source->timestamp);
}
public function testMustCompileExisting()
{
$tpl = $this->smarty->createTemplate('helloworld.tpl');
$this->assertFalse($tpl->mustCompile());
}
public function testMustCompileAtForceCompile()
{
$this->smarty->setForceCompile(true);
$tpl = $this->smarty->createTemplate('helloworld.tpl');
$this->assertTrue($tpl->mustCompile());
}
public function testMustCompileTouchedSourcePrepare()
{
// touch to prepare next test
sleep(2);
$tpl = $this->smarty->createTemplate('helloworld.tpl');
touch($tpl->source->filepath);
}
public function testMustCompileTouchedSource()
{
$tpl = $this->smarty->createTemplate('helloworld.tpl');
$this->assertTrue($tpl->mustCompile());
// clean up for next tests
$this->cleanDir($this->smarty->getCompileDir());
}
public function testCompileTemplateFile()
{
$tpl = $this->smarty->createTemplate('helloworld.tpl');
$tpl->compileTemplateSource();
$this->assertTrue(file_exists($tpl->compiled->filepath));
}
public function testGetCachedFilepath()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$tpl = $this->smarty->createTemplate('helloworld.tpl');
$this->assertEquals($this->buildCachedPath($tpl, false, null, null, 'helloworld.tpl', 'file', $this->smarty->getTemplateDir(0), 'file')
, $tpl->cached->filepath
);
}
public function testGetCachedTimestamp()
{
// create dummy cache file for the following test
file_put_contents($this->buildCachedPath($this->smarty, false, null, null, 'helloworld.tpl', 'file', $this->smarty->getTemplateDir(0), 'file')
, '<?php ?>');
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$tpl = $this->smarty->createTemplate('helloworld.tpl');
$this->assertTrue(is_integer($tpl->cached->timestamp));
$this->assertEquals(10, strlen($tpl->cached->timestamp));
}
public function testGetRenderedTemplate()
{
$tpl = $this->smarty->createTemplate('helloworld.tpl');
$this->assertEquals('hello world', $tpl->fetch());
}
public function testRelativeInclude()
{
$result = $this->smarty->fetch('relative.tpl');
$this->assertContains('hello world', $result);
}
/**
*
* @run InSeparateProcess
* @preserveGlobalState disabled
*
*/
public function testRelativeIncludeSub()
{
$result = $this->smarty->fetch('sub/relative.tpl');
$this->assertContains('hello world', $result);
}
public function testRelativeIncludeFail()
{
try {
$this->smarty->fetch('relative_sub.tpl');
}
catch (Exception $e) {
$this->assertContains(htmlentities("Unable to load template"), $e->getMessage());
return;
}
$this->fail('Exception for unknown relative filepath has not been raised.');
}
public function testRelativeIncludeFailOtherDir()
{
$this->smarty->addTemplateDir('./templates_2');
try {
$this->smarty->fetch('relative_notexist.tpl');
}
catch (Exception $e) {
$this->assertContains("Unable to load template", $e->getMessage());
return;
}
$this->fail('Exception for unknown relative filepath has not been raised.');
}
protected function _relativeMap($map, $cwd = null)
{
foreach ($map as $file => $result) {
$this->cleanDir($this->smarty->getCompileDir());
$this->cleanDir($this->smarty->getCacheDir());
if ($result === null) {
try {
$this->smarty->fetch($file);
if ($cwd !== null) {
chdir($cwd);
}
$this->fail('Exception expected for ' . $file);
return;
}
catch (SmartyException $e) {
// this was expected to fail
}
} else {
try {
$_res = $this->smarty->fetch($file);
$this->assertEquals(str_replace("\r", '', $result), $_res, $file);
}
catch (Exception $e) {
if ($cwd !== null) {
chdir($cwd);
}
throw $e;
}
}
}
if ($cwd !== null) {
chdir($cwd);
}
}
}

View File

@@ -0,0 +1,91 @@
<?php
/**
* Smarty PHPunit tests for File resources
*
* @package PHPunit
* @author Rodney Rehm
* @backupStaticAttributes enabled
*/
class IndexedFileResourceTest extends PHPUnit_Smarty
{
public function setUp()
{
$this->setUpSmarty(__DIR__);
$path = str_replace(array("\\", "/"), DS, dirname(__FILE__));
$this->smarty->addTemplateDir($path . DS. 'templates_2');
// note that 10 is a string!
$this->smarty->addTemplateDir($path . DS. 'templates_3', '10');
$this->smarty->addTemplateDir($path . DS . 'templates_4', 'foo');
}
protected function relative($path)
{
$path = str_replace(str_replace("\\", "/", dirname(__FILE__)), '.', str_replace("\\", "/", $path));
return $path;
}
public function testGetTemplateFilepath()
{
$tpl = $this->smarty->createTemplate('dirname.tpl');
$this->assertEquals("./templates/dirname.tpl", $this->relative($tpl->source->filepath));
}
public function testGetTemplateFilepathNumber()
{
$tpl = $this->smarty->createTemplate('[1]dirname.tpl');
$this->assertEquals('./templates_2/dirname.tpl', $this->relative($tpl->source->filepath));
}
public function testGetTemplateFilepathNumeric()
{
$tpl = $this->smarty->createTemplate('[10]dirname.tpl');
$this->assertEquals('./templates_3/dirname.tpl', $this->relative($tpl->source->filepath));
}
public function testGetTemplateFilepathName()
{
$tpl = $this->smarty->createTemplate('[foo]dirname.tpl');
$this->assertEquals('./templates_4/dirname.tpl', $this->relative($tpl->source->filepath));
}
public function testFetch()
{
$tpl = $this->smarty->createTemplate('dirname.tpl');
$this->assertEquals('templates', $this->smarty->fetch($tpl));
}
public function testFetchNumber()
{
$tpl = $this->smarty->createTemplate('[1]dirname.tpl');
$this->assertEquals('templates_2', $this->smarty->fetch($tpl));
}
public function testFetchNumeric()
{
$tpl = $this->smarty->createTemplate('[10]dirname.tpl');
$this->assertEquals('templates_3', $this->smarty->fetch($tpl));
}
public function testFetchName()
{
$tpl = $this->smarty->createTemplate('[foo]dirname.tpl');
$this->assertEquals('templates_4', $this->smarty->fetch($tpl));
}
public function testGetCompiledFilepath()
{
$tpl = $this->smarty->createTemplate('[foo]dirname.tpl');
$this->assertEquals($this->buildCompiledPath($tpl, false, false, null, 'dirname.tpl', 'file', $this->smarty->getTemplateDir('foo')), $tpl->compiled->filepath);
}
public function testGetCachedFilepath()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$tpl = $this->smarty->createTemplate('[foo]dirname.tpl');
$this->assertEquals($this->buildCachedPath($tpl, false, null, null, 'dirname.tpl', 'file', $this->smarty->getTemplateDir('foo'))
, $tpl->cached->filepath);
}
}

View File

@@ -0,0 +1 @@
templates

View File

@@ -0,0 +1 @@
hello world

View File

@@ -0,0 +1 @@
{include file="./helloworld.tpl"}

View File

@@ -0,0 +1 @@
{include file="./hello.tpl"}

View File

@@ -0,0 +1 @@
{include file="../helloworld.tpl"}

View File

@@ -0,0 +1 @@
relativity

View File

@@ -0,0 +1 @@
relativity

View File

@@ -0,0 +1 @@
theory

View File

@@ -0,0 +1 @@
{include file="../helloworld.tpl"}

View File

@@ -0,0 +1 @@
templates_2

View File

@@ -0,0 +1 @@
templates_2

View File

@@ -0,0 +1 @@
hello world

View File

@@ -0,0 +1 @@
php hello world

View File

@@ -0,0 +1 @@
templates_3

View File

@@ -0,0 +1,5 @@
{block name="alpha"}templates_3{/block}
{block name="bravo"}
{block name="bravo_1"}templates_3{/block}
{block name="bravo_2"}templates_3{/block}
{/block}

View File

@@ -0,0 +1 @@
templates_4

View File

@@ -0,0 +1,3 @@
{block name="alpha"}templates_4{/block}
{block name="bravo"}templates_4{/block}
{block name="charlie"}templates_4{/block}

View File

@@ -0,0 +1,285 @@
<?php
/**
* Smarty PHPunit tests for PHP resources
*
* @package PHPunit
* @author Uwe Tews
*/
/**
* class for PHP resource tests
*
* @backupStaticAttributes enabled
*/
class PhpResourceTest extends PHPUnit_Smarty
{
public function setUp()
{
$this->setUpSmarty(__DIR__);
}
public function testInit()
{
$this->cleanDirs();
}
protected function relative($path)
{
$path = str_replace(str_replace("\\", "/", dirname(__FILE__)), '.', str_replace("\\", "/", $path));
return $path;
}
/**
* test getTemplateFilepath
*/
public function testGetTemplateFilepath()
{
$tpl = $this->smarty->createTemplate('php:phphelloworld.php');
$this->assertEquals("./templates/phphelloworld.php", str_replace('\\', '/', $tpl->source->filepath));
}
/**
* test getTemplateTimestamp
*/
public function testGetTemplateTimestamp()
{
$tpl = $this->smarty->createTemplate('php:phphelloworld.php');
$this->assertTrue(is_integer($tpl->source->timestamp));
$this->assertEquals(10, strlen($tpl->source->timestamp));
}
/**
* test getTemplateSource
*-/
* public function testGetTemplateSource()
* {
* $tpl = $this->smarty->createTemplate('php:phphelloworld.php');
* $this->assertContains('php hello world', $tpl->source->content);
* }
* /**
* test usesCompiler
*/
public function testUsesCompiler()
{
$tpl = $this->smarty->createTemplate('php:phphelloworld.php');
$this->assertTrue($tpl->source->uncompiled);
}
/**
* test isEvaluated
*/
public function testIsEvaluated()
{
$tpl = $this->smarty->createTemplate('php:phphelloworld.php');
$this->assertFalse($tpl->source->recompiled);
}
/**
* test getCompiledFilepath
*/
public function testGetCompiledFilepath()
{
$tpl = $this->smarty->createTemplate('php:phphelloworld.php');
$this->assertFalse($tpl->compiled->filepath);
}
/**
* test getCompiledTimestamp
*/
public function testGetCompiledTimestamp()
{
$tpl = $this->smarty->createTemplate('php:phphelloworld.php');
$this->assertFalse($tpl->compiled->timestamp);
}
/**
* test mustCompile
*/
public function testMustCompile()
{
$tpl = $this->smarty->createTemplate('php:phphelloworld.php');
$this->assertFalse($tpl->mustCompile());
}
/**
* test getCachedFilepath
*/
public function testGetCachedFilepath()
{
$this->smarty->setAllowPhpTemplates(true);
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$tpl = $this->smarty->createTemplate('php:phphelloworld.php');
$expected = $this->buildCachedPath($tpl, false, null, null, 'phphelloworld.php', 'php', $this->smarty->getTemplateDir(0), 'file');
$this->assertEquals($expected, $tpl->cached->filepath);
}
/**
* test create cache file used by the following tests
*/
public function testCreateCacheFile()
{
// create dummy cache file
$this->smarty->setAllowPhpTemplates(true);
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$tpl = $this->smarty->createTemplate('php:phphelloworld.php');
$this->assertContains('php hello world', $this->smarty->fetch($tpl));
}
/**
* test getCachedTimestamp caching enabled
*
* @run InSeparateProcess
* @preserveGlobalState disabled
*
*/
public function testGetCachedTimestamp()
{
$this->smarty->setAllowPhpTemplates(true);
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$tpl = $this->smarty->createTemplate('php:phphelloworld.php');
$this->assertTrue(is_integer($tpl->cached->timestamp));
$this->assertEquals(10, strlen($tpl->cached->timestamp));
}
/**
* test isCached
*
* @run InSeparateProcess
* @preserveGlobalState disabled
*
*/
public function testIsCached()
{
$this->smarty->setAllowPhpTemplates(true);
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 10000;
$tpl = $this->smarty->createTemplate('php:phphelloworld.php');
$this->assertTrue($tpl->isCached());
}
/**
* test isCached caching disabled
*/
public function testIsCachedCachingDisabled()
{
$this->smarty->setAllowPhpTemplates(true);
$tpl = $this->smarty->createTemplate('php:phphelloworld.php');
$this->assertFalse($tpl->isCached());
}
/**
* test isCached on touched source
*
* @run InSeparateProcess
* @preserveGlobalState disabled
*
*/
public function testIsCachedTouchedSourcePrepare()
{
$this->smarty->setAllowPhpTemplates(true);
$tpl = $this->smarty->createTemplate('php:phphelloworld.php');
sleep(2);
touch($tpl->source->filepath);
}
/**
*
* @run InSeparateProcess
* @preserveGlobalState disabled
*
*/
public function testIsCachedTouchedSource()
{
$this->smarty->setAllowPhpTemplates(true);
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$tpl = $this->smarty->createTemplate('php:phphelloworld.php');
$this->assertFalse($tpl->isCached());
}
/**
* test is cache file is written
*/
public function testWriteCachedContent()
{
$this->smarty->setAllowPhpTemplates(true);
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$this->cleanCacheDir();
$tpl = $this->smarty->createTemplate('php:phphelloworld.php');
$this->smarty->fetch($tpl);
$this->assertTrue(file_exists($tpl->cached->filepath));
}
/**
* test getRenderedTemplate
*/
public function testGetRenderedTemplate()
{
$this->smarty->setAllowPhpTemplates(true);
$tpl = $this->smarty->createTemplate('php:phphelloworld.php');
$this->assertContains('php hello world', $tpl->fetch());
}
/**
* test $smarty->is_cached
*/
public function testSmartyIsCachedPrepare()
{
// clean up for next tests
$this->cleanCacheDir();
$this->smarty->setAllowPhpTemplates(true);
// prepare files for next test
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$tpl = $this->smarty->createTemplate('php:phphelloworld.php');
$this->smarty->fetch($tpl);
}
/**
*
* @run InSeparateProcess
* @preserveGlobalState disabled
*
*/
public function testSmartyIsCached()
{
$this->smarty->setAllowPhpTemplates(true);
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$tpl = $this->smarty->createTemplate('php:phphelloworld.php');
$this->assertTrue($this->smarty->isCached($tpl));
}
/**
* test $smarty->is_cached caching disabled
*/
public function testSmartyIsCachedCachingDisabled()
{
$this->smarty->setAllowPhpTemplates(true);
$tpl = $this->smarty->createTemplate('php:phphelloworld.php');
$this->assertFalse($this->smarty->isCached($tpl));
}
public function testGetTemplateFilepathName()
{
$this->smarty->addTemplateDir('./templates_2', 'foo');
$tpl = $this->smarty->createTemplate('php:[foo]helloworld.php');
$this->assertEquals('./templates_2/helloworld.php', $this->relative($tpl->source->filepath));
}
public function testGetCachedFilepathName()
{
$this->smarty->addTemplateDir('./templates_2', 'foo');
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 1000;
$tpl = $this->smarty->createTemplate('php:[foo]helloworld.php');
$path = $tpl->cached->filepath;
$expected = $this->buildCachedPath($tpl, false, null, null, 'helloworld.php', 'php', $this->smarty->getTemplateDir('foo'), 'file');
$this->assertEquals($expected, $path);
}
}

View File

@@ -0,0 +1 @@
php hello world

View File

@@ -0,0 +1 @@
php hello world

View File

@@ -0,0 +1,128 @@
<?php
/**
* Smarty PHPunit tests register->resource
*
* @package PHPunit
* @author Uwe Tews
*/
/**
* class for register->resource tests
*
* @backupStaticAttributes enabled
*/
class RegisteredResourceTest extends PHPUnit_Smarty
{
public function setUp()
{
$this->setUpSmarty(__DIR__);
$this->smarty->registerResource("rr", array("rr_get_template",
"rr_get_timestamp",
"rr_get_secure",
"rr_get_trusted"));
}
public function testInit()
{
$this->cleanDirs();
}
/**
* test resource plugin rendering
*/
public function testResourcePlugin()
{
$this->assertEquals('hello world', $this->smarty->fetch('rr:test'));
}
public function testClearCompiledResourcePlugin()
{
$this->assertEquals(1, $this->smarty->clearCompiledTemplate('rr:test'));
}
/**
* test resource plugin timesatmp
*/
public function testResourcePluginTimestamp()
{
$tpl = $this->smarty->createTemplate('rr:test');
$this->assertTrue(is_integer($tpl->source->timestamp));
$this->assertEquals(10, strlen($tpl->source->timestamp));
}
/**
* test compile_id change
*/
public function testResourceCompileIdChange()
{
$this->smarty->registerResource('myresource', array('getSource', 'getTimestamp', 'getSecure', 'getTrusted'));
$this->smarty->compile_id = 'a';
$this->assertEquals('this is template 1', $this->smarty->fetch('myresource:some'));
$this->assertEquals('this is template 1', $this->smarty->fetch('myresource:some'));
$this->smarty->compile_id = 'b';
$this->assertEquals('this is template 2', $this->smarty->fetch('myresource:some'));
$this->assertEquals('this is template 2', $this->smarty->fetch('myresource:some'));
}
}
/**
* resource functions
*/
function rr_get_template($tpl_name, &$tpl_source, $smarty_obj)
{
// populating $tpl_source
$tpl_source = '{$x="hello world"}{$x}';
return true;
}
function rr_get_timestamp($tpl_name, &$tpl_timestamp, $smarty_obj)
{
// $tpl_timestamp.
$tpl_timestamp = (int) floor(time() / 100) * 100;
return true;
}
function rr_get_secure($tpl_name, $smarty_obj)
{
// assume all templates are secure
return true;
}
function rr_get_trusted($tpl_name, $smarty_obj)
{
// not used for templates
}
// resource functions for compile_id change test
function getSecure($name, $smarty)
{
return true;
}
function getTrusted($name, $smarty)
{
}
function getSource($name, &$source, $smarty)
{
// we update a counter, so that we return a new source for every call
static $counter = 0;
$counter ++;
// construct a new source
$source = "this is template $counter";
return true;
}
function getTimestamp($name, &$timestamp, $smarty)
{
// always pretend the template is brand new
$timestamp = time();
return true;
}

View File

@@ -0,0 +1,37 @@
<?php
/*
* Smarty plugin
* -------------------------------------------------------------
* File: resource.db.php
* Type: resource
* Name: db
* Purpose: Fetches templates from a database
* -------------------------------------------------------------
*/
function smarty_resource_db_source($tpl_name, &$tpl_source, $smarty)
{
// do database call here to fetch your template,
// populating $tpl_source
$tpl_source = '{$x="hello world"}{$x}';
return true;
}
function smarty_resource_db_timestamp($tpl_name, &$tpl_timestamp, $smarty)
{
// $tpl_timestamp.
$tpl_timestamp = (int) floor(time() / 100) * 100;
return true;
}
function smarty_resource_db_secure($tpl_name, $smarty)
{
// assume all templates are secure
return true;
}
function smarty_resource_db_trusted($tpl_name, $smarty)
{
// not used for templates
}

View File

@@ -0,0 +1,27 @@
<?php
/*
* Smarty plugin
* -------------------------------------------------------------
* File: resource.db2.php
* Type: resource
* Name: db
* Purpose: Fetches templates from a database
* -------------------------------------------------------------
*/
class Smarty_Resource_Db2 extends Smarty_Resource_Recompiled
{
public function populate(Smarty_Template_Source $source, Smarty_Internal_Template $_template = null)
{
$source->filepath = 'db2:';
$source->uid = sha1($source->resource);
$source->timestamp = 0;
$source->exists = true;
}
public function getContent(Smarty_Template_Source $source)
{
return '{$x="hello world"}{$x}';
}
}

View File

@@ -0,0 +1,32 @@
<?php
/*
* Smarty plugin
* -------------------------------------------------------------
* File: resource.db3.php
* Type: resource
* Name: db
* Purpose: Fetches templates from a database
* -------------------------------------------------------------
*/
class Smarty_Resource_Db3 extends Smarty_Resource
{
public function populate(Smarty_Template_Source $source, Smarty_Internal_Template $_template = null)
{
$source->filepath = 'db3:';
$source->uid = sha1($source->resource);
$source->timestamp = 0;
$source->exists = true;
}
public function getContent(Smarty_Template_Source $source)
{
return '{$x="hello world"}{$x}';
}
public function getCompiledFilepath(Smarty_Internal_Template $_template)
{
return false;
}
}

View File

@@ -0,0 +1,31 @@
<?php
/*
* Smarty plugin
* -------------------------------------------------------------
* File: resource.db3.php
* Type: resource
* Name: db
* Purpose: Fetches templates from a database
* -------------------------------------------------------------
*/
class Smarty_Resource_Db4 extends Smarty_Resource
{
public function populate(Smarty_Template_Source $source, Smarty_Internal_Template $_template = null)
{
$source->filepath = 'db4:';
$source->uid = sha1($source->resource);
$source->timestamp = 0;
$source->exists = true;
}
public function getContent(Smarty_Template_Source $source)
{
if ($source->is_config) {
return "foo = 'bar'\n";
}
return '{$x="hello world"}{$x}';
}
}

View File

@@ -0,0 +1,86 @@
<?php
/**
* Smarty PHPunit tests resource plugins
*
* @package PHPunit
* @author Uwe Tews
*/
/**
* class for resource plugins tests
*
* @backupStaticAttributes enabled
*/
class ResourcePluginTest extends PHPUnit_Smarty
{
public function setUp()
{
if (self::$config['cacheResource']['MysqlEnable'] != 'true') {
$this->markTestSkipped('mysql tests are disabled');
}
if (self::$init) {
$this->getConnection();
}
$this->setUpSmarty(__DIR__);
}
public function testInit()
{
$this->cleanDirs();
}
/**
* test resource plugin rendering
*/
public function testResourcePlugin()
{
$this->smarty->addPluginsDir("./PHPunitplugins/");
$this->assertEquals('hello world', $this->smarty->fetch('db:test'));
}
/**
* test resource plugin rendering
*/
public function testResourcePluginObject()
{
$this->smarty->addPluginsDir("./PHPunitplugins/");
$this->assertEquals('hello world', $this->smarty->fetch('db2:test'));
}
/**
* test resource plugin rendering of a registered object
*/
public function testResourcePluginRegisteredInstance()
{
$this->smarty->addPluginsDir("./PHPunitplugins/");
$this->smarty->loadPlugin('Smarty_Resource_Db2');
$this->smarty->registerResource('db2a', new Smarty_Resource_Db2('db2a'));
$this->assertEquals('hello world', $this->smarty->fetch('db2a:test'));
}
/**
* test resource plugin non-existent compiled cache of a recompiling resource
*/
public function testResourcePluginRecompiledCompiledFilepath()
{
$this->smarty->addPluginsDir("./PHPunitplugins/");
$tpl = $this->smarty->createTemplate('db2:test.tpl');
$expected = realpath('./templates_c/' . sha1('db2:test.tpl') . '.db2.test.tpl.php');
$this->assertFalse(!!$expected);
$this->assertFalse($tpl->compiled->filepath);
}
/**
* test resource plugin timestamp
*/
public function testResourcePluginTimestamp()
{
$this->smarty->addPluginsDir("./PHPunitplugins/");
$tpl = $this->smarty->createTemplate('db:test');
$this->assertTrue(is_integer($tpl->source->timestamp));
$this->assertEquals(10, strlen($tpl->source->timestamp));
}
}

View File

@@ -0,0 +1,2 @@
{block name="alpha"}templates{/block}
{block name="bravo_2"}templates{/block}

View File

@@ -0,0 +1,2 @@
{block name="alpha"}templates{/block}
{block name="bravo_2"}templates{/block}

View File

@@ -0,0 +1 @@
templates_2

View File

@@ -0,0 +1 @@
hello world

View File

@@ -0,0 +1 @@
php hello world

View File

@@ -0,0 +1 @@
templates_3

View File

@@ -0,0 +1,5 @@
{block name="alpha"}templates_3{/block}
{block name="bravo"}
{block name="bravo_1"}templates_3{/block}
{block name="bravo_2"}templates_3{/block}
{/block}

View File

@@ -0,0 +1 @@
templates_4

View File

@@ -0,0 +1,3 @@
{block name="alpha"}templates_4{/block}
{block name="bravo"}templates_4{/block}
{block name="charlie"}templates_4{/block}

View File

@@ -0,0 +1,277 @@
<?php
/**
* Smarty PHPunit tests for stream resources
*
* @package PHPunit
* @author Uwe Tews
*/
/**
* class for stream resource tests
*
* @backupStaticAttributes enabled
*/
class StreamResourceTest extends PHPUnit_Smarty
{
public function setUp()
{
$this->setUpSmarty(__DIR__);
$this->smarty->assign('foo', 'bar');
stream_wrapper_register("global", "ResourceStream")
or die("Failed to register protocol");
$fp = fopen("global://mytest", "r+");
fwrite($fp, 'hello world {$foo}');
fclose($fp);
}
public function testInit()
{
$this->cleanDirs();
}
public function tearDown()
{
parent::tearDown();
stream_wrapper_unregister("global");
}
/**
* test getTemplateFilepath
*/
public function testGetTemplateFilepath()
{
$tpl = $this->smarty->createTemplate('global:mytest');
$this->assertEquals('global://mytest', $tpl->source->filepath);
}
/**
* test getTemplateTimestamp
*/
public function testGetTemplateTimestamp()
{
$tpl = $this->smarty->createTemplate('global:mytest');
$this->assertFalse($tpl->source->timestamp);
}
/**
* test getTemplateSource
*/
public function testGetTemplateSource()
{
$tpl = $this->smarty->createTemplate('global:mytest', null, null, $this->smarty);
$this->assertEquals('hello world {$foo}', $tpl->source->content);
}
/**
* test usesCompiler
*/
public function testUsesCompiler()
{
$tpl = $this->smarty->createTemplate('global:mytest');
$this->assertFalse($tpl->source->uncompiled);
}
/**
* test isEvaluated
*/
public function testIsEvaluated()
{
$tpl = $this->smarty->createTemplate('global:mytest');
$this->assertTrue($tpl->source->recompiled);
}
/**
* test mustCompile
*/
public function testMustCompile()
{
$tpl = $this->smarty->createTemplate('global:mytest');
$this->assertTrue($tpl->mustCompile());
}
/**
* test getCompiledFilepath
*/
public function testGetCompiledFilepath()
{
$tpl = $this->smarty->createTemplate('global:mytest');
$this->assertFalse($tpl->compiled->filepath);
}
/**
* test getCompiledTimestamp
*/
public function testGetCompiledTimestamp()
{
$tpl = $this->smarty->createTemplate('global:mytest');
$this->assertFalse($tpl->compiled->timestamp);
}
/**
* test template file exits
*/
public function testTemplateStreamExists1()
{
$tpl = $this->smarty->createTemplate('global:mytest');
$this->assertTrue($tpl->source->exists);
}
public function testTemplateStreamExists2()
{
$this->assertTrue($this->smarty->templateExists('global:mytest'));
}
/**
* test template is not existing
*/
public function testTemplateStreamNotExists1()
{
$tpl = $this->smarty->createTemplate('global:notthere');
$this->assertFalse($tpl->source->exists);
}
public function testTemplateStramNotExists2()
{
$this->assertFalse($this->smarty->templateExists('global:notthere'));
}
public function testTemplateStramNotExists3()
{
try {
$result = $this->smarty->fetch('global:notthere');
}
catch (Exception $e) {
$this->assertContains('Unable to load template global \'notthere\'', $e->getMessage());
return;
}
$this->fail('Exception for not existing template is missing');
}
/**
* test writeCachedContent
*/
public function testWriteCachedContent()
{
$tpl = $this->smarty->createTemplate('global:mytest');
$this->assertFalse($tpl->writeCachedContent('dummy'));
}
/**
* test isCached
*/
public function testIsCached()
{
$tpl = $this->smarty->createTemplate('global:mytest');
$this->assertFalse($tpl->isCached());
}
/**
* test getRenderedTemplate
*/
public function testGetRenderedTemplate()
{
$tpl = $this->smarty->createTemplate('global:mytest', null, null, $this->smarty);
$this->assertEquals('hello world bar', $tpl->fetch());
}
/**
* test that no complied template and cache file was produced
*/
public function testNoFiles()
{
$this->cleanDir($this->smarty->getCacheDir());
$this->cleanDir($this->smarty->getCompileDir());
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 20;
$tpl = $this->smarty->createTemplate('global:mytest', null, null, $this->smarty);
$this->assertEquals('hello world bar', $this->smarty->fetch($tpl));
$this->assertEquals(0, $this->smarty->clearAllCache());
$this->assertEquals(0, $this->smarty->clearCompiledTemplate());
}
/**
* test $smarty->is_cached
*/
public function testSmartyIsCached()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 20;
$tpl = $this->smarty->createTemplate('global:mytest', null, null, $this->smarty);
$this->assertEquals('hello world bar', $this->smarty->fetch($tpl));
$this->assertFalse($this->smarty->isCached($tpl));
}
}
class ResourceStream
{
private $position;
private $varname;
public function stream_open($path, $mode, $options, &$opened_path)
{
$url = parse_url($path);
$this->varname = $url["host"];
$this->position = 0;
return true;
}
public function stream_read($count)
{
$p = &$this->position;
$ret = substr($GLOBALS[$this->varname], $p, $count);
$p += strlen($ret);
return $ret;
}
public function stream_write($data)
{
$v = &$GLOBALS[$this->varname];
$l = strlen($data);
$p = &$this->position;
$v = substr($v, 0, $p) . $data . substr($v, $p += $l);
return $l;
}
public function stream_tell()
{
return $this->position;
}
public function stream_eof()
{
if (!isset($GLOBALS[$this->varname])) {
return true;
}
return $this->position >= strlen($GLOBALS[$this->varname]);
}
public function stream_seek($offset, $whence)
{
$l = strlen($GLOBALS[$this->varname]);
$p = &$this->position;
switch ($whence) {
case SEEK_SET:
$newPos = $offset;
break;
case SEEK_CUR:
$newPos = $p + $offset;
break;
case SEEK_END:
$newPos = $l + $offset;
break;
default:
return false;
}
$ret = ($newPos >= 0 && $newPos <= $l);
if ($ret) {
$p = $newPos;
}
return $ret;
}
}

View File

@@ -0,0 +1,191 @@
<?php
/**
* Smarty PHPunit tests for string resources
*
* @package PHPunit
* @author Uwe Tews
*/
/**
* class for string resource tests
*
* @backupStaticAttributes enabled
*/
class StringResourceTest extends PHPUnit_Smarty
{
public function setUp()
{
$this->setUpSmarty(__DIR__);
}
public function testInit()
{
$this->cleanDirs();
}
protected function relative($path)
{
$path = str_replace(dirname(__FILE__), '.', $path);
if (DS == "\\") {
$path = str_replace("\\", "/", $path);
}
return $path;
}
/**
* test template string exits
*/
public function testTemplateStringExists1()
{
$tpl = $this->smarty->createTemplate('string:{$foo}');
$this->assertTrue($tpl->source->exists);
}
public function testTemplateStringExists2()
{
$this->assertTrue($this->smarty->templateExists('string:{$foo}'));
}
/**
* test getTemplateFilepath
*/
public function testGetTemplateFilepath()
{
$tpl = $this->smarty->createTemplate('string:hello world');
$this->assertEquals('2aae6c35c94fcfb415dbe95f408b9ce91ee846ed', $tpl->source->filepath);
}
/**
* test getTemplateTimestamp
*/
public function testGetTemplateTimestamp()
{
$tpl = $this->smarty->createTemplate('string:hello world');
$this->assertEquals(0, $tpl->source->timestamp);
}
/**
* test getTemplateSource
*/
public function testGetTemplateSource()
{
$tpl = $this->smarty->createTemplate('string:hello world{$foo}');
$this->assertEquals('hello world{$foo}', $tpl->source->content);
}
/**
* test usesCompiler
*/
public function testUsesCompiler()
{
$tpl = $this->smarty->createTemplate('string:hello world');
$this->assertFalse($tpl->source->uncompiled);
}
/**
* test isEvaluated
*/
public function testIsEvaluated()
{
$tpl = $this->smarty->createTemplate('string:hello world');
$this->assertFalse($tpl->source->recompiled);
}
/**
* test mustCompile
*/
public function testMustCompile()
{
$tpl = $this->smarty->createTemplate('string:hello world');
$this->assertTrue($tpl->mustCompile());
}
/**
* test getCompiledFilepath
*/
public function testGetCompiledFilepath()
{
$tpl = $this->smarty->createTemplate('string:hello world');
$this->assertEquals($this->buildCompiledPath($tpl, false, false, null, 'hello world', 'string', $this->smarty->getTemplateDir(0)), $tpl->compiled->filepath);
}
/**
* test getCompiledTimestamp
*/
public function testGetCompiledTimestamp()
{
$tpl = $this->smarty->createTemplate('string:hello world');
$this->assertFalse($tpl->compiled->timestamp);
}
/**
* test empty templates
*/
public function testEmptyTemplate()
{
$tpl = $this->smarty->createTemplate('string:');
$this->assertEquals('', $this->smarty->fetch($tpl));
}
/**
* test getCachedTimestamp
*/
public function testGetCachedTimestamp()
{
$tpl = $this->smarty->createTemplate('string:hello world');
$this->assertFalse($tpl->cached->timestamp);
}
/**
* test writeCachedContent
*/
public function testWriteCachedContent()
{
$tpl = $this->smarty->createTemplate('string:hello world');
$this->assertFalse($tpl->writeCachedContent('dummy'));
}
/**
* test isCached
*/
public function testIsCached()
{
$tpl = $this->smarty->createTemplate('string:hello world');
$this->assertFalse($tpl->isCached());
}
/**
* test getRenderedTemplate
*/
public function testGetRenderedTemplate()
{
$tpl = $this->smarty->createTemplate('string:hello world');
$this->assertEquals('hello world', $tpl->fetch());
}
/**
* test $smarty->is_cached
*/
public function testSmartyIsCached()
{
$this->smarty->caching = true;
$this->smarty->cache_lifetime = 20;
$tpl = $this->smarty->createTemplate('string:hello world');
$this->assertEquals('hello world', $this->smarty->fetch($tpl));
$this->assertTrue($this->smarty->isCached($tpl));
}
public function testUrlencodeTemplate()
{
$tpl = $this->smarty->createTemplate('string:urlencode:%7B%22foobar%22%7Cescape%7D');
$this->assertEquals('foobar', $tpl->fetch());
}
public function testBase64Template()
{
$tpl = $this->smarty->createTemplate('string:base64:eyJmb29iYXIifGVzY2FwZX0=');
$this->assertEquals('foobar', $tpl->fetch());
}
}

View File

@@ -0,0 +1,42 @@
<?php
/**
* Smarty PHPunit tests of function calls
*
* @package PHPunit
* @author Uwe Tews
*/
/**
* class for function tests
*
* @backupStaticAttributes enabled
*/
class FunctionTest extends PHPUnit_Smarty
{
public function setUp()
{
$this->setUpSmarty(__DIR__);
}
public function testInit()
{
$this->cleanDirs();
}
/**
* test unknown function error
*/
public function testUnknownFunction()
{
$this->smarty->enableSecurity();
try {
$this->smarty->fetch('eval:{unknown()}');
}
catch (Exception $e) {
$this->assertContains("PHP function 'unknown' not allowed by security setting", $e->getMessage());
return;
}
$this->fail('Exception for unknown function has not been raised.');
}
}

View File

@@ -0,0 +1,383 @@
<?php
/**
* Smarty PHPunit tests for security
*
* @package PHPunit
* @author Uwe Tews
*/
/**
* class for security test
*
* @backupStaticAttributes enabled
*/
class SecurityTest extends PHPUnit_Smarty
{
public $loadSmartyBC = true;
public function setUp()
{
$this->setUpSmarty(__DIR__);
$this->smarty->setForceCompile(true);
$this->smarty->enableSecurity();
$this->smartyBC->setForceCompile(true);
$this->smartyBC->enableSecurity();
$this->cleanDir($this->smarty->getCacheDir());
$this->cleanDir($this->smarty->getCompileDir());
}
/**
* test that security is loaded
*/
public function testSecurityLoaded()
{
$this->assertTrue(is_object($this->smarty->security_policy));
}
/**
* test trusted PHP function
*/
public function testTrustedPHPFunction()
{
$this->assertEquals("5", $this->smarty->fetch('eval:{assign var=foo value=[1,2,3,4,5]}{count($foo)}'));
}
/**
* test not trusted PHP function
*/
public function testNotTrustedPHPFunction()
{
$this->smarty->security_policy->php_functions = array('null');
try {
$this->smarty->fetch('eval:{assign var=foo value=[1,2,3,4,5]}{count($foo)}');
}
catch (Exception $e) {
$this->assertContains(htmlentities("PHP function 'count' not allowed by security setting"), $e->getMessage());
return;
}
$this->fail('Exception for not trusted modifier has not been raised.');
}
/**
* test not trusted PHP function at disabled security
*/
public function testDisabledTrustedPHPFunction()
{
$this->smarty->security_policy->php_functions = array('null');
$this->smarty->disableSecurity();
$this->assertEquals("5", $this->smarty->fetch('eval:{assign var=foo value=[1,2,3,4,5]}{count($foo)}'));
}
/**
* test trusted modifier
*/
public function testTrustedModifier()
{
$this->assertEquals("5", $this->smarty->fetch('eval:{assign var=foo value=[1,2,3,4,5]}{$foo|@count}'));
}
/**
* test not trusted modifier
*/
public function testNotTrustedModifier()
{
$this->smarty->security_policy->php_modifiers = array('null');
try {
$this->smarty->fetch('eval:{assign var=foo value=[1,2,3,4,5]}{$foo|@count}');
}
catch (Exception $e) {
$this->assertContains(htmlentities("modifier 'count' not allowed by security setting"), $e->getMessage());
return;
}
$this->fail('Exception for not trusted modifier has not been raised.');
}
/**
* test not trusted modifier at disabled security
*/
public function testDisabledTrustedModifier()
{
$this->smarty->security_policy->php_modifiers = array('null');
$this->smarty->disableSecurity();
$this->assertEquals("5", $this->smarty->fetch('eval:{assign var=foo value=[1,2,3,4,5]}{$foo|@count}'));
}
/**
* test allowed tags
*/
public function testAllowedTags1()
{
$this->smarty->security_policy->allowed_tags = array('counter');
$this->assertEquals("1", $this->smarty->fetch('eval:{counter start=1}'));
}
/**
* test not allowed tag
*/
public function testNotAllowedTags2()
{
$this->smarty->security_policy->allowed_tags = array('counter');
try {
$this->smarty->fetch('eval:{counter}{cycle values="1,2"}');
}
catch (Exception $e) {
$this->assertContains(htmlentities("tag 'cycle' not allowed by security setting"), $e->getMessage());
return;
}
$this->fail('Exception for not allowed tag has not been raised.');
}
/**
* test disabled tag
*/
public function testDisabledTags()
{
$this->smarty->security_policy->disabled_tags = array('cycle');
try {
$this->smarty->fetch('eval:{counter}{cycle values="1,2"}');
}
catch (Exception $e) {
$this->assertContains(htmlentities("tag 'cycle' disabled by security setting"), $e->getMessage());
return;
}
$this->fail('Exception for disabled tag has not been raised.');
}
/**
* test allowed modifier
*/
public function testAllowedModifier1()
{
error_reporting(E_ALL & ~E_DEPRECATED | E_STRICT);
$this->smarty->security_policy->allowed_modifiers = array('capitalize');
$this->assertEquals("Hello World", $this->smarty->fetch('eval:{"hello world"|capitalize}'));
error_reporting(E_ALL | E_STRICT);
}
public function testAllowedModifier2()
{
$this->smarty->security_policy->allowed_modifiers = array('upper');
$this->assertEquals("HELLO WORLD", $this->smarty->fetch('eval:{"hello world"|upper}'));
}
/**
* test not allowed modifier
*/
public function testNotAllowedModifier()
{
$this->smarty->security_policy->allowed_modifiers = array('upper');
try {
$this->smarty->fetch('eval:{"hello"|upper}{"world"|lower}');
}
catch (Exception $e) {
$this->assertContains(htmlentities("modifier 'lower' not allowed by security setting"), $e->getMessage());
return;
}
$this->fail('Exception for not allowed tag has not been raised.');
}
/**
* test disabled modifier
*/
public function testDisabledModifier()
{
$this->smarty->security_policy->disabled_modifiers = array('lower');
try {
$this->smarty->fetch('eval:{"hello"|upper}{"world"|lower}');
}
catch (Exception $e) {
$this->assertContains(htmlentities("modifier 'lower' disabled by security setting"), $e->getMessage());
return;
}
$this->fail('Exception for disabled tag has not been raised.');
}
/**
* test Smarty::PHP_QUOTE
*/
public function testSmartyPhpQuote()
{
$this->smarty->security_policy->php_handling = Smarty::PHP_QUOTE;
$this->assertEquals('&lt;?php echo "hello world"; ?&gt;', $this->smarty->fetch('eval:<?php echo "hello world"; ?>'));
}
public function testSmartyPhpQuoteAsp()
{
// NOTE: asp_tags cannot be changed by ini_set()
if (!ini_get('asp_tags')) {
$this->markTestSkipped('asp tags disabled in php.ini');
}
$this->smarty->security_policy->php_handling = Smarty::PHP_QUOTE;
$this->assertEquals('&lt;% echo "hello world"; %&gt;', $this->smarty->fetch('eval:<% echo "hello world"; %>'));
}
/**
* test Smarty::PHP_REMOVE
*/
public function testSmartyPhpRemove()
{
$this->smarty->security_policy->php_handling = Smarty::PHP_REMOVE;
$this->assertEquals(' echo "hello world"; ', $this->smarty->fetch('eval:<?php echo "hello world"; ?>'));
}
public function testSmartyPhpRemoveAsp()
{
// NOTE: asp_tags cannot be changed by ini_set()
if (!ini_get('asp_tags')) {
$this->markTestSkipped('asp tags disabled in php.ini');
}
$this->smarty->security_policy->php_handling = Smarty::PHP_REMOVE;
$this->assertEquals(' echo "hello world"; ', $this->smarty->fetch('eval:<% echo "hello world"; %>'));
}
/**
* test Smarty::PHP_ALLOW
*/
public function testSmartyPhpAllow()
{
$this->smartyBC->security_policy->php_handling = Smarty::PHP_ALLOW;
$this->assertEquals('hello world', $this->smartyBC->fetch('eval:<?php echo "hello world"; ?>'));
}
public function testSmartyPhpAllowAsp()
{
// NOTE: asp_tags cannot be changed by ini_set()
if (!ini_get('asp_tags')) {
$this->markTestSkipped('asp tags disabled in php.ini');
}
$this->smartyBC->security_policy->php_handling = Smarty::PHP_ALLOW;
$this->assertEquals('hello world', $this->smartyBC->fetch('eval:<% echo "hello world"; %>'));
}
/**
* test standard directory
*/
public function testStandardDirectory()
{
$content = $this->smarty->fetch('eval:{include file="helloworld.tpl"}');
$this->assertEquals("hello world", $content);
}
/**
* test trusted directory
*/
public function testTrustedDirectory()
{
$this->smarty->security_policy->secure_dir = array('.' . DIRECTORY_SEPARATOR . 'templates_2' . DIRECTORY_SEPARATOR);
$this->assertEquals("hello world", $this->smarty->fetch('eval:{include file="templates_2/hello.tpl"}'));
}
/**
* test not trusted directory
*/
public function testNotTrustedDirectory()
{
$this->smarty->security_policy->secure_dir = array(str_replace('\\', '/', __DIR__ . '/templates_3/'));
try {
$this->smarty->fetch('eval:{include file="templates_2/hello.tpl"}');
}
catch (Exception $e) {
$this->assertContains(str_replace('\\', '/', __DIR__ . "/templates_2/hello.tpl' not allowed by security setting"), str_replace('\\', '/', $e->getMessage()));
return;
}
$this->fail('Exception for not trusted directory has not been raised.');
}
/**
* test disabled security for not trusted dir
*/
public function testDisabledTrustedDirectory()
{
$this->smarty->disableSecurity();
$this->assertEquals("hello world", $this->smarty->fetch('eval:{include file="templates_2/hello.tpl"}'));
}
/**
* test trusted static class
*/
public function testTrustedStaticClass()
{
$this->smarty->security_policy->static_classes = array('mysecuritystaticclass');
$tpl = $this->smarty->createTemplate('eval:{mysecuritystaticclass::square(5)}');
$this->assertEquals('25', $this->smarty->fetch($tpl));
}
/**
* test not trusted PHP function
*/
public function testNotTrustedStaticClass()
{
$this->smarty->security_policy->static_classes = array('null');
try {
$this->smarty->fetch('eval:{mysecuritystaticclass::square(5)}');
}
catch (Exception $e) {
$this->assertContains(htmlentities("access to static class 'mysecuritystaticclass' not allowed by security setting"), $e->getMessage());
return;
}
$this->fail('Exception for not trusted static class has not been raised.');
}
public function testChangedTrustedDirectory()
{
$this->smarty->security_policy->secure_dir = array(
'.' . DS . 'templates_2' . DS,
);
$this->assertEquals("hello world", $this->smarty->fetch('eval:{include file="templates_2/hello.tpl"}'));
$this->smarty->security_policy->secure_dir = array(
'.' . DS . 'templates_2' . DS,
'.' . DS . 'templates_3' . DS,
);
$this->assertEquals("templates_3", $this->smarty->fetch('eval:{include file="templates_3/dirname.tpl"}'));
}
public function testTrustedUri()
{
$this->smarty->security_policy->trusted_uri = array(
'#^http://.+smarty\.net$#i'
);
try {
$this->smarty->fetch('eval:{fetch file="http://www.smarty.net/foo.bar"}');
}
catch (SmartyException $e) {
$this->assertNotContains(htmlentities("not allowed by security setting"), $e->getMessage());
}
try {
$this->smarty->fetch('eval:{fetch file="https://www.smarty.net/foo.bar"}');
$this->fail("Exception for unknown resource not thrown (protocol)");
}
catch (SmartyException $e) {
$this->assertContains(htmlentities("not allowed by security setting"), $e->getMessage());
}
try {
$this->smarty->fetch('eval:{fetch file="http://www.smarty.com/foo.bar"}');
$this->fail("Exception for unknown resource not thrown (domain)");
}
catch (SmartyException $e) {
$this->assertContains(htmlentities("not allowed by security setting"), $e->getMessage());
}
}
}
class mysecuritystaticclass
{
const STATIC_CONSTANT_VALUE = 3;
static $static_var = 5;
static function square($i)
{
return $i * $i;
}
}

View File

@@ -0,0 +1 @@
hello world

View File

@@ -0,0 +1 @@
hello world

View File

@@ -0,0 +1 @@
templates_3

View File

@@ -0,0 +1,84 @@
<?php
/**
* Smarty PHPunit tests append method
*
* @package PHPunit
* @author Uwe Tews
*/
/**
* class for append tests
*
* @backupStaticAttributes enabled
*/
class AppendTest extends PHPUnit_Smarty
{
public function setUp()
{
$this->setUpSmarty(__DIR__);
}
public function testInit()
{
$this->cleanDirs();
}
/**
* test append
*/
public function testAppend()
{
$this->smarty->assign('foo', 'bar');
$this->smarty->append('foo', 'bar2');
$this->assertEquals('bar bar2', $this->smarty->fetch('eval:{$foo[0]} {$foo[1]}'));
}
/**
* test append to unassigned variable
*/
public function testAppendUnassigned()
{
$this->smarty->append('foo', 'bar');
$this->assertEquals('bar', $this->smarty->fetch('eval:{$foo[0]}'));
}
/**
* test append merge
*/
public function testAppendMerge()
{
$this->smarty->assign('foo', array('a' => 'a', 'b' => 'b', 'c' => 'c'));
$this->smarty->append('foo', array('b' => 'd'), true);
$this->assertEquals('a d c', $this->smarty->fetch('eval:{$foo["a"]} {$foo["b"]} {$foo["c"]}'));
}
/**
* test append array merge
*/
public function testAppendArrayMerge()
{
$this->smarty->assign('foo', array('b' => 'd'));
$this->smarty->append('foo', array('a' => 'a', 'b' => 'b', 'c' => 'c'), true);
$this->assertEquals('a b c', $this->smarty->fetch('eval:{$foo["a"]} {$foo["b"]} {$foo["c"]}'));
}
/**
* test array append
*/
public function testArrayAppend()
{
$this->smarty->assign('foo', 'foo');
$this->smarty->append(array('bar' => 'bar2', 'foo' => 'foo2'));
$this->assertEquals('foo foo2 bar2', $this->smarty->fetch('eval:{$foo[0]} {$foo[1]} {$bar[0]}'));
}
/**
* test array append array merge
*/
public function testArrayAppendArrayMerge()
{
$this->smarty->assign('foo', array('b' => 'd'));
$this->smarty->append(array('bar' => 'bar', 'foo' => array('a' => 'a', 'b' => 'b', 'c' => 'c')), null, true);
$this->assertEquals('a b c bar', $this->smarty->fetch('eval:{$foo["a"]} {$foo["b"]} {$foo["c"]} {$bar[0]}'));
}
}

View File

@@ -0,0 +1,46 @@
<?php
/**
* Smarty PHPunit tests appendByRef method
*
* @package PHPunit
* @author Uwe Tews
*/
/**
* class for appendByRef tests
*
* @backupStaticAttributes enabled
*/
class AppendByRefBCTest extends PHPUnit_Smarty
{
public $loadSmartyBC = true;
public $loadSmarty = false;
public function setUp()
{
$this->setUpSmarty(__DIR__);
}
public function testInit()
{
$this->cleanDirs();
}
public function testSmarty2AppendByRef()
{
$bar = 'bar';
$bar2 = 'bar2';
$this->smartyBC->append_by_ref('foo', $bar);
$this->smartyBC->append_by_ref('foo', $bar2);
$bar = 'newbar';
$bar2 = 'newbar2';
$this->assertEquals('newbar newbar2', $this->smartyBC->fetch('eval:{$foo[0]} {$foo[1]}'));
}
public function testSmarty2AppendByRefUnassigned()
{
$bar2 = 'bar2';
$this->smartyBC->append_by_ref('foo', $bar2);
$bar2 = 'newbar2';
$this->assertEquals('newbar2', $this->smartyBC->fetch('eval:{$foo[0]}'));
}
}

Some files were not shown because too many files have changed in this diff Show More