提交thinkPHP

This commit is contained in:
2025-08-08 11:25:39 +08:00
parent ca1fed3588
commit 026e8d23a5
2987 changed files with 484280 additions and 0 deletions

4
thinkphp/tests/.gitignore vendored Normal file
View File

@@ -0,0 +1,4 @@
/runtime/
/application/common.php
/application/demo/
/application/runtime/

132
thinkphp/tests/README.md Normal file
View File

@@ -0,0 +1,132 @@
## 测试目录结构
测试文件主要在 tests 文件下面,主要有以下几个文件夹
- conf 测试环境配置文件。
- script 测试环境配置脚本。
- thinkphp 测试用例和相关文件,与项目文件夹结构一致。
- mock.php 测试入口文件。
## 主要测试流程
thinkphp5 的测试的主要流程是跟 thinkphp 的系统流程是相似的,大体的流程为:
1. 引用 mock.php 文件加载框架
2. 根据文件目录,添加测试文件
3. 执行单元测试,输出结果
## 测试举例
例如测试 thinkphp 里的 apc 缓存,将分为以下几个过程:
1. 创建 apcTest.php 文件
该文件应与 apc.php 目录路径 `thinkphp/library/think/cache/driver` 一致,命名空间与目录所在一致,并引用 `PHPUnit_Framework_TestCase`
```php
<?php
namespace tests\thinkphp\library\think\cache\driver;
class apcTest extends \PHPUnit_Framework_TestCase
{
//设定基境
public function setUp()
{
}
}
```
2. 编写测试文件
- 引用 app、config 和 cache
```php
use think\app;
use think\cache;
use think\config;
```
- 在 setUp 函数中设定 require 条件
```php
if(!extension_loaded('apc')){
$this->markTestSkipped('apc扩展不可用');
};
```
- 编写测试用例
*具体写法参照 [PHPUnit 官方文档](https://phpunit.de/manual/4.8/zh_cn/index.html)*
```php
public function testGet()
{
App::run();
$this->assertInstanceOf(
'\think\cache\driver\Apc',
Cache::connect(['type' => 'apc', 'expire' => 1])
);
$this->assertTrue(Cache::set('key', 'value'));
$this->assertEquals('value', Cache::get('key'));
$this->assertTrue(Cache::rm('key'));
$this->assertFalse(Cache::get('key'));
$this->assertTrue(Cache::clear('key'));
Config::reset();
}
```
3. 执行单元测试命令
在项目根目录执行
```bash
$ phpunit
```
若想看到所有结果,请添加-v参数
```bash
$ phpunit -v
```
4. 输出结果
## 相关文档
[各个部分单元测试说明](http://www.kancloud.cn/brother_simon/tp5_test/96971 "各部分单元测试说明")
## 大家一起来
单元测试的内容会跟框架同步,测试内容方方面面,是一个相对复杂的模块,同时也是一个值得重视的部分。希望大家能够多多提出意见,多多参与。如果你有任何问题或想法,可以随时提 issue我们期待着收到听大家的质疑和讨论。
## 任务进度
单元测试任务进度,请大家认领模块
|模块|认领人|进度|
|---|---|---|
|Base|||
|App|Haotong Lin|√|
|Build|刘志淳||
|Config|Haotong Lin|√|
|Cache|||
|Controller|Haotong Lin|√|
|Cookie|Haotong Lin|√|
|Db|||
|Debug|大漠|√|
|Error|大漠||
|Exception|Haotong Lin|√|
|Hook|流年|√|
|Input|Haotong Lin|√|
|Lang|流年|√|
|Loader|流年||
|Log|||
|Model|||
|Response|大漠|√|
|Route|流年||
|Session|大漠|√|
|Template|oldrind||
|Url|流年||
|View|mahuan||

View File

@@ -0,0 +1,33 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id$
return [
'url_route_on' => true,
'log' => [
'type' => 'file', // 支持 socket trace file
],
'view' => [
// 模板引擎
'engine_type' => 'think',
// 模板引擎配置
'engine_config' => [
// 模板路径
'view_path' => '',
// 模板后缀
'view_suffix' => '.html',
// 模板文件名分隔符
'view_depr' => DS,
],
// 输出字符串替换
'parse_str' => [],
],
];

View File

@@ -0,0 +1,44 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id$
return [
// 数据库类型
'type' => 'mysql',
// 数据库连接DSN配置
'dsn' => '',
// 服务器地址
'hostname' => '127.0.0.1',
// 数据库名
'database' => '',
// 数据库用户名
'username' => 'root',
// 数据库密码
'password' => '',
// 数据库连接端口
'hostport' => '',
// 数据库连接参数
'params' => [],
// 数据库编码默认采用utf8
'charset' => 'utf8',
// 数据库表前缀
'prefix' => '',
// 数据库调试模式
'debug' => true,
// 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
'deploy' => 0,
// 数据库读写是否分离 主从式有效
'rw_separate' => false,
// 读写分离后 主服务器数量
'master_num' => 1,
// 指定从服务器序号
'slave_no' => '',
];

View File

@@ -0,0 +1,10 @@
<?php
namespace app\index\controller;
class Index
{
public function index()
{
return '<style type="text/css">*{ padding: 0; margin: 0; } div{ padding: 4px 48px;} a{color:#2E5CD5;cursor: pointer;text-decoration: none} a:hover{text-decoration:underline; } body{ background: #fff; font-family: "Century Gothic","Microsoft yahei"; color: #333;font-size:18px} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.6em; font-size: 42px }</style><div style="padding: 24px 48px;"> <h1>:)</h1><p> ThinkPHP V5<br/><span style="font-size:30px">十年磨一剑 - 为API开发设计的高性能框架</span></p><span style="font-size:22px;">[ V5.0 版本由 <a href="http://www.qiniu.com" target="qiniu">七牛云</a> 独家赞助发布 ]</span></div><script type="text/javascript" src="http://tajs.qq.com/stats?sId=9347272" charset="UTF-8"></script><script type="text/javascript" src="http://ad.topthink.com/Public/static/client.js"></script><thinkad id="ad_bd568ce7058a1091"></thinkad>';
}
}

View File

@@ -0,0 +1,22 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id$
return [
'__pattern__' => [
'name' => '\w+',
],
'[hello]' => [
':id' => ['index/hello', ['method' => 'get'], ['id' => '\d+']],
':name' => ['index/hello', ['method' => 'post']],
],
];

View File

@@ -0,0 +1 @@
{$name??'default'}

View File

@@ -0,0 +1 @@
{$name??'default'}

View File

@@ -0,0 +1,2 @@
{extend name="extend2" /}
{block name="head"}header{/block}

View File

@@ -0,0 +1,17 @@
{layout name="layout2" replace="[__REPLACE__]" /}
{block name="head"}{/block}
<div id="wrap">
{include file="include" name="info" value="$info.value" /}
{block name="main"}
{block name="side"}
side
{/block}
{block name="mainbody"}
{/block}
{/block}
{literal}
{$name}
{/literal}
<?php echo 'php code'; ?>
</div>

View File

@@ -0,0 +1,2 @@
<input name="[name]" value="[value]">
{include file="include2" /}

View File

@@ -0,0 +1 @@
{$info.value}:

View File

@@ -0,0 +1,2 @@
<div>{__CONTENT__}
</div>

View File

@@ -0,0 +1,2 @@
<nav>[__REPLACE__]
</nav>

View File

@@ -0,0 +1 @@
extension=memcached.so

View File

@@ -0,0 +1 @@
extension=redis.so

View File

@@ -0,0 +1 @@
date.timezone = UTC

20
thinkphp/tests/mock.php Normal file
View File

@@ -0,0 +1,20 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// 测试入口文件
$_SERVER['REQUEST_METHOD'] = 'GET';
// 定义项目测试基础路径
define('TEST_PATH', __DIR__ . '/');
// 定义项目路径
define('APP_PATH', __DIR__ . '/application/');
// 加载框架基础文件
require __DIR__ . '/../base.php';
\think\Loader::addNamespace('tests', TEST_PATH);

View File

@@ -0,0 +1,13 @@
#!/bin/bash
if [ $(phpenv version-name) != "hhvm" ]; then
cp tests/extensions/$(phpenv version-name)/*.so $(php-config --extension-dir)
phpenv config-add tests/conf/memcached.ini
phpenv config-add tests/conf/redis.ini
phpenv config-add tests/conf/timezone.ini
fi
composer install --no-interaction --ignore-platform-reqs
composer update

View File

@@ -0,0 +1,39 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Haotong Lin <lofanmi@gmail.com>
// +----------------------------------------------------------------------
/**
* 保证运行环境正常
*/
class baseTest extends \PHPUnit_Framework_TestCase
{
public function testConstants()
{
$this->assertNotEmpty(THINK_START_TIME);
$this->assertNotEmpty(THINK_START_MEM);
$this->assertNotEmpty(THINK_VERSION);
$this->assertNotEmpty(DS);
$this->assertNotEmpty(THINK_PATH);
$this->assertNotEmpty(LIB_PATH);
$this->assertNotEmpty(EXTEND_PATH);
$this->assertNotEmpty(CORE_PATH);
$this->assertNotEmpty(TRAIT_PATH);
$this->assertNotEmpty(APP_PATH);
$this->assertNotEmpty(RUNTIME_PATH);
$this->assertNotEmpty(LOG_PATH);
$this->assertNotEmpty(CACHE_PATH);
$this->assertNotEmpty(TEMP_PATH);
$this->assertNotEmpty(VENDOR_PATH);
$this->assertNotEmpty(EXT);
$this->assertNotEmpty(ENV_PREFIX);
$this->assertTrue(!is_null(IS_WIN));
$this->assertTrue(!is_null(IS_CLI));
}
}

View File

@@ -0,0 +1,90 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
/**
* app类测试
* @author Haotong Lin <lofanmi@gmail.com>
*/
namespace tests\thinkphp\library\think;
use think\App;
use think\Config;
use think\Request;
function func_trim($value)
{
return trim($value);
}
function func_strpos($haystack, $needle)
{
return strpos($haystack, $needle);
}
class AppInvokeMethodTestClass
{
public static function staticRun($string)
{
return $string;
}
public function run($string)
{
return $string;
}
}
class appTest extends \PHPUnit_Framework_TestCase
{
public function testRun()
{
$response = App::run(Request::create("http://www.example.com"));
$expectOutputString = '<style type="text/css">*{ padding: 0; margin: 0; } div{ padding: 4px 48px;} a{color:#2E5CD5;cursor: pointer;text-decoration: none} a:hover{text-decoration:underline; } body{ background: #fff; font-family: "Century Gothic","Microsoft yahei"; color: #333;font-size:18px} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.6em; font-size: 42px }</style><div style="padding: 24px 48px;"> <h1>:)</h1><p> ThinkPHP V5<br/><span style="font-size:30px">十年磨一剑 - 为API开发设计的高性能框架</span></p><span style="font-size:22px;">[ V5.0 版本由 <a href="http://www.qiniu.com" target="qiniu">七牛云</a> 独家赞助发布 ]</span></div><script type="text/javascript" src="http://tajs.qq.com/stats?sId=9347272" charset="UTF-8"></script><script type="text/javascript" src="http://ad.topthink.com/Public/static/client.js"></script><thinkad id="ad_bd568ce7058a1091"></thinkad>';
$this->assertEquals($expectOutputString, $response->getContent());
$this->assertEquals(200, $response->getCode());
$this->assertEquals(true, function_exists('lang'));
$this->assertEquals(true, function_exists('config'));
$this->assertEquals(true, function_exists('input'));
$this->assertEquals(Config::get('default_timezone'), date_default_timezone_get());
}
// function调度
public function testInvokeFunction()
{
$args1 = ['a b c '];
$this->assertEquals(
trim($args1[0]),
App::invokeFunction('tests\thinkphp\library\think\func_trim', $args1)
);
$args2 = ['abcdefg', 'g'];
$this->assertEquals(
strpos($args2[0], $args2[1]),
App::invokeFunction('tests\thinkphp\library\think\func_strpos', $args2)
);
}
// 类method调度
public function testInvokeMethod()
{
$result = App::invokeMethod(['tests\thinkphp\library\think\AppInvokeMethodTestClass', 'run'], ['thinkphp']);
$this->assertEquals('thinkphp', $result);
$result = App::invokeMethod('tests\thinkphp\library\think\AppInvokeMethodTestClass::staticRun', ['thinkphp']);
$this->assertEquals('thinkphp', $result);
}
}

View File

@@ -0,0 +1,15 @@
<?php
namespace tests\thinkphp\library\think\behavior;
class One
{
public function run(&$data) {
$data['id'] = 1;
return true;
}
public function test(&$data) {
$data['name'] = 'test';
return false;
}
}

View File

@@ -0,0 +1,9 @@
<?php
namespace tests\thinkphp\library\think\behavior;
class Three
{
public function run(&$data) {
$data['id'] = 3;
}
}

View File

@@ -0,0 +1,9 @@
<?php
namespace tests\thinkphp\library\think\behavior;
class Two
{
public function run(&$data) {
$data['id'] = 2;
}
}

View File

@@ -0,0 +1,73 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
/**
* build测试
* @author 刘志淳 <chun@engineer.com>
*/
namespace tests\thinkphp\library\think;
use think\Build;
class buildTest extends \PHPUnit_Framework_TestCase
{
public function testRun()
{
$build = [
// Test run directory
'__dir__' => ['runtime/cache', 'runtime/log', 'runtime/temp', 'runtime/template'],
'__file__' => ['common.php'],
// Test generation module
'demo' => [
'__file__' => ['common.php'],
'__dir__' => ['behavior', 'controller', 'model', 'view', 'service'],
'controller' => ['Index', 'Test', 'UserType'],
'model' => ['User', 'UserType'],
'service' => ['User', 'UserType'],
'view' => ['index/index'],
],
];
Build::run($build);
$this->buildFileExists($build);
}
protected function buildFileExists($build)
{
foreach ($build as $module => $list) {
if ('__dir__' == $module || '__file__' == $module) {
foreach ($list as $file) {
$this->assertFileExists(APP_PATH . $file);
}
} else {
foreach ($list as $path => $moduleList) {
if ('__file__' == $path || '__dir__' == $path) {
foreach ($moduleList as $file) {
$this->assertFileExists(APP_PATH . $module . '/' . $file);
}
} else {
foreach ($moduleList as $file) {
if ('view' == $path) {
$file_name = APP_PATH . $module . '/' . $path . '/' . $file . '.html';
} else {
$file_name = APP_PATH . $module . '/' . $path . '/' . $file . EXT;
}
$this->assertFileExists($file_name);
}
}
}
$this->assertFileExists(APP_PATH . ($module ? $module . DS : '') . 'config.php');
}
}
}
}

View File

@@ -0,0 +1,207 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
/**
* 缓存抽象类,提供一些测试
* @author simon <mahuan@d1web.top>
*/
namespace tests\thinkphp\library\think\cache\driver;
use think\Cache;
abstract class cacheTestCase extends \PHPUnit_Framework_TestCase
{
/**
* 获取缓存句柄,子类必须有
* @access protected
*/
abstract protected function getCacheInstance();
/**
* tearDown函数
*/
protected function tearDown()
{
}
/**
* 设定一组测试值,包括测试字符串、整数、数组和对象
* @return mixed
* @access public
*/
public function prepare()
{
$cache = $this->getCacheInstance();
$cache->clear();
$cache->set('string_test', 'string_test');
$cache->set('number_test', 11);
$cache->set('array_test', ['array_test' => 'array_test']);
return $cache;
}
/**
* 测试缓存设置,包括测试字符串、整数、数组和对象
* @return mixed
* @access public
*/
public function testSet()
{
$cache = $this->getCacheInstance();
$this->assertTrue($cache->set('string_test', 'string_test'));
$this->assertTrue($cache->set('number_test', 11));
$this->assertTrue($cache->set('array_test', ['array_test' => 'array_test']));
}
/**
* 测试缓存自增
* @return mixed
* @access public
*/
public function testInc()
{
$cache = $this->getCacheInstance();
$this->assertEquals(14, $cache->inc('number_test', 3));
}
/**
* 测试缓存自减
* @return mixed
* @access public
*/
public function testDec()
{
$cache = $this->getCacheInstance();
$this->assertEquals(8, $cache->dec('number_test', 6));
}
/**
* 测试缓存读取,包括测试字符串、整数、数组和对象
* @return mixed
* @access public
*/
public function testGet()
{
$cache = $this->prepare();
$this->assertEquals('string_test', $cache->get('string_test'));
$this->assertEquals(11, $cache->get('number_test'));
$array = $cache->get('array_test');
$this->assertArrayHasKey('array_test', $array);
$this->assertEquals('array_test', $array['array_test']);
$result = $cache->set('no_expire', 1, 0);
$this->assertTrue($result);
}
/**
* 测试缓存存在情况,包括测试字符串、整数、数组和对象
* @return mixed
* @access public
*/
public function testExists()
{
$cache = $this->prepare();
$this->assertNotEmpty($cache->has('string_test'));
$this->assertNotEmpty($cache->has('number_test'));
$this->assertFalse($cache->has('not_exists'));
}
/**
* 测试缓存不存在情况,包括测试字符串、整数、数组和对象
* @return mixed
* @access public
*/
public function testGetNonExistent()
{
$cache = $this->getCacheInstance();
$this->assertFalse($cache->get('non_existent_key', false));
}
/**
* 测试特殊值缓存,包括测试字符串、整数、数组和对象
* @return mixed
* @access public
*/
public function testStoreSpecialValues()
{
$cache = $this->getCacheInstance();
$cache->set('null_value', null);
//清空缓存后返回null而不是false
$this->assertTrue(is_null($cache->get('null_value')));
}
/**
* 缓存过期测试
* @return mixed
* @access public
*/
public function testExpire()
{
$cache = $this->getCacheInstance();
$this->assertTrue($cache->set('expire_test', 'expire_test', 1));
usleep(600000);
$this->assertEquals('expire_test', $cache->get('expire_test'));
usleep(800000);
$this->assertFalse($cache->get('expire_test'));
}
/**
* 删除缓存测试
* @return mixed
* @access public
*/
public function testDelete()
{
$cache = $this->prepare();
$this->assertNotNull($cache->rm('number_test'));
$this->assertFalse($cache->get('number_test'));
}
/**
* 获取并删除缓存测试
* @return mixed
* @access public
*/
public function testPull()
{
$cache = $this->prepare();
$this->assertEquals(11, $cache->pull('number_test'));
$this->assertFalse($cache->get('number_test'));
}
/**
* 清空缓存测试
* @return mixed
* @access public
*/
public function testClear()
{
$cache = $this->prepare();
$this->assertTrue($cache->clear());
$this->assertFalse($cache->get('number_test'));
}
public function testStaticCall()
{
$this->assertTrue(Cache::set('a', 1));
$this->assertEquals(1, Cache::get('a'));
$this->assertEquals(2, Cache::inc('a'));
$this->assertEquals(4, Cache::inc('a', 2));
$this->assertEquals(4, Cache::get('a'));
$this->assertEquals(3, Cache::dec('a'));
$this->assertEquals(1, Cache::dec('a', 2));
$this->assertEquals(1, Cache::get('a'));
$this->assertNotNull(Cache::rm('a'));
$this->assertNotNull(Cache::clear());
}
}

View File

@@ -0,0 +1,46 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
/**
* File缓存驱动测试
* @author 刘志淳 <chun@engineer.com>
*/
namespace tests\thinkphp\library\think\cache\driver;
class fileTest extends cacheTestCase
{
private $_cacheInstance = null;
/**
* 基境缓存类型
*/
protected function setUp()
{
\think\Cache::connect(['type' => 'File', 'path' => CACHE_PATH]);
}
/**
* @return FileCache
*/
protected function getCacheInstance()
{
if (null === $this->_cacheInstance) {
$this->_cacheInstance = new \think\cache\driver\File();
}
return $this->_cacheInstance;
}
// skip testExpire
public function testExpire()
{
}
}

View File

@@ -0,0 +1,69 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
/**
* Lite缓存驱动测试
* @author 刘志淳 <chun@engineer.com>
*/
namespace tests\thinkphp\library\think\cache\driver;
use think\Cache;
class liteTest extends \PHPUnit_Framework_TestCase
{
protected function getCacheInstance()
{
return Cache::connect(['type' => 'Lite', 'path' => CACHE_PATH]);
}
/**
* 测试缓存读取
* @return mixed
* @access public
*/
public function testGet()
{
$cache = $this->getCacheInstance();
$this->assertFalse($cache->get('test'));
}
/**
* 测试缓存设置
* @return mixed
* @access public
*/
public function testSet()
{
$cache = $this->getCacheInstance();
$this->assertNotEmpty($cache->set('test', 'test'));
}
/**
* 删除缓存测试
* @return mixed
* @access public
*/
public function testRm()
{
$cache = $this->getCacheInstance();
$this->assertTrue($cache->rm('test'));
}
/**
* 清空缓存测试
* @return mixed
* @access public
*/
public function testClear()
{
}
}

View File

@@ -0,0 +1,49 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
/**
* Memcache缓存驱动测试
* @author 刘志淳 <chun@engineer.com>
*/
namespace tests\thinkphp\library\think\cache\driver;
class memcacheTest extends cacheTestCase
{
private $_cacheInstance = null;
/**
* 基境缓存类型
*/
protected function setUp()
{
if (!extension_loaded('memcache')) {
$this->markTestSkipped("Memcache没有安装已跳过测试");
}
\think\Cache::connect(['type' => 'memcache', 'expire' => 2]);
}
/**
* @return ApcCache
*/
protected function getCacheInstance()
{
if (null === $this->_cacheInstance) {
$this->_cacheInstance = new \think\cache\driver\Memcache(['length' => 3]);
}
return $this->_cacheInstance;
}
// skip testExpire
public function testExpire()
{
}
}

View File

@@ -0,0 +1,72 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
/**
* Memcached缓存驱动测试
* @author 7IN0SAN9 <me@7in0.me>
*/
namespace tests\thinkphp\library\think\cache\driver;
class memcachedTest extends cacheTestCase
{
private $_cacheInstance = null;
/**
* 基境缓存类型
*/
protected function setUp()
{
if (!extension_loaded("memcached") && !extension_loaded('memcache')) {
$this->markTestSkipped("Memcached或Memcache没有安装已跳过测试");
}
\think\Cache::connect(array('type' => 'memcached', 'expire' => 2));
}
/**
* @return ApcCache
*/
protected function getCacheInstance()
{
if (null === $this->_cacheInstance) {
$this->_cacheInstance = new \think\cache\driver\Memcached(['length' => 3]);
}
return $this->_cacheInstance;
}
/**
* 缓存过期测试《提出来测试,因为目前看通不过缓存过期测试,所以还需研究》
* @return mixed
* @access public
*/
public function testExpire()
{
}
public function testStaticCall()
{
}
/**
* 测试缓存自增
* @return mixed
* @access public
*/
public function testInc()
{
}
/**
* 测试缓存自减
* @return mixed
* @access public
*/
public function testDec()
{
}
}

View File

@@ -0,0 +1,66 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
/**
* Redis缓存驱动测试
* @author 7IN0SAN9 <me@7in0.me>
*/
namespace tests\thinkphp\library\think\cache\driver;
class redisTest extends cacheTestCase
{
private $_cacheInstance = null;
protected function setUp()
{
if (!extension_loaded("redis")) {
$this->markTestSkipped("Redis没有安装已跳过测试");
}
\think\Cache::connect(array('type' => 'redis', 'expire' => 2));
}
protected function getCacheInstance()
{
if (null === $this->_cacheInstance) {
$this->_cacheInstance = new \think\cache\driver\Redis(['length' => 3]);
}
return $this->_cacheInstance;
}
public function testGet()
{
$cache = $this->prepare();
$this->assertEquals('string_test', $cache->get('string_test'));
$this->assertEquals(11, $cache->get('number_test'));
$result = $cache->get('array_test');
$this->assertEquals('array_test', $result['array_test']);
}
public function testStoreSpecialValues()
{
$redis = new \think\cache\driver\Redis(['length' => 3]);
$redis->set('key', 'value');
$redis->get('key');
$redis->handler()->setnx('key', 'value');
$value = $redis->handler()->get('key');
$this->assertEquals('value', $value);
$redis->handler()->hset('hash', 'key', 'value');
$value = $redis->handler()->hget('hash', 'key');
$this->assertEquals('value', $value);
}
public function testExpire()
{
}
}

View File

@@ -0,0 +1,315 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace tests\thinkphp\library\think;
use tests\thinkphp\library\think\config\ConfigInitTrait;
use think\Cache;
use think\Config;
class cacheTest extends \PHPUnit_Framework_TestCase
{
use ConfigInitTrait {
ConfigInitTrait::tearDown as ConfigTearDown;
}
public function tearDown()
{
$this->ConfigTearDown();
call_user_func(\Closure::bind(function () {
Cache::$handler = null;
Cache::$instance = [];
Cache::$readTimes = 0;
Cache::$writeTimes = 0;
}, null, '\think\Cache'));
}
/**
* @dataProvider provideTestConnect
*/
public function testConnect($options, $expected)
{
$connection = Cache::connect($options);
$this->assertInstanceOf($expected, $connection);
$this->assertSame($connection, Cache::connect($options));
$instance = $this->getPropertyVal('instance');
$this->assertArrayHasKey(md5(serialize($options)), $instance);
$newConnection = Cache::connect($options, true);
$newInstance = $this->getPropertyVal('instance');
$this->assertInstanceOf($expected, $connection);
$this->assertNotSame($connection, $newConnection);
$this->assertEquals($instance, $newInstance);
}
/**
* @dataProvider provideTestInit
*/
public function testInit($options, $expected)
{
$connection = Cache::init($options);
$this->assertInstanceOf($expected, $connection);
$connectionNew = Cache::init(['type' => 'foo']);
$this->assertSame($connection, $connectionNew);
}
public function testStore()
{
Config::set('cache.redis', ['type' => 'redis']);
$connectionDefault = Cache::store();
$this->assertInstanceOf('\think\cache\driver\File', $connectionDefault);
Config::set('cache.type', false);
$connectionNotRedis = Cache::store('redis');
$this->assertSame($connectionDefault, $connectionNotRedis);
Config::set('cache.type', 'complex');
$connectionRedis = Cache::store('redis');
$this->assertNotSame($connectionNotRedis, $connectionRedis);
$this->assertInstanceOf('\think\cache\driver\Redis', $connectionRedis);
// 即便成功切换到其他存储类型,也不影响原先的操作句柄
$this->assertSame($connectionDefault, Cache::store());
}
public function testHas()
{
$key = $this->buildTestKey('Has');
$this->assertFalse(Cache::has($key));
Cache::set($key, 5);
$this->assertTrue(Cache::has($key));
}
public function testGet()
{
$key = $this->buildTestKey('Get');
$this->assertFalse(Cache::get($key));
$this->assertEquals('default', Cache::get($key, 'default'));
Cache::set($key, 5);
$this->assertSame(5, Cache::get($key));
}
public function testSet()
{
$key = $this->buildTestKey('Set');
$this->assertTrue(Cache::set(null, null));
$this->assertTrue(Cache::set($key, 'ThinkPHP3.2'));
$this->assertTrue(Cache::set($key, 'ThinkPHP5.0', null));
$this->assertTrue(Cache::set($key, 'ThinkPHP5.0', -1));
$this->assertTrue(Cache::set($key, 'ThinkPHP5.0', 0));
$this->assertTrue(Cache::set($key, 'ThinkPHP5.0', 7200));
}
public function testInc()
{
$key = $this->buildTestKey('Inc');
Cache::inc($key);
$this->assertEquals(1, Cache::get($key));
Cache::inc($key, '2');
$this->assertEquals(3, Cache::get($key));
Cache::inc($key, -1);
$this->assertEquals(2, Cache::get($key));
Cache::inc($key, null);
$this->assertEquals(2, Cache::get($key));
Cache::inc($key, true);
$this->assertEquals(3, Cache::get($key));
Cache::inc($key, false);
$this->assertEquals(3, Cache::get($key));
Cache::inc($key, 0.789);
$this->assertEquals(3.789, Cache::get($key));
}
public function testDec()
{
$key = $this->buildTestKey('Dec');
Cache::dec($key);
$this->assertEquals(-1, Cache::get($key));
Cache::dec($key, '2');
$this->assertEquals(-3, Cache::get($key));
Cache::dec($key, -1);
$this->assertEquals(-2, Cache::get($key));
Cache::dec($key, null);
$this->assertEquals(-2, Cache::get($key));
Cache::dec($key, true);
$this->assertEquals(-3, Cache::get($key));
Cache::dec($key, false);
$this->assertEquals(-3, Cache::get($key));
Cache::dec($key, 0.359);
$this->assertEquals(-3.359, Cache::get($key));
}
public function testRm()
{
$key = $this->buildTestKey('Rm');
$this->assertFalse(Cache::rm($key));
Cache::set($key, 'ThinkPHP');
$this->assertTrue(Cache::rm($key));
}
public function testClear()
{
$key1 = $this->buildTestKey('Clear1');
$key2 = $this->buildTestKey('Clear2');
Cache::set($key1, 'ThinkPHP3.2');
Cache::set($key2, 'ThinkPHP5.0');
$this->assertEquals('ThinkPHP3.2', Cache::get($key1));
$this->assertEquals('ThinkPHP5.0', Cache::get($key2));
Cache::clear();
$this->assertFalse(Cache::get($key1));
$this->assertFalse(Cache::get($key2));
}
public function testPull()
{
$key = $this->buildTestKey('Pull');
$this->assertNull(Cache::pull($key));
Cache::set($key, 'ThinkPHP');
$this->assertEquals('ThinkPHP', Cache::pull($key));
$this->assertFalse(Cache::get($key));
}
public function testRemember()
{
$key1 = $this->buildTestKey('Remember1');
$key2 = $this->buildTestKey('Remember2');
$this->assertEquals('ThinkPHP3.2', Cache::remember($key1, 'ThinkPHP3.2'));
$this->assertEquals('ThinkPHP3.2', Cache::remember($key1, 'ThinkPHP5.0'));
$this->assertEquals('ThinkPHP5.0', Cache::remember($key2, function () {
return 'ThinkPHP5.0';
}));
$this->assertEquals('ThinkPHP5.0', Cache::remember($key2, function () {
return 'ThinkPHP3.2';
}));
}
public function testTag()
{
$key = $this->buildTestKey('Tag');
$cacheTagWithoutName = Cache::tag(null);
$this->assertInstanceOf('think\cache\Driver', $cacheTagWithoutName);
$cacheTagWithKey = Cache::tag($key, [1, 2, 3]);
$this->assertSame($cacheTagWithoutName, $cacheTagWithKey);
}
protected function getPropertyVal($name)
{
static $reflectionClass;
if (empty($reflectionClass)) {
$reflectionClass = new \ReflectionClass('\think\Cache');
}
$property = $reflectionClass->getProperty($name);
$property->setAccessible(true);
return $property->getValue();
}
public function provideTestConnect()
{
$provideData = [];
$options = ['type' => null];
$expected = '\think\cache\driver\File';
$provideData[] = [$options, $expected];
$options = ['type' => 'File'];
$expected = '\think\cache\driver\File';
$provideData[] = [$options, $expected];
$options = ['type' => 'Lite'];
$expected = '\think\cache\driver\Lite';
$provideData[] = [$options, $expected];
$options = ['type' => 'Memcached'];
$expected = '\think\cache\driver\Memcached';
$provideData[] = [$options, $expected];
$options = ['type' => 'Redis'];
$expected = '\think\cache\driver\Redis';
$provideData[] = [$options, $expected];
// TODO
// $options = ['type' => 'Memcache'];
// $expected = '\think\cache\driver\Memcache';
// $provideData[] = [$options, $expected];
//
// $options = ['type' => 'Wincache'];
// $expected = '\think\cache\driver\Wincache';
// $provideData[] = [$options, $expected];
// $options = ['type' => 'Sqlite'];
// $expected = '\think\cache\driver\Sqlite';
// $provideData[] = [$options, $expected];
//
// $options = ['type' => 'Xcache'];
// $expected = '\think\cache\driver\Xcache';
// $provideData[] = [$options, $expected];
return $provideData;
}
public function provideTestInit()
{
$provideData = [];
$options = [];
$expected = '\think\cache\driver\File';
$provideData[] = [$options, $expected];
$options = ['type' => 'File'];
$expected = '\think\cache\driver\File';
$provideData[] = [$options, $expected];
$options = ['type' => 'Lite'];
$expected = '\think\cache\driver\Lite';
$provideData[] = [$options, $expected];
return $provideData;
}
protected function buildTestKey($tag)
{
return sprintf('ThinkPHP_Test_%s_%d_%d', $tag, time(), rand(0, 10000));
}
}

View File

@@ -0,0 +1,52 @@
<?php
/**
* 测试用例在使用Config时(如reset),可能会影响其他测试用例
* 此Trait在每次执行测试用例后会对Config进行还原
*/
namespace tests\thinkphp\library\think\config;
use think\Config;
trait ConfigInitTrait
{
/**
* @var \Closure
*/
protected static $internalConfigFoo;
/**
* @var \Closure
*/
protected static $internalRangeFoo;
/**
* @var mixed
*/
protected static $originConfig;
/**
* @var string
*/
protected static $originRange;
public static function setUpBeforeClass()
{
self::$internalConfigFoo = \Closure::bind(function ($value = null) {
return !is_null($value) ? Config::$config = $value : Config::$config;
}, null, '\\Think\\Config');
self::$internalRangeFoo = \Closure::bind(function ($value = null) {
return !is_null($value) ? Config::$range = $value : Config::$range;
}, null, '\\Think\\Config');
self::$originConfig = call_user_func(self::$internalConfigFoo);
self::$originRange = call_user_func(self::$internalRangeFoo);
}
public function tearDown()
{
call_user_func(self::$internalConfigFoo, self::$originConfig);
call_user_func(self::$internalRangeFoo, self::$originRange);
}
}

View File

@@ -0,0 +1 @@
inifile=1

View File

@@ -0,0 +1 @@
{"jsonstring":1}

View File

@@ -0,0 +1,6 @@
<?xml version="1.0"?>
<document>
<xmlfile>
<istrue>1</istrue>
</xmlfile>
</document>

View File

@@ -0,0 +1,36 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
/**
* Ini配置测试
* @author 7IN0SAN9 <me@7in0.me>
*/
namespace tests\thinkphp\library\think\config\driver;
use tests\thinkphp\library\think\config\ConfigInitTrait;
use think\config;
class iniTest extends \PHPUnit_Framework_TestCase
{
use ConfigInitTrait;
public function testParse()
{
Config::parse('inistring=1', 'ini');
$this->assertEquals(1, Config::get('inistring'));
Config::reset();
Config::parse(__DIR__ . '/fixtures/config.ini');
$this->assertTrue(Config::has('inifile'));
$this->assertEquals(1, Config::get('inifile'));
Config::reset();
}
}

View File

@@ -0,0 +1,36 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
/**
* Xml配置测试
* @author 7IN0SAN9 <me@7in0.me>
*/
namespace tests\thinkphp\library\think\config\driver;
use tests\thinkphp\library\think\config\ConfigInitTrait;
use think\config;
class jsonTest extends \PHPUnit_Framework_TestCase
{
use ConfigInitTrait;
public function testParse()
{
Config::parse('{"jsonstring":1}', 'json');
$this->assertEquals(1, Config::get('jsonstring'));
Config::reset();
Config::parse(__DIR__ . '/fixtures/config.json');
$this->assertTrue(Config::has('jsonstring'));
$this->assertEquals(1, Config::get('jsonstring'));
Config::reset();
}
}

View File

@@ -0,0 +1,36 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
/**
* Xml配置测试
* @author 7IN0SAN9 <me@7in0.me>
*/
namespace tests\thinkphp\library\think\config\driver;
use tests\thinkphp\library\think\config\ConfigInitTrait;
use think\config;
class xmlTest extends \PHPUnit_Framework_TestCase
{
use ConfigInitTrait;
public function testParse()
{
Config::parse('<?xml version="1.0"?><document><xmlstring>1</xmlstring></document>', 'xml');
$this->assertEquals(1, Config::get('xmlstring'));
Config::reset();
Config::parse(__DIR__ . '/fixtures/config.xml');
$this->assertTrue(Config::has('xmlfile.istrue'));
$this->assertEquals(1, Config::get('xmlfile.istrue'));
Config::reset();
}
}

View File

@@ -0,0 +1,149 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
/**
* 配置测试
* @author Haotong Lin <lofanmi@gmail.com>
*/
namespace tests\thinkphp\library\think;
use tests\thinkphp\library\think\config\ConfigInitTrait;
use think\Config;
class configTest extends \PHPUnit_Framework_TestCase
{
use ConfigInitTrait;
public function testRange()
{
// test default range
$this->assertEquals('_sys_', call_user_func(self::$internalRangeFoo));
$this->assertTrue(is_array(call_user_func(self::$internalConfigFoo)));
// test range initialization
Config::range('_test_');
$this->assertEquals('_test_', call_user_func(self::$internalRangeFoo));
$this->assertEquals([], call_user_func(self::$internalConfigFoo)['_test_']);
}
// public function testParse()
// {
// see \think\config\driver\...Test.php
// }
public function testLoad()
{
$file = APP_PATH . 'config' . EXT;
$config = array_change_key_case(include $file);
$name = '_name_';
$range = '_test_';
$this->assertEquals($config, Config::load($file, $name, $range));
$this->assertNotEquals(null, Config::load($file, $name, $range));
}
public function testHas()
{
$range = '_test_';
$this->assertFalse(Config::has('abcd', $range));
call_user_func(self::$internalConfigFoo, [
$range => ['abcd' => 'value'],
]);
$this->assertTrue(Config::has('abcd', $range));
// else ...
$this->assertFalse(Config::has('abcd.efg', $range));
call_user_func(self::$internalConfigFoo, [
$range => ['abcd' => ['efg' => 'value']],
]);
$this->assertTrue(Config::has('abcd.efg', $range));
}
public function testGet()
{
$range = '_test_';
call_user_func(self::$internalConfigFoo, [
$range => []
]);
$this->assertEquals([], Config::get(null, $range));
$this->assertEquals(null, Config::get(null, 'does_not_exist'));
$value = 'value';
// test getting configuration
call_user_func(self::$internalConfigFoo, [
$range => ['abcd' => 'efg']
]);
$this->assertEquals('efg', Config::get('abcd', $range));
$this->assertEquals(null, Config::get('does_not_exist', $range));
$this->assertEquals(null, Config::get('abcd', 'does_not_exist'));
// test getting configuration with dot syntax
call_user_func(self::$internalConfigFoo, [
$range => ['one' => ['two' => $value]]
]);
$this->assertEquals($value, Config::get('one.two', $range));
$this->assertEquals(null, Config::get('one.does_not_exist', $range));
$this->assertEquals(null, Config::get('one.two', 'does_not_exist'));
}
public function testSet()
{
$range = '_test_';
// without dot syntax
$name = 'name';
$value = 'value';
Config::set($name, $value, $range);
$config = call_user_func(self::$internalConfigFoo);
$this->assertEquals($value, $config[$range][$name]);
// with dot syntax
$name = 'one.two';
$value = 'dot value';
Config::set($name, $value, $range);
$config = call_user_func(self::$internalConfigFoo);
$this->assertEquals($value, $config[$range]['one']['two']);
// if (is_array($name)):
// see testLoad()
// ...
// test getting all configurations...?
// return self::$config[$range]; ??
$value = ['all' => 'configuration'];
call_user_func(self::$internalConfigFoo, [$range => $value]);
$this->assertEquals($value, Config::set(null, null, $range));
$this->assertNotEquals(null, Config::set(null, null, $range));
}
public function testReset()
{
$range = '_test_';
call_user_func(self::$internalConfigFoo, [$range => ['abcd' => 'efg']]);
// clear all configurations
Config::reset(true);
$config = call_user_func(self::$internalConfigFoo);
$this->assertEquals([], $config);
// clear the configuration in range of parameter.
call_user_func(self::$internalConfigFoo, [
$range => [
'abcd' => 'efg',
'hijk' => 'lmn',
],
'a' => 'b',
]);
Config::reset($range);
$config = call_user_func(self::$internalConfigFoo);
$this->assertEquals([
$range => [],
'a' => 'b',
], $config);
}
}

View File

@@ -0,0 +1,2 @@
*
!.gitignore

View File

@@ -0,0 +1,194 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
/**
* 控制器测试
* @author Haotong Lin <lofanmi@gmail.com>
*/
namespace tests\thinkphp\library\think;
use ReflectionClass;
use think\Controller;
use think\Request;
use think\View;
require_once CORE_PATH . '../../helper.php';
class Foo extends Controller
{
public $test = 'test';
public function _initialize()
{
$this->test = 'abcd';
}
public function assignTest()
{
$this->assign('abcd', 'dcba');
$this->assign(['key1' => 'value1', 'key2' => 'value2']);
}
public function fetchTest()
{
$template = APP_PATH . 'views' . DS .'display.html';
return $this->fetch($template, ['name' => 'ThinkPHP']);
}
public function displayTest()
{
$template = APP_PATH . 'views' . DS .'display.html';
return $this->display($template, ['name' => 'ThinkPHP']);
}
public function test()
{
$data = [
'username' => 'username',
'nickname' => 'nickname',
'password' => '123456',
'repassword' => '123456',
'email' => 'abc@abc.com',
'sex' => '0',
'age' => '20',
'code' => '1234',
];
$validate = [
['username', 'length:5,15', '用户名长度为5到15个字符'],
['nickname', 'require', '请填昵称'],
['password', '[\w-]{6,15}', '密码长度为6到15个字符'],
['repassword', 'confirm:password', '两次密码不一到致'],
['email', 'filter:validate_email', '邮箱格式错误'],
['sex', 'in:0,1', '性别只能为为男或女'],
['age', 'between:1,80', '年龄只能在10-80之间'],
];
return $this->validate($data, $validate);
}
}
class Bar extends Controller
{
public $test = 1;
public $beforeActionList = ['action1', 'action2'];
public function action1()
{
$this->test += 2;
return 'action1';
}
public function action2()
{
$this->test += 4;
return 'action2';
}
}
class Baz extends Controller
{
public $test = 1;
public $beforeActionList = [
'action1' => ['only' => 'index'],
'action2' => ['except' => 'index'],
'action3' => ['only' => 'abcd'],
'action4' => ['except' => 'abcd'],
];
public function action1()
{
$this->test += 2;
return 'action1';
}
public function action2()
{
$this->test += 4;
return 'action2';
}
public function action3()
{
$this->test += 8;
return 'action2';
}
public function action4()
{
$this->test += 16;
return 'action2';
}
}
class controllerTest extends \PHPUnit_Framework_TestCase
{
public function testInitialize()
{
$foo = new Foo(Request::instance());
$this->assertEquals('abcd', $foo->test);
}
public function testBeforeAction()
{
$obj = new Bar(Request::instance());
$this->assertEquals(7, $obj->test);
$obj = new Baz(Request::instance());
$this->assertEquals(19, $obj->test);
}
private function getView($controller)
{
$view = new View();
$rc = new ReflectionClass(get_class($controller));
$property = $rc->getProperty('view');
$property->setAccessible(true);
$property->setValue($controller, $view);
return $view;
}
public function testFetch()
{
$controller = new Foo(Request::instance());
$view = $this->getView($controller);
$template = APP_PATH . 'views' . DS .'display.html';
$viewFetch = $view->fetch($template, ['name' => 'ThinkPHP']);
$this->assertEquals($controller->fetchTest(), $viewFetch);
}
public function testDisplay()
{
$controller = new Foo;
$view = $this->getView($controller);
$template = APP_PATH . 'views' . DS .'display.html';
$viewFetch = $view->display($template, ['name' => 'ThinkPHP']);
$this->assertEquals($controller->displayTest(), $viewFetch);
}
public function testAssign()
{
$controller = new Foo(Request::instance());
$view = $this->getView($controller);
$controller->assignTest();
$expect = ['abcd' => 'dcba', 'key1' => 'value1', 'key2' => 'value2'];
$this->assertAttributeEquals($expect, 'data', $view);
}
public function testValidate()
{
$controller = new Foo(Request::instance());
$result = $controller->test();
$this->assertTrue($result);
}
}

View File

@@ -0,0 +1,150 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
/**
* Cookie测试
* @author Haotong Lin <lofanmi@gmail.com>
*/
namespace tests\thinkphp\library\think;
use ReflectionClass;
use think\Cookie;
class cookieTest extends \PHPUnit_Framework_TestCase
{
protected $ref;
protected $default = [
// cookie 名称前缀
'prefix' => '',
// cookie 保存时间
'expire' => 0,
// cookie 保存路径
'path' => '/',
// cookie 有效域名
'domain' => '',
// cookie 启用安全传输
'secure' => false,
// httponly设置
'httponly' => '',
// 是否使用 setcookie
'setcookie' => false,
];
protected function setUp()
{
$reflectedClass = new ReflectionClass('\think\Cookie');
$reflectedPropertyConfig = $reflectedClass->getProperty('config');
$reflectedPropertyConfig->setAccessible(true);
$reflectedPropertyConfig->setValue($this->default);
$this->ref = $reflectedPropertyConfig;
}
public function testInit()
{
$config = [
// cookie 名称前缀
'prefix' => 'think_',
// cookie 保存时间
'expire' => 0,
// cookie 保存路径
'path' => '/path/to/test/',
// cookie 有效域名
'domain' => '.thinkphp.cn',
// cookie 启用安全传输
'secure' => true,
// httponly设置
'httponly' => '1',
];
Cookie::init($config);
$this->assertEquals(
array_merge($this->default, array_change_key_case($config)),
$this->ref->getValue()
);
}
public function testPrefix()
{
$this->assertEquals($this->default['prefix'], Cookie::prefix());
$prefix = '_test_';
$this->assertNotEquals($prefix, Cookie::prefix());
Cookie::prefix($prefix);
$config = $this->ref->getValue();
$this->assertEquals($prefix, $config['prefix']);
}
public function testSet()
{
$value = 'value';
$name = 'name1';
Cookie::set($name, $value, 10);
$this->assertEquals($value, $_COOKIE[$this->default['prefix'] . $name]);
$name = 'name2';
Cookie::set($name, $value, null);
$this->assertEquals($value, $_COOKIE[$this->default['prefix'] . $name]);
$name = 'name3';
Cookie::set($name, $value, 'expire=100&prefix=pre_');
$this->assertEquals($value, $_COOKIE['pre_' . $name]);
$name = 'name4';
$value = ['_test_中文_'];
Cookie::set($name, $value);
$this->assertEquals('think:' . json_encode([urlencode('_test_中文_')]), $_COOKIE[$name]);
}
public function testGet()
{
$_COOKIE = [
'a' => 'b',
'pre_abc' => 'c',
'd' => 'think:' . json_encode([urlencode('_test_中文_')]),
];
$this->assertEquals('b', Cookie::get('a'));
$this->assertEquals(null, Cookie::get('does_not_exist'));
$this->assertEquals('c', Cookie::get('abc', 'pre_'));
$this->assertEquals(['_test_中文_'], Cookie::get('d'));
}
public function testDelete()
{
$_COOKIE = [
'a' => 'b',
'pre_abc' => 'c',
];
$this->assertEquals('b', Cookie::get('a'));
Cookie::delete('a');
$this->assertEquals(null, Cookie::get('a'));
$this->assertEquals('c', Cookie::get('abc', 'pre_'));
Cookie::delete('abc', 'pre_');
$this->assertEquals(null, Cookie::get('abc', 'pre_'));
}
public function testClear()
{
$_COOKIE = [];
$this->assertEquals(null, Cookie::clear());
$_COOKIE = [
'a' => 'b',
'pre_abc' => 'c',
];
Cookie::clear('pre_');
$this->assertEquals(['a' => 'b'], $_COOKIE);
}
}

View File

@@ -0,0 +1,2 @@
*
!.gitignore

View File

@@ -0,0 +1,352 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
/**
* Db类测试
* @author: 刘志淳 <chun@engineer.com>
*/
namespace tests\thinkphp\library\think;
use think\Db;
class dbTest extends \PHPUnit_Framework_TestCase
{
// 获取测试数据库配置
private function getConfig()
{
return [
// 数据库类型
'type' => 'mysql',
// 服务器地址
'hostname' => '127.0.0.1',
// 数据库名
'database' => 'test',
// 用户名
'username' => 'root',
// 密码
'password' => '',
// 端口
'hostport' => '',
// 连接dsn
'dsn' => '',
// 数据库连接参数
'params' => [],
// 数据库编码默认采用utf8
'charset' => 'utf8',
// 数据库表前缀
'prefix' => 'tp_',
// 数据库调试模式
'debug' => true,
// 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
'deploy' => 0,
// 数据库读写是否分离 主从式有效
'rw_separate' => false,
// 读写分离后 主服务器数量
'master_num' => 1,
// 指定从服务器序号
'slave_no' => '',
// 是否严格检查字段是否存在
'fields_strict' => true,
// 数据集返回类型 array 数组 collection Collection对象
'resultset_type' => 'array',
// 是否自动写入时间戳字段
'auto_timestamp' => false,
// 是否需要进行SQL性能分析
'sql_explain' => false,
];
}
// 获取创建数据库 SQL
private function getCreateTableSql()
{
$sql[] = <<<EOF
DROP TABLE IF EXISTS `tp_user`;
EOF;
$sql[] = <<<EOF
CREATE TABLE `tp_user` (
`id` int(10) unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT,
`username` char(40) NOT NULL DEFAULT '' COMMENT '用户名',
`password` char(40) NOT NULL DEFAULT '' COMMENT '密码',
`status` tinyint(1) NOT NULL DEFAULT '0' COMMENT '状态',
`create_time` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '创建时间'
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='会员表';
EOF;
$sql[] = <<<EOF
ALTER TABLE `tp_user` ADD INDEX(`create_time`);
EOF;
$sql[] = <<<EOF
DROP TABLE IF EXISTS `tp_order`;
EOF;
$sql[] = <<<EOF
CREATE TABLE `tp_order` (
`id` int(10) unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT,
`user_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '用户id',
`sn` char(20) NOT NULL DEFAULT '' COMMENT '订单号',
`amount` decimal(10,2) unsigned NOT NULL DEFAULT '0' COMMENT '金额',
`freight_fee` decimal(10,2) unsigned NOT NULL DEFAULT '0' COMMENT '运费',
`address_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '地址id',
`status` tinyint(1) NOT NULL DEFAULT '0' COMMENT '状态',
`create_time` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '创建时间'
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='订单表';
EOF;
$sql[] = <<<EOF
DROP TABLE IF EXISTS `tp_user_address`;
EOF;
$sql[] = <<<EOF
CREATE TABLE `tp_user_address` (
`id` int(10) unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT,
`user_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '用户id',
`consignee` varchar(60) NOT NULL DEFAULT '' COMMENT '收货人',
`area_info` varchar(50) NOT NULL DEFAULT '' COMMENT '地区信息',
`city_id` smallint(5) unsigned NOT NULL DEFAULT '0' COMMENT '城市id',
`area_id` smallint(5) unsigned NOT NULL DEFAULT '0' COMMENT '地区id',
`address` varchar(120) NOT NULL DEFAULT '' COMMENT '地址',
`tel` varchar(60) NOT NULL DEFAULT '' COMMENT '电话',
`mobile` varchar(60) NOT NULL DEFAULT '' COMMENT '手机',
`isdefault` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '是否默认'
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='地址表';
EOF;
$sql[] = <<<EOF
DROP TABLE IF EXISTS `tp_role_user`;
EOF;
$sql[] = <<<EOF
CREATE TABLE `tp_role_user` (
`role_id` smallint(5) unsigned NOT NULL,
`user_id` int(10) unsigned NOT NULL,
`remark` varchar(250) NOT NULL DEFAULT '',
PRIMARY KEY (`role_id`,`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
EOF;
return $sql;
}
public function testConnect()
{
$config = $this->getConfig();
$result = Db::connect($config)->execute('show databases');
$this->assertNotEmpty($result);
}
public function testExecute()
{
$config = $this->getConfig();
$sql = $this->getCreateTableSql();
foreach ($sql as $one) {
Db::connect($config)->execute($one);
}
$tableNum = Db::connect($config)->execute("show tables;");
$this->assertEquals(4, $tableNum);
}
public function testQuery()
{
$config = $this->getConfig();
$sql = $this->getCreateTableSql();
Db::connect($config)->batchQuery($sql);
$tableQueryResult = Db::connect($config)->query("show tables;");
$this->assertTrue(is_array($tableQueryResult));
$tableNum = count($tableQueryResult);
$this->assertEquals(4, $tableNum);
}
public function testBatchQuery()
{
$config = $this->getConfig();
$sql = $this->getCreateTableSql();
Db::connect($config)->batchQuery($sql);
$tableNum = Db::connect($config)->execute("show tables;");
$this->assertEquals(4, $tableNum);
}
public function testTable()
{
$config = $this->getConfig();
$tableName = 'tp_user';
$result = Db::connect($config)->table($tableName);
$this->assertEquals($tableName, $result->getOptions()['table']);
}
public function testName()
{
$config = $this->getConfig();
$tableName = 'user';
$result = Db::connect($config)->name($tableName);
$this->assertEquals($config['prefix'] . $tableName, $result->getTable());
}
public function testInsert()
{
$config = $this->getConfig();
$data = [
'username' => 'chunice',
'password' => md5('chunice'),
'status' => 1,
'create_time' => time(),
];
$result = Db::connect($config)->name('user')->insert($data);
$this->assertEquals(1, $result);
}
public function testUpdate()
{
$config = $this->getConfig();
$data = [
'username' => 'chunice_update',
'password' => md5('chunice'),
'status' => 1,
'create_time' => time(),
];
$result = Db::connect($config)->name('user')->where('username', 'chunice')->update($data);
$this->assertEquals(1, $result);
}
public function testFind()
{
$config = $this->getConfig();
$mustFind = Db::connect($config)->name('user')->where('username', 'chunice_update')->find();
$this->assertNotEmpty($mustFind);
$mustNotFind = Db::connect($config)->name('user')->where('username', 'chunice')->find();
$this->assertEmpty($mustNotFind);
}
public function testInsertAll()
{
$config = $this->getConfig();
$data = [
['username' => 'foo', 'password' => md5('foo'), 'status' => 1, 'create_time' => time()],
['username' => 'bar', 'password' => md5('bar'), 'status' => 1, 'create_time' => time()],
];
$insertNum = Db::connect($config)->name('user')->insertAll($data);
$this->assertEquals(count($data), $insertNum);
}
public function testSelect()
{
$config = $this->getConfig();
$mustFound = Db::connect($config)->name('user')->where('status', 1)->select();
$this->assertNotEmpty($mustFound);
$mustNotFound = Db::connect($config)->name('user')->where('status', 0)->select();
$this->assertEmpty($mustNotFound);
}
public function testValue()
{
$config = $this->getConfig();
$username = Db::connect($config)->name('user')->where('id', 1)->value('username');
$this->assertEquals('chunice_update', $username);
$usernameNull = Db::connect($config)->name('user')->where('id', 0)->value('username');
$this->assertEmpty($usernameNull);
}
public function testColumn()
{
$config = $this->getConfig();
$username = Db::connect($config)->name('user')->where('status', 1)->column('username');
$this->assertNotEmpty($username);
$usernameNull = Db::connect($config)->name('user')->where('status', 0)->column('username');
$this->assertEmpty($usernameNull);
}
public function testInsertGetId()
{
$config = $this->getConfig();
$id = Db::connect($config)->name('user')->order('id', 'desc')->value('id');
$data = [
'username' => uniqid(),
'password' => md5('chunice'),
'status' => 1,
'create_time' => time(),
];
$lastId = Db::connect($config)->name('user')->insertGetId($data);
$this->assertEquals($id + 1, $lastId);
}
public function testGetLastInsId()
{
$config = $this->getConfig();
$data = [
'username' => uniqid(),
'password' => md5('chunice'),
'status' => 1,
'create_time' => time(),
];
$lastId = Db::connect($config)->name('user')->insertGetId($data);
$lastInsId = Db::connect($config)->name('user')->getLastInsID();
$this->assertEquals($lastId, $lastInsId);
}
public function testSetField()
{
$config = $this->getConfig();
$setFieldNum = Db::connect($config)->name('user')->where('id', 1)->setField('username', 'chunice_setField');
$this->assertEquals(1, $setFieldNum);
$setFieldNum = Db::connect($config)->name('user')->where('id', 1)->setField('username', 'chunice_setField');
$this->assertEquals(0, $setFieldNum);
}
public function testSetInc()
{
$config = $this->getConfig();
$originCreateTime = Db::connect($config)->name('user')->where('id', 1)->value('create_time');
Db::connect($config)->name('user')->where('id', 1)->setInc('create_time');
$newCreateTime = Db::connect($config)->name('user')->where('id', 1)->value('create_time');
$this->assertEquals($originCreateTime + 1, $newCreateTime);
}
public function testSetDec()
{
$config = $this->getConfig();
$originCreateTime = Db::connect($config)->name('user')->where('id', 1)->value('create_time');
Db::connect($config)->name('user')->where('id', 1)->setDec('create_time');
$newCreateTime = Db::connect($config)->name('user')->where('id', 1)->value('create_time');
$this->assertEquals($originCreateTime - 1, $newCreateTime);
}
public function testDelete()
{
$config = $this->getConfig();
Db::connect($config)->name('user')->where('id', 1)->delete();
$result = Db::connect($config)->name('user')->where('id', 1)->find();
$this->assertEmpty($result);
}
public function testChunk()
{
// todo 暂未想到测试方法
}
public function testCache()
{
$config = $this->getConfig();
$result = Db::connect($config)->name('user')->where('id', 1)->cache('key', 60)->find();
$cache = \think\Cache::get('key');
$this->assertEquals($result, $cache);
$updateCache = Db::connect($config)->name('user')->cache('key')->find(1);
$this->assertEquals($cache, $updateCache);
}
}

View File

@@ -0,0 +1,220 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
/**
* Debug测试
* @author 大漠 <zhylninc@gmail.com>
*/
namespace tests\thinkphp\library\think;
use tests\thinkphp\library\think\config\ConfigInitTrait;
use think\Config;
use think\Debug;
use think\Response;
use think\response\Redirect;
class debugTest extends \PHPUnit_Framework_TestCase
{
use ConfigInitTrait;
/**
*
* @var Debug
*/
protected $object;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
{
$this->object = new Debug();
}
/**
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*/
protected function tearDown()
{}
/**
* @covers \think\Debug::remark
* @todo Implement testRemark().
*/
public function testRemark()
{
$name = "testremarkkey";
Debug::remark($name);
}
/**
* @covers \think\Debug::getRangeTime
* @todo Implement testGetRangeTime().
*/
public function testGetRangeTime()
{
$start = "testGetRangeTimeStart";
$end = "testGetRangeTimeEnd";
Debug::remark($start);
usleep(20000);
// \think\Debug::remark($end);
$time = Debug::getRangeTime($start, $end);
$this->assertLessThan(0.03, $time);
//$this->assertEquals(0.03, ceil($time));
}
/**
* @covers \think\Debug::getUseTime
* @todo Implement testGetUseTime().
*/
public function testGetUseTime()
{
$time = Debug::getUseTime();
$this->assertLessThan(30, $time);
}
/**
* @covers \think\Debug::getThroughputRate
* @todo Implement testGetThroughputRate().
*/
public function testGetThroughputRate()
{
usleep(100000);
$throughputRate = Debug::getThroughputRate();
$this->assertLessThan(10, $throughputRate);
}
/**
* @covers \think\Debug::getRangeMem
* @todo Implement testGetRangeMem().
*/
public function testGetRangeMem()
{
$start = "testGetRangeMemStart";
$end = "testGetRangeMemEnd";
Debug::remark($start);
$str = "";
for ($i = 0; $i < 10000; $i++) {
$str .= "mem";
}
$rangeMem = Debug::getRangeMem($start, $end);
$this->assertLessThan(33, explode(" ", $rangeMem)[0]);
}
/**
* @covers \think\Debug::getUseMem
* @todo Implement testGetUseMem().
*/
public function testGetUseMem()
{
$useMem = Debug::getUseMem();
$this->assertLessThan(35, explode(" ", $useMem)[0]);
}
/**
* @covers \think\Debug::getMemPeak
* @todo Implement testGetMemPeak().
*/
public function testGetMemPeak()
{
$start = "testGetMemPeakStart";
$end = "testGetMemPeakEnd";
Debug::remark($start);
$str = "";
for ($i = 0; $i < 100000; $i++) {
$str .= "mem";
}
$memPeak = Debug::getMemPeak($start, $end);
$this->assertLessThan(500, explode(" ", $memPeak)[0]);
}
/**
* @covers \think\Debug::getFile
* @todo Implement testGetFile().
*/
public function testGetFile()
{
$count = Debug::getFile();
$this->assertEquals(count(get_included_files()), $count);
$info = Debug::getFile(true);
$this->assertEquals(count(get_included_files()), count($info));
$this->assertContains("KB", $info[0]);
}
/**
* @covers \think\Debug::dump
* @todo Implement testDump().
*/
public function testDump()
{
if (strstr(PHP_VERSION, 'hhvm')) {
return;
}
$var = [];
$var["key"] = "val";
$output = Debug::dump($var, false, $label = "label");
$array = explode("array", json_encode($output));
if (IS_WIN) {
$this->assertEquals("(1) {\\n [\\\"key\\\"] => string(3) \\\"val\\\"\\n}\\n\\r\\n\"", end($array));
} elseif (strstr(PHP_OS, 'Darwin')) {
$this->assertEquals("(1) {\\n [\\\"key\\\"] => string(3) \\\"val\\\"\\n}\\n\\n\"", end($array));
} else {
$this->assertEquals("(1) {\\n 'key' =>\\n string(3) \\\"val\\\"\\n}\\n\\n\"", end($array));
}
}
/**
* @expectedException \think\exception\ClassNotFoundException
*/
public function testInjectWithErrorType()
{
Config::set('trace', ['type' => 'NullDebug']);
$response = new Response();
$context = 'TestWithErrorType';
Debug::inject($response, $context);
}
public function testInject()
{
Config::set('trace', ['type' => 'Console']);
$response = new Response();
$context = 'TestWithoutBodyTag';
Debug::inject($response, $context);
$this->assertNotEquals('TestWithoutBodyTag', $context);
$this->assertStringStartsWith('TestWithoutBodyTag', $context);
$response = new Response();
$context = '<body></body>';
Debug::inject($response, $context);
$this->assertNotEquals('<body></body>', $context);
$this->assertStringStartsWith('<body>', $context);
$this->assertStringEndsWith('</body>', $context);
$response = new Redirect();
$context = '<body></body>';
Debug::inject($response, $context);
$this->assertEquals('<body></body>', $context);
}
}

View File

@@ -0,0 +1,52 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
/**
* exception类测试
* @author Haotong Lin <lofanmi@gmail.com>
*/
namespace tests\thinkphp\library\think;
use ReflectionMethod;
use think\Exception as ThinkException;
use think\exception\HttpException;
class MyException extends ThinkException
{
}
class exceptionTest extends \PHPUnit_Framework_TestCase
{
public function testGetHttpStatus()
{
try {
throw new HttpException(404, "Error Processing Request");
} catch (HttpException $e) {
$this->assertEquals(404, $e->getStatusCode());
}
}
public function testDebugData()
{
$data = ['a' => 'b', 'c' => 'd'];
try {
$e = new MyException("Error Processing Request", 1);
$method = new ReflectionMethod($e, 'setData');
$method->setAccessible(true);
$method->invokeArgs($e, ['test', $data]);
throw $e;
} catch (MyException $e) {
$this->assertEquals(['test' => $data], $e->getData());
}
}
}

View File

@@ -0,0 +1,67 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
/**
* Hook类测试
* @author liu21st <liu21st@gmail.com>
*/
namespace tests\thinkphp\library\think;
use think\Hook;
class hookTest extends \PHPUnit_Framework_TestCase
{
public function testRun()
{
Hook::add('my_pos', '\tests\thinkphp\library\think\behavior\One');
Hook::add('my_pos', ['\tests\thinkphp\library\think\behavior\Two']);
Hook::add('my_pos', '\tests\thinkphp\library\think\behavior\Three', true);
$data['id'] = 0;
$data['name'] = 'thinkphp';
Hook::listen('my_pos', $data);
$this->assertEquals(2, $data['id']);
$this->assertEquals('thinkphp', $data['name']);
$this->assertEquals([
'\tests\thinkphp\library\think\behavior\Three',
'\tests\thinkphp\library\think\behavior\One',
'\tests\thinkphp\library\think\behavior\Two'],
Hook::get('my_pos'));
}
public function testImport()
{
Hook::import(['my_pos' => [
'\tests\thinkphp\library\think\behavior\One',
'\tests\thinkphp\library\think\behavior\Three'],
]);
Hook::import(['my_pos' => ['\tests\thinkphp\library\think\behavior\Two']], false);
Hook::import(['my_pos' => ['\tests\thinkphp\library\think\behavior\Three', '_overlay' => true]]);
$data['id'] = 0;
$data['name'] = 'thinkphp';
Hook::listen('my_pos', $data);
$this->assertEquals(3, $data['id']);
}
public function testExec()
{
$data['id'] = 0;
$data['name'] = 'thinkphp';
$this->assertEquals(true, Hook::exec('\tests\thinkphp\library\think\behavior\One'));
$this->assertEquals(false, Hook::exec('\tests\thinkphp\library\think\behavior\One', 'test', $data));
$this->assertEquals('test', $data['name']);
$this->assertEquals('Closure', Hook::exec(function (&$data) {$data['name'] = 'Closure';return 'Closure';}));
}
}

View File

@@ -0,0 +1,4 @@
<?php
return [
'load'=>'加载',
];

View File

@@ -0,0 +1,76 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
/**
* Lang测试
* @author liu21st <liu21st@gmail.com>
*/
namespace tests\thinkphp\library\think;
use think\Config;
use think\Lang;
class langTest extends \PHPUnit_Framework_TestCase
{
public function testSetAndGet()
{
Lang::set('hello,%s', '欢迎,%s');
$this->assertEquals('欢迎,ThinkPHP', Lang::get('hello,%s', ['ThinkPHP']));
Lang::set('hello,%s', '歡迎,%s', 'zh-tw');
$this->assertEquals('歡迎,ThinkPHP', Lang::get('hello,%s', ['ThinkPHP'], 'zh-tw'));
Lang::set(['hello' => '欢迎', 'use' => '使用']);
$this->assertEquals('欢迎', Lang::get('hello'));
$this->assertEquals('欢迎', Lang::get('HELLO'));
$this->assertEquals('使用', Lang::get('use'));
Lang::set('hello,{:name}', '欢迎,{:name}');
$this->assertEquals('欢迎,liu21st', Lang::get('hello,{:name}', ['name' => 'liu21st']));
}
public function testLoad()
{
Lang::load(__DIR__ . DS . 'lang' . DS . 'lang.php');
$this->assertEquals('加载', Lang::get('load'));
Lang::load(__DIR__ . DS . 'lang' . DS . 'lang.php', 'test');
$this->assertEquals('加载', Lang::get('load', [], 'test'));
}
public function testDetect()
{
Config::set('lang_list', ['zh-cn', 'zh-tw']);
Lang::set('hello', '欢迎', 'zh-cn');
Lang::set('hello', '歡迎', 'zh-tw');
Config::set('lang_detect_var', 'lang');
Config::set('lang_cookie_var', 'think_cookie');
$_GET['lang'] = 'zh-tw';
Lang::detect();
$this->assertEquals('歡迎', Lang::get('hello'));
$_GET['lang'] = 'zh-cn';
Lang::detect();
$this->assertEquals('欢迎', Lang::get('hello'));
}
public function testRange()
{
$this->assertEquals('zh-cn', Lang::range());
Lang::set('hello', '欢迎', 'test');
Lang::range('test');
$this->assertEquals('test', Lang::range());
$this->assertEquals('欢迎', Lang::get('hello'));
}
}

View File

@@ -0,0 +1,7 @@
<?php
namespace top\test;
class Hello
{
}

View File

@@ -0,0 +1,71 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
/**
* Loader测试
* @author liu21st <liu21st@gmail.com>
*/
namespace tests\thinkphp\library\think;
use think\Loader;
class loaderTest extends \PHPUnit_Framework_TestCase
{
public function testAutoload()
{
$this->assertEquals(false, Loader::autoload('\think\Url'));
$this->assertEquals(false, Loader::autoload('think\Test'));
$this->assertEquals(false, Loader::autoload('my\HelloTest'));
}
public function testAddClassMap()
{
Loader::addClassMap('my\hello\Test', __DIR__ . DS . 'loader' . DS . 'Test.php');
}
public function testAddNamespace()
{
Loader::addNamespace('top', __DIR__ . DS . 'loader' . DS);
$this->assertEquals(true, Loader::autoload('top\test\Hello'));
}
public function testAddNamespaceAlias()
{
Loader::addNamespaceAlias('top', 'top\test');
Loader::addNamespaceAlias(['top' => 'top\test', 'app' => 'app\index']);
//$this->assertEquals(true, Loader::autoload('top\Hello'));
}
public function testTable()
{
Loader::db('mysql://root@127.0.0.1/test#utf8');
}
public function testImport()
{
$this->assertEquals(false, Loader::import('think.log.driver.MyTest'));
}
public function testParseName()
{
$this->assertEquals('HelloTest', Loader::parseName('hello_test', 1));
$this->assertEquals('hello_test', Loader::parseName('HelloTest', 0));
}
public function testParseClass()
{
$this->assertEquals('app\index\controller\User', Loader::parseClass('index', 'controller', 'user'));
$this->assertEquals('app\index\controller\user\Type', Loader::parseClass('index', 'controller', 'user.type'));
$this->assertEquals('app\admin\model\UserType', Loader::parseClass('admin', 'model', 'user_type'));
}
}

View File

@@ -0,0 +1,34 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
/**
* Test File Log
*/
namespace tests\thinkphp\library\think\log\driver;
use think\Log;
class fileTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
Log::init(['type' => 'file']);
}
public function testRecord()
{
$record_msg = 'record';
Log::record($record_msg, 'notice');
$logs = Log::getLog();
$this->assertEquals([], $logs);
}
}

View File

@@ -0,0 +1,39 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
/**
* Log测试
* @author liu21st <liu21st@gmail.com>
*/
namespace tests\thinkphp\library\think;
use think\Log;
class logTest extends \PHPUnit_Framework_TestCase
{
public function testSave()
{
Log::init(['type' => 'test']);
Log::clear();
Log::record('test');
Log::record([1, 2, 3]);
$this->assertTrue(Log::save());
}
public function testWrite()
{
Log::init(['type' => 'test']);
Log::clear();
$this->assertTrue(Log::write('hello', 'info'));
$this->assertTrue(Log::write([1, 2, 3], 'log'));
}
}

View File

@@ -0,0 +1,2 @@
*
!.gitignore

View File

@@ -0,0 +1,40 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: yunwuxin <448901948@qq.com>
// +----------------------------------------------------------------------
namespace tests\thinkphp\library\think;
use think\paginator\driver\Bootstrap;
class paginateTest extends \PHPUnit_Framework_TestCase
{
public function testPaginatorInfo()
{
$p = Bootstrap::make($array = ['item3', 'item4'], 2, 2, 4);
$this->assertEquals(4, $p->total());
$this->assertEquals(2, $p->listRows());
$this->assertEquals(2, $p->currentPage());
$p2 = Bootstrap::make($array2 = ['item3', 'item4'], 2, 2, 2);
$this->assertEquals(1, $p2->currentPage());
}
public function testPaginatorRender()
{
$p = Bootstrap::make($array = ['item3', 'item4'], 2, 2, 100);
$render = '<ul class="pagination"><li><a href="/?page=1">&laquo;</a></li> <li><a href="/?page=1">1</a></li><li class="active"><span>2</span></li><li><a href="/?page=3">3</a></li><li><a href="/?page=4">4</a></li><li><a href="/?page=5">5</a></li><li><a href="/?page=6">6</a></li><li><a href="/?page=7">7</a></li><li><a href="/?page=8">8</a></li><li class="disabled"><span>...</span></li><li><a href="/?page=49">49</a></li><li><a href="/?page=50">50</a></li> <li><a href="/?page=3">&raquo;</a></li></ul>';
$this->assertEquals($render, $p->render());
}
}

View File

@@ -0,0 +1,203 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
/**
* Db类测试
*/
namespace tests\thinkphp\library\think;
use think\Config;
use think\Request;
class requestTest extends \PHPUnit_Framework_TestCase
{
protected $request;
public function setUp()
{
//$request = Request::create('http://www.domain.com/index/index/hello/?name=thinkphp');
}
public function testCreate()
{
$request = Request::create('http://www.thinkphp.cn/index/index/hello.html?name=thinkphp');
$this->assertEquals('http://www.thinkphp.cn', $request->domain());
$this->assertEquals('/index/index/hello.html?name=thinkphp', $request->url());
$this->assertEquals('/index/index/hello.html', $request->baseurl());
$this->assertEquals('index/index/hello.html', $request->pathinfo());
$this->assertEquals('index/index/hello', $request->path());
$this->assertEquals('html', $request->ext());
$this->assertEquals('name=thinkphp', $request->query());
$this->assertEquals('www.thinkphp.cn', $request->host());
$this->assertEquals(80, $request->port());
$this->assertEquals($_SERVER['REQUEST_TIME'], $request->time());
$this->assertEquals($_SERVER['REQUEST_TIME_FLOAT'], $request->time(true));
$this->assertEquals('GET', $request->method());
$this->assertEquals(['name' => 'thinkphp'], $request->param());
$this->assertFalse($request->isSsl());
$this->assertEquals('http', $request->scheme());
}
public function testDomain()
{
$request = Request::instance();
$request->domain('http://thinkphp.cn');
$this->assertEquals('http://thinkphp.cn', $request->domain());
}
public function testUrl()
{
$request = Request::instance();
$request->url('/index.php/index/hello?name=thinkphp');
$this->assertEquals('/index.php/index/hello?name=thinkphp', $request->url());
$this->assertEquals('http://thinkphp.cn/index.php/index/hello?name=thinkphp', $request->url(true));
}
public function testBaseUrl()
{
$request = Request::instance();
$request->baseurl('/index.php/index/hello');
$this->assertEquals('/index.php/index/hello', $request->baseurl());
$this->assertEquals('http://thinkphp.cn/index.php/index/hello', $request->baseurl(true));
}
public function testbaseFile()
{
$request = Request::instance();
$request->basefile('/index.php');
$this->assertEquals('/index.php', $request->basefile());
$this->assertEquals('http://thinkphp.cn/index.php', $request->basefile(true));
}
public function testroot()
{
$request = Request::instance();
$request->root('/index.php');
$this->assertEquals('/index.php', $request->root());
$this->assertEquals('http://thinkphp.cn/index.php', $request->root(true));
}
public function testType()
{
$request = Request::instance();
$request->server(['HTTP_ACCEPT' => 'application/json']);
$this->assertEquals('json', $request->type());
$request->mimeType('test', 'application/test');
$request->mimeType(['test' => 'application/test']);
$request->server(['HTTP_ACCEPT' => 'application/test']);
$this->assertEquals('test', $request->type());
}
public function testmethod()
{
$_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] = 'DELETE';
$request = Request::create('', '');
$this->assertEquals('DELETE', $request->method());
$this->assertEquals('GET', $request->method(true));
Config::set('var_method', '_method');
$_POST['_method'] = 'POST';
$request = Request::create('', '');
$this->assertEquals('POST', $request->method());
$this->assertEquals('GET', $request->method(true));
$this->assertTrue($request->isPost());
$this->assertFalse($request->isGet());
$this->assertFalse($request->isPut());
$this->assertFalse($request->isDelete());
$this->assertFalse($request->isHead());
$this->assertFalse($request->isPatch());
$this->assertFalse($request->isOptions());
}
public function testCli()
{
$request = Request::instance();
$this->assertTrue($request->isCli());
}
public function testVar()
{
Config::set('app_multi_module', true);
$request = Request::create('');
$request->route(['name' => 'thinkphp', 'id' => 6]);
$request->get(['id' => 10]);
$request->post(['id' => 8]);
$request->put(['id' => 7]);
$request->request(['test' => 'value']);
$this->assertEquals(['name' => 'thinkphp', 'id' => 6], $request->route());
//$this->assertEquals(['id' => 10], $request->get());
$this->assertEquals('thinkphp', $request->route('name'));
$this->assertEquals('default', $request->route('test', 'default'));
$this->assertEquals(10, $request->get('id'));
$this->assertEquals(0, $request->get('ids', 0));
$this->assertEquals(8, $request->post('id'));
$this->assertEquals(7, $request->put('id'));
$this->assertEquals('value', $request->request('test'));
$this->assertEquals('thinkphp', $request->param('name'));
$this->assertEquals(6, $request->param('id'));
$this->assertFalse($request->has('user_id'));
$this->assertTrue($request->has('test', 'request'));
$this->assertEquals(['id' => 6], $request->only('id'));
$this->assertEquals(['name' => 'thinkphp', 'lang' => 'zh-cn'], $request->except('id'));
$this->assertEquals('THINKPHP', $request->param('name', '', 'strtoupper'));
}
public function testIsAjax()
{
$request = Request::create('');
$this->assertFalse($request->isAjax());
$_SERVER['HTTP_X_REQUESTED_WITH'] = 'xmlhttprequest';
$this->assertFalse($request->isAjax());
$this->assertFalse($request->isAjax(true));
$request->server(['HTTP_X_REQUESTED_WITH' => 'xmlhttprequest']);
$this->assertTrue($request->isAjax());
}
public function testIsPjax()
{
$request = Request::create('');
$this->assertFalse($request->isPjax());
$_SERVER['HTTP_X_PJAX'] = true;
$this->assertFalse($request->isPjax());
$this->assertFalse($request->isPjax(true));
$request->server(['HTTP_X_PJAX' => true]);
$this->assertTrue($request->isPjax());
$request->server(['HTTP_X_PJAX' => false]);
$this->assertTrue($request->isPjax());
}
public function testIsMobile()
{
$request = Request::create('');
$_SERVER['HTTP_VIA'] = 'wap';
$this->assertTrue($request->isMobile());
}
public function testBind()
{
$request = Request::create('');
$request->user = 'User1';
$request->bind(['user' => 'User2']);
$this->assertEquals('User2', $request->user);
}
}

View File

@@ -0,0 +1,95 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
/**
* Response测试
* @author 大漠 <zhylninc@gmail.com>
*/
namespace tests\thinkphp\library\think;
use think\Config;
use think\Request;
use think\Response;
class responseTest extends \PHPUnit_Framework_TestCase
{
/**
*
* @var \think\Response
*/
protected $object;
protected $default_return_type;
protected $default_ajax_return;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
{
// 1.
// restore_error_handler();
// Warning: Cannot modify header information - headers already sent by (output started at PHPUnit\Util\Printer.php:173)
// more see in https://www.analysisandsolutions.com/blog/html/writing-phpunit-tests-for-wordpress-plugins-wp-redirect-and-continuing-after-php-errors.htm
// 2.
// the Symfony used the HeaderMock.php
// 3.
// not run the eclipse will held, and travis-ci.org Searching for coverage reports
// **> Python coverage not found
// **> No coverage report found.
// add the
// /**
// * @runInSeparateProcess
// */
if (!$this->default_return_type) {
$this->default_return_type = Config::get('default_return_type');
}
if (!$this->default_ajax_return) {
$this->default_ajax_return = Config::get('default_ajax_return');
}
}
/**
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*/
protected function tearDown()
{
Config::set('default_ajax_return', $this->default_ajax_return);
Config::set('default_return_type', $this->default_return_type);
}
/**
* @covers think\Response::send
* @todo Implement testSend().
*/
public function testSend()
{
$dataArr = [];
$dataArr["key"] = "value";
$response = Response::create($dataArr, 'json');
$result = $response->getContent();
$this->assertEquals('{"key":"value"}', $result);
$request = Request::instance();
$request->get(['callback' => 'callback']);
$response = Response::create($dataArr, 'jsonp');
$result = $response->getContent();
$this->assertEquals('callback({"key":"value"});', $result);
}
}

View File

@@ -0,0 +1,287 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
/**
* Route测试
* @author liu21st <liu21st@gmail.com>
*/
namespace tests\thinkphp\library\think;
use think\Config;
use think\Request;
use think\Route;
class routeTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
Config::set('app_multi_module', true);
}
public function testRegister()
{
$request = Request::instance();
Route::get('hello/:name', 'index/hello');
Route::get(['hello/:name' => 'index/hello']);
Route::post('hello/:name', 'index/post');
Route::put('hello/:name', 'index/put');
Route::delete('hello/:name', 'index/delete');
Route::patch('hello/:name', 'index/patch');
Route::any('user/:id', 'index/user');
$result = Route::check($request, 'hello/thinkphp');
$this->assertEquals([null, 'index', 'hello'], $result['module']);
$this->assertEquals(['hello' => true, 'user/:id' => true, 'hello/:name' => ['rule' => 'hello/:name', 'route' => 'index/hello', 'var' => ['name' => 1], 'option' => [], 'pattern' => []]], Route::rules('GET'));
Route::rule('type1/:name', 'index/type', 'PUT|POST');
Route::rule(['type2/:name' => 'index/type1']);
Route::rule([['type3/:name', 'index/type2', ['method' => 'POST']]]);
Route::rule(['name', 'type4/:name'], 'index/type4');
}
public function testImport()
{
$rule = [
'__domain__' => ['subdomain2.thinkphp.cn' => 'blog1'],
'__alias__' => ['blog1' => 'blog1'],
'__rest__' => ['res' => ['index/blog']],
'bbb' => ['index/blog1', ['method' => 'POST']],
'ddd' => '',
['hello1/:ddd', 'index/hello1', ['method' => 'POST']],
];
Route::import($rule);
}
public function testResource()
{
$request = Request::instance();
Route::resource('res', 'index/blog');
Route::resource(['res' => ['index/blog']]);
$result = Route::check($request, 'res');
$this->assertEquals(['index', 'blog', 'index'], $result['module']);
$result = Route::check($request, 'res/create');
$this->assertEquals(['index', 'blog', 'create'], $result['module']);
$result = Route::check($request, 'res/8');
$this->assertEquals(['index', 'blog', 'read'], $result['module']);
$result = Route::check($request, 'res/8/edit');
$this->assertEquals(['index', 'blog', 'edit'], $result['module']);
Route::resource('blog.comment', 'index/comment');
$result = Route::check($request, 'blog/8/comment/10');
$this->assertEquals(['index', 'comment', 'read'], $result['module']);
$result = Route::check($request, 'blog/8/comment/10/edit');
$this->assertEquals(['index', 'comment', 'edit'], $result['module']);
}
public function testRest()
{
$request = Request::instance();
Route::rest('read', ['GET', '/:id', 'look']);
Route::rest('create', ['GET', '/create', 'add']);
Route::rest(['read' => ['GET', '/:id', 'look'], 'create' => ['GET', '/create', 'add']]);
Route::resource('res', 'index/blog');
$result = Route::check($request, 'res/create');
$this->assertEquals(['index', 'blog', 'add'], $result['module']);
$result = Route::check($request, 'res/8');
$this->assertEquals(['index', 'blog', 'look'], $result['module']);
}
public function testMixVar()
{
$request = Request::instance();
Route::get('hello-<name>', 'index/hello', [], ['name' => '\w+']);
$result = Route::check($request, 'hello-thinkphp');
$this->assertEquals([null, 'index', 'hello'], $result['module']);
Route::get('hello-<name><id?>', 'index/hello', [], ['name' => '\w+', 'id' => '\d+']);
$result = Route::check($request, 'hello-thinkphp2016');
$this->assertEquals([null, 'index', 'hello'], $result['module']);
Route::get('hello-<name>/[:id]', 'index/hello', [], ['name' => '\w+', 'id' => '\d+']);
$result = Route::check($request, 'hello-thinkphp/2016');
$this->assertEquals([null, 'index', 'hello'], $result['module']);
}
public function testParseUrl()
{
$result = Route::parseUrl('hello');
$this->assertEquals(['hello', null, null], $result['module']);
$result = Route::parseUrl('index/hello');
$this->assertEquals(['index', 'hello', null], $result['module']);
$result = Route::parseUrl('index/hello?name=thinkphp');
$this->assertEquals(['index', 'hello', null], $result['module']);
$result = Route::parseUrl('index/user/hello');
$this->assertEquals(['index', 'user', 'hello'], $result['module']);
$result = Route::parseUrl('index/user/hello/name/thinkphp');
$this->assertEquals(['index', 'user', 'hello'], $result['module']);
$result = Route::parseUrl('index-index-hello', '-');
$this->assertEquals(['index', 'index', 'hello'], $result['module']);
}
public function testCheckRoute()
{
Route::get('hello/:name', 'index/hello');
Route::get('blog/:id', 'blog/read', [], ['id' => '\d+']);
$request = Request::instance();
$this->assertEquals(false, Route::check($request, 'test/thinkphp'));
$this->assertEquals(false, Route::check($request, 'blog/thinkphp'));
$result = Route::check($request, 'blog/5');
$this->assertEquals([null, 'blog', 'read'], $result['module']);
$result = Route::check($request, 'hello/thinkphp/abc/test');
$this->assertEquals([null, 'index', 'hello'], $result['module']);
}
public function testCheckRouteGroup()
{
$request = Request::instance();
Route::pattern(['id' => '\d+']);
Route::pattern('name', '\w{6,25}');
Route::group('group', [':id' => 'index/hello', ':name' => 'index/say']);
$this->assertEquals(false, Route::check($request, 'empty/think'));
$result = Route::check($request, 'group/think');
$this->assertEquals(false, $result['module']);
$result = Route::check($request, 'group/10');
$this->assertEquals([null, 'index', 'hello'], $result['module']);
$result = Route::check($request, 'group/thinkphp');
$this->assertEquals([null, 'index', 'say'], $result['module']);
Route::group('group2', function () {
Route::group('group3', [':id' => 'index/hello', ':name' => 'index/say']);
Route::rule(':name', 'index/hello');
Route::auto('index');
});
$result = Route::check($request, 'group2/thinkphp');
$this->assertEquals([null, 'index', 'hello'], $result['module']);
$result = Route::check($request, 'group2/think');
$this->assertEquals(['index', 'group2', 'think'], $result['module']);
$result = Route::check($request, 'group2/group3/thinkphp');
$this->assertEquals([null, 'index', 'say'], $result['module']);
Route::group('group4', function () {
Route::group('group3', [':id' => 'index/hello', ':name' => 'index/say']);
Route::rule(':name', 'index/hello');
Route::miss('index/__miss__');
});
$result = Route::check($request, 'group4/thinkphp');
$this->assertEquals([null, 'index', 'hello'], $result['module']);
$result = Route::check($request, 'group4/think');
$this->assertEquals([null, 'index', '__miss__'], $result['module']);
Route::group(['prefix' => 'prefix/'], function () {
Route::rule('hello4/:name', 'hello');
});
Route::group(['prefix' => 'prefix/'], [
'hello4/:name' => 'hello',
]);
$result = Route::check($request, 'hello4/thinkphp');
$this->assertEquals([null, 'prefix', 'hello'], $result['module']);
Route::group('group5', [
[':name', 'hello', ['method' => 'GET|POST']],
':id' => 'hello',
], ['prefix' => 'prefix/']);
$result = Route::check($request, 'group5/thinkphp');
$this->assertEquals([null, 'prefix', 'hello'], $result['module']);
}
public function testControllerRoute()
{
$request = Request::instance();
Route::controller('controller', 'index/Blog');
$result = Route::check($request, 'controller/info');
$this->assertEquals(['index', 'Blog', 'getinfo'], $result['module']);
Route::setMethodPrefix('GET', 'read');
Route::setMethodPrefix(['get' => 'read']);
Route::controller('controller', 'index/Blog');
$result = Route::check($request, 'controller/phone');
$this->assertEquals(['index', 'Blog', 'readphone'], $result['module']);
}
public function testAliasRoute()
{
$request = Request::instance();
Route::alias('alias', 'index/Alias');
$result = Route::check($request, 'alias/info');
$this->assertEquals('index/Alias/info', $result['module']);
}
public function testRouteToModule()
{
$request = Request::instance();
Route::get('hello/:name', 'index/hello');
Route::get('blog/:id', 'blog/read', [], ['id' => '\d+']);
$this->assertEquals(false, Route::check($request, 'test/thinkphp'));
$this->assertEquals(false, Route::check($request, 'blog/thinkphp'));
$result = Route::check($request, 'hello/thinkphp');
$this->assertEquals([null, 'index', 'hello'], $result['module']);
$result = Route::check($request, 'blog/5');
$this->assertEquals([null, 'blog', 'read'], $result['module']);
}
public function testRouteToController()
{
$request = Request::instance();
Route::get('say/:name', '@index/hello');
$this->assertEquals(['type' => 'controller', 'controller' => 'index/hello', 'var' => []], Route::check($request, 'say/thinkphp'));
}
public function testRouteToMethod()
{
$request = Request::instance();
Route::get('user/:name', '\app\index\service\User::get', [], ['name' => '\w+']);
Route::get('info/:name', '\app\index\model\Info@getInfo', [], ['name' => '\w+']);
$this->assertEquals(['type' => 'method', 'method' => '\app\index\service\User::get', 'var' => []], Route::check($request, 'user/thinkphp'));
$this->assertEquals(['type' => 'method', 'method' => ['\app\index\model\Info', 'getInfo'], 'var' => []], Route::check($request, 'info/thinkphp'));
}
public function testRouteToRedirect()
{
$request = Request::instance();
Route::get('art/:id', '/article/read/id/:id', [], ['id' => '\d+']);
$this->assertEquals(['type' => 'redirect', 'url' => '/article/read/id/8', 'status' => 301], Route::check($request, 'art/8'));
}
public function testBind()
{
$request = Request::instance();
Route::bind('index/blog');
Route::get('blog/:id', 'index/blog/read');
$result = Route::check($request, 'blog/10');
$this->assertEquals(['index', 'blog', 'read'], $result['module']);
$result = Route::parseUrl('test');
$this->assertEquals(['index', 'blog', 'test'], $result['module']);
Route::bind('\app\index\controller', 'namespace');
$this->assertEquals(['type' => 'method', 'method' => ['\app\index\controller\Blog', 'read'], 'var' => []], Route::check($request, 'blog/read'));
Route::bind('\app\index\controller\Blog', 'class');
$this->assertEquals(['type' => 'method', 'method' => ['\app\index\controller\Blog', 'read'], 'var' => []], Route::check($request, 'read'));
}
public function testDomain()
{
$request = Request::create('http://subdomain.thinkphp.cn');
Route::domain('subdomain.thinkphp.cn', 'sub?abc=test&status=1');
$rules = Route::rules('GET');
Route::checkDomain($request, $rules);
$this->assertEquals('sub', Route::getbind('module'));
$this->assertEquals('test', $_GET['abc']);
$this->assertEquals(1, $_GET['status']);
Route::domain('subdomain.thinkphp.cn', '\app\index\controller');
$rules = Route::rules('GET');
Route::checkDomain($request, $rules);
$this->assertEquals('\app\index\controller', Route::getbind('namespace'));
Route::domain(['subdomain.thinkphp.cn' => '@\app\index\controller\blog']);
$rules = Route::rules('GET');
Route::checkDomain($request, $rules);
$this->assertEquals('\app\index\controller\blog', Route::getbind('class'));
}
}

View File

@@ -0,0 +1,2 @@
*
!.gitignore

View File

@@ -0,0 +1,319 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
/**
* Session测试
* @author 大漠 <zhylninc@gmail.com>
*/
namespace tests\thinkphp\library\think;
use think\Session;
class sessionTest extends \PHPUnit_Framework_TestCase
{
/**
*
* @var \think\Session
*/
protected $object;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
{
// $this->object = new Session ();
// register_shutdown_function ( function () {
// } ); // 此功能无法取消,需要回调函数配合。
set_exception_handler(function () {});
set_error_handler(function () {});
}
/**
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*/
protected function tearDown()
{
register_shutdown_function('think\Error::appShutdown');
set_error_handler('think\Error::appError');
set_exception_handler('think\Error::appException');
}
/**
* @covers think\Session::prefix
*
* @todo Implement testPrefix().
*/
public function testPrefix()
{
Session::prefix(null);
Session::prefix('think_');
$this->assertEquals('think_', Session::prefix());
}
/**
* @covers think\Session::init
*
* @todo Implement testInit().
*/
public function testInit()
{
Session::prefix(null);
$config = [
// cookie 名称前缀
'prefix' => 'think_',
// cookie 保存时间
'expire' => 60,
// cookie 保存路径
'path' => '/path/to/test/session/',
// cookie 有效域名
'domain' => '.thinkphp.cn',
'var_session_id' => 'sessionidtest',
'id' => 'sess_8fhgkjuakhatbeg2fa14lo84q1',
'name' => 'session_name',
'use_trans_sid' => '1',
'use_cookies' => '1',
'cache_limiter' => '60',
'cache_expire' => '60',
'type' => '', // memcache
'namespace' => '\\think\\session\\driver\\', // ?
'auto_start' => '1',
];
$_REQUEST[$config['var_session_id']] = $config['id'];
Session::init($config);
// 开始断言
$this->assertEquals($config['prefix'], Session::prefix());
$this->assertEquals($config['id'], $_REQUEST[$config['var_session_id']]);
$this->assertEquals($config['name'], session_name());
$this->assertEquals($config['path'], session_save_path());
$this->assertEquals($config['use_cookies'], ini_get('session.use_cookies'));
$this->assertEquals($config['domain'], ini_get('session.cookie_domain'));
$this->assertEquals($config['expire'], ini_get('session.gc_maxlifetime'));
$this->assertEquals($config['expire'], ini_get('session.cookie_lifetime'));
$this->assertEquals($config['cache_limiter'], session_cache_limiter($config['cache_limiter']));
$this->assertEquals($config['cache_expire'], session_cache_expire($config['cache_expire']));
// 检测分支
$_REQUEST[$config['var_session_id']] = null;
session_write_close();
session_destroy();
Session::init($config);
// 测试auto_start
// PHP_SESSION_DISABLED
// PHP_SESSION_NONE
// PHP_SESSION_ACTIVE
// session_status()
if (strstr(PHP_VERSION, 'hhvm')) {
$this->assertEquals('', ini_get('session.auto_start'));
} else {
$this->assertEquals(0, ini_get('session.auto_start'));
}
$this->assertEquals($config['use_trans_sid'], ini_get('session.use_trans_sid'));
Session::init($config);
$this->assertEquals($config['id'], session_id());
}
/**
* 单独重现异常
* @expectedException \think\Exception
*/
public function testException()
{
$config = [
// cookie 名称前缀
'prefix' => 'think_',
// cookie 保存时间
'expire' => 0,
// cookie 保存路径
'path' => '/path/to/test/session/',
// cookie 有效域名
'domain' => '.thinkphp.cn',
'var_session_id' => 'sessionidtest',
'id' => 'sess_8fhgkjuakhatbeg2fa14lo84q1',
'name' => 'session_name',
'use_trans_sid' => '1',
'use_cookies' => '1',
'cache_limiter' => '60',
'cache_expire' => '60',
'type' => '\\think\\session\\driver\\Memcache', //
'auto_start' => '1',
];
// 测试session驱动是否存在
// @expectedException 异常类名
$this->setExpectedException('\think\exception\ClassNotFoundException', 'error session handler');
Session::init($config);
}
/**
* @covers think\Session::set
*
* @todo Implement testSet().
*/
public function testSet()
{
Session::prefix(null);
Session::set('sessionname', 'sessionvalue');
$this->assertEquals('sessionvalue', $_SESSION['sessionname']);
Session::set('sessionnamearr.subname', 'sessionvalue');
$this->assertEquals('sessionvalue', $_SESSION['sessionnamearr']['subname']);
Session::set('sessionnameper', 'sessionvalue', 'think_');
$this->assertEquals('sessionvalue', $_SESSION['think_']['sessionnameper']);
Session::set('sessionnamearrper.subname', 'sessionvalue', 'think_');
$this->assertEquals('sessionvalue', $_SESSION['think_']['sessionnamearrper']['subname']);
}
/**
* @covers think\Session::get
*
* @todo Implement testGet().
*/
public function testGet()
{
Session::prefix(null);
Session::set('sessionnameget', 'sessionvalue');
$this->assertEquals(Session::get('sessionnameget'), $_SESSION['sessionnameget']);
Session::set('sessionnamegetarr.subname', 'sessionvalue');
$this->assertEquals(Session::get('sessionnamegetarr.subname'), $_SESSION['sessionnamegetarr']['subname']);
Session::set('sessionnamegetarrperall', 'sessionvalue', 'think_');
$this->assertEquals(Session::get('', 'think_')['sessionnamegetarrperall'], $_SESSION['think_']['sessionnamegetarrperall']);
Session::set('sessionnamegetper', 'sessionvalue', 'think_');
$this->assertEquals(Session::get('sessionnamegetper', 'think_'), $_SESSION['think_']['sessionnamegetper']);
Session::set('sessionnamegetarrper.subname', 'sessionvalue', 'think_');
$this->assertEquals(Session::get('sessionnamegetarrper.subname', 'think_'), $_SESSION['think_']['sessionnamegetarrper']['subname']);
}
public function testPull()
{
Session::prefix(null);
Session::set('sessionnamedel', 'sessionvalue');
$this->assertEquals('sessionvalue', Session::pull('sessionnameget'));
$this->assertNull(Session::get('sessionnameget'));
}
/**
* @covers think\Session::delete
*
* @todo Implement testDelete().
*/
public function testDelete()
{
Session::prefix(null);
Session::set('sessionnamedel', 'sessionvalue');
Session::delete('sessionnamedel');
$this->assertEmpty($_SESSION['sessionnamedel']);
Session::set('sessionnamedelarr.subname', 'sessionvalue');
Session::delete('sessionnamedelarr.subname');
$this->assertEmpty($_SESSION['sessionnamedelarr']['subname']);
Session::set('sessionnamedelper', 'sessionvalue', 'think_');
Session::delete('sessionnamedelper', 'think_');
$this->assertEmpty($_SESSION['think_']['sessionnamedelper']);
Session::set('sessionnamedelperarr.subname', 'sessionvalue', 'think_');
Session::delete('sessionnamedelperarr.subname', 'think_');
$this->assertEmpty($_SESSION['think_']['sessionnamedelperarr']['subname']);
}
/**
* @covers think\Session::clear
*
* @todo Implement testClear().
*/
public function testClear()
{
Session::prefix(null);
Session::set('sessionnameclsper', 'sessionvalue1', 'think_');
Session::clear('think_');
$this->assertNull($_SESSION['think_']);
Session::set('sessionnameclsper', 'sessionvalue1', 'think_');
Session::clear();
$this->assertEmpty($_SESSION);
}
/**
* @covers think\Session::has
*
* @todo Implement testHas().
*/
public function testHas()
{
Session::prefix(null);
Session::set('sessionnamehas', 'sessionvalue');
$this->assertTrue(Session::has('sessionnamehas'));
Session::set('sessionnamehasarr.subname', 'sessionvalue');
$this->assertTrue(Session::has('sessionnamehasarr.subname'));
Session::set('sessionnamehasper', 'sessionvalue', 'think_');
$this->assertTrue(Session::has('sessionnamehasper', 'think_'));
Session::set('sessionnamehasarrper.subname', 'sessionvalue', 'think_');
$this->assertTrue(Session::has('sessionnamehasarrper.subname', 'think_'));
}
/**
* @covers think\Session::pause
*
* @todo Implement testPause().
*/
public function testPause()
{
Session::pause();
}
/**
* @covers think\Session::start
*
* @todo Implement testStart().
*/
public function testStart()
{
Session::start();
}
/**
* @covers think\Session::destroy
*
* @todo Implement testDestroy().
*/
public function testDestroy()
{
Session::set('sessionnamedestroy', 'sessionvalue');
Session::destroy();
$this->assertEmpty($_SESSION['sessionnamedestroy']);
}
}

View File

@@ -0,0 +1,2 @@
*
!.gitignore

View File

@@ -0,0 +1,575 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
/**
* 模板测试
* @author Haotong Lin <lofanmi@gmail.com>
*/
namespace tests\thinkphp\library\think\tempplate\taglib;
use think\Template;
use think\template\taglib\Cx;
class cxTest extends \PHPUnit_Framework_TestCase
{
public function testPhp()
{
$template = new template();
$cx = new Cx($template);
$content = <<<EOF
{php}echo \$a;{/php}
EOF;
$data = <<<EOF
<?php echo \$a; ?>
EOF;
$cx->parseTag($content);
$this->assertEquals($content, $data);
}
public function testVolist()
{
$template = new template();
$cx = new Cx($template);
$content = <<<EOF
{volist name="list" id="vo" key="key"}
{/volist}
EOF;
$data = <<<EOF
<?php if(is_array(\$list) || \$list instanceof \\think\\Collection || \$list instanceof \\think\\Paginator): \$key = 0; \$__LIST__ = \$list;if( count(\$__LIST__)==0 ) : echo "" ;else: foreach(\$__LIST__ as \$key=>\$vo): \$mod = (\$key % 2 );++\$key;?>
<?php endforeach; endif; else: echo "" ;endif; ?>
EOF;
$cx->parseTag($content);
$this->assertEquals($data, $content);
$content = <<<EOF
{volist name="\$list" id="vo" key="key" offset="1" length="3"}
{\$vo}
{/volist}
EOF;
$template->display($content, ['list' => [1, 2, 3, 4, 5]]);
$this->expectOutputString('234');
}
public function testForeach()
{
$template = new template();
$cx = new Cx($template);
$content = <<<EOF
{foreach \$list as \$key=>\$val}
{/foreach}
EOF;
$data = <<<EOF
<?php foreach(\$list as \$key=>\$val): ?>
<?php endforeach; ?>
EOF;
$cx->parseTag($content);
$this->assertEquals($content, $data);
$content = <<<EOF
{foreach name="list" id="val" key="key" empty="empty"}
{/foreach}
EOF;
$data = <<<EOF
<?php if(is_array(\$list) || \$list instanceof \\think\\Collection || \$list instanceof \\think\\Paginator): if( count(\$list)==0 ) : echo "empty" ;else: foreach(\$list as \$key=>\$val): ?>
<?php endforeach; endif; else: echo "empty" ;endif; ?>
EOF;
$cx->parseTag($content);
$this->assertEquals($content, $data);
$content = <<<EOF
{foreach name=":explode(',', '1,2,3,4,5')" id="val" key="key" index="index" mod="2" offset="1" length="3"}
{\$val}
{/foreach}
EOF;
$template->display($content);
$this->expectOutputString('234');
}
public function testIf()
{
$template = new template();
$cx = new Cx($template);
$content = <<<EOF
{if \$var.a==\$var.b}
one
{elseif !empty(\$var.a) /}
two
{else /}
default
{/if}
EOF;
$data = <<<EOF
<?php if(\$var['a']==\$var['b']): ?>
one
<?php elseif(!empty(\$var['a'])): ?>
two
<?php else: ?>
default
<?php endif; ?>
EOF;
$cx->parseTag($content);
$this->assertEquals($content, $data);
}
public function testSwitch()
{
$template = new template();
$cx = new Cx($template);
$content = <<<EOF
{switch \$var}
{case \$a /}
a
{/case}
{case b|c}
b
{/case}
{case d}
d
{/case}
{default /}
default
{/switch}
EOF;
$data = <<<EOF
<?php switch(\$var): ?>
<?php case \$a: ?>
a
<?php break; ?>
<?php case "b":case "c": ?>
b
<?php break; ?>
<?php case "d": ?>
d
<?php break; ?>
<?php default: ?>
default
<?php endswitch; ?>
EOF;
$cx->parseTag($content);
$this->assertEquals($content, $data);
}
public function testCompare()
{
$template = new template();
$cx = new Cx($template);
$content = <<<EOF
{eq name="\$var.a" value="\$var.b"}
default
{/eq}
EOF;
$data = <<<EOF
<?php if(\$var['a'] == \$var['b']): ?>
default
<?php endif; ?>
EOF;
$cx->parseTag($content);
$this->assertEquals($content, $data);
$content = <<<EOF
{equal name="\$var.a" value="0"}
default
{/equal}
EOF;
$data = <<<EOF
<?php if(\$var['a'] == '0'): ?>
default
<?php endif; ?>
EOF;
$cx->parseTag($content);
$this->assertEquals($content, $data);
$content = <<<EOF
{neq name="\$var.a" value="0"}
default
{/neq}
EOF;
$data = <<<EOF
<?php if(\$var['a'] != '0'): ?>
default
<?php endif; ?>
EOF;
$cx->parseTag($content);
$this->assertEquals($content, $data);
$content = <<<EOF
{notequal name="\$var.a" value="0"}
default
{/notequal}
EOF;
$data = <<<EOF
<?php if(\$var['a'] != '0'): ?>
default
<?php endif; ?>
EOF;
$cx->parseTag($content);
$this->assertEquals($content, $data);
$content = <<<EOF
{gt name="\$var.a" value="0"}
default
{/gt}
EOF;
$data = <<<EOF
<?php if(\$var['a'] > '0'): ?>
default
<?php endif; ?>
EOF;
$cx->parseTag($content);
$this->assertEquals($content, $data);
$content = <<<EOF
{egt name="\$var.a" value="0"}
default
{/egt}
EOF;
$data = <<<EOF
<?php if(\$var['a'] >= '0'): ?>
default
<?php endif; ?>
EOF;
$cx->parseTag($content);
$this->assertEquals($content, $data);
$content = <<<EOF
{lt name="\$var.a" value="0"}
default
{/lt}
EOF;
$data = <<<EOF
<?php if(\$var['a'] < '0'): ?>
default
<?php endif; ?>
EOF;
$cx->parseTag($content);
$this->assertEquals($content, $data);
$content = <<<EOF
{elt name="\$var.a" value="0"}
default
{/elt}
EOF;
$data = <<<EOF
<?php if(\$var['a'] <= '0'): ?>
default
<?php endif; ?>
EOF;
$cx->parseTag($content);
$this->assertEquals($content, $data);
$content = <<<EOF
{heq name="\$var.a" value="0"}
default
{/heq}
EOF;
$data = <<<EOF
<?php if(\$var['a'] === '0'): ?>
default
<?php endif; ?>
EOF;
$cx->parseTag($content);
$this->assertEquals($content, $data);
$content = <<<EOF
{nheq name="\$var.a" value="0"}
default
{/nheq}
EOF;
$data = <<<EOF
<?php if(\$var['a'] !== '0'): ?>
default
<?php endif; ?>
EOF;
$cx->parseTag($content);
$this->assertEquals($content, $data);
}
public function testRange()
{
$template = new template();
$cx = new Cx($template);
$content = <<<EOF
{in name="var" value="\$value"}
default
{/in}
EOF;
$data = <<<EOF
<?php if(in_array((\$var), is_array(\$value)?\$value:explode(',',\$value))): ?>
default
<?php endif; ?>
EOF;
$cx->parseTag($content);
$this->assertEquals($content, $data);
$content = <<<EOF
{notin name="var" value="1,2,3"}
default
{/notin}
EOF;
$data = <<<EOF
<?php if(!in_array((\$var), explode(',',"1,2,3"))): ?>
default
<?php endif; ?>
EOF;
$cx->parseTag($content);
$this->assertEquals($content, $data);
$content = <<<EOF
{between name=":floor(5.1)" value="1,5"}yes{/between}
{notbetween name=":ceil(5.1)" value="1,5"}no{/notbetween}
EOF;
$template->display($content);
$this->expectOutputString('yesno');
}
public function testPresent()
{
$template = new template();
$cx = new Cx($template);
$content = <<<EOF
{present name="var"}
default
{/present}
EOF;
$data = <<<EOF
<?php if(isset(\$var)): ?>
default
<?php endif; ?>
EOF;
$cx->parseTag($content);
$this->assertEquals($content, $data);
$content = <<<EOF
{notpresent name="var"}
default
{/notpresent}
EOF;
$data = <<<EOF
<?php if(!isset(\$var)): ?>
default
<?php endif; ?>
EOF;
$cx->parseTag($content);
$this->assertEquals($content, $data);
}
public function testEmpty()
{
$template = new template();
$cx = new Cx($template);
$content = <<<EOF
{empty name="var"}
default
{/empty}
EOF;
$data = <<<EOF
<?php if(empty(\$var) || ((\$var instanceof \\think\\Collection || \$var instanceof \\think\\Paginator ) && \$var->isEmpty())): ?>
default
<?php endif; ?>
EOF;
$cx->parseTag($content);
$this->assertEquals($content, $data);
$content = <<<EOF
{notempty name="var"}
default
{/notempty}
EOF;
$data = <<<EOF
<?php if(!(empty(\$var) || ((\$var instanceof \\think\\Collection || \$var instanceof \\think\\Paginator ) && \$var->isEmpty()))): ?>
default
<?php endif; ?>
EOF;
$cx->parseTag($content);
$this->assertEquals($content, $data);
}
public function testDefined()
{
$template = new template();
$cx = new Cx($template);
$content = <<<EOF
{defined name="URL"}
default
{/defined}
EOF;
$data = <<<EOF
<?php if(defined("URL")): ?>
default
<?php endif; ?>
EOF;
$cx->parseTag($content);
$this->assertEquals($content, $data);
$content = <<<EOF
{notdefined name="URL"}
default
{/notdefined}
EOF;
$data = <<<EOF
<?php if(!defined("URL")): ?>
default
<?php endif; ?>
EOF;
$cx->parseTag($content);
$this->assertEquals($content, $data);
}
public function testImport()
{
$template = new template();
$cx = new Cx($template);
$content = <<<EOF
{load file="base.php" value="\$name.a" /}
EOF;
$data = <<<EOF
<?php if(isset(\$name['a'])): ?><?php include "base.php"; ?><?php endif; ?>
EOF;
$cx->parseTag($content);
$this->assertEquals($content, $data);
$content = <<<EOF
{js file="base.js" /}
EOF;
$data = <<<EOF
<script type="text/javascript" src="base.js"></script>
EOF;
$cx->parseTag($content);
$this->assertEquals($content, $data);
$content = <<<EOF
{css file="base.css" /}
EOF;
$data = <<<EOF
<link rel="stylesheet" type="text/css" href="base.css" />
EOF;
$cx->parseTag($content);
$this->assertEquals($content, $data);
}
public function testAssign()
{
$template = new template();
$cx = new Cx($template);
$content = <<<EOF
{assign name="total" value="0" /}
EOF;
$data = <<<EOF
<?php \$total = '0'; ?>
EOF;
$cx->parseTag($content);
$this->assertEquals($content, $data);
$content = <<<EOF
{assign name="total" value=":count(\$list)" /}
EOF;
$data = <<<EOF
<?php \$total = count(\$list); ?>
EOF;
$cx->parseTag($content);
$this->assertEquals($content, $data);
}
public function testDefine()
{
$template = new template();
$cx = new Cx($template);
$content = <<<EOF
{define name="INFO_NAME" value="test" /}
EOF;
$data = <<<EOF
<?php define('INFO_NAME', 'test'); ?>
EOF;
$cx->parseTag($content);
$this->assertEquals($content, $data);
$content = <<<EOF
{define name="INFO_NAME" value="\$name" /}
EOF;
$data = <<<EOF
<?php define('INFO_NAME', \$name); ?>
EOF;
$cx->parseTag($content);
$this->assertEquals($content, $data);
}
public function testFor()
{
$template = new template();
$content = <<<EOF
{for start="1" end=":strlen(1000000000)" comparison="lt" step="1" name="i" }
{\$i}
{/for}
EOF;
$template->display($content);
$this->expectOutputString('123456789');
}
public function testUrl()
{
$template = new template();
$content = <<<EOF
{url link="Index/index" /}
EOF;
$template->display($content);
$this->expectOutputString(\think\Url::build('Index/index'));
}
public function testFunction()
{
$template = new template();
$data = [
'list' => ['language' => 'php', 'version' => ['5.4', '5.5']],
'a' => '[',
'b' => ']',
];
$content = <<<EOF
{function name="func" vars="\$data" call="\$list" use="&\$a,&\$b"}
{foreach \$data as \$key=>\$val}
{if is_array(\$val)}
{~\$func(\$val)}
{else}
{if !is_numeric(\$key)}
{\$key.':'.\$val.','}
{else}
{\$a.\$val.\$b}
{/if}
{/if}
{/foreach}
{/function}
EOF;
$template->display($content, $data);
$this->expectOutputString("language:php,[5.4][5.5]");
}
}

View File

@@ -0,0 +1,415 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
/**
* 模板测试
* @author oldrind
*/
namespace tests\thinkphp\library\think;
use think\Cache;
use think\Template;
class templateTest extends \PHPUnit_Framework_TestCase
{
/**
* @var Template
*/
protected $template;
public function setUp()
{
$this->template = new Template();
}
public function testAssign()
{
$reflectProperty = new \ReflectionProperty(get_class($this->template), 'data');
$reflectProperty->setAccessible(true);
$this->template->assign('version', 'ThinkPHP3.2');
$data = $reflectProperty->getValue($this->template);
$this->assertEquals('ThinkPHP3.2', $data['version']);
$this->template->assign(['name' => 'Gao', 'version' => 'ThinkPHP5']);
$data = $reflectProperty->getValue($this->template);
$this->assertEquals('Gao', $data['name']);
$this->assertEquals('ThinkPHP5', $data['version']);
}
public function testGet()
{
$this->template = new Template();
$data = [
'project' => 'ThinkPHP',
'version' => [
'ThinkPHP5' => ['Think5.0', 'Think5.1']
]
];
$this->template->assign($data);
$this->assertSame($data, $this->template->get());
$this->assertSame('ThinkPHP', $this->template->get('project'));
$this->assertSame(['Think5.0', 'Think5.1'], $this->template->get('version.ThinkPHP5'));
$this->assertNull($this->template->get('version.ThinkPHP3.2'));
}
/**
* @dataProvider provideTestParseWithVar
*/
public function testParseWithVar($content, $expected)
{
$this->template = new Template();
$this->template->parse($content);
$this->assertEquals($expected, $content);
}
/**
* @dataProvider provideTestParseWithVarFunction
*/
public function testParseWithVarFunction($content, $expected)
{
$this->template = new Template();
$this->template->parse($content);
$this->assertEquals($expected, $content);
}
/**
* @dataProvider provideTestParseWithVarIdentify
*/
public function testParseWithVarIdentify($content, $expected, $config)
{
$this->template = new Template($config);
$this->template->parse($content);
$this->assertEquals($expected, $content);
}
/**
* @dataProvider provideTestParseWithThinkVar
*/
public function testParseWithThinkVar($content, $expected)
{
$config['tpl_begin'] = '{';
$config['tpl_end'] = '}';
$this->template = new Template($config);
$_SERVER['SERVER_NAME'] = 'server_name';
$_GET['action'] = 'action';
$_POST['action'] = 'action';
$_COOKIE['name'] = 'name';
$_SESSION['action'] = ['name' => 'name'];
$this->template->parse($content);
$this->assertEquals($expected, $content);
}
/**
* @expectedException \think\exception\TemplateNotFoundException
*/
public function testFetchWithEmptyTemplate()
{
$this->template = new Template();
$this->template->fetch('Foo');
}
/**
* @dataProvider provideTestFetchWithNoCache
*/
public function testFetchWithNoCache($data, $expected)
{
$this->template = new Template();
$this->template->fetch($data['template'], $data['vars'], $data['config']);
$this->expectOutputString($expected);
}
public function testFetchWithCache()
{
$this->template = new Template();
$data = [
'name' => 'value'
];
$config = [
'cache_id' => 'TEST_FETCH_WITH_CACHE',
'display_cache' => true,
];
$this->template->fetch(APP_PATH . 'views' . DS .'display.html', $data, $config);
$this->expectOutputString('value');
$this->assertEquals('value', Cache::get($config['cache_id']));
}
public function testDisplay()
{
$config = [
'view_path' => APP_PATH . DS . 'views' . DS,
'view_suffix' => '.html',
'layout_on' => true,
'layout_name' => 'layout'
];
$this->template = new Template($config);
$this->template->assign('files', ['extend' => 'extend', 'include' => 'include']);
$this->template->assign('user', ['name' => 'name', 'account' => 100]);
$this->template->assign('message', 'message');
$this->template->assign('info', ['value' => 'value']);
$content = <<<EOF
{extend name="\$files.extend" /}
{block name="main"}
main
{block name="side"}
{__BLOCK__}
{include file="\$files.include" name="\$user.name" value="\$user.account" /}
{\$message}{literal}{\$message}{/literal}
{/block}
{block name="mainbody"}
mainbody
{/block}
{/block}
EOF;
$expected = <<<EOF
<nav>
header
<div id="wrap">
<input name="info" value="value">
value:
main
side
<input name="name" value="100">
value:
message{\$message}
mainbody
{\$name}
php code</div>
</nav>
EOF;
$this->template->display($content);
$this->expectOutputString($expected);
}
/**
* @dataProvider provideTestLayout
*/
public function testLayout($data, $expected)
{
$this->template = new Template();
$this->template->layout($data['name'], $data['replace']);
$this->assertSame($expected['layout_on'], $this->template->config('layout_on'));
$this->assertSame($expected['layout_name'], $this->template->config('layout_name'));
$this->assertSame($expected['layout_item'], $this->template->config('layout_item'));
}
public function testParseAttr()
{
$attributes = $this->template->parseAttr("<name version='ThinkPHP' name=\"Gao\"></name>");
$this->assertSame(['version' => 'ThinkPHP', 'name' => 'Gao'], $attributes);
$attributes = $this->template->parseAttr("<name version='ThinkPHP' name=\"Gao\">TestCase</name>", 'version');
$this->assertSame('ThinkPHP', $attributes);
}
public function testIsCache()
{
$this->template = new Template();
$config = [
'cache_id' => rand(0, 10000) . rand(0, 10000) . time(),
'display_cache' => true
];
$this->assertFalse($this->template->isCache($config['cache_id']));
$this->template->fetch(APP_PATH . 'views' . DS .'display.html', [], $config);
$this->assertTrue($this->template->isCache($config['cache_id']));
}
public function provideTestParseWithVar()
{
return [
["{\$name.a.b}", "<?php echo \$name['a']['b']; ?>"],
["{\$name.a??'test'}", "<?php echo isset(\$name['a'])?\$name['a']:'test'; ?>"],
["{\$name.a?='test'}", "<?php if(!empty(\$name['a'])) echo 'test'; ?>"],
["{\$name.a?:'test'}", "<?php echo !empty(\$name['a'])?\$name['a']:'test'; ?>"],
["{\$name.a?\$name.b:'no'}", "<?php echo !empty(\$name['a'])?\$name['b']:'no'; ?>"],
["{\$name.a==\$name.b?='test'}", "<?php if(\$name['a']==\$name['b']) echo 'test'; ?>"],
["{\$name.a==\$name.b?'a':'b'}", "<?php echo \$name['a']==\$name['b']?'a':'b'; ?>"],
["{\$name.a|default='test'==\$name.b?'a':'b'}", "<?php echo (isset(\$name['a']) && (\$name['a'] !== '')?\$name['a']:'test')==\$name['b']?'a':'b'; ?>"],
["{\$name.a|trim==\$name.b?='eq'}", "<?php if(trim(\$name['a'])==\$name['b']) echo 'eq'; ?>"],
["{:ltrim(rtrim(\$name.a))}", "<?php echo ltrim(rtrim(\$name['a'])); ?>"],
["{~echo(trim(\$name.a))}", "<?php echo(trim(\$name['a'])); ?>"],
["{++\$name.a}", "<?php echo ++\$name['a']; ?>"],
["{/*\$name*/}", ""],
["{\$0a}", "{\$0a}"]
];
}
public function provideTestParseWithVarFunction()
{
return [
["{\$name.a.b|default='test'}", "<?php echo (isset(\$name['a']['b']) && (\$name['a']['b'] !== '')?\$name['a']['b']:'test'); ?>"],
["{\$create_time|date=\"y-m-d\",###}", "<?php echo date(\"y-m-d\",\$create_time); ?>"],
["{\$name}\n{\$name|trim|substr=0,3}", "<?php echo \$name; ?>\n<?php echo substr(trim(\$name),0,3); ?>"]
];
}
public function provideTestParseWithVarIdentify()
{
$config['tpl_begin'] = '<#';
$config['tpl_end'] = '#>';
$config['tpl_var_identify'] = '';
return [
[
"<#\$info.a??'test'#>",
"<?php echo ((is_array(\$info)?\$info['a']:\$info->a)) ? (is_array(\$info)?\$info['a']:\$info->a) : 'test'; ?>",
$config
],
[
"<#\$info.a?='test'#>",
"<?php if((is_array(\$info)?\$info['a']:\$info->a)) echo 'test'; ?>",
$config
],
[
"<#\$info.a==\$info.b?='test'#>",
"<?php if((is_array(\$info)?\$info['a']:\$info->a)==(is_array(\$info)?\$info['b']:\$info->b)) echo 'test'; ?>",
$config
],
[
"<#\$info.a|default='test'?'yes':'no'#>",
"<?php echo ((is_array(\$info)?\$info['a']:\$info->a) ?: 'test')?'yes':'no'; ?>",
$config
],
[
"{\$info2.b|trim?'yes':'no'}",
"<?php echo trim(\$info2->b)?'yes':'no'; ?>",
array_merge(['tpl_var_identify' => 'obj'])
]
];
}
public function provideTestParseWithThinkVar()
{
return [
["{\$Think.SERVER.SERVER_NAME}<br/>", "<?php echo \\think\\Request::instance()->server('SERVER_NAME'); ?><br/>"],
["{\$Think.GET.action}<br/>", "<?php echo \\think\\Request::instance()->get('action'); ?><br/>"],
["{\$Think.POST.action}<br/>", "<?php echo \\think\\Request::instance()->post('action'); ?><br/>"],
["{\$Think.COOKIE.action}<br/>", "<?php echo \\think\\Cookie::get('action'); ?><br/>"],
["{\$Think.COOKIE.action.name}<br/>", "<?php echo \\think\\Cookie::get('action.name'); ?><br/>"],
["{\$Think.SESSION.action}<br/>", "<?php echo \\think\\Session::get('action'); ?><br/>"],
["{\$Think.SESSION.action.name}<br/>", "<?php echo \\think\\Session::get('action.name'); ?><br/>"],
["{\$Think.ENV.OS}<br/>", "<?php echo \\think\\Request::instance()->env('OS'); ?><br/>"],
["{\$Think.REQUEST.action}<br/>", "<?php echo \\think\\Request::instance()->request('action'); ?><br/>"],
["{\$Think.CONST.THINK_VERSION}<br/>", "<?php echo THINK_VERSION; ?><br/>"],
["{\$Think.LANG.action}<br/>", "<?php echo \\think\\Lang::get('action'); ?><br/>"],
["{\$Think.CONFIG.action.name}<br/>", "<?php echo \\think\\Config::get('action.name'); ?><br/>"],
["{\$Think.NOW}<br/>", "<?php echo date('Y-m-d g:i a',time()); ?><br/>"],
["{\$Think.VERSION}<br/>", "<?php echo THINK_VERSION; ?><br/>"],
["{\$Think.LDELIM}<br/>", "<?php echo '{'; ?><br/>"],
["{\$Think.RDELIM}<br/>", "<?php echo '}'; ?><br/>"],
["{\$Think.THINK_VERSION}<br/>", "<?php echo THINK_VERSION; ?><br/>"],
["{\$Think.SITE.URL}", "<?php echo ''; ?>"]
];
}
public function provideTestFetchWithNoCache()
{
$provideData = [];
$this->template = [
'template' => APP_PATH . 'views' . DS .'display.html',
'vars' => [],
'config' => []
];
$expected = 'default';
$provideData[] = [$this->template, $expected];
$this->template = [
'template' => APP_PATH . 'views' . DS .'display.html',
'vars' => ['name' => 'ThinkPHP5'],
'config' => []
];
$expected = 'ThinkPHP5';
$provideData[] = [$this->template, $expected];
$this->template = [
'template' => 'views@display',
'vars' => [],
'config' => [
'view_suffix' => 'html'
]
];
$expected = 'default';
$provideData[] = [$this->template, $expected];
$this->template = [
'template' => 'views@/display',
'vars' => ['name' => 'ThinkPHP5'],
'config' => [
'view_suffix' => 'phtml'
]
];
$expected = 'ThinkPHP5';
$provideData[] = [$this->template, $expected];
$this->template = [
'template' => 'display',
'vars' => ['name' => 'ThinkPHP5'],
'config' => [
'view_suffix' => 'html',
'view_base' => APP_PATH . 'views' . DS
]
];
$expected = 'ThinkPHP5';
$provideData[] = [$this->template, $expected];
return $provideData;
}
public function provideTestLayout()
{
$provideData = [];
$data = ['name' => false, 'replace' => ''];
$expected = ['layout_on' => false, 'layout_name' => 'layout', 'layout_item' => '{__CONTENT__}'];
$provideData[] = [$data, $expected];
$data = ['name' => null, 'replace' => ''];
$expected = ['layout_on' => true, 'layout_name' => 'layout', 'layout_item' => '{__CONTENT__}'];
$provideData[] = [$data, $expected];
$data = ['name' => 'ThinkName', 'replace' => 'ThinkReplace'];
$expected = ['layout_on' => true, 'layout_name' => 'ThinkName', 'layout_item' => 'ThinkReplace'];
$provideData[] = [$data, $expected];
return $provideData;
}
}

View File

@@ -0,0 +1,129 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
/**
* Url测试
* @author liu21st <liu21st@gmail.com>
*/
namespace tests\thinkphp\library\think;
use tests\thinkphp\library\think\config\ConfigInitTrait;
use think\Config;
use think\Route;
use think\Url;
class urlTest extends \PHPUnit_Framework_TestCase
{
use ConfigInitTrait;
public function setUp()
{
Route::rules(['get' => [],
'post' => [],
'put' => [],
'delete' => [],
'patch' => [],
'head' => [],
'options' => [],
'*' => [],
'alias' => [],
'domain' => [],
'pattern' => [],
'name' => []]);
Route::name([]);
}
public function testBuildModule()
{
Route::get('blog/:name', 'index/blog');
Route::get('blog/:id', 'index/blog');
Config::set('pathinfo_depr', '/');
Config::set('url_html_suffix', '');
$this->assertEquals('/blog/thinkphp', Url::build('index/blog?name=thinkphp'));
$this->assertEquals('/blog/thinkphp.html', Url::build('index/blog', 'name=thinkphp', 'html'));
$this->assertEquals('/blog/10', Url::build('index/blog?id=10'));
$this->assertEquals('/blog/10.html', Url::build('index/blog', 'id=10', 'html'));
Route::get('item-<name><id?>', 'blog/item', [], ['name' => '\w+', 'id' => '\d+']);
$this->assertEquals('/item-thinkphp', Url::build('blog/item?name=thinkphp'));
$this->assertEquals('/item-thinkphp2016', Url::build('blog/item?name=thinkphp&id=2016'));
}
public function testBuildController()
{
Config::set('url_html_suffix', '');
Route::get('blog/:id', '@index/blog/read');
$this->assertEquals('/blog/10.html', Url::build('@index/blog/read', 'id=10', 'html'));
Route::get('foo/bar', '@foo/bar/index');
$this->assertEquals('/foo/bar', Url::build('@foo/bar/index'));
Route::get('foo/bar/baz', '@foo/bar.BAZ/index');
$this->assertEquals('/foo/bar/baz', Url::build('@foo/bar.BAZ/index'));
}
public function testBuildMethod()
{
Route::get('blog/:id', '\app\index\controller\blog@read');
$this->assertEquals('/blog/10.html', Url::build('\app\index\controller\blog@read', 'id=10', 'html'));
}
public function testBuildRoute()
{
Route::get('blog/:id', 'index/blog');
Config::set('url_html_suffix', 'shtml');
$this->assertNotEquals('/blog/10.html', Url::build('/blog/10'));
$this->assertEquals('/blog/10.shtml', Url::build('/blog/10'));
}
public function testBuildNameRoute()
{
Route::get(['name', 'blog/:id'], 'index/blog');
$this->assertEquals([['blog/:id', ['id' => 1], null, null]], Route::name('name'));
Config::set('url_html_suffix', 'shtml');
$this->assertEquals('/blog/10.shtml', Url::build('name?id=10'));
}
public function testBuildAnchor()
{
Route::get('blog/:id', 'index/blog');
Config::set('url_html_suffix', 'shtml');
$this->assertEquals('/blog/10.shtml#detail', Url::build('index/blog#detail', 'id=10'));
Config::set('url_common_param', true);
$this->assertEquals('/blog/10.shtml?foo=bar#detail', Url::build('index/blog#detail', "id=10&foo=bar"));
}
public function testBuildDomain()
{
Config::set('url_domain_deploy', true);
Route::domain('subdomain.thinkphp.cn', 'admin');
$this->assertEquals('http://subdomain.thinkphp.cn/blog/10.html', Url::build('/blog/10'));
Route::domain('subdomain.thinkphp.cn', [
'hello/:name' => 'index/hello',
]);
$this->assertEquals('http://subdomain.thinkphp.cn/hello/thinkphp.html', Url::build('index/hello?name=thinkphp'));
}
public function testRoot()
{
Config::set('url_domain_deploy', false);
Config::set('url_common_param', false);
Url::root('/index.php');
Route::get('blog/:id', 'index/blog/read');
Config::set('url_html_suffix', 'shtml');
$this->assertEquals('/index.php/blog/10/name/thinkphp.shtml', Url::build('index/blog/read?id=10&name=thinkphp'));
}
}

View File

@@ -0,0 +1,200 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
/**
* Validate类测试
*/
namespace tests\thinkphp\library\think;
use think\File;
use think\Validate;
class validateTest extends \PHPUnit_Framework_TestCase
{
public function testCheck()
{
$rule = [
'name' => 'require|max:25',
'age' => 'number|between:1,120',
'email' => 'email',
];
$msg = [
'name.require' => '名称必须',
'name.max' => '名称最多不能超过25个字符',
'age.number' => '年龄必须是数字',
'age.between' => '年龄只能在1-120之间',
'email' => '邮箱格式错误',
];
$data = [
'name' => 'thinkphp',
'age' => 10,
'email' => 'thinkphp@qq.com',
];
$validate = new Validate($rule, $msg);
$result = $validate->check($data);
$this->assertEquals(true, $result);
}
public function testRule()
{
$rule = [
'name' => 'require|method:get|alphaNum|max:25|expire:2016-1-1,2026-1-1',
'account' => 'requireIf:name,thinkphp|alphaDash|min:4|length:4,30',
'age' => 'number|between:1,120',
'email' => 'requireWith:name|email',
'host' => 'activeUrl|activeUrl:A',
'url' => 'url',
'ip' => 'ip|ip:ipv4',
'score' => 'float|gt:60|notBetween:90,100|notIn:70,80|lt:100|elt:100|egt:60',
'status' => 'integer|in:0,1,2',
'begin_time' => 'after:2016-3-18|beforeWith:end_time',
'end_time' => 'before:2016-10-01|afterWith:begin_time',
'info' => 'require|array|length:4|max:5|min:2',
'info.name' => 'require|length:8|alpha|same:thinkphp',
'value' => 'same:100|different:status',
'bool' => 'boolean',
'title' => 'chsAlpha',
'city' => 'chs',
'nickname' => 'chsDash',
'aliasname' => 'chsAlphaNum',
'file' => 'file|fileSize:20480',
'image' => 'image|fileMime:image/png|image:80,80,png',
'test' => 'test',
];
$data = [
'name' => 'thinkphp',
'account' => 'liuchen',
'age' => 10,
'email' => 'thinkphp@qq.com',
'host' => 'thinkphp.cn',
'url' => 'http://thinkphp.cn/topic',
'ip' => '114.34.54.5',
'score' => '89.15',
'status' => 1,
'begin_time' => '2016-3-20',
'end_time' => '2016-5-1',
'info' => [1, 2, 3, 'name' => 'thinkphp'],
'zip' => '200000',
'date' => '16-3-8',
'ok' => 'yes',
'value' => 100,
'bool' => true,
'title' => '流年ThinkPHP',
'city' => '上海',
'nickname' => '流年ThinkPHP_2016',
'aliasname' => '流年Think2016',
'file' => new File(THINK_PATH . 'base.php'),
'image' => new File(THINK_PATH . 'logo.png'),
'test' => 'test',
];
$validate = new Validate($rule);
$validate->extend('test', function ($value) {return 'test' == $value ? true : false;});
$validate->rule('zip', '/^\d{6}$/');
$validate->rule([
'ok' => 'require|accepted',
'date' => 'date|dateFormat:y-m-d',
]);
$result = $validate->batch()->check($data);
$this->assertEquals(true, $result);
}
public function testMsg()
{
$validate = new Validate();
$validate->message('name.require', '名称必须');
$validate->message([
'name.require' => '名称必须',
'name.max' => '名称最多不能超过25个字符',
'age.number' => '年龄必须是数字',
'age.between' => '年龄只能在1-120之间',
'email' => '邮箱格式错误',
]);
}
public function testMake()
{
$rule = [
'name' => 'require|max:25',
'age' => 'number|between:1,120',
'email' => 'email',
];
$msg = [
'name.require' => '名称必须',
'name.max' => '名称最多不能超过25个字符',
'age.number' => '年龄必须是数字',
'age.between' => '年龄只能在1-120之间',
'email' => '邮箱格式错误',
];
$validate = Validate::make($rule, $msg);
}
public function testExtend()
{
$validate = new Validate(['name' => 'check:1']);
$validate->extend('check', function ($value, $rule) {return $rule == $value ? true : false;});
$validate->extend(['check' => function ($value, $rule) {return $rule == $value ? true : false;}]);
$data = ['name' => 1];
$result = $validate->check($data);
$this->assertEquals(true, $result);
}
public function testScene()
{
$rule = [
'name' => 'require|max:25',
'age' => 'number|between:1,120',
'email' => 'email',
];
$msg = [
'name.require' => '名称必须',
'name.max' => '名称最多不能超过25个字符',
'age.number' => '年龄必须是数字',
'age.between' => '年龄只能在1-120之间',
'email' => '邮箱格式错误',
];
$data = [
'name' => 'thinkphp',
'age' => 10,
'email' => 'thinkphp@qq.com',
];
$validate = new Validate($rule);
$validate->scene(['edit' => ['name', 'age']]);
$validate->scene('edit', ['name', 'age']);
$validate->scene('edit');
$result = $validate->check($data);
$this->assertEquals(true, $result);
}
public function testSetTypeMsg()
{
$rule = [
'name|名称' => 'require|max:25',
'age' => 'number|between:1,120',
'email' => 'email',
['sex', 'in:1,2', '性别错误'],
];
$data = [
'name' => '',
'age' => 10,
'email' => 'thinkphp@qq.com',
'sex' => '3',
];
$validate = new Validate($rule);
$validate->setTypeMsg('require', ':attribute必须');
$validate->setTypeMsg(['require' => ':attribute必须']);
$result = $validate->batch()->check($data);
$this->assertFalse($result);
$this->assertEquals(['name' => '名称必须', 'sex' => '性别错误'], $validate->getError());
}
}

View File

@@ -0,0 +1,2 @@
*
!.gitignore

View File

@@ -0,0 +1,14 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
</head>
<body>
</body>
</html>

View File

@@ -0,0 +1,76 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
/**
* view测试
* @author mahuan <mahuan@d1web.top>
*/
namespace tests\thinkphp\library\think;
class viewTest extends \PHPUnit_Framework_TestCase
{
/**
* 句柄测试
* @return mixed
* @access public
*/
public function testGetInstance()
{
\think\Cookie::get('a');
$view_instance = \think\View::instance();
$this->assertInstanceOf('\think\view', $view_instance, 'instance方法返回错误');
}
/**
* 测试变量赋值
* @return mixed
* @access public
*/
public function testAssign()
{
$view_instance = \think\View::instance();
$view_instance->key = 'value';
$this->assertTrue(isset($view_instance->key));
$this->assertEquals('value', $view_instance->key);
$data = $view_instance->assign(array('key' => 'value'));
$data = $view_instance->assign('key2', 'value2');
//测试私有属性
$expect_data = array('key' => 'value', 'key2' => 'value2');
$this->assertAttributeEquals($expect_data, 'data', $view_instance);
}
/**
* 测试引擎设置
* @return mixed
* @access public
*/
public function testEngine()
{
$view_instance = \think\View::instance();
$data = $view_instance->engine('php');
$data = $view_instance->engine(['type' => 'php', 'view_path' => '', 'view_suffix' => '.php', 'view_depr' => DS]);
$php_engine = new \think\view\driver\Php(['view_path' => '', 'view_suffix' => '.php', 'view_depr' => DS]);
$this->assertAttributeEquals($php_engine, 'engine', $view_instance);
//测试模板引擎驱动
$data = $view_instance->engine(['type' => 'think', 'view_path' => '', 'view_suffix' => '.html', 'view_depr' => DS]);
$think_engine = new \think\view\driver\Think(['view_path' => '', 'view_suffix' => '.html', 'view_depr' => DS]);
$this->assertAttributeEquals($think_engine, 'engine', $view_instance);
}
public function testReplace()
{
$view_instance = \think\View::instance();
$view_instance->replace('string', 'replace')->display('string');
}
}

View File

@@ -0,0 +1,339 @@
<?php
namespace tests\thinkphp\library\traits\controller;
use think\Config;
use think\Request;
use think\Response;
use think\response\Redirect;
use think\View;
use traits\controller\Jump;
class jumpTest extends \PHPUnit_Framework_TestCase
{
/**
* @var testClassWithJump
*/
protected $testClass;
/**
* @var Request
*/
protected $request;
/**
* @var mixed
*/
protected $originServerData;
public function setUp()
{
$this->testClass = new testClassWithJump();
$this->request = Request::create('');
$this->originServerData = Request::instance()->server();
}
public function tearDown()
{
Request::instance()->server($this->originServerData);
}
/**
* @dataProvider provideTestSuccess
*/
public function testSuccess($arguments, $expected, array $extra)
{
if (isset($extra['server'])) {
$this->request->server($extra['server']);
}
$mock = $this->getMockBuilder(get_class($this->testClass))->setMethods(['getResponseType'])->getMock();
$mock->expects($this->any())->method('getResponseType')->willReturn($extra['return']);
try {
call_user_func_array([$mock, 'success'], $arguments);
$this->setExpectedException('\think\exception\HttpResponseException');
} catch (\Exception $e) {
$this->assertInstanceOf('\think\exception\HttpResponseException', $e);
/** @var Response $response */
$response = $e->getResponse();
$this->assertInstanceOf('\Think\Response', $response);
$this->assertEquals($expected['header'], $response->getHeader());
$this->assertEquals($expected['data'], $response->getData());
}
}
/**
* @dataProvider provideTestError
*/
public function testError($arguments, $expected, array $extra)
{
if (isset($extra['server'])) {
$this->request->server($extra['server']);
}
$mock = $this->getMockBuilder(get_class($this->testClass))->setMethods(['getResponseType'])->getMock();
$mock->expects($this->any())->method('getResponseType')->willReturn($extra['return']);
try {
call_user_func_array([$mock, 'error'], $arguments);
$this->setExpectedException('\think\exception\HttpResponseException');
} catch (\Exception $e) {
$this->assertInstanceOf('\think\exception\HttpResponseException', $e);
/** @var Response $response */
$response = $e->getResponse();
$this->assertInstanceOf('\Think\Response', $response);
$this->assertEquals($expected['header'], $response->getHeader());
$this->assertEquals($expected['data'], $response->getData());
}
}
/**
* @dataProvider provideTestResult
*/
public function testResult($arguments, $expected, array $extra)
{
if (isset($extra['server'])) {
$this->request->server($extra['server']);
}
$mock = $this->getMockBuilder(get_class($this->testClass))->setMethods(['getResponseType'])->getMock();
$mock->expects($this->any())->method('getResponseType')->willReturn($extra['return']);
try {
call_user_func_array([$mock, 'result'], $arguments);
$this->setExpectedException('\think\exception\HttpResponseException');
} catch (\Exception $e) {
$this->assertInstanceOf('\think\exception\HttpResponseException', $e);
/** @var Response $response */
$response = $e->getResponse();
$this->assertInstanceOf('\Think\Response', $response);
$this->assertEquals($expected['header'], $response->getHeader());
$this->assertEquals($expected['data'], $response->getData());
}
}
/**
* @dataProvider provideTestRedirect
*/
public function testRedirect($arguments, $expected)
{
try {
call_user_func_array([$this->testClass, 'redirect'], $arguments);
$this->setExpectedException('\think\exception\HttpResponseException');
} catch (\Exception $e) {
$this->assertInstanceOf('\think\exception\HttpResponseException', $e);
/** @var Redirect $response */
$response = $e->getResponse();
$this->assertInstanceOf('\think\response\Redirect', $response);
$this->assertEquals($expected['url'], $response->getTargetUrl());
$this->assertEquals($expected['code'], $response->getCode());
}
}
public function testGetResponseType()
{
Request::instance()->server(['HTTP_X_REQUESTED_WITH' => null]);
$this->assertEquals('html', $this->testClass->getResponseType());
Request::instance()->server(['HTTP_X_REQUESTED_WITH' => true]);
$this->assertEquals('html', $this->testClass->getResponseType());
Request::instance()->server(['HTTP_X_REQUESTED_WITH' => 'xmlhttprequest']);
$this->assertEquals('json', $this->testClass->getResponseType());
}
public function provideTestSuccess()
{
$provideData = [];
$arguments = ['', null, '', 3, []];
$expected = [
'header' => [
'Content-Type' => 'text/html; charset=utf-8'
],
'data' => View::instance(Config::get('template'), Config::get('view_replace_str'))
->fetch(Config::get('dispatch_error_tmpl'), [
'code' => 1,
'msg' => '',
'data' => '',
'url' => '/index.php/',
'wait' => 3,
])
];
$provideData[] = [$arguments, $expected, ['server' => ['HTTP_REFERER' => null], 'return' => 'html']];
$arguments = ['thinkphp', null, ['foo'], 4, ['Power-By' => 'thinkphp', 'Content-Type' => 'text/html; charset=gbk']];
$expected = [
'header' => [
'Content-Type' => 'text/html; charset=gbk',
'Power-By' => 'thinkphp'
],
'data' => View::instance(Config::get('template'), Config::get('view_replace_str'))
->fetch(Config::get('dispatch_error_tmpl'), [
'code' => 1,
'msg' => 'thinkphp',
'data' => ['foo'],
'url' => 'http://www.thinkphp.cn',
'wait' => 4,
])
];
$provideData[] = [$arguments, $expected, ['server' => ['HTTP_REFERER' => 'http://www.thinkphp.cn'], 'return' => 'html']];
$arguments = ['thinkphp', 'index', ['foo'], 5, []];
$expected = [
'header' => [
'Content-Type' => 'application/json; charset=utf-8'
],
'data' => [
'code' => 1,
'msg' => 'thinkphp',
'data' => ['foo'],
'url' => '/index.php/index.html',
'wait' => 5,
]
];
$provideData[] = [$arguments, $expected, ['server' => ['HTTP_REFERER' => null], 'return' => 'json']];
return $provideData;
}
public function provideTestError()
{
$provideData = [];
$arguments = ['', null, '', 3, []];
$expected = [
'header' => [
'Content-Type' => 'text/html; charset=utf-8'
],
'data' => View::instance(Config::get('template'), Config::get('view_replace_str'))
->fetch(Config::get('dispatch_error_tmpl'), [
'code' => 0,
'msg' => '',
'data' => '',
'url' => 'javascript:history.back(-1);',
'wait' => 3,
])
];
$provideData[] = [$arguments, $expected, ['return' => 'html']];
$arguments = ['thinkphp', 'http://www.thinkphp.cn', ['foo'], 4, ['Power-By' => 'thinkphp', 'Content-Type' => 'text/html; charset=gbk']];
$expected = [
'header' => [
'Content-Type' => 'text/html; charset=gbk',
'Power-By' => 'thinkphp'
],
'data' => View::instance(Config::get('template'), Config::get('view_replace_str'))
->fetch(Config::get('dispatch_error_tmpl'), [
'code' => 0,
'msg' => 'thinkphp',
'data' => ['foo'],
'url' => 'http://www.thinkphp.cn',
'wait' => 4,
])
];
$provideData[] = [$arguments, $expected, ['return' => 'html']];
$arguments = ['thinkphp', '', ['foo'], 5, []];
$expected = [
'header' => [
'Content-Type' => 'application/json; charset=utf-8'
],
'data' => [
'code' => 0,
'msg' => 'thinkphp',
'data' => ['foo'],
'url' => '',
'wait' => 5,
]
];
$provideData[] = [$arguments, $expected, ['return' => 'json']];
return $provideData;
}
public function provideTestResult()
{
$provideData = [];
$arguments = [null, 0, '', '', []];
$expected = [
'header' => [
'Content-Type' => 'text/html; charset=utf-8'
],
'data' => [
'code' => 0,
'msg' => '',
'time' => Request::create('')->server('REQUEST_TIME'),
'data' => null,
]
];
$provideData[] = [$arguments, $expected, ['return' => 'html']];
$arguments = [['foo'], 200, 'thinkphp', 'json', ['Power-By' => 'thinkphp']];
$expected = [
'header' => [
'Power-By' => 'thinkphp',
'Content-Type' => 'application/json; charset=utf-8'
],
'data' => [
'code' => 200,
'msg' => 'thinkphp',
'time' => 1000,
'data' => ['foo'],
]
];
$provideData[] = [$arguments, $expected, ['server' => ['REQUEST_TIME' => 1000], 'return' => 'json']];
return $provideData;
}
public function provideTestRedirect()
{
$provideData = [];
$arguments = ['', [], 302, []];
$expected = [
'code'=> 302,
'url' => '/index.php/'
];
$provideData[] = [$arguments, $expected, []];
$arguments = ['index', 302, null, []];
$expected = [
'code'=> 302,
'url' => '/index.php/index.html'
];
$provideData[] = [$arguments, $expected, []];
$arguments = ['http://www.thinkphp.cn', 301, 302, []];
$expected = [
'code'=> 301,
'url' => 'http://www.thinkphp.cn'
];
$provideData[] = [$arguments, $expected, []];
return $provideData;
}
}
class testClassWithJump
{
use Jump {
success as public;
error as public;
result as public;
redirect as public;
getResponseType as public;
}
}

View File

@@ -0,0 +1,179 @@
<?php
namespace tests\thinkphp\library\traits\model;
use think\Db;
use think\Model;
use traits\model\SoftDelete;
class softDeleteTest extends \PHPUnit_Framework_TestCase
{
const TEST_TIME = 10000;
public function setUp()
{
$config = (new testClassWithSoftDelete())->connection;
$sql[] = <<<SQL
DROP TABLE IF EXISTS `tp_soft_delete`;
SQL;
$sql[] = <<<SQL
CREATE TABLE `tp_soft_delete` (
`id` int(10) unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT,
`name` char(40) NOT NULL DEFAULT '' COMMENT '用户名',
`delete_time` int(10) DEFAULT NULL COMMENT '软删除时间'
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='ThinkPHP SoftDelete Test';
SQL;
$time = self::TEST_TIME;
$sql[] = "INSERT INTO tp_soft_delete (`id`, `name`, `delete_time`) VALUES (1, 'valid data1', null)";
$sql[] = "INSERT INTO tp_soft_delete (`id`, `name`, `delete_time`) VALUES (2, 'invalid data2', {$time})";
$sql[] = "INSERT INTO tp_soft_delete (`id`, `name`, `delete_time`) VALUES (3, 'invalid data3', {$time})";
$sql[] = "INSERT INTO tp_soft_delete (`id`, `name`, `delete_time`) VALUES (4, 'valid data4', null)";
$sql[] = "INSERT INTO tp_soft_delete (`id`, `name`, `delete_time`) VALUES (5, 'valid data5', null)";
foreach ($sql as $one) {
Db::connect($config)->execute($one);
}
}
public function testTrashed()
{
/** @var testClassWithSoftDelete[] $selections */
$selections = testClassWithSoftDelete::withTrashed()->select();
$this->assertFalse($selections[0]->trashed());
$this->assertTrue($selections[1]->trashed());
$this->assertTrue($selections[2]->trashed());
}
public function testDefaultTrashed()
{
$this->assertCount(3, testClassWithSoftDelete::all());
}
public function testWithTrashed()
{
$this->assertCount(5, testClassWithSoftDelete::withTrashed()->select());
}
public function testOnlyTrashed()
{
$this->assertCount(2, testClassWithSoftDelete::onlyTrashed()->select());
}
public function testSoftDelete()
{
$this->assertEquals(1, testClassWithSoftDelete::get(1)->delete());
$this->assertNotNull(testClassWithSoftDelete::withTrashed()->find(1)->getData('delete_time'));
}
public function testForceDelete()
{
$this->assertEquals(1, testClassWithSoftDelete::get(1)->delete(true));
$this->assertNull(testClassWithSoftDelete::get(1));
}
public function testSoftDestroy()
{
$this->assertEquals(5, testClassWithSoftDelete::destroy([1, 2, 3, 4, 5, 6]));
$this->assertNotNull(testClassWithSoftDelete::withTrashed()->find(2)->getData('delete_time'));
$this->assertNotEquals(self::TEST_TIME, testClassWithSoftDelete::withTrashed()->find(2)->getData('delete_time'));
$this->assertNotEquals(self::TEST_TIME, testClassWithSoftDelete::withTrashed()->find(3)->getData('delete_time'));
$this->assertNotNull(testClassWithSoftDelete::withTrashed()->find(4)->getData('delete_time'));
$this->assertNotNull(testClassWithSoftDelete::withTrashed()->find(5)->getData('delete_time'));
}
public function testForceDestroy()
{
$this->assertEquals(5, testClassWithSoftDelete::destroy([1, 2, 3, 4, 5, 6], true));
$this->assertNull(testClassWithSoftDelete::withTrashed()->find(1));
$this->assertNull(testClassWithSoftDelete::withTrashed()->find(2));
$this->assertNull(testClassWithSoftDelete::withTrashed()->find(3));
$this->assertNull(testClassWithSoftDelete::withTrashed()->find(4));
$this->assertNull(testClassWithSoftDelete::withTrashed()->find(5));
}
public function testRestore()
{
/** @var testClassWithSoftDelete[] $selections */
$selections = testClassWithSoftDelete::withTrashed()->select();
$this->assertEquals(0, $selections[0]->restore());
$this->assertEquals(1, $selections[1]->restore());
$this->assertEquals(1, $selections[2]->restore());
$this->assertEquals(0, $selections[3]->restore());
$this->assertEquals(0, $selections[4]->restore());
$this->assertNull(testClassWithSoftDelete::withTrashed()->find(1)->getData('delete_time'));
$this->assertNull(testClassWithSoftDelete::withTrashed()->find(2)->getData('delete_time'));
}
public function testGetDeleteTimeField()
{
$testClass = new testClassWithSoftDelete();
$this->assertEquals('delete_time', $testClass->getDeleteTimeField());
$testClass->deleteTime = 'create_time';
$this->assertEquals('create_time', $testClass->getDeleteTimeField());
$testClass->deleteTime = 'test.create_time';
$this->assertEquals('create_time', $testClass->getDeleteTimeField());
$testClass->deleteTime = 'create_time';
$this->assertEquals('__TABLE__.create_time', $testClass->getDeleteTimeField(true));
}
}
class testClassWithSoftDelete extends Model
{
public $table = 'tp_soft_delete';
public $deleteTime = 'delete_time';
public $connection = [
// 数据库类型
'type' => 'mysql',
// 服务器地址
'hostname' => '127.0.0.1',
// 数据库名
'database' => 'test',
// 用户名
'username' => 'root',
// 密码
'password' => '',
// 端口
'hostport' => '',
// 连接dsn
'dsn' => '',
// 数据库连接参数
'params' => [],
// 数据库编码默认采用utf8
'charset' => 'utf8',
// 数据库表前缀
'prefix' => '',
// 数据库调试模式
'debug' => true,
// 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
'deploy' => 0,
// 数据库读写是否分离 主从式有效
'rw_separate' => false,
// 读写分离后 主服务器数量
'master_num' => 1,
// 指定从服务器序号
'slave_no' => '',
// 是否严格检查字段是否存在
'fields_strict' => true,
// 数据集返回类型 array 数组 collection Collection对象
'resultset_type' => 'array',
// 是否自动写入时间戳字段
'auto_timestamp' => false,
// 是否需要进行SQL性能分析
'sql_explain' => false,
];
use SoftDelete {
getDeleteTimeField as public;
}
}

View File

@@ -0,0 +1,60 @@
<?php
namespace tests\thinkphp\library\traits\think;
use traits\think\Instance;
class instanceTest extends \PHPUnit_Framework_TestCase
{
public function testInstance()
{
$father = InstanceTestFather::instance();
$this->assertInstanceOf('\tests\thinkphp\library\traits\think\InstanceTestFather', $father);
$this->assertEquals([], $father->options);
$son = InstanceTestFather::instance(['son']);
$this->assertSame($father, $son);
}
public function testCallStatic()
{
$father = InstanceTestFather::instance();
$this->assertEquals([], $father->options);
$this->assertEquals($father::__protectedStaticFunc(['thinkphp']), 'protectedStaticFunc["thinkphp"]');
try {
$father::_protectedStaticFunc();
$this->setExpectedException('\think\Exception');
} catch (\Exception $e) {
$this->assertInstanceOf('\think\Exception', $e);
}
}
protected function tearDown()
{
call_user_func(\Closure::bind(function () {
InstanceTestFather::$instance = null;
}, null, '\tests\thinkphp\library\traits\think\InstanceTestFather'));
}
}
class InstanceTestFather
{
use Instance;
public $options = null;
public function __construct($options)
{
$this->options = $options;
}
protected static function _protectedStaticFunc($params)
{
return 'protectedStaticFunc' . json_encode($params);
}
}
class InstanceTestSon extends InstanceTestFather
{
}