first commit

This commit is contained in:
Valentin
2024-03-26 13:31:26 +01:00
commit a56b4dc2fc
922 changed files with 133572 additions and 0 deletions

View File

@@ -0,0 +1,847 @@
<?php
use Codeception\Util\Fixtures;
use Grav\Common\Grav;
use Grav\Common\Assets;
/**
* Class AssetsTest
*/
class AssetsTest extends \Codeception\TestCase\Test
{
/** @var Grav $grav */
protected $grav;
/** @var Assets $assets */
protected $assets;
protected function _before(): void
{
$grav = Fixtures::get('grav');
$this->grav = $grav();
$this->assets = $this->grav['assets'];
}
protected function _after(): void
{
}
public function testAddingAssets(): void
{
//test add()
$this->assets->add('test.css');
$css = $this->assets->css();
self::assertSame('<link href="/test.css" type="text/css" rel="stylesheet">' . PHP_EOL, $css);
$array = $this->assets->getCss();
/** @var Assets\BaseAsset $item */
$item = reset($array);
$actual = json_encode($item);
$expected = '
{
"type":"css",
"elements":{
"asset":"\/test.css",
"asset_type":"css",
"order":0,
"group":"head",
"position":"pipeline",
"priority":10,
"attributes":{
"type":"text\/css",
"rel":"stylesheet"
},
"modified":false,
"query":""
}
}';
self::assertJsonStringEqualsJsonString($expected, $actual);
$this->assets->add('test.js');
$js = $this->assets->js();
self::assertSame('<script src="/test.js"></script>' . PHP_EOL, $js);
$array = $this->assets->getJs();
/** @var Assets\BaseAsset $item */
$item = reset($array);
$actual = json_encode($item);
$expected = '
{
"type":"js",
"elements":{
"asset":"\/test.js",
"asset_type":"js",
"order":0,
"group":"head",
"position":"pipeline",
"priority":10,
"attributes":[
],
"modified":false,
"query":""
}
}';
self::assertJsonStringEqualsJsonString($expected, $actual);
//test addCss(). Test adding asset to a separate group
$this->assets->reset();
$this->assets->addCSS('test.css');
$css = $this->assets->css();
self::assertSame('<link href="/test.css" type="text/css" rel="stylesheet">' . PHP_EOL, $css);
$array = $this->assets->getCss();
/** @var Assets\BaseAsset $item */
$item = reset($array);
$actual = json_encode($item);
$expected = '
{
"type":"css",
"elements":{
"asset":"\/test.css",
"asset_type":"css",
"order":0,
"group":"head",
"position":"pipeline",
"priority":10,
"attributes":{
"type":"text\/css",
"rel":"stylesheet"
},
"modified":false,
"query":""
}
}';
self::assertJsonStringEqualsJsonString($expected, $actual);
//test addCss(). Testing with remote URL
$this->assets->reset();
$this->assets->addCSS('http://www.somesite.com/test.css');
$css = $this->assets->css();
self::assertSame('<link href="http://www.somesite.com/test.css" type="text/css" rel="stylesheet">' . PHP_EOL, $css);
$array = $this->assets->getCss();
/** @var Assets\BaseAsset $item */
$item = reset($array);
$actual = json_encode($item);
$expected = '
{
"type":"css",
"elements":{
"asset":"http:\/\/www.somesite.com\/test.css",
"asset_type":"css",
"order":0,
"group":"head",
"position":"pipeline",
"priority":10,
"attributes":{
"type":"text\/css",
"rel":"stylesheet"
},
"query":""
}
}';
self::assertJsonStringEqualsJsonString($expected, $actual);
//test addCss() adding asset to a separate group, and with an alternate rel attribute
$this->assets->reset();
$this->assets->addCSS('test.css', ['group' => 'alternate', 'rel' => 'alternate']);
$css = $this->assets->css('alternate');
self::assertSame('<link href="/test.css" type="text/css" rel="alternate">' . PHP_EOL, $css);
//test addJs()
$this->assets->reset();
$this->assets->addJs('test.js');
$js = $this->assets->js();
self::assertSame('<script src="/test.js"></script>' . PHP_EOL, $js);
$array = $this->assets->getJs();
/** @var Assets\BaseAsset $item */
$item = reset($array);
$actual = json_encode($item);
$expected = '
{
"type":"js",
"elements":{
"asset":"\/test.js",
"asset_type":"js",
"order":0,
"group":"head",
"position":"pipeline",
"priority":10,
"attributes":[],
"modified":false,
"query":""
}
}';
self::assertJsonStringEqualsJsonString($expected, $actual);
//Test CSS Groups
$this->assets->reset();
$this->assets->addCSS('test.css', ['group' => 'footer']);
$css = $this->assets->css();
self::assertEmpty($css);
$css = $this->assets->css('footer');
self::assertSame('<link href="/test.css" type="text/css" rel="stylesheet">' . PHP_EOL, $css);
$array = $this->assets->getCss();
/** @var Assets\BaseAsset $item */
$item = reset($array);
$actual = json_encode($item);
$expected = '
{
"type": "css",
"elements": {
"asset": "/test.css",
"asset_type": "css",
"order": 0,
"group": "footer",
"position": "pipeline",
"priority": 10,
"attributes": {
"type": "text/css",
"rel": "stylesheet"
},
"modified": false,
"query": ""
}
}
';
self::assertJsonStringEqualsJsonString($expected, $actual);
//Test JS Groups
$this->assets->reset();
$this->assets->addJs('test.js', ['group' => 'footer']);
$js = $this->assets->js();
self::assertEmpty($js);
$js = $this->assets->js('footer');
self::assertSame('<script src="/test.js"></script>' . PHP_EOL, $js);
$array = $this->assets->getJs();
/** @var Assets\BaseAsset $item */
$item = reset($array);
$actual = json_encode($item);
$expected = '
{
"type": "js",
"elements": {
"asset": "/test.js",
"asset_type": "js",
"order": 0,
"group": "footer",
"position": "pipeline",
"priority": 10,
"attributes": [],
"modified": false,
"query": ""
}
}';
self::assertJsonStringEqualsJsonString($expected, $actual);
//Test async / defer
$this->assets->reset();
$this->assets->addJs('test.js', ['loading' => 'async']);
$js = $this->assets->js();
self::assertSame('<script src="/test.js" async></script>' . PHP_EOL, $js);
$array = $this->assets->getJs();
/** @var Assets\BaseAsset $item */
$item = reset($array);
$actual = json_encode($item);
$expected = '
{
"type": "js",
"elements": {
"asset": "/test.js",
"asset_type": "js",
"order": 0,
"group": "head",
"position": "pipeline",
"priority": 10,
"attributes": {
"loading": "async"
},
"modified": false,
"query": ""
}
}';
self::assertJsonStringEqualsJsonString($expected, $actual);
$this->assets->reset();
$this->assets->addJs('test.js', ['loading' => 'defer']);
$js = $this->assets->js();
self::assertSame('<script src="/test.js" defer></script>' . PHP_EOL, $js);
$array = $this->assets->getJs();
/** @var Assets\BaseAsset $item */
$item = reset($array);
$actual = json_encode($item);
$expected = '
{
"type": "js",
"elements": {
"asset": "/test.js",
"asset_type": "js",
"order": 0,
"group": "head",
"position": "pipeline",
"priority": 10,
"attributes": {
"loading": "defer"
},
"modified": false,
"query": ""
}
}';
self::assertJsonStringEqualsJsonString($expected, $actual);
//Test inline
$this->assets->reset();
$this->assets->setJsPipeline(true);
$this->assets->addJs('/system/assets/jquery/jquery-3.x.min.js');
$js = $this->assets->js('head', ['loading' => 'inline']);
self::assertStringContainsString('"jquery",[],function()', $js);
$this->assets->reset();
$this->assets->setCssPipeline(true);
$this->assets->addCss('/system/assets/debugger/phpdebugbar.css');
$css = $this->assets->css('head', ['loading' => 'inline']);
self::assertStringContainsString('div.phpdebugbar', $css);
$this->assets->reset();
$this->assets->setCssPipeline(true);
$this->assets->addCss('https://fonts.googleapis.com/css?family=Roboto');
$css = $this->assets->css('head', ['loading' => 'inline']);
self::assertStringContainsString('font-family:\'Roboto\';', $css);
//Test adding media queries
$this->assets->reset();
$this->assets->add('test.css', ['media' => 'only screen and (min-width: 640px)']);
$css = $this->assets->css();
self::assertSame('<link href="/test.css" type="text/css" rel="stylesheet" media="only screen and (min-width: 640px)">' . PHP_EOL, $css);
}
public function testAddingAssetPropertiesWithArray(): void
{
//Test adding assets with object to define properties
$this->assets->reset();
$this->assets->addJs('test.js', ['loading' => 'async']);
$js = $this->assets->js();
self::assertSame('<script src="/test.js" async></script>' . PHP_EOL, $js);
$this->assets->reset();
}
public function testAddingJSAssetPropertiesWithArrayFromCollection(): void
{
//Test adding properties with array
$this->assets->reset();
$this->assets->addJs('jquery', ['loading' => 'async']);
$js = $this->assets->js();
self::assertSame('<script src="/system/assets/jquery/jquery-3.x.min.js" async></script>' . PHP_EOL, $js);
//Test priority too
$this->assets->reset();
$this->assets->addJs('jquery', ['loading' => 'async', 'priority' => 1]);
$this->assets->addJs('test.js', ['loading' => 'async', 'priority' => 2]);
$js = $this->assets->js();
self::assertSame('<script src="/test.js" async></script>' . PHP_EOL .
'<script src="/system/assets/jquery/jquery-3.x.min.js" async></script>' . PHP_EOL, $js);
//Test multiple groups
$this->assets->reset();
$this->assets->addJs('jquery', ['loading' => 'async', 'priority' => 1, 'group' => 'footer']);
$this->assets->addJs('test.js', ['loading' => 'async', 'priority' => 2]);
$js = $this->assets->js();
self::assertSame('<script src="/test.js" async></script>' . PHP_EOL, $js);
$js = $this->assets->js('footer');
self::assertSame('<script src="/system/assets/jquery/jquery-3.x.min.js" async></script>' . PHP_EOL, $js);
//Test adding array of assets
//Test priority too
$this->assets->reset();
$this->assets->addJs(['jquery', 'test.js'], ['loading' => 'async']);
$js = $this->assets->js();
self::assertSame('<script src="/system/assets/jquery/jquery-3.x.min.js" async></script>' . PHP_EOL .
'<script src="/test.js" async></script>' . PHP_EOL, $js);
}
public function testAddingLegacyFormat(): void
{
// regular CSS add
//test addCss(). Test adding asset to a separate group
$this->assets->reset();
$this->assets->addCSS('test.css', 15, true, 'bottom', 'async');
$css = $this->assets->css('bottom');
self::assertSame('<link href="/test.css" type="text/css" rel="stylesheet" async>' . PHP_EOL, $css);
$array = $this->assets->getCss();
/** @var Assets\BaseAsset $item */
$item = reset($array);
$actual = json_encode($item);
$expected = '
{
"type":"css",
"elements":{
"asset":"\/test.css",
"asset_type":"css",
"order":0,
"group":"bottom",
"position":"pipeline",
"priority":15,
"attributes":{
"type":"text\/css",
"rel":"stylesheet",
"loading":"async"
},
"modified":false,
"query":""
}
}';
self::assertJsonStringEqualsJsonString($expected, $actual);
$this->assets->reset();
$this->assets->addJs('test.js', 15, false, 'defer', 'bottom');
$js = $this->assets->js('bottom');
self::assertSame('<script src="/test.js" defer></script>' . PHP_EOL, $js);
$array = $this->assets->getJs();
/** @var Assets\BaseAsset $item */
$item = reset($array);
$actual = json_encode($item);
$expected = '
{
"type": "js",
"elements": {
"asset": "/test.js",
"asset_type": "js",
"order": 0,
"group": "bottom",
"position": "after",
"priority": 15,
"attributes": {
"loading": "defer"
},
"modified": false,
"query": ""
}
}';
self::assertJsonStringEqualsJsonString($expected, $actual);
$this->assets->reset();
$this->assets->addInlineCss('body { color: black }', 15, 'bottom');
$css = $this->assets->css('bottom');
self::assertSame('<style>' . PHP_EOL . 'body { color: black }' . PHP_EOL . '</style>' . PHP_EOL, $css);
$this->assets->reset();
$this->assets->addInlineJs('alert("test")', 15, 'bottom', ['id' => 'foo']);
$js = $this->assets->js('bottom');
self::assertSame('<script id="foo">' . PHP_EOL . 'alert("test")' . PHP_EOL . '</script>' . PHP_EOL, $js);
}
public function testAddingCSSAssetPropertiesWithArrayFromCollection(): void
{
$this->assets->registerCollection('test', ['/system/assets/whoops.css']);
//Test priority too
$this->assets->reset();
$this->assets->addCss('test', ['priority' => 1]);
$this->assets->addCss('test.css', ['priority' => 2]);
$css = $this->assets->css();
self::assertSame('<link href="/test.css" type="text/css" rel="stylesheet">' . PHP_EOL .
'<link href="/system/assets/whoops.css" type="text/css" rel="stylesheet">' . PHP_EOL, $css);
//Test multiple groups
$this->assets->reset();
$this->assets->addCss('test', ['priority' => 1, 'group' => 'footer']);
$this->assets->addCss('test.css', ['priority' => 2]);
$css = $this->assets->css();
self::assertSame('<link href="/test.css" type="text/css" rel="stylesheet">' . PHP_EOL, $css);
$css = $this->assets->css('footer');
self::assertSame('<link href="/system/assets/whoops.css" type="text/css" rel="stylesheet">' . PHP_EOL, $css);
//Test adding array of assets
//Test priority too
$this->assets->reset();
$this->assets->addCss(['test', 'test.css'], ['loading' => 'async']);
$css = $this->assets->css();
self::assertSame('<link href="/system/assets/whoops.css" type="text/css" rel="stylesheet" async>' . PHP_EOL .
'<link href="/test.css" type="text/css" rel="stylesheet" async>' . PHP_EOL, $css);
}
public function testAddingAssetPropertiesWithArrayFromCollectionAndParameters(): void
{
$this->assets->registerCollection('collection_multi_params', [
'foo.js' => [ 'defer' => true ],
'bar.js' => [ 'integrity' => 'sha512-abc123' ],
'foobar.css' => [ 'defer' => null, 'loading' => null ]
]);
// # Test adding properties with array
$this->assets->addJs('collection_multi_params', ['loading' => 'async']);
$js = $this->assets->js();
// expected output
$expected = [
'<script src="/foo.js" async defer="1"></script>',
'<script src="/bar.js" async integrity="sha512-abc123"></script>',
'<script src="/foobar.css"></script>',
];
self::assertCount(count($expected), array_filter(explode("\n", $js)));
self::assertSame(implode("\n", $expected) . PHP_EOL, $js);
// # Test priority as second argument + render JS should not have any css
$this->assets->reset();
$this->assets->add('low_priority.js', 1);
$this->assets->add('collection_multi_params', 2);
$js = $this->assets->js();
// expected output
$expected = [
'<script src="/foo.js" defer="1"></script>',
'<script src="/bar.js" integrity="sha512-abc123"></script>',
'<script src="/low_priority.js"></script>',
];
self::assertCount(3, array_filter(explode("\n", $js)));
self::assertSame(implode("\n", $expected) . PHP_EOL, $js);
// # Test rendering CSS, should not have any JS
$this->assets->reset();
$this->assets->add('collection_multi_params', [ 'class' => '__classname' ]);
$css = $this->assets->css();
// expected output
$expected = [
'<link href="/foobar.css" type="text/css" rel="stylesheet" class="__classname">',
];
self::assertCount(1, array_filter(explode("\n", $css)));
self::assertSame(implode("\n", $expected) . PHP_EOL, $css);
}
public function testPriorityOfAssets(): void
{
$this->assets->reset();
$this->assets->add('test.css');
$this->assets->add('test-after.css');
$css = $this->assets->css();
self::assertSame('<link href="/test.css" type="text/css" rel="stylesheet">' . PHP_EOL .
'<link href="/test-after.css" type="text/css" rel="stylesheet">' . PHP_EOL, $css);
//----------------
$this->assets->reset();
$this->assets->add('test-after.css', 1);
$this->assets->add('test.css', 2);
$css = $this->assets->css();
self::assertSame('<link href="/test.css" type="text/css" rel="stylesheet">' . PHP_EOL .
'<link href="/test-after.css" type="text/css" rel="stylesheet">' . PHP_EOL, $css);
//----------------
$this->assets->reset();
$this->assets->add('test-after.css', 1);
$this->assets->add('test.css', 2);
$this->assets->add('test-before.css', 3);
$css = $this->assets->css();
self::assertSame('<link href="/test-before.css" type="text/css" rel="stylesheet">' . PHP_EOL .
'<link href="/test.css" type="text/css" rel="stylesheet">' . PHP_EOL .
'<link href="/test-after.css" type="text/css" rel="stylesheet">' . PHP_EOL, $css);
}
public function testPipeline(): void
{
$this->assets->reset();
//File not existing. Pipeline searches for that file without reaching it. Output is empty.
$this->assets->add('test.css', null, true);
$this->assets->setCssPipeline(true);
$css = $this->assets->css();
self::assertRegExp('#<link href=\"\/assets\/(.*).css\" type=\"text\/css\" rel=\"stylesheet\">#', $css);
//Add a core Grav CSS file, which is found. Pipeline will now return a file
$this->assets->add('/system/assets/debugger/phpdebugbar', null, true);
$css = $this->assets->css();
self::assertRegExp('#<link href=\"\/assets\/(.*).css\" type=\"text\/css\" rel=\"stylesheet\">#', $css);
}
public function testPipelineWithTimestamp(): void
{
$this->assets->reset();
$this->assets->setTimestamp('foo');
$this->assets->setCssPipeline(true);
//Add a core Grav CSS file, which is found. Pipeline will now return a file
$this->assets->add('/system/assets/debugger.css', null, true);
$css = $this->assets->css();
self::assertRegExp('#<link href=\"\/assets\/(.*).css\?foo\" type=\"text\/css\" rel=\"stylesheet\">#', $css);
}
public function testInline(): void
{
$this->assets->reset();
//File not existing. Pipeline searches for that file without reaching it. Output is empty.
$this->assets->add('test.css', ['loading' => 'inline']);
$css = $this->assets->css();
self::assertSame("<style>\n\n</style>\n", $css);
$this->assets->reset();
//Add a core Grav CSS file, which is found. Pipeline will now return its content.
$this->assets->addCss('https://fonts.googleapis.com/css?family=Roboto', ['loading' => 'inline']);
$this->assets->addCss('/system/assets/debugger/phpdebugbar.css', ['loading' => 'inline']);
$css = $this->assets->css();
self::assertStringContainsString('font-family: \'Roboto\';', $css);
self::assertStringContainsString('div.phpdebugbar-header', $css);
}
public function testInlinePipeline(): void
{
$this->assets->reset();
$this->assets->setCssPipeline(true);
//File not existing. Pipeline searches for that file without reaching it. Output is empty.
$this->assets->add('test.css');
$css = $this->assets->css('head', ['loading' => 'inline']);
self::assertSame("<style>\n\n</style>\n", $css);
//Add a core Grav CSS file, which is found. Pipeline will now return its content.
$this->assets->addCss('https://fonts.googleapis.com/css?family=Roboto', null, true);
$this->assets->add('/system/assets/debugger/phpdebugbar.css', null, true);
$css = $this->assets->css('head', ['loading' => 'inline']);
self::assertStringContainsString('font-family:\'Roboto\';', $css);
self::assertStringContainsString('div.phpdebugbar', $css);
}
public function testAddAsyncJs(): void
{
$this->assets->reset();
$this->assets->addAsyncJs('jquery');
$js = $this->assets->js();
self::assertSame('<script src="/system/assets/jquery/jquery-3.x.min.js" async></script>' . PHP_EOL, $js);
}
public function testAddDeferJs(): void
{
$this->assets->reset();
$this->assets->addDeferJs('jquery');
$js = $this->assets->js();
self::assertSame('<script src="/system/assets/jquery/jquery-3.x.min.js" defer></script>' . PHP_EOL, $js);
}
public function testTimestamps(): void
{
// local CSS nothing extra
$this->assets->reset();
$this->assets->setTimestamp('foo');
$this->assets->addCSS('test.css');
$css = $this->assets->css();
self::assertSame('<link href="/test.css?foo" type="text/css" rel="stylesheet">' . PHP_EOL, $css);
// local CSS already with param
$this->assets->reset();
$this->assets->setTimestamp('foo');
$this->assets->addCSS('test.css?bar');
$css = $this->assets->css();
self::assertSame('<link href="/test.css?bar&foo" type="text/css" rel="stylesheet">' . PHP_EOL, $css);
// external CSS already
$this->assets->reset();
$this->assets->setTimestamp('foo');
$this->assets->addCSS('http://somesite.com/test.css');
$css = $this->assets->css();
self::assertSame('<link href="http://somesite.com/test.css?foo" type="text/css" rel="stylesheet">' . PHP_EOL, $css);
// external CSS already with param
$this->assets->reset();
$this->assets->setTimestamp('foo');
$this->assets->addCSS('http://somesite.com/test.css?bar');
$css = $this->assets->css();
self::assertSame('<link href="http://somesite.com/test.css?bar&foo" type="text/css" rel="stylesheet">' . PHP_EOL, $css);
// local JS nothing extra
$this->assets->reset();
$this->assets->setTimestamp('foo');
$this->assets->addJs('test.js');
$css = $this->assets->js();
self::assertSame('<script src="/test.js?foo"></script>' . PHP_EOL, $css);
// local JS already with param
$this->assets->reset();
$this->assets->setTimestamp('foo');
$this->assets->addJs('test.js?bar');
$css = $this->assets->js();
self::assertSame('<script src="/test.js?bar&foo"></script>' . PHP_EOL, $css);
// external JS already
$this->assets->reset();
$this->assets->setTimestamp('foo');
$this->assets->addJs('http://somesite.com/test.js');
$css = $this->assets->js();
self::assertSame('<script src="http://somesite.com/test.js?foo"></script>' . PHP_EOL, $css);
// external JS already with param
$this->assets->reset();
$this->assets->setTimestamp('foo');
$this->assets->addJs('http://somesite.com/test.js?bar');
$css = $this->assets->js();
self::assertSame('<script src="http://somesite.com/test.js?bar&foo"></script>' . PHP_EOL, $css);
}
public function testAddInlineCss(): void
{
$this->assets->reset();
$this->assets->addInlineCss('body { color: black }');
$css = $this->assets->css();
self::assertSame('<style>' . PHP_EOL . 'body { color: black }' . PHP_EOL . '</style>' . PHP_EOL, $css);
}
public function testAddInlineJs(): void
{
$this->assets->reset();
$this->assets->addInlineJs('alert("test")');
$js = $this->assets->js();
self::assertSame('<script>' . PHP_EOL . 'alert("test")' . PHP_EOL . '</script>' . PHP_EOL, $js);
}
public function testGetCollections(): void
{
self::assertIsArray($this->assets->getCollections());
self::assertContains('jquery', array_keys($this->assets->getCollections()));
self::assertContains('system://assets/jquery/jquery-3.x.min.js', $this->assets->getCollections());
}
public function testExists(): void
{
self::assertTrue($this->assets->exists('jquery'));
self::assertFalse($this->assets->exists('another-unexisting-library'));
}
public function testRegisterCollection(): void
{
$this->assets->registerCollection('debugger', ['/system/assets/debugger.css']);
self::assertTrue($this->assets->exists('debugger'));
self::assertContains('debugger', array_keys($this->assets->getCollections()));
}
public function testRegisterCollectionWithParameters(): void
{
$this->assets->registerCollection('collection_multi_params', [
'foo.js' => [ 'defer' => true ],
'bar.js' => [ 'integrity' => 'sha512-abc123' ],
'foobar.css' => [ 'defer' => null ],
]);
self::assertTrue($this->assets->exists('collection_multi_params'));
$collection = $this->assets->getCollections()['collection_multi_params'];
self::assertArrayHasKey('foo.js', $collection);
self::assertArrayHasKey('bar.js', $collection);
self::assertArrayHasKey('foobar.css', $collection);
self::assertArrayHasKey('defer', $collection['foo.js']);
self::assertArrayHasKey('defer', $collection['foobar.css']);
self::assertNull($collection['foobar.css']['defer']);
self::assertTrue($collection['foo.js']['defer']);
}
public function testReset(): void
{
$this->assets->addInlineJs('alert("test")');
$this->assets->reset();
self::assertCount(0, (array) $this->assets->getJs());
$this->assets->addAsyncJs('jquery');
$this->assets->reset();
self::assertCount(0, (array) $this->assets->getJs());
$this->assets->addInlineCss('body { color: black }');
$this->assets->reset();
self::assertCount(0, (array) $this->assets->getCss());
$this->assets->add('/system/assets/debugger.css', null, true);
$this->assets->reset();
self::assertCount(0, (array) $this->assets->getCss());
}
public function testResetJs(): void
{
$this->assets->addInlineJs('alert("test")');
$this->assets->resetJs();
self::assertCount(0, (array) $this->assets->getJs());
$this->assets->addAsyncJs('jquery');
$this->assets->resetJs();
self::assertCount(0, (array) $this->assets->getJs());
}
public function testResetCss(): void
{
$this->assets->addInlineCss('body { color: black }');
$this->assets->resetCss();
self::assertCount(0, (array) $this->assets->getCss());
$this->assets->add('/system/assets/debugger.css', null, true);
$this->assets->resetCss();
self::assertCount(0, (array) $this->assets->getCss());
}
public function testAddDirCss(): void
{
$this->assets->addDirCss('/system');
self::assertIsArray($this->assets->getCss());
self::assertGreaterThan(0, (array) $this->assets->getCss());
self::assertIsArray($this->assets->getJs());
self::assertCount(0, (array) $this->assets->getJs());
$this->assets->reset();
$this->assets->addDirCss('/system/assets');
self::assertIsArray($this->assets->getCss());
self::assertGreaterThan(0, (array) $this->assets->getCss());
self::assertIsArray($this->assets->getJs());
self::assertCount(0, (array) $this->assets->getJs());
$this->assets->reset();
$this->assets->addDirJs('/system');
self::assertIsArray($this->assets->getCss());
self::assertCount(0, (array) $this->assets->getCss());
self::assertIsArray($this->assets->getJs());
self::assertGreaterThan(0, (array) $this->assets->getJs());
$this->assets->reset();
$this->assets->addDirJs('/system/assets');
self::assertIsArray($this->assets->getCss());
self::assertCount(0, (array) $this->assets->getCss());
self::assertIsArray($this->assets->getJs());
self::assertGreaterThan(0, (array) $this->assets->getJs());
$this->assets->reset();
$this->assets->addDir('/system/assets');
self::assertIsArray($this->assets->getCss());
self::assertGreaterThan(0, (array) $this->assets->getCss());
self::assertIsArray($this->assets->getJs());
self::assertGreaterThan(0, (array) $this->assets->getJs());
//Use streams
$this->assets->reset();
$this->assets->addDir('system://assets');
self::assertIsArray($this->assets->getCss());
self::assertGreaterThan(0, (array) $this->assets->getCss());
self::assertIsArray($this->assets->getJs());
self::assertGreaterThan(0, (array) $this->assets->getJs());
}
}

View File

@@ -0,0 +1,51 @@
<?php
use Codeception\Util\Fixtures;
use Grav\Common\Grav;
/**
* Class BrowserTest
*/
class BrowserTest extends \Codeception\TestCase\Test
{
/** @var Grav $grav */
protected $grav;
protected function _before(): void
{
$grav = Fixtures::get('grav');
$this->grav = $grav();
}
protected function _after(): void
{
}
public function testGetBrowser(): void
{
/* Already covered by PhpUserAgent tests */
}
public function testGetPlatform(): void
{
/* Already covered by PhpUserAgent tests */
}
public function testGetLongVersion(): void
{
/* Already covered by PhpUserAgent tests */
}
public function testGetVersion(): void
{
/* Already covered by PhpUserAgent tests */
}
public function testIsHuman(): void
{
//Already Partially covered by PhpUserAgent tests
//Make sure it recognizes the test as not human
self::assertFalse($this->grav['browser']->isHuman());
}
}

View File

@@ -0,0 +1,31 @@
<?php
use Codeception\Util\Fixtures;
use Grav\Common\Composer;
class ComposerTest extends \Codeception\TestCase\Test
{
protected function _before(): void
{
}
protected function _after(): void
{
}
public function testGetComposerLocation(): void
{
$composerLocation = Composer::getComposerLocation();
self::assertIsString($composerLocation);
self::assertSame('/', $composerLocation[0]);
}
public function testGetComposerExecutor(): void
{
$composerExecutor = Composer::getComposerExecutor();
self::assertIsString($composerExecutor);
self::assertSame('/', $composerExecutor[0]);
self::assertNotNull(strstr($composerExecutor, 'php'));
self::assertNotNull(strstr($composerExecutor, 'composer'));
}
}

View File

@@ -0,0 +1,72 @@
<?php
use Grav\Common\Config\Config;
use Grav\Common\Data\Blueprint;
use Grav\Common\Grav;
/**
* Class InstallCommandTest
*/
class BlueprintTest extends \Codeception\TestCase\Test
{
/**
*/
public function testValidateStrict(): void
{
$blueprint = $this->loadBlueprint('strict');
$blueprint->validate(['test' => 'string']);
}
/**
* @depends testValidateStrict
*/
public function testValidateStrictRequired(): void
{
$blueprint = $this->loadBlueprint('strict');
$this->expectException(\Grav\Common\Data\ValidationException::class);
$blueprint->validate([]);
}
/**
* @depends testValidateStrict
*/
public function testValidateStrictExtra(): void
{
$blueprint = $this->loadBlueprint('strict');
$blueprint->validate(['test' => 'string', 'wrong' => 'field']);
}
/**
* @depends testValidateStrict
*/
public function testValidateStrictExtraException(): void
{
$blueprint = $this->loadBlueprint('strict');
/** @var Config $config */
$config = Grav::instance()['config'];
$var = 'system.strict_mode.blueprint_strict_compat';
$config->set($var, false);
$this->expectException(\Grav\Common\Data\ValidationException::class);
$blueprint->validate(['test' => 'string', 'wrong' => 'field']);
$config->set($var, true);
}
/**
* @param string $filename
* @return Blueprint
*/
protected function loadBlueprint($filename): Blueprint
{
$blueprint = new Blueprint('strict');
$blueprint->setContext(dirname(__DIR__, 3). '/data/blueprints');
$blueprint->load()->init();
return $blueprint;
}
}

View File

@@ -0,0 +1,329 @@
<?php
use Codeception\Util\Fixtures;
use Grav\Common\Grav;
use Grav\Common\GPM\GPM;
define('EXCEPTION_BAD_FORMAT', 1);
define('EXCEPTION_INCOMPATIBLE_VERSIONS', 2);
/**
* Class GpmStub
*/
class GpmStub extends GPM
{
/** @var array */
public $data;
/**
* @inheritdoc
*/
public function findPackage($search, $ignore_exception = false)
{
return $this->data[$search] ?? false;
}
/**
* @inheritdoc
*/
public function findPackages($searches = [])
{
return $this->data;
}
}
/**
* Class InstallCommandTest
*/
class GpmTest extends \Codeception\TestCase\Test
{
/** @var Grav $grav */
protected $grav;
/** @var GpmStub */
protected $gpm;
protected function _before(): void
{
$this->grav = Fixtures::get('grav');
$this->gpm = new GpmStub();
}
protected function _after(): void
{
}
public function testCalculateMergedDependenciesOfPackages(): void
{
//////////////////////////////////////////////////////////////////////////////////////////
// First working example
//////////////////////////////////////////////////////////////////////////////////////////
$this->gpm->data = [
'admin' => (object)[
'dependencies' => [
['name' => 'grav', 'version' => '>=1.0.10'],
['name' => 'form', 'version' => '~2.0'],
['name' => 'login', 'version' => '>=2.0'],
['name' => 'errors', 'version' => '*'],
['name' => 'problems'],
]
],
'test' => (object)[
'dependencies' => [
['name' => 'errors', 'version' => '>=1.0']
]
],
'grav',
'form' => (object)[
'dependencies' => [
['name' => 'errors', 'version' => '>=3.2']
]
]
];
$packages = ['admin', 'test'];
$dependencies = $this->gpm->calculateMergedDependenciesOfPackages($packages);
self::assertIsArray($dependencies);
self::assertCount(5, $dependencies);
self::assertSame('>=1.0.10', $dependencies['grav']);
self::assertArrayHasKey('errors', $dependencies);
self::assertArrayHasKey('problems', $dependencies);
//////////////////////////////////////////////////////////////////////////////////////////
// Second working example
//////////////////////////////////////////////////////////////////////////////////////////
$packages = ['admin', 'form'];
$dependencies = $this->gpm->calculateMergedDependenciesOfPackages($packages);
self::assertIsArray($dependencies);
self::assertCount(5, $dependencies);
self::assertSame('>=3.2', $dependencies['errors']);
//////////////////////////////////////////////////////////////////////////////////////////
// Third working example
//////////////////////////////////////////////////////////////////////////////////////////
$this->gpm->data = [
'admin' => (object)[
'dependencies' => [
['name' => 'errors', 'version' => '>=4.0'],
]
],
'test' => (object)[
'dependencies' => [
['name' => 'errors', 'version' => '>=1.0']
]
],
'another' => (object)[
'dependencies' => [
['name' => 'errors', 'version' => '>=3.2']
]
]
];
$packages = ['admin', 'test', 'another'];
$dependencies = $this->gpm->calculateMergedDependenciesOfPackages($packages);
self::assertIsArray($dependencies);
self::assertCount(1, $dependencies);
self::assertSame('>=4.0', $dependencies['errors']);
//////////////////////////////////////////////////////////////////////////////////////////
// Test alpha / beta / rc
//////////////////////////////////////////////////////////////////////////////////////////
$this->gpm->data = [
'admin' => (object)[
'dependencies' => [
['name' => 'package1', 'version' => '>=4.0.0-rc1'],
['name' => 'package4', 'version' => '>=3.2.0'],
]
],
'test' => (object)[
'dependencies' => [
['name' => 'package1', 'version' => '>=4.0.0-rc2'],
['name' => 'package2', 'version' => '>=3.2.0-alpha'],
['name' => 'package3', 'version' => '>=3.2.0-alpha.2'],
['name' => 'package4', 'version' => '>=3.2.0-alpha'],
]
],
'another' => (object)[
'dependencies' => [
['name' => 'package2', 'version' => '>=3.2.0-beta.11'],
['name' => 'package3', 'version' => '>=3.2.0-alpha.1'],
['name' => 'package4', 'version' => '>=3.2.0-beta'],
]
]
];
$packages = ['admin', 'test', 'another'];
$dependencies = $this->gpm->calculateMergedDependenciesOfPackages($packages);
self::assertSame('>=4.0.0-rc2', $dependencies['package1']);
self::assertSame('>=3.2.0-beta.11', $dependencies['package2']);
self::assertSame('>=3.2.0-alpha.2', $dependencies['package3']);
self::assertSame('>=3.2.0', $dependencies['package4']);
//////////////////////////////////////////////////////////////////////////////////////////
// Raise exception if no version is specified
//////////////////////////////////////////////////////////////////////////////////////////
$this->gpm->data = [
'admin' => (object)[
'dependencies' => [
['name' => 'errors', 'version' => '>=4.0'],
]
],
'test' => (object)[
'dependencies' => [
['name' => 'errors', 'version' => '>=']
]
],
];
$packages = ['admin', 'test'];
try {
$this->gpm->calculateMergedDependenciesOfPackages($packages);
self::fail('Expected Exception not thrown');
} catch (Exception $e) {
self::assertEquals(EXCEPTION_BAD_FORMAT, $e->getCode());
self::assertStringStartsWith('Bad format for version of dependency', $e->getMessage());
}
//////////////////////////////////////////////////////////////////////////////////////////
// Raise exception if incompatible versions are specified
//////////////////////////////////////////////////////////////////////////////////////////
$this->gpm->data = [
'admin' => (object)[
'dependencies' => [
['name' => 'errors', 'version' => '~4.0'],
]
],
'test' => (object)[
'dependencies' => [
['name' => 'errors', 'version' => '~3.0']
]
],
];
$packages = ['admin', 'test'];
try {
$this->gpm->calculateMergedDependenciesOfPackages($packages);
self::fail('Expected Exception not thrown');
} catch (Exception $e) {
self::assertEquals(EXCEPTION_INCOMPATIBLE_VERSIONS, $e->getCode());
self::assertStringEndsWith('required in two incompatible versions', $e->getMessage());
}
//////////////////////////////////////////////////////////////////////////////////////////
// Test dependencies of dependencies
//////////////////////////////////////////////////////////////////////////////////////////
$this->gpm->data = [
'admin' => (object)[
'dependencies' => [
['name' => 'grav', 'version' => '>=1.0.10'],
['name' => 'form', 'version' => '~2.0'],
['name' => 'login', 'version' => '>=2.0'],
['name' => 'errors', 'version' => '*'],
['name' => 'problems'],
]
],
'login' => (object)[
'dependencies' => [
['name' => 'antimatter', 'version' => '>=1.0']
]
],
'grav',
'antimatter' => (object)[
'dependencies' => [
['name' => 'something', 'version' => '>=3.2']
]
]
];
$packages = ['admin'];
$dependencies = $this->gpm->calculateMergedDependenciesOfPackages($packages);
self::assertIsArray($dependencies);
self::assertCount(7, $dependencies);
self::assertSame('>=1.0.10', $dependencies['grav']);
self::assertArrayHasKey('errors', $dependencies);
self::assertArrayHasKey('problems', $dependencies);
self::assertArrayHasKey('antimatter', $dependencies);
self::assertArrayHasKey('something', $dependencies);
self::assertSame('>=3.2', $dependencies['something']);
}
public function testVersionFormatIsNextSignificantRelease(): void
{
self::assertFalse($this->gpm->versionFormatIsNextSignificantRelease('>=1.0'));
self::assertFalse($this->gpm->versionFormatIsNextSignificantRelease('>=2.3.4'));
self::assertFalse($this->gpm->versionFormatIsNextSignificantRelease('>=2.3.x'));
self::assertFalse($this->gpm->versionFormatIsNextSignificantRelease('1.0'));
self::assertTrue($this->gpm->versionFormatIsNextSignificantRelease('~2.3.x'));
self::assertTrue($this->gpm->versionFormatIsNextSignificantRelease('~2.0'));
}
public function testVersionFormatIsEqualOrHigher(): void
{
self::assertTrue($this->gpm->versionFormatIsEqualOrHigher('>=1.0'));
self::assertTrue($this->gpm->versionFormatIsEqualOrHigher('>=2.3.4'));
self::assertTrue($this->gpm->versionFormatIsEqualOrHigher('>=2.3.x'));
self::assertFalse($this->gpm->versionFormatIsEqualOrHigher('~2.3.x'));
self::assertFalse($this->gpm->versionFormatIsEqualOrHigher('1.0'));
}
public function testCheckNextSignificantReleasesAreCompatible(): void
{
/*
* ~1.0 is equivalent to >=1.0 < 2.0.0
* ~1.2 is equivalent to >=1.2 <2.0.0
* ~1.2.3 is equivalent to >=1.2.3 <1.3.0
*/
self::assertTrue($this->gpm->checkNextSignificantReleasesAreCompatible('1.0', '1.2'));
self::assertTrue($this->gpm->checkNextSignificantReleasesAreCompatible('1.2', '1.0'));
self::assertTrue($this->gpm->checkNextSignificantReleasesAreCompatible('1.0', '1.0.10'));
self::assertTrue($this->gpm->checkNextSignificantReleasesAreCompatible('1.1', '1.1.10'));
self::assertTrue($this->gpm->checkNextSignificantReleasesAreCompatible('30.0', '30.10'));
self::assertTrue($this->gpm->checkNextSignificantReleasesAreCompatible('1.0', '1.1.10'));
self::assertTrue($this->gpm->checkNextSignificantReleasesAreCompatible('1.0', '1.8'));
self::assertTrue($this->gpm->checkNextSignificantReleasesAreCompatible('1.0.1', '1.1'));
self::assertTrue($this->gpm->checkNextSignificantReleasesAreCompatible('2.0.0-beta', '2.0'));
self::assertTrue($this->gpm->checkNextSignificantReleasesAreCompatible('2.0.0-rc.1', '2.0'));
self::assertTrue($this->gpm->checkNextSignificantReleasesAreCompatible('2.0', '2.0.0-alpha'));
self::assertFalse($this->gpm->checkNextSignificantReleasesAreCompatible('1.0', '2.2'));
self::assertFalse($this->gpm->checkNextSignificantReleasesAreCompatible('1.0.0-beta.1', '2.0'));
self::assertFalse($this->gpm->checkNextSignificantReleasesAreCompatible('0.9.99', '1.0.0'));
self::assertFalse($this->gpm->checkNextSignificantReleasesAreCompatible('0.9.99', '1.0.10'));
self::assertFalse($this->gpm->checkNextSignificantReleasesAreCompatible('0.9.99', '1.0.10.2'));
}
public function testCalculateVersionNumberFromDependencyVersion(): void
{
self::assertSame('2.0', $this->gpm->calculateVersionNumberFromDependencyVersion('>=2.0'));
self::assertSame('2.0.2', $this->gpm->calculateVersionNumberFromDependencyVersion('>=2.0.2'));
self::assertSame('2.0.2', $this->gpm->calculateVersionNumberFromDependencyVersion('~2.0.2'));
self::assertSame('1', $this->gpm->calculateVersionNumberFromDependencyVersion('~1'));
self::assertNull($this->gpm->calculateVersionNumberFromDependencyVersion(''));
self::assertNull($this->gpm->calculateVersionNumberFromDependencyVersion('*'));
self::assertSame('2.0.2', $this->gpm->calculateVersionNumberFromDependencyVersion('2.0.2'));
}
}

View File

@@ -0,0 +1,120 @@
<?php
use Codeception\Util\Fixtures;
use Grav\Common\Helpers\Excerpts;
use Grav\Common\Grav;
use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Common\Uri;
use Grav\Common\Config\Config;
use Grav\Common\Page\Pages;
use Grav\Common\Language\Language;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
/**
* Class ExcerptsTest
*/
class ExcerptsTest extends \Codeception\TestCase\Test
{
/** @var Parsedown $parsedown */
protected $parsedown;
/** @var Grav $grav */
protected $grav;
/** @var PageInterface $page */
protected $page;
/** @var Pages $pages */
protected $pages;
/** @var Config $config */
protected $config;
/** @var Uri $uri */
protected $uri;
/** @var Language $language */
protected $language;
protected $old_home;
protected function _before(): void
{
$grav = Fixtures::get('grav');
$this->grav = $grav();
$this->pages = $this->grav['pages'];
$this->config = $this->grav['config'];
$this->uri = $this->grav['uri'];
$this->language = $this->grav['language'];
$this->old_home = $this->config->get('system.home.alias');
$this->config->set('system.home.alias', '/item1');
$this->config->set('system.absolute_urls', false);
$this->config->set('system.languages.supported', []);
unset($this->grav['language']);
$this->grav['language'] = new Language($this->grav);
/** @var UniformResourceLocator $locator */
$locator = $this->grav['locator'];
$locator->addPath('page', '', 'tests/fake/nested-site/user/pages', false);
$this->pages->init();
$defaults = [
'extra' => false,
'auto_line_breaks' => false,
'auto_url_links' => false,
'escape_markup' => false,
'special_chars' => ['>' => 'gt', '<' => 'lt'],
];
$this->page = $this->pages->find('/item2/item2-2');
$this->uri->initializeWithURL('http://testing.dev/item2/item2-2')->init();
}
protected function _after(): void
{
$this->config->set('system.home.alias', $this->old_home);
}
public function testProcessImageHtml(): void
{
self::assertRegexp(
'|<img alt="Sample Image" src="\/images\/.*-sample-image.jpe?g\" data-src="sample-image\.jpg\?cropZoom=300,300" \/>|',
Excerpts::processImageHtml('<img src="sample-image.jpg?cropZoom=300,300" alt="Sample Image" />', $this->page)
);
self::assertRegexp(
'|<img alt="Sample Image" class="foo" src="\/images\/.*-sample-image.jpe?g\" data-src="sample-image\.jpg\?classes=foo" \/>|',
Excerpts::processImageHtml('<img src="sample-image.jpg?classes=foo" alt="Sample Image" />', $this->page)
);
}
public function testNoProcess(): void
{
self::assertStringStartsWith(
'<a href="https://play.google.com/store/apps/details?hl=de" id="org.jitsi.meet" target="_blank"',
Excerpts::processLinkHtml('<a href="https://play.google.com/store/apps/details?id=org.jitsi.meet&hl=de&target=_blank">regular process</a>')
);
self::assertStringStartsWith(
'<a href="https://play.google.com/store/apps/details?id=org.jitsi.meet&hl=de&target=_blank"',
Excerpts::processLinkHtml('<a href="https://play.google.com/store/apps/details?id=org.jitsi.meet&hl=de&target=_blank&noprocess">noprocess</a>')
);
self::assertStringStartsWith(
'<a href="https://play.google.com/store/apps/details?id=org.jitsi.meet&hl=de" target="_blank"',
Excerpts::processLinkHtml('<a href="https://play.google.com/store/apps/details?id=org.jitsi.meet&hl=de&target=_blank&noprocess=id">noprocess=id</a>')
);
}
public function testTarget(): void
{
self::assertStringStartsWith(
'<a href="https://play.google.com/store/apps/details" target="_blank"',
Excerpts::processLinkHtml('<a href="https://play.google.com/store/apps/details?target=_blank">only target</a>')
);
self::assertStringStartsWith(
'<a href="https://meet.weikamp.biz/Support" rel="nofollow" target="_blank"',
Excerpts::processLinkHtml('<a href="https://meet.weikamp.biz/Support?rel=nofollow&target=_blank">target and rel</a>')
);
}
}

View File

@@ -0,0 +1,145 @@
<?php
use Codeception\Util\Fixtures;
use Grav\Common\Grav;
use Grav\Common\Inflector;
use Grav\Common\Utils;
/**
* Class InflectorTest
*/
class InflectorTest extends \Codeception\TestCase\Test
{
/** @var Grav $grav */
protected $grav;
/** @var Inflector $uri */
protected $inflector;
protected function _before(): void
{
$grav = Fixtures::get('grav');
$this->grav = $grav();
$this->inflector = $this->grav['inflector'];
}
protected function _after(): void
{
}
public function testPluralize(): void
{
self::assertSame('words', $this->inflector->pluralize('word'));
self::assertSame('kisses', $this->inflector->pluralize('kiss'));
self::assertSame('volcanoes', $this->inflector->pluralize('volcanoe'));
self::assertSame('cherries', $this->inflector->pluralize('cherry'));
self::assertSame('days', $this->inflector->pluralize('day'));
self::assertSame('knives', $this->inflector->pluralize('knife'));
}
public function testSingularize(): void
{
self::assertSame('word', $this->inflector->singularize('words'));
self::assertSame('kiss', $this->inflector->singularize('kisses'));
self::assertSame('volcanoe', $this->inflector->singularize('volcanoe'));
self::assertSame('cherry', $this->inflector->singularize('cherries'));
self::assertSame('day', $this->inflector->singularize('days'));
self::assertSame('knife', $this->inflector->singularize('knives'));
}
public function testTitleize(): void
{
self::assertSame('This String Is Titleized', $this->inflector->titleize('ThisStringIsTitleized'));
self::assertSame('This String Is Titleized', $this->inflector->titleize('this string is titleized'));
self::assertSame('This String Is Titleized', $this->inflector->titleize('this_string_is_titleized'));
self::assertSame('This String Is Titleized', $this->inflector->titleize('this-string-is-titleized'));
self::assertSame('This string is titleized', $this->inflector->titleize('ThisStringIsTitleized', 'first'));
self::assertSame('This string is titleized', $this->inflector->titleize('this string is titleized', 'first'));
self::assertSame('This string is titleized', $this->inflector->titleize('this_string_is_titleized', 'first'));
self::assertSame('This string is titleized', $this->inflector->titleize('this-string-is-titleized', 'first'));
}
public function testCamelize(): void
{
self::assertSame('ThisStringIsCamelized', $this->inflector->camelize('This String Is Camelized'));
self::assertSame('ThisStringIsCamelized', $this->inflector->camelize('thisStringIsCamelized'));
self::assertSame('ThisStringIsCamelized', $this->inflector->camelize('This_String_Is_Camelized'));
self::assertSame('ThisStringIsCamelized', $this->inflector->camelize('this string is camelized'));
self::assertSame('GravSPrettyCoolMy1', $this->inflector->camelize("Grav's Pretty Cool. My #1!"));
}
public function testUnderscorize(): void
{
self::assertSame('this_string_is_underscorized', $this->inflector->underscorize('This String Is Underscorized'));
self::assertSame('this_string_is_underscorized', $this->inflector->underscorize('ThisStringIsUnderscorized'));
self::assertSame('this_string_is_underscorized', $this->inflector->underscorize('This_String_Is_Underscorized'));
self::assertSame('this_string_is_underscorized', $this->inflector->underscorize('This-String-Is-Underscorized'));
}
public function testHyphenize(): void
{
self::assertSame('this-string-is-hyphenized', $this->inflector->hyphenize('This String Is Hyphenized'));
self::assertSame('this-string-is-hyphenized', $this->inflector->hyphenize('ThisStringIsHyphenized'));
self::assertSame('this-string-is-hyphenized', $this->inflector->hyphenize('This-String-Is-Hyphenized'));
self::assertSame('this-string-is-hyphenized', $this->inflector->hyphenize('This_String_Is_Hyphenized'));
}
public function testHumanize(): void
{
//self::assertSame('This string is humanized', $this->inflector->humanize('ThisStringIsHumanized'));
self::assertSame('This string is humanized', $this->inflector->humanize('this_string_is_humanized'));
//self::assertSame('This string is humanized', $this->inflector->humanize('this-string-is-humanized'));
self::assertSame('This String Is Humanized', $this->inflector->humanize('this_string_is_humanized', 'all'));
//self::assertSame('This String Is Humanized', $this->inflector->humanize('this-string-is-humanized'), 'all');
}
public function testVariablize(): void
{
self::assertSame('thisStringIsVariablized', $this->inflector->variablize('This String Is Variablized'));
self::assertSame('thisStringIsVariablized', $this->inflector->variablize('ThisStringIsVariablized'));
self::assertSame('thisStringIsVariablized', $this->inflector->variablize('This_String_Is_Variablized'));
self::assertSame('thisStringIsVariablized', $this->inflector->variablize('this string is variablized'));
self::assertSame('gravSPrettyCoolMy1', $this->inflector->variablize("Grav's Pretty Cool. My #1!"));
}
public function testTableize(): void
{
self::assertSame('people', $this->inflector->tableize('Person'));
self::assertSame('pages', $this->inflector->tableize('Page'));
self::assertSame('blog_pages', $this->inflector->tableize('BlogPage'));
self::assertSame('admin_dependencies', $this->inflector->tableize('adminDependency'));
self::assertSame('admin_dependencies', $this->inflector->tableize('admin-dependency'));
self::assertSame('admin_dependencies', $this->inflector->tableize('admin_dependency'));
}
public function testClassify(): void
{
self::assertSame('Person', $this->inflector->classify('people'));
self::assertSame('Page', $this->inflector->classify('pages'));
self::assertSame('BlogPage', $this->inflector->classify('blog_pages'));
self::assertSame('AdminDependency', $this->inflector->classify('admin_dependencies'));
}
public function testOrdinalize(): void
{
self::assertSame('1st', $this->inflector->ordinalize(1));
self::assertSame('2nd', $this->inflector->ordinalize(2));
self::assertSame('3rd', $this->inflector->ordinalize(3));
self::assertSame('4th', $this->inflector->ordinalize(4));
self::assertSame('5th', $this->inflector->ordinalize(5));
self::assertSame('16th', $this->inflector->ordinalize(16));
self::assertSame('51st', $this->inflector->ordinalize(51));
self::assertSame('111th', $this->inflector->ordinalize(111));
self::assertSame('123rd', $this->inflector->ordinalize(123));
}
public function testMonthize(): void
{
self::assertSame(0, $this->inflector->monthize(10));
self::assertSame(1, $this->inflector->monthize(33));
self::assertSame(1, $this->inflector->monthize(41));
self::assertSame(11, $this->inflector->monthize(364));
}
}

View File

@@ -0,0 +1,27 @@
<?php
use Grav\Common\Language\LanguageCodes;
/**
* Class ParsedownTest
*/
class LanguageCodesTest extends \Codeception\TestCase\Test
{
public function testRtl(): void
{
self::assertSame(
'ltr',
LanguageCodes::getOrientation('en')
);
self::assertSame(
'rtl',
LanguageCodes::getOrientation('ar')
);
self::assertSame(
'rtl',
LanguageCodes::getOrientation('he')
);
self::assertTrue(LanguageCodes::isRtl('ar'));
self::assertFalse(LanguageCodes::isRtl('fr'));
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,299 @@
<?php
use Codeception\Util\Fixtures;
use Grav\Common\Grav;
use Grav\Common\Page\Pages;
use Grav\Common\Page\Page;
use Grav\Common\Page\Interfaces\PageInterface;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
/**
* Class PagesTest
*/
class PagesTest extends \Codeception\TestCase\Test
{
/** @var Grav $grav */
protected $grav;
/** @var Pages $pages */
protected $pages;
/** @var PageInterface $root_page */
protected $root_page;
protected function _before(): void
{
$grav = Fixtures::get('grav');
$this->grav = $grav();
$this->pages = $this->grav['pages'];
$this->grav['config']->set('system.home.alias', '/home');
/** @var UniformResourceLocator $locator */
$locator = $this->grav['locator'];
$locator->addPath('page', '', 'tests/fake/simple-site/user/pages', false);
$this->pages->init();
}
public function testBase(): void
{
self::assertSame('', $this->pages->base());
$this->pages->base('/test');
self::assertSame('/test', $this->pages->base());
$this->pages->base('');
self::assertSame($this->pages->base(), '');
}
public function testLastModified(): void
{
self::assertNull($this->pages->lastModified());
$this->pages->lastModified('test');
self::assertSame('test', $this->pages->lastModified());
}
public function testInstances(): void
{
self::assertIsArray($this->pages->instances());
foreach ($this->pages->instances() as $instance) {
self::assertInstanceOf(PageInterface::class, $instance);
}
}
public function testRoutes(): void
{
/** @var UniformResourceLocator $locator */
$locator = $this->grav['locator'];
$folder = $locator->findResource('tests://');
self::assertIsArray($this->pages->routes());
self::assertSame($folder . '/fake/simple-site/user/pages/01.home', $this->pages->routes()['/']);
self::assertSame($folder . '/fake/simple-site/user/pages/01.home', $this->pages->routes()['/home']);
self::assertSame($folder . '/fake/simple-site/user/pages/02.blog', $this->pages->routes()['/blog']);
self::assertSame($folder . '/fake/simple-site/user/pages/02.blog/post-one', $this->pages->routes()['/blog/post-one']);
self::assertSame($folder . '/fake/simple-site/user/pages/02.blog/post-two', $this->pages->routes()['/blog/post-two']);
self::assertSame($folder . '/fake/simple-site/user/pages/03.about', $this->pages->routes()['/about']);
}
public function testAddPage(): void
{
/** @var UniformResourceLocator $locator */
$locator = $this->grav['locator'];
$folder = $locator->findResource('tests://');
$path = $folder . '/fake/single-pages/01.simple-page/default.md';
$aPage = new Page();
$aPage->init(new \SplFileInfo($path));
$this->pages->addPage($aPage, '/new-page');
self::assertContains('/new-page', array_keys($this->pages->routes()));
self::assertSame($folder . '/fake/single-pages/01.simple-page', $this->pages->routes()['/new-page']);
}
public function testSort(): void
{
/** @var UniformResourceLocator $locator */
$locator = $this->grav['locator'];
$folder = $locator->findResource('tests://');
$aPage = $this->pages->find('/blog');
$subPagesSorted = $this->pages->sort($aPage);
self::assertIsArray($subPagesSorted);
self::assertCount(2, $subPagesSorted);
self::assertSame($folder . '/fake/simple-site/user/pages/02.blog/post-one', array_keys($subPagesSorted)[0]);
self::assertSame($folder . '/fake/simple-site/user/pages/02.blog/post-two', array_keys($subPagesSorted)[1]);
self::assertContains($folder . '/fake/simple-site/user/pages/02.blog/post-one', array_keys($subPagesSorted));
self::assertContains($folder . '/fake/simple-site/user/pages/02.blog/post-two', array_keys($subPagesSorted));
self::assertSame(['slug' => 'post-one'], $subPagesSorted[$folder . '/fake/simple-site/user/pages/02.blog/post-one']);
self::assertSame(['slug' => 'post-two'], $subPagesSorted[$folder . '/fake/simple-site/user/pages/02.blog/post-two']);
$subPagesSorted = $this->pages->sort($aPage, null, 'desc');
self::assertIsArray($subPagesSorted);
self::assertCount(2, $subPagesSorted);
self::assertSame($folder . '/fake/simple-site/user/pages/02.blog/post-two', array_keys($subPagesSorted)[0]);
self::assertSame($folder . '/fake/simple-site/user/pages/02.blog/post-one', array_keys($subPagesSorted)[1]);
self::assertContains($folder . '/fake/simple-site/user/pages/02.blog/post-one', array_keys($subPagesSorted));
self::assertContains($folder . '/fake/simple-site/user/pages/02.blog/post-two', array_keys($subPagesSorted));
self::assertSame(['slug' => 'post-one'], $subPagesSorted[$folder . '/fake/simple-site/user/pages/02.blog/post-one']);
self::assertSame(['slug' => 'post-two'], $subPagesSorted[$folder . '/fake/simple-site/user/pages/02.blog/post-two']);
}
public function testSortCollection(): void
{
/** @var UniformResourceLocator $locator */
$locator = $this->grav['locator'];
$folder = $locator->findResource('tests://');
$aPage = $this->pages->find('/blog');
$subPagesSorted = $this->pages->sortCollection($aPage->children(), $aPage->orderBy());
self::assertIsArray($subPagesSorted);
self::assertCount(2, $subPagesSorted);
self::assertSame($folder . '/fake/simple-site/user/pages/02.blog/post-one', array_keys($subPagesSorted)[0]);
self::assertSame($folder . '/fake/simple-site/user/pages/02.blog/post-two', array_keys($subPagesSorted)[1]);
self::assertContains($folder . '/fake/simple-site/user/pages/02.blog/post-one', array_keys($subPagesSorted));
self::assertContains($folder . '/fake/simple-site/user/pages/02.blog/post-two', array_keys($subPagesSorted));
self::assertSame(['slug' => 'post-one'], $subPagesSorted[$folder . '/fake/simple-site/user/pages/02.blog/post-one']);
self::assertSame(['slug' => 'post-two'], $subPagesSorted[$folder . '/fake/simple-site/user/pages/02.blog/post-two']);
$subPagesSorted = $this->pages->sortCollection($aPage->children(), $aPage->orderBy(), 'desc');
self::assertIsArray($subPagesSorted);
self::assertCount(2, $subPagesSorted);
self::assertSame($folder . '/fake/simple-site/user/pages/02.blog/post-two', array_keys($subPagesSorted)[0]);
self::assertSame($folder . '/fake/simple-site/user/pages/02.blog/post-one', array_keys($subPagesSorted)[1]);
self::assertContains($folder . '/fake/simple-site/user/pages/02.blog/post-one', array_keys($subPagesSorted));
self::assertContains($folder . '/fake/simple-site/user/pages/02.blog/post-two', array_keys($subPagesSorted));
self::assertSame(['slug' => 'post-one'], $subPagesSorted[$folder . '/fake/simple-site/user/pages/02.blog/post-one']);
self::assertSame(['slug' => 'post-two'], $subPagesSorted[$folder . '/fake/simple-site/user/pages/02.blog/post-two']);
}
public function testGet(): void
{
/** @var UniformResourceLocator $locator */
$locator = $this->grav['locator'];
$folder = $locator->findResource('tests://');
//Page existing
$aPage = $this->pages->get($folder . '/fake/simple-site/user/pages/03.about');
self::assertInstanceOf(PageInterface::class, $aPage);
//Page not existing
$anotherPage = $this->pages->get($folder . '/fake/simple-site/user/pages/03.non-existing');
self::assertNull($anotherPage);
}
public function testChildren(): void
{
/** @var UniformResourceLocator $locator */
$locator = $this->grav['locator'];
$folder = $locator->findResource('tests://');
//Page existing
$children = $this->pages->children($folder . '/fake/simple-site/user/pages/02.blog');
self::assertInstanceOf('Grav\Common\Page\Collection', $children);
//Page not existing
$children = $this->pages->children($folder . '/fake/whatever/non-existing');
self::assertSame([], $children->toArray());
}
public function testDispatch(): void
{
$aPage = $this->pages->dispatch('/blog');
self::assertInstanceOf(PageInterface::class, $aPage);
$aPage = $this->pages->dispatch('/about');
self::assertInstanceOf(PageInterface::class, $aPage);
$aPage = $this->pages->dispatch('/blog/post-one');
self::assertInstanceOf(PageInterface::class, $aPage);
//Page not existing
$aPage = $this->pages->dispatch('/non-existing');
self::assertNull($aPage);
}
public function testRoot(): void
{
$root = $this->pages->root();
self::assertInstanceOf(PageInterface::class, $root);
self::assertSame('pages', $root->folder());
}
public function testBlueprints(): void
{
}
public function testAll()
{
self::assertIsObject($this->pages->all());
self::assertIsArray($this->pages->all()->toArray());
foreach ($this->pages->all() as $page) {
self::assertInstanceOf(PageInterface::class, $page);
}
}
public function testGetList(): void
{
$list = $this->pages->getList();
self::assertIsArray($list);
self::assertSame('&mdash;-&rtrif; Home', $list['/']);
self::assertSame('&mdash;-&rtrif; Blog', $list['/blog']);
}
public function testTranslatedLanguages(): void
{
/** @var UniformResourceLocator $locator */
$locator = $this->grav['locator'];
$folder = $locator->findResource('tests://');
$page = $this->pages->get($folder . '/fake/simple-site/user/pages/04.page-translated');
$this->assertInstanceOf(PageInterface::class, $page);
$translatedLanguages = $page->translatedLanguages();
$this->assertIsArray($translatedLanguages);
$this->assertSame(["en" => "/page-translated", "fr" => "/page-translated"], $translatedLanguages);
}
public function testLongPathTranslatedLanguages(): void
{
/** @var UniformResourceLocator $locator */
$locator = $this->grav['locator'];
$folder = $locator->findResource('tests://');
$page = $this->pages->get($folder . '/fake/simple-site/user/pages/05.translatedlong/part2');
$this->assertInstanceOf(PageInterface::class, $page);
$translatedLanguages = $page->translatedLanguages();
$this->assertIsArray($translatedLanguages);
$this->assertSame(["en" => "/translatedlong/part2", "fr" => "/translatedlong/part2"], $translatedLanguages);
}
public function testGetTypes(): void
{
}
public function testTypes(): void
{
}
public function testModularTypes(): void
{
}
public function testPageTypes(): void
{
}
public function testAccessLevels(): void
{
}
public function testParents(): void
{
}
public function testParentsRawRoutes(): void
{
}
public function testGetHomeRoute(): void
{
}
public function testResetPages(): void
{
}
}

View File

@@ -0,0 +1,202 @@
<?php
use Codeception\Util\Fixtures;
use Grav\Common\Grav;
use Grav\Common\Twig\Extension\GravExtension;
/**
* Class GravExtensionTest
*/
class GravExtensionTest extends \Codeception\TestCase\Test
{
/** @var Grav $grav */
protected $grav;
/** @var GravExtension $twig_ext */
protected $twig_ext;
protected function _before(): void
{
$this->grav = Fixtures::get('grav');
$this->twig_ext = new GravExtension();
}
public function testInflectorFilter(): void
{
self::assertSame('people', $this->twig_ext->inflectorFilter('plural', 'person'));
self::assertSame('shoe', $this->twig_ext->inflectorFilter('singular', 'shoes'));
self::assertSame('Welcome Page', $this->twig_ext->inflectorFilter('title', 'welcome page'));
self::assertSame('SendEmail', $this->twig_ext->inflectorFilter('camel', 'send_email'));
self::assertSame('camel_cased', $this->twig_ext->inflectorFilter('underscor', 'CamelCased'));
self::assertSame('something-text', $this->twig_ext->inflectorFilter('hyphen', 'Something Text'));
self::assertSame('Something text to read', $this->twig_ext->inflectorFilter('human', 'something_text_to_read'));
self::assertSame(5, $this->twig_ext->inflectorFilter('month', '175'));
self::assertSame('10th', $this->twig_ext->inflectorFilter('ordinal', '10'));
}
public function testMd5Filter(): void
{
self::assertSame(md5('grav'), $this->twig_ext->md5Filter('grav'));
self::assertSame(md5('devs@getgrav.org'), $this->twig_ext->md5Filter('devs@getgrav.org'));
}
public function testKsortFilter(): void
{
$object = array("name"=>"Bob","age"=>8,"colour"=>"red");
self::assertSame(array("age"=>8,"colour"=>"red","name"=>"Bob"), $this->twig_ext->ksortFilter($object));
}
public function testContainsFilter(): void
{
self::assertTrue($this->twig_ext->containsFilter('grav', 'grav'));
self::assertTrue($this->twig_ext->containsFilter('So, I found this new cms, called grav, and it\'s pretty awesome guys', 'grav'));
}
public function testNicetimeFilter(): void
{
$now = time();
$threeMinutes = time() - (60*3);
$threeHours = time() - (60*60*3);
$threeDays = time() - (60*60*24*3);
$threeMonths = time() - (60*60*24*30*3);
$threeYears = time() - (60*60*24*365*3);
$measures = ['minutes','hours','days','months','years'];
self::assertSame('No date provided', $this->twig_ext->nicetimeFunc(null));
for ($i=0; $i<count($measures); $i++) {
$time = 'three' . ucfirst($measures[$i]);
self::assertSame('3 ' . $measures[$i] . ' ago', $this->twig_ext->nicetimeFunc($$time));
}
}
public function testRandomizeFilter(): void
{
$array = [1,2,3,4,5];
self::assertContains(2, $this->twig_ext->randomizeFilter($array));
self::assertSame($array, $this->twig_ext->randomizeFilter($array, 5));
self::assertSame($array[0], $this->twig_ext->randomizeFilter($array, 1)[0]);
self::assertSame($array[3], $this->twig_ext->randomizeFilter($array, 4)[3]);
self::assertSame($array[1], $this->twig_ext->randomizeFilter($array, 4)[1]);
}
public function testModulusFilter(): void
{
self::assertSame(3, $this->twig_ext->modulusFilter(3, 4));
self::assertSame(1, $this->twig_ext->modulusFilter(11, 2));
self::assertSame(0, $this->twig_ext->modulusFilter(10, 2));
self::assertSame(2, $this->twig_ext->modulusFilter(10, 4));
}
public function testAbsoluteUrlFilter(): void
{
}
public function testMarkdownFilter(): void
{
}
public function testStartsWithFilter(): void
{
}
public function testEndsWithFilter(): void
{
}
public function testDefinedDefaultFilter(): void
{
}
public function testRtrimFilter(): void
{
}
public function testLtrimFilter(): void
{
}
public function testRepeatFunc(): void
{
}
public function testRegexReplace(): void
{
}
public function testUrlFunc(): void
{
}
public function testEvaluateFunc(): void
{
}
public function testDump(): void
{
}
public function testGistFunc(): void
{
}
public function testRandomStringFunc(): void
{
}
public function testPadFilter(): void
{
}
public function testArrayFunc(): void
{
self::assertSame(
'this is my text',
$this->twig_ext->regexReplace('<p>this is my text</p>', '(<\/?p>)', '')
);
self::assertSame(
'<i>this is my text</i>',
$this->twig_ext->regexReplace('<p>this is my text</p>', ['(<p>)','(<\/p>)'], ['<i>','</i>'])
);
}
public function testArrayKeyValue(): void
{
self::assertSame(
['meat' => 'steak'],
$this->twig_ext->arrayKeyValueFunc('meat', 'steak')
);
self::assertSame(
['fruit' => 'apple', 'meat' => 'steak'],
$this->twig_ext->arrayKeyValueFunc('meat', 'steak', ['fruit' => 'apple'])
);
}
public function stringFunc(): void
{
}
public function testRangeFunc(): void
{
$hundred = [];
for ($i = 0; $i <= 100; $i++) {
$hundred[] = $i;
}
self::assertSame([0], $this->twig_ext->rangeFunc(0, 0));
self::assertSame([0, 1, 2], $this->twig_ext->rangeFunc(0, 2));
self::assertSame([0, 5, 10, 15], $this->twig_ext->rangeFunc(0, 16, 5));
// default (min 0, max 100, step 1)
self::assertSame($hundred, $this->twig_ext->rangeFunc());
// 95 items, starting from 5, (min 5, max 100, step 1)
self::assertSame(array_slice($hundred, 5), $this->twig_ext->rangeFunc(5));
// reversed range
self::assertSame(array_reverse($hundred), $this->twig_ext->rangeFunc(100, 0));
self::assertSame([4, 2, 0], $this->twig_ext->rangeFunc(4, 0, 2));
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,572 @@
<?php
use Codeception\Util\Fixtures;
use Grav\Common\Grav;
use Grav\Common\Uri;
use Grav\Common\Utils;
/**
* Class UtilsTest
*/
class UtilsTest extends \Codeception\TestCase\Test
{
/** @var Grav $grav */
protected $grav;
/** @var Uri $uri */
protected $uri;
protected function _before(): void
{
$grav = Fixtures::get('grav');
$this->grav = $grav();
$this->uri = $this->grav['uri'];
}
protected function _after(): void
{
}
public function testStartsWith(): void
{
self::assertTrue(Utils::startsWith('english', 'en'));
self::assertTrue(Utils::startsWith('English', 'En'));
self::assertTrue(Utils::startsWith('ENGLISH', 'EN'));
self::assertTrue(Utils::startsWith(
'ENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISH',
'EN'
));
self::assertFalse(Utils::startsWith('english', 'En'));
self::assertFalse(Utils::startsWith('English', 'EN'));
self::assertFalse(Utils::startsWith('ENGLISH', 'en'));
self::assertFalse(Utils::startsWith(
'ENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISH',
'e'
));
self::assertTrue(Utils::startsWith('english', 'En', false));
self::assertTrue(Utils::startsWith('English', 'EN', false));
self::assertTrue(Utils::startsWith('ENGLISH', 'en', false));
self::assertTrue(Utils::startsWith(
'ENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISH',
'e',
false
));
}
public function testEndsWith(): void
{
self::assertTrue(Utils::endsWith('english', 'sh'));
self::assertTrue(Utils::endsWith('EngliSh', 'Sh'));
self::assertTrue(Utils::endsWith('ENGLISH', 'SH'));
self::assertTrue(Utils::endsWith(
'ENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISH',
'ENGLISH'
));
self::assertFalse(Utils::endsWith('english', 'de'));
self::assertFalse(Utils::endsWith('EngliSh', 'sh'));
self::assertFalse(Utils::endsWith('ENGLISH', 'Sh'));
self::assertFalse(Utils::endsWith(
'ENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISH',
'DEUSTCH'
));
self::assertTrue(Utils::endsWith('english', 'SH', false));
self::assertTrue(Utils::endsWith('EngliSh', 'sH', false));
self::assertTrue(Utils::endsWith('ENGLISH', 'sh', false));
self::assertTrue(Utils::endsWith(
'ENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISH',
'english',
false
));
}
public function testContains(): void
{
self::assertTrue(Utils::contains('english', 'nglis'));
self::assertTrue(Utils::contains('EngliSh', 'gliSh'));
self::assertTrue(Utils::contains('ENGLISH', 'ENGLI'));
self::assertTrue(Utils::contains(
'ENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISH',
'ENGLISH'
));
self::assertFalse(Utils::contains('EngliSh', 'GLI'));
self::assertFalse(Utils::contains('EngliSh', 'English'));
self::assertFalse(Utils::contains('ENGLISH', 'SCH'));
self::assertFalse(Utils::contains(
'ENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISH',
'DEUSTCH'
));
self::assertTrue(Utils::contains('EngliSh', 'GLI', false));
self::assertTrue(Utils::contains('EngliSh', 'ENGLISH', false));
self::assertTrue(Utils::contains('ENGLISH', 'ish', false));
self::assertTrue(Utils::contains(
'ENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISHENGLISH',
'english',
false
));
}
public function testSubstrToString(): void
{
self::assertEquals('en', Utils::substrToString('english', 'glish'));
self::assertEquals('english', Utils::substrToString('english', 'test'));
self::assertNotEquals('en', Utils::substrToString('english', 'lish'));
self::assertEquals('en', Utils::substrToString('english', 'GLISH', false));
self::assertEquals('english', Utils::substrToString('english', 'TEST', false));
self::assertNotEquals('en', Utils::substrToString('english', 'LISH', false));
}
public function testMergeObjects(): void
{
$obj1 = new stdClass();
$obj1->test1 = 'x';
$obj2 = new stdClass();
$obj2->test2 = 'y';
$objMerged = Utils::mergeObjects($obj1, $obj2);
self::arrayHasKey('test1', (array) $objMerged);
self::arrayHasKey('test2', (array) $objMerged);
}
public function testDateFormats(): void
{
$dateFormats = Utils::dateFormats();
self::assertIsArray($dateFormats);
self::assertContainsOnly('string', $dateFormats);
$default_format = $this->grav['config']->get('system.pages.dateformat.default');
if ($default_format !== null) {
self::assertArrayHasKey($default_format, $dateFormats);
}
}
public function testTruncate(): void
{
self::assertEquals('engli' . '&hellip;', Utils::truncate('english', 5));
self::assertEquals('english', Utils::truncate('english'));
self::assertEquals('This is a string to truncate', Utils::truncate('This is a string to truncate'));
self::assertEquals('Th' . '&hellip;', Utils::truncate('This is a string to truncate', 2));
self::assertEquals('engli' . '...', Utils::truncate('english', 5, true, " ", "..."));
self::assertEquals('english', Utils::truncate('english'));
self::assertEquals('This is a string to truncate', Utils::truncate('This is a string to truncate'));
self::assertEquals('This' . '&hellip;', Utils::truncate('This is a string to truncate', 3, true));
self::assertEquals('<input' . '&hellip;', Utils::truncate('<input type="file" id="file" multiple />', 6, true));
}
public function testSafeTruncate(): void
{
self::assertEquals('This' . '&hellip;', Utils::safeTruncate('This is a string to truncate', 1));
self::assertEquals('This' . '&hellip;', Utils::safeTruncate('This is a string to truncate', 4));
self::assertEquals('This is' . '&hellip;', Utils::safeTruncate('This is a string to truncate', 5));
}
public function testTruncateHtml(): void
{
self::assertEquals('T...', Utils::truncateHtml('This is a string to truncate', 1));
self::assertEquals('This is...', Utils::truncateHtml('This is a string to truncate', 7));
self::assertEquals('<p>T...</p>', Utils::truncateHtml('<p>This is a string to truncate</p>', 1));
self::assertEquals('<p>This...</p>', Utils::truncateHtml('<p>This is a string to truncate</p>', 4));
self::assertEquals('<p>This is a...</p>', Utils::truncateHtml('<p>This is a string to truncate</p>', 10));
self::assertEquals('<p>This is a string to truncate</p>', Utils::truncateHtml('<p>This is a string to truncate</p>', 100));
self::assertEquals('<input type="file" id="file" multiple />', Utils::truncateHtml('<input type="file" id="file" multiple />', 6));
self::assertEquals('<ol><li>item 1 <i>so...</i></li></ol>', Utils::truncateHtml('<ol><li>item 1 <i>something</i></li><li>item 2 <strong>bold</strong></li></ol>', 10));
self::assertEquals("<p>This is a string.</p>\n<p>It splits two lines.</p>", Utils::truncateHtml("<p>This is a string.</p>\n<p>It splits two lines.</p>", 100));
}
public function testSafeTruncateHtml(): void
{
self::assertEquals('This...', Utils::safeTruncateHtml('This is a string to truncate', 1));
self::assertEquals('This is a...', Utils::safeTruncateHtml('This is a string to truncate', 3));
self::assertEquals('<p>This...</p>', Utils::safeTruncateHtml('<p>This is a string to truncate</p>', 1));
self::assertEquals('<p>This is...</p>', Utils::safeTruncateHtml('<p>This is a string to truncate</p>', 2));
self::assertEquals('<p>This is a string to...</p>', Utils::safeTruncateHtml('<p>This is a string to truncate</p>', 5));
self::assertEquals('<p>This is a string to truncate</p>', Utils::safeTruncateHtml('<p>This is a string to truncate</p>', 20));
self::assertEquals('<input type="file" id="file" multiple />', Utils::safeTruncateHtml('<input type="file" id="file" multiple />', 6));
self::assertEquals('<ol><li>item 1 <i>something</i></li><li>item 2...</li></ol>', Utils::safeTruncateHtml('<ol><li>item 1 <i>something</i></li><li>item 2 <strong>bold</strong></li></ol>', 5));
}
public function testGenerateRandomString(): void
{
self::assertNotEquals(Utils::generateRandomString(), Utils::generateRandomString());
self::assertNotEquals(Utils::generateRandomString(20), Utils::generateRandomString(20));
}
public function download(): void
{
}
public function testGetMimeByExtension(): void
{
self::assertEquals('application/octet-stream', Utils::getMimeByExtension(''));
self::assertEquals('text/html', Utils::getMimeByExtension('html'));
self::assertEquals('application/json', Utils::getMimeByExtension('json'));
self::assertEquals('application/atom+xml', Utils::getMimeByExtension('atom'));
self::assertEquals('application/rss+xml', Utils::getMimeByExtension('rss'));
self::assertEquals('image/jpeg', Utils::getMimeByExtension('jpg'));
self::assertEquals('image/png', Utils::getMimeByExtension('png'));
self::assertEquals('text/plain', Utils::getMimeByExtension('txt'));
self::assertEquals('application/msword', Utils::getMimeByExtension('doc'));
self::assertEquals('application/octet-stream', Utils::getMimeByExtension('foo'));
self::assertEquals('foo/bar', Utils::getMimeByExtension('foo', 'foo/bar'));
self::assertEquals('text/html', Utils::getMimeByExtension('foo', 'text/html'));
}
public function testGetExtensionByMime(): void
{
self::assertEquals('html', Utils::getExtensionByMime('*/*'));
self::assertEquals('html', Utils::getExtensionByMime('text/*'));
self::assertEquals('html', Utils::getExtensionByMime('text/html'));
self::assertEquals('json', Utils::getExtensionByMime('application/json'));
self::assertEquals('atom', Utils::getExtensionByMime('application/atom+xml'));
self::assertEquals('rss', Utils::getExtensionByMime('application/rss+xml'));
self::assertEquals('jpg', Utils::getExtensionByMime('image/jpeg'));
self::assertEquals('png', Utils::getExtensionByMime('image/png'));
self::assertEquals('txt', Utils::getExtensionByMime('text/plain'));
self::assertEquals('doc', Utils::getExtensionByMime('application/msword'));
self::assertEquals('html', Utils::getExtensionByMime('foo/bar'));
self::assertEquals('baz', Utils::getExtensionByMime('foo/bar', 'baz'));
}
public function testNormalizePath(): void
{
self::assertEquals('/test', Utils::normalizePath('/test'));
self::assertEquals('test', Utils::normalizePath('test'));
self::assertEquals('test', Utils::normalizePath('../test'));
self::assertEquals('/test', Utils::normalizePath('/../test'));
self::assertEquals('/test2', Utils::normalizePath('/test/../test2'));
self::assertEquals('/test3', Utils::normalizePath('/test/../test2/../test3'));
self::assertEquals('//cdnjs.cloudflare.com/ajax/libs/Leaflet.awesome-markers/2.0.2/leaflet.awesome-markers.css', Utils::normalizePath('//cdnjs.cloudflare.com/ajax/libs/Leaflet.awesome-markers/2.0.2/leaflet.awesome-markers.css'));
self::assertEquals('//use.fontawesome.com/releases/v5.8.1/css/all.css', Utils::normalizePath('//use.fontawesome.com/releases/v5.8.1/css/all.css'));
self::assertEquals('//use.fontawesome.com/releases/v5.8.1/webfonts/fa-brands-400.eot', Utils::normalizePath('//use.fontawesome.com/releases/v5.8.1/css/../webfonts/fa-brands-400.eot'));
self::assertEquals('http://cdnjs.cloudflare.com/ajax/libs/Leaflet.awesome-markers/2.0.2/leaflet.awesome-markers.css', Utils::normalizePath('http://cdnjs.cloudflare.com/ajax/libs/Leaflet.awesome-markers/2.0.2/leaflet.awesome-markers.css'));
self::assertEquals('http://use.fontawesome.com/releases/v5.8.1/css/all.css', Utils::normalizePath('http://use.fontawesome.com/releases/v5.8.1/css/all.css'));
self::assertEquals('http://use.fontawesome.com/releases/v5.8.1/webfonts/fa-brands-400.eot', Utils::normalizePath('http://use.fontawesome.com/releases/v5.8.1/css/../webfonts/fa-brands-400.eot'));
self::assertEquals('https://cdnjs.cloudflare.com/ajax/libs/Leaflet.awesome-markers/2.0.2/leaflet.awesome-markers.css', Utils::normalizePath('https://cdnjs.cloudflare.com/ajax/libs/Leaflet.awesome-markers/2.0.2/leaflet.awesome-markers.css'));
self::assertEquals('https://use.fontawesome.com/releases/v5.8.1/css/all.css', Utils::normalizePath('https://use.fontawesome.com/releases/v5.8.1/css/all.css'));
self::assertEquals('https://use.fontawesome.com/releases/v5.8.1/webfonts/fa-brands-400.eot', Utils::normalizePath('https://use.fontawesome.com/releases/v5.8.1/css/../webfonts/fa-brands-400.eot'));
}
public function testIsFunctionDisabled(): void
{
$disabledFunctions = explode(',', ini_get('disable_functions'));
if ($disabledFunctions[0]) {
self::assertEquals(Utils::isFunctionDisabled($disabledFunctions[0]), true);
}
}
public function testTimezones(): void
{
$timezones = Utils::timezones();
self::assertIsArray($timezones);
self::assertContainsOnly('string', $timezones);
}
public function testArrayFilterRecursive(): void
{
$array = [
'test' => '',
'test2' => 'test2'
];
$array = Utils::arrayFilterRecursive($array, function ($k, $v) {
return !(is_null($v) || $v === '');
});
self::assertContainsOnly('string', $array);
self::assertArrayNotHasKey('test', $array);
self::assertArrayHasKey('test2', $array);
self::assertEquals('test2', $array['test2']);
}
public function testPathPrefixedByLangCode(): void
{
$languagesEnabled = $this->grav['config']->get('system.languages.supported', []);
$arrayOfLanguages = ['en', 'de', 'it', 'es', 'dk', 'el'];
$languagesNotEnabled = array_diff($arrayOfLanguages, $languagesEnabled);
$oneLanguageNotEnabled = reset($languagesNotEnabled);
if (count($languagesEnabled)) {
$languageCodePathPrefix = Utils::pathPrefixedByLangCode('/' . $languagesEnabled[0] . '/test');
$this->assertIsString($languageCodePathPrefix);
$this->assertTrue(in_array($languageCodePathPrefix, $languagesEnabled));
}
self::assertFalse(Utils::pathPrefixedByLangCode('/' . $oneLanguageNotEnabled . '/test'));
self::assertFalse(Utils::pathPrefixedByLangCode('/test'));
self::assertFalse(Utils::pathPrefixedByLangCode('/xx'));
self::assertFalse(Utils::pathPrefixedByLangCode('/xx/'));
self::assertFalse(Utils::pathPrefixedByLangCode('/'));
}
public function testDate2timestamp(): void
{
$timestamp = strtotime('10 September 2000');
self::assertSame($timestamp, Utils::date2timestamp('10 September 2000'));
self::assertSame($timestamp, Utils::date2timestamp('2000-09-10 00:00:00'));
}
public function testResolve(): void
{
$array = [
'test' => [
'test2' => 'test2Value'
]
];
self::assertEquals('test2Value', Utils::resolve($array, 'test.test2'));
}
public function testGetDotNotation(): void
{
$array = [
'test' => [
'test2' => 'test2Value',
'test3' => [
'test4' => 'test4Value'
]
]
];
self::assertEquals('test2Value', Utils::getDotNotation($array, 'test.test2'));
self::assertEquals('test4Value', Utils::getDotNotation($array, 'test.test3.test4'));
self::assertEquals('defaultValue', Utils::getDotNotation($array, 'test.non_existent', 'defaultValue'));
}
public function testSetDotNotation(): void
{
$array = [
'test' => [
'test2' => 'test2Value',
'test3' => [
'test4' => 'test4Value'
]
]
];
$new = [
'test1' => 'test1Value'
];
Utils::setDotNotation($array, 'test.test3.test4', $new);
self::assertEquals('test1Value', $array['test']['test3']['test4']['test1']);
}
public function testIsPositive(): void
{
self::assertTrue(Utils::isPositive(true));
self::assertTrue(Utils::isPositive(1));
self::assertTrue(Utils::isPositive('1'));
self::assertTrue(Utils::isPositive('yes'));
self::assertTrue(Utils::isPositive('on'));
self::assertTrue(Utils::isPositive('true'));
self::assertFalse(Utils::isPositive(false));
self::assertFalse(Utils::isPositive(0));
self::assertFalse(Utils::isPositive('0'));
self::assertFalse(Utils::isPositive('no'));
self::assertFalse(Utils::isPositive('off'));
self::assertFalse(Utils::isPositive('false'));
self::assertFalse(Utils::isPositive('some'));
self::assertFalse(Utils::isPositive(2));
}
public function testGetNonce(): void
{
self::assertIsString(Utils::getNonce('test-action'));
self::assertIsString(Utils::getNonce('test-action', true));
self::assertSame(Utils::getNonce('test-action'), Utils::getNonce('test-action'));
self::assertNotSame(Utils::getNonce('test-action'), Utils::getNonce('test-action2'));
}
public function testVerifyNonce(): void
{
self::assertTrue(Utils::verifyNonce(Utils::getNonce('test-action'), 'test-action'));
}
public function testGetPagePathFromToken(): void
{
self::assertEquals('', Utils::getPagePathFromToken(''));
self::assertEquals('/test/path', Utils::getPagePathFromToken('/test/path'));
}
public function testUrl(): void
{
$this->uri->initializeWithUrl('http://testing.dev/path1/path2')->init();
// Fail hard
self::assertSame(false, Utils::url('', true));
self::assertSame(false, Utils::url(''));
self::assertSame(false, Utils::url(new stdClass()));
self::assertSame(false, Utils::url(['foo','bar','baz']));
self::assertSame(false, Utils::url('user://does/not/exist'));
// Fail Gracefully
self::assertSame('/', Utils::url('/', false, true));
self::assertSame('/', Utils::url('', false, true));
self::assertSame('/', Utils::url(new stdClass(), false, true));
self::assertSame('/', Utils::url(['foo','bar','baz'], false, true));
self::assertSame('/user/does/not/exist', Utils::url('user://does/not/exist', false, true));
// Simple paths
self::assertSame('/', Utils::url('/'));
self::assertSame('/path1', Utils::url('/path1'));
self::assertSame('/path1/path2', Utils::url('/path1/path2'));
self::assertSame('/random/path1/path2', Utils::url('/random/path1/path2'));
self::assertSame('/foobar.jpg', Utils::url('/foobar.jpg'));
self::assertSame('/path1/foobar.jpg', Utils::url('/path1/foobar.jpg'));
self::assertSame('/path1/path2/foobar.jpg', Utils::url('/path1/path2/foobar.jpg'));
self::assertSame('/random/path1/path2/foobar.jpg', Utils::url('/random/path1/path2/foobar.jpg'));
// Simple paths with domain
self::assertSame('http://testing.dev/', Utils::url('/', true));
self::assertSame('http://testing.dev/path1', Utils::url('/path1', true));
self::assertSame('http://testing.dev/path1/path2', Utils::url('/path1/path2', true));
self::assertSame('http://testing.dev/random/path1/path2', Utils::url('/random/path1/path2', true));
self::assertSame('http://testing.dev/foobar.jpg', Utils::url('/foobar.jpg', true));
self::assertSame('http://testing.dev/path1/foobar.jpg', Utils::url('/path1/foobar.jpg', true));
self::assertSame('http://testing.dev/path1/path2/foobar.jpg', Utils::url('/path1/path2/foobar.jpg', true));
self::assertSame('http://testing.dev/random/path1/path2/foobar.jpg', Utils::url('/random/path1/path2/foobar.jpg', true));
// Relative paths from Grav root.
self::assertSame('/subdir', Utils::url('subdir'));
self::assertSame('/subdir/path1', Utils::url('subdir/path1'));
self::assertSame('/subdir/path1/path2', Utils::url('subdir/path1/path2'));
self::assertSame('/path1', Utils::url('path1'));
self::assertSame('/path1/path2', Utils::url('path1/path2'));
self::assertSame('/foobar.jpg', Utils::url('foobar.jpg'));
self::assertSame('http://testing.dev/foobar.jpg', Utils::url('foobar.jpg', true));
// Relative paths from Grav root with domain.
self::assertSame('http://testing.dev/foobar.jpg', Utils::url('foobar.jpg', true));
self::assertSame('http://testing.dev/foobar.jpg', Utils::url('/foobar.jpg', true));
self::assertSame('http://testing.dev/path1/foobar.jpg', Utils::url('/path1/foobar.jpg', true));
// All Non-existing streams should be treated as external URI / protocol.
self::assertSame('http://domain.com/path', Utils::url('http://domain.com/path'));
self::assertSame('ftp://domain.com/path', Utils::url('ftp://domain.com/path'));
self::assertSame('sftp://domain.com/path', Utils::url('sftp://domain.com/path'));
self::assertSame('ssh://domain.com', Utils::url('ssh://domain.com'));
self::assertSame('pop://domain.com', Utils::url('pop://domain.com'));
self::assertSame('foo://bar/baz', Utils::url('foo://bar/baz'));
self::assertSame('foo://bar/baz', Utils::url('foo://bar/baz', true));
// self::assertSame('mailto:joe@domain.com', Utils::url('mailto:joe@domain.com', true)); // FIXME <-
}
public function testUrlWithRoot(): void
{
$this->uri->initializeWithUrlAndRootPath('http://testing.dev/subdir/path1/path2', '/subdir')->init();
// Fail hard
self::assertSame(false, Utils::url('', true));
self::assertSame(false, Utils::url(''));
self::assertSame(false, Utils::url(new stdClass()));
self::assertSame(false, Utils::url(['foo','bar','baz']));
self::assertSame(false, Utils::url('user://does/not/exist'));
// Fail Gracefully
self::assertSame('/subdir/', Utils::url('/', false, true));
self::assertSame('/subdir/', Utils::url('', false, true));
self::assertSame('/subdir/', Utils::url(new stdClass(), false, true));
self::assertSame('/subdir/', Utils::url(['foo','bar','baz'], false, true));
self::assertSame('/subdir/user/does/not/exist', Utils::url('user://does/not/exist', false, true));
// Simple paths
self::assertSame('/subdir/', Utils::url('/'));
self::assertSame('/subdir/path1', Utils::url('/path1'));
self::assertSame('/subdir/path1/path2', Utils::url('/path1/path2'));
self::assertSame('/subdir/random/path1/path2', Utils::url('/random/path1/path2'));
self::assertSame('/subdir/foobar.jpg', Utils::url('/foobar.jpg'));
self::assertSame('/subdir/path1/foobar.jpg', Utils::url('/path1/foobar.jpg'));
self::assertSame('/subdir/path1/path2/foobar.jpg', Utils::url('/path1/path2/foobar.jpg'));
self::assertSame('/subdir/random/path1/path2/foobar.jpg', Utils::url('/random/path1/path2/foobar.jpg'));
// Simple paths with domain
self::assertSame('http://testing.dev/subdir/', Utils::url('/', true));
self::assertSame('http://testing.dev/subdir/path1', Utils::url('/path1', true));
self::assertSame('http://testing.dev/subdir/path1/path2', Utils::url('/path1/path2', true));
self::assertSame('http://testing.dev/subdir/random/path1/path2', Utils::url('/random/path1/path2', true));
self::assertSame('http://testing.dev/subdir/foobar.jpg', Utils::url('/foobar.jpg', true));
self::assertSame('http://testing.dev/subdir/path1/foobar.jpg', Utils::url('/path1/foobar.jpg', true));
self::assertSame('http://testing.dev/subdir/path1/path2/foobar.jpg', Utils::url('/path1/path2/foobar.jpg', true));
self::assertSame('http://testing.dev/subdir/random/path1/path2/foobar.jpg', Utils::url('/random/path1/path2/foobar.jpg', true));
// Absolute Paths including the grav base.
self::assertSame('/subdir/', Utils::url('/subdir'));
self::assertSame('/subdir/', Utils::url('/subdir/'));
self::assertSame('/subdir/path1', Utils::url('/subdir/path1'));
self::assertSame('/subdir/path1/path2', Utils::url('/subdir/path1/path2'));
self::assertSame('/subdir/foobar.jpg', Utils::url('/subdir/foobar.jpg'));
self::assertSame('/subdir/path1/foobar.jpg', Utils::url('/subdir/path1/foobar.jpg'));
// Absolute paths from Grav root with domain.
self::assertSame('http://testing.dev/subdir/', Utils::url('/subdir', true));
self::assertSame('http://testing.dev/subdir/', Utils::url('/subdir/', true));
self::assertSame('http://testing.dev/subdir/path1', Utils::url('/subdir/path1', true));
self::assertSame('http://testing.dev/subdir/path1/path2', Utils::url('/subdir/path1/path2', true));
self::assertSame('http://testing.dev/subdir/foobar.jpg', Utils::url('/subdir/foobar.jpg', true));
self::assertSame('http://testing.dev/subdir/path1/foobar.jpg', Utils::url('/subdir/path1/foobar.jpg', true));
// Relative paths from Grav root.
self::assertSame('/subdir/sub', Utils::url('/sub'));
self::assertSame('/subdir/subdir', Utils::url('subdir'));
self::assertSame('/subdir/subdir2/sub', Utils::url('/subdir2/sub'));
self::assertSame('/subdir/subdir/path1', Utils::url('subdir/path1'));
self::assertSame('/subdir/subdir/path1/path2', Utils::url('subdir/path1/path2'));
self::assertSame('/subdir/path1', Utils::url('path1'));
self::assertSame('/subdir/path1/path2', Utils::url('path1/path2'));
self::assertSame('/subdir/foobar.jpg', Utils::url('foobar.jpg'));
self::assertSame('http://testing.dev/subdir/foobar.jpg', Utils::url('foobar.jpg', true));
// All Non-existing streams should be treated as external URI / protocol.
self::assertSame('http://domain.com/path', Utils::url('http://domain.com/path'));
self::assertSame('ftp://domain.com/path', Utils::url('ftp://domain.com/path'));
self::assertSame('sftp://domain.com/path', Utils::url('sftp://domain.com/path'));
self::assertSame('ssh://domain.com', Utils::url('ssh://domain.com'));
self::assertSame('pop://domain.com', Utils::url('pop://domain.com'));
self::assertSame('foo://bar/baz', Utils::url('foo://bar/baz'));
self::assertSame('foo://bar/baz', Utils::url('foo://bar/baz', true));
// self::assertSame('mailto:joe@domain.com', Utils::url('mailto:joe@domain.com', true)); // FIXME <-
}
public function testUrlWithStreams(): void
{
}
public function testUrlwithExternals(): void
{
$this->uri->initializeWithUrl('http://testing.dev/path1/path2')->init();
self::assertSame('http://foo.com', Utils::url('http://foo.com'));
self::assertSame('https://foo.com', Utils::url('https://foo.com'));
self::assertSame('//foo.com', Utils::url('//foo.com'));
self::assertSame('//foo.com?param=x', Utils::url('//foo.com?param=x'));
}
public function testCheckFilename(): void
{
// configure extension for consistent results
/** @var \Grav\Common\Config\Config $config */
$config = $this->grav['config'];
$config->set('security.uploads_dangerous_extensions', ['php', 'html', 'htm', 'exe', 'js']);
self::assertFalse(Utils::checkFilename('foo.php'));
self::assertFalse(Utils::checkFilename('foo.PHP'));
self::assertFalse(Utils::checkFilename('bar.js'));
self::assertTrue(Utils::checkFilename('foo.json'));
self::assertTrue(Utils::checkFilename('foo.xml'));
self::assertTrue(Utils::checkFilename('foo.yaml'));
self::assertTrue(Utils::checkFilename('foo.yml'));
}
}

View File

@@ -0,0 +1,28 @@
<?php
use Codeception\Util\Fixtures;
use Grav\Common\Grav;
use Grav\Console\Gpm\InstallCommand;
/**
* Class InstallCommandTest
*/
class InstallCommandTest extends \Codeception\TestCase\Test
{
/** @var Grav $grav */
protected $grav;
/** @var InstallCommand */
protected $installCommand;
protected function _before(): void
{
$this->grav = Fixtures::get('grav');
$this->installCommand = new InstallCommand();
}
protected function _after(): void
{
}
}

View File

@@ -0,0 +1,48 @@
<?php
use Grav\Framework\File\Formatter\CsvFormatter;
/**
* Class CsvFormatterTest
*/
class CsvFormatterTest extends \Codeception\TestCase\Test
{
public function testEncodeWithAssocColumns(): void
{
$data = [
['col1' => 1, 'col2' => 2, 'col3' => 3],
['col1' => 'aaa', 'col2' => 'bbb', 'col3' => 'ccc'],
];
$encoded = (new CsvFormatter())->encode($data);
$lines = array_filter(explode(PHP_EOL, $encoded));
self::assertCount(3, $lines);
self::assertEquals('col1,col2,col3', $lines[0]);
}
/**
* TBD - If indexes are all numeric, what's the purpose
* of displaying header
*/
public function testEncodeWithIndexColumns(): void
{
$data = [
[0 => 1, 1 => 2, 2 => 3],
];
$encoded = (new CsvFormatter())->encode($data);
$lines = array_filter(explode(PHP_EOL, $encoded));
self::assertCount(2, $lines);
self::assertEquals('0,1,2', $lines[0]);
}
public function testEncodeEmptyData(): void
{
$encoded = (new CsvFormatter())->encode([]);
self::assertEquals('', $encoded);
}
}

View File

@@ -0,0 +1,338 @@
<?php
use Grav\Framework\Filesystem\Filesystem;
/**
* Class FilesystemTest
*/
class FilesystemTest extends \Codeception\TestCase\Test
{
protected $class;
protected $tests = [
'' => [
'parent' => '',
'normalize' => '',
'dirname' => '',
'pathinfo' => [
'basename' => '',
'filename' => '',
]
],
'.' => [
'parent' => '',
'normalize' => '',
'dirname' => '.',
'pathinfo' => [
'dirname' => '.',
'basename' => '.',
'extension' => '',
'filename' => '',
]
],
'./' => [
'parent' => '',
'normalize' => '',
'dirname' => '.',
'pathinfo' => [
'dirname' => '.',
'basename' => '.',
'extension' => '',
'filename' => '',
]
],
'././.' => [
'parent' => '',
'normalize' => '',
'dirname' => './.',
'pathinfo' => [
'dirname' => './.',
'basename' => '.',
'extension' => '',
'filename' => '',
]
],
'.file' => [
'parent' => '.',
'normalize' => '.file',
'dirname' => '.',
'pathinfo' => [
'dirname' => '.',
'basename' => '.file',
'extension' => 'file',
'filename' => '',
]
],
'/' => [
'parent' => '',
'normalize' => '/',
'dirname' => '/',
'pathinfo' => [
'dirname' => '/',
'basename' => '',
'filename' => '',
]
],
'/absolute' => [
'parent' => '/',
'normalize' => '/absolute',
'dirname' => '/',
'pathinfo' => [
'dirname' => '/',
'basename' => 'absolute',
'filename' => 'absolute',
]
],
'/absolute/' => [
'parent' => '/',
'normalize' => '/absolute',
'dirname' => '/',
'pathinfo' => [
'dirname' => '/',
'basename' => 'absolute',
'filename' => 'absolute',
]
],
'/very/long/absolute/path' => [
'parent' => '/very/long/absolute',
'normalize' => '/very/long/absolute/path',
'dirname' => '/very/long/absolute',
'pathinfo' => [
'dirname' => '/very/long/absolute',
'basename' => 'path',
'filename' => 'path',
]
],
'/very/long/absolute/../path' => [
'parent' => '/very/long',
'normalize' => '/very/long/path',
'dirname' => '/very/long/absolute/..',
'pathinfo' => [
'dirname' => '/very/long/absolute/..',
'basename' => 'path',
'filename' => 'path',
]
],
'relative' => [
'parent' => '.',
'normalize' => 'relative',
'dirname' => '.',
'pathinfo' => [
'dirname' => '.',
'basename' => 'relative',
'filename' => 'relative',
]
],
'very/long/relative/path' => [
'parent' => 'very/long/relative',
'normalize' => 'very/long/relative/path',
'dirname' => 'very/long/relative',
'pathinfo' => [
'dirname' => 'very/long/relative',
'basename' => 'path',
'filename' => 'path',
]
],
'path/to/file.jpg' => [
'parent' => 'path/to',
'normalize' => 'path/to/file.jpg',
'dirname' => 'path/to',
'pathinfo' => [
'dirname' => 'path/to',
'basename' => 'file.jpg',
'extension' => 'jpg',
'filename' => 'file',
]
],
'user://' => [
'parent' => '',
'normalize' => 'user://',
'dirname' => 'user://',
'pathinfo' => [
'dirname' => 'user://',
'basename' => '',
'filename' => '',
'scheme' => 'user',
]
],
'user://.' => [
'parent' => '',
'normalize' => 'user://',
'dirname' => 'user://',
'pathinfo' => [
'dirname' => 'user://',
'basename' => '',
'filename' => '',
'scheme' => 'user',
]
],
'user://././.' => [
'parent' => '',
'normalize' => 'user://',
'dirname' => 'user://',
'pathinfo' => [
'dirname' => 'user://',
'basename' => '',
'filename' => '',
'scheme' => 'user',
]
],
'user://./././file' => [
'parent' => 'user://',
'normalize' => 'user://file',
'dirname' => 'user://',
'pathinfo' => [
'dirname' => 'user://',
'basename' => 'file',
'filename' => 'file',
'scheme' => 'user',
]
],
'user://./././folder/file' => [
'parent' => 'user://folder',
'normalize' => 'user://folder/file',
'dirname' => 'user://folder',
'pathinfo' => [
'dirname' => 'user://folder',
'basename' => 'file',
'filename' => 'file',
'scheme' => 'user',
]
],
'user://.file' => [
'parent' => 'user://',
'normalize' => 'user://.file',
'dirname' => 'user://',
'pathinfo' => [
'dirname' => 'user://',
'basename' => '.file',
'extension' => 'file',
'filename' => '',
'scheme' => 'user',
]
],
'user:///' => [
'parent' => '',
'normalize' => 'user:///',
'dirname' => 'user:///',
'pathinfo' => [
'dirname' => 'user:///',
'basename' => '',
'filename' => '',
'scheme' => 'user',
]
],
'user:///absolute' => [
'parent' => 'user:///',
'normalize' => 'user:///absolute',
'dirname' => 'user:///',
'pathinfo' => [
'dirname' => 'user:///',
'basename' => 'absolute',
'filename' => 'absolute',
'scheme' => 'user',
]
],
'user:///very/long/absolute/path' => [
'parent' => 'user:///very/long/absolute',
'normalize' => 'user:///very/long/absolute/path',
'dirname' => 'user:///very/long/absolute',
'pathinfo' => [
'dirname' => 'user:///very/long/absolute',
'basename' => 'path',
'filename' => 'path',
'scheme' => 'user',
]
],
'user://relative' => [
'parent' => 'user://',
'normalize' => 'user://relative',
'dirname' => 'user://',
'pathinfo' => [
'dirname' => 'user://',
'basename' => 'relative',
'filename' => 'relative',
'scheme' => 'user',
]
],
'user://very/long/relative/path' => [
'parent' => 'user://very/long/relative',
'normalize' => 'user://very/long/relative/path',
'dirname' => 'user://very/long/relative',
'pathinfo' => [
'dirname' => 'user://very/long/relative',
'basename' => 'path',
'filename' => 'path',
'scheme' => 'user',
]
],
'user://path/to/file.jpg' => [
'parent' => 'user://path/to',
'normalize' => 'user://path/to/file.jpg',
'dirname' => 'user://path/to',
'pathinfo' => [
'dirname' => 'user://path/to',
'basename' => 'file.jpg',
'extension' => 'jpg',
'filename' => 'file',
'scheme' => 'user',
]
],
];
protected function _before(): void
{
$this->class = Filesystem::getInstance();
}
protected function _after(): void
{
unset($this->class);
}
/**
* @param array $tests
* @param string $method
*/
protected function runTestSet(array $tests, $method): void
{
$class = $this->class;
foreach ($tests as $path => $candidates) {
if (!array_key_exists($method, $candidates)) {
continue;
}
$expected = $candidates[$method];
$result = $class->{$method}($path);
self::assertSame($expected, $result, "Test {$method}('{$path}')");
if (function_exists($method) && !strpos($path, '://')) {
$cmp_result = $method($path);
self::assertSame($cmp_result, $result, "Compare to original {$method}('{$path}')");
}
}
}
public function testParent(): void
{
$this->runTestSet($this->tests, 'parent');
}
public function testNormalize(): void
{
$this->runTestSet($this->tests, 'normalize');
}
public function testDirname(): void
{
$this->runTestSet($this->tests, 'dirname');
}
public function testPathinfo(): void
{
$this->runTestSet($this->tests, 'pathinfo');
}
}

View File

@@ -0,0 +1,3 @@
<?php
// Here you can initialize variables that will be available to your tests
define('GRAV_CLI', true);

View File

@@ -0,0 +1,15 @@
form:
validation: strict
fields:
tabs:
type: tabs
fields:
tab:
type: tab
fields:
test:
type: text
label: Test
validate:
required: true