fix/reset unit tests

This commit is contained in:
nobody 2022-07-04 06:34:46 +10:00
parent 0a08fc732f
commit a23be70d68
13 changed files with 11 additions and 1582 deletions

View file

@ -1,201 +0,0 @@
<?php
/*
* Copyright (c) 2017 Hubzilla
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
namespace Code\Tests\Unit\Access;
use Code\Tests\Unit\UnitTestCase;
use Code\Access\AccessControl;
/**
* @brief Unit Test case for AccessList class.
*
* @covers Code\Access\AccessControl
*/
class AccessListTest extends UnitTestCase
{
/**
* @brief Expected result for most tests.
* @var array
*/
protected $expectedResult = [
'allow_cid' => '<acid><acid2>',
'allow_gid' => '<agid>',
'deny_cid' => '',
'deny_gid' => '<dgid><dgid2>'
];
public function testConstructor()
{
$channel = [
'channel_allow_cid' => '<acid><acid2>',
'channel_allow_gid' => '<agid>',
'channel_deny_cid' => '',
'channel_deny_gid' => '<dgid><dgid2>'
];
$accessList = new AccessControl($channel);
$this->assertEquals($this->expectedResult, $accessList->get());
$this->assertFalse($accessList->get_explicit());
}
/**
* @expectedException PHPUnit\Framework\Error\Error
*/
public function testPHPErrorOnInvalidConstructor()
{
$accessList = new AccessControl('invalid');
// Causes: "Illegal string offset 'channel_allow_cid'"
}
public function testDefaultGetExplicit()
{
$accessList = new AccessControl([]);
$this->assertFalse($accessList->get_explicit());
}
public function testDefaultGet()
{
$arr = [
'allow_cid' => '',
'allow_gid' => '',
'deny_cid' => '',
'deny_gid' => ''
];
$accessList = new AccessControl([]);
$this->assertEquals($arr, $accessList->get());
}
public function testSet()
{
$arr = [
'allow_cid' => '<acid><acid2>',
'allow_gid' => '<agid>',
'deny_cid' => '',
'deny_gid' => '<dgid><dgid2>'
];
$accessList = new AccessControl([]);
// default explicit true
$accessList->set($arr);
$this->assertEquals($this->expectedResult, $accessList->get());
$this->assertTrue($accessList->get_explicit());
// set explicit false
$accessList->set($arr, false);
$this->assertEquals($this->expectedResult, $accessList->get());
$this->assertFalse($accessList->get_explicit());
}
/**
* @expectedException PHPUnit\Framework\Error\Error
*/
public function testPHPErrorOnInvalidSet()
{
$accessList = new AccessControl([]);
$accessList->set('invalid');
// Causes: "Illegal string offset 'allow_cid'"
}
/**
* set_from_[] calls some other functions, too which are not yet unit tested.
* @uses ::perms2str
* @uses ::sanitise_acl
* @uses ::notags
*/
public function testSetFromArray()
{
// array
$arraySetFromArray = [
'contact_allow' => ['acid', 'acid2'],
'group_allow' => ['agid'],
'contact_deny' => [],
'group_deny' => ['dgid', 'dgid2']
];
$accessList = new AccessControl([]);
$accessList->set_from_array($arraySetFromArray);
$this->assertEquals($this->expectedResult, $accessList->get());
$this->assertTrue($accessList->get_explicit());
// string
$stringSetFromArray = [
'contact_allow' => 'acid,acid2',
'group_allow' => 'agid',
'contact_deny' => '',
'group_deny' => 'dgid, dgid2'
];
$accessList2 = new AccessControl([]);
$accessList2->set_from_array($stringSetFromArray, false);
$this->assertEquals($this->expectedResult, $accessList2->get());
$this->assertFalse($accessList2->get_explicit());
}
/**
* @dataProvider isprivateProvider
*/
public function testIsPrivate($channel)
{
$accessListPublic = new AccessControl([]);
$this->assertFalse($accessListPublic->is_private());
$accessListPrivate = new AccessControl($channel);
$this->assertTrue($accessListPrivate->is_private());
}
public function isprivateProvider()
{
return [
'all set' => [[
'channel_allow_cid' => '<acid>',
'channel_allow_gid' => '<agid>',
'channel_deny_cid' => '<dcid>',
'channel_deny_gid' => '<dgid>'
]],
'only one set' => [[
'channel_allow_cid' => '<acid>',
'channel_allow_gid' => '',
'channel_deny_cid' => '',
'channel_deny_gid' => ''
]],
'acid+null' => [[
'channel_allow_cid' => '<acid>',
'channel_allow_gid' => null,
'channel_deny_cid' => '',
'channel_deny_gid' => ''
]]
];
}
}

View file

@ -1,80 +0,0 @@
<?php
/*
* Copyright (c) 2017 Hubzilla
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
namespace Code\Tests\Unit\Access;
use phpmock\phpunit\PHPMock;
use Code\Tests\Unit\UnitTestCase;
use Code\Access\PermissionLimits;
use Code\Extend\Hook;
/**
* @brief Unit Test case for PermissionLimits class.
*
* @covers Code\Access\PermissionLimits
*/
class PermissionLimitsTest extends UnitTestCase
{
use PHPMock;
/**
* @todo If we could replace static call to Permissions::Perms() in
* Std_Limits() we could better unit test this method, now we test the
* result of Permissions::Perms() mostly.
*
* @uses Code\Access\Permissions::Perms
* @uses ::Hook::call
*/
public function testStd_Limits()
{
// There are 18 default perms
$permsCount = 18;
// Create a stub for global function t() with expectation
$t = $this->getFunctionMock('Code\Access', 't');
$t->expects($this->exactly($permsCount));
$stdlimits = PermissionLimits::Std_Limits();
$this->assertCount($permsCount, $stdlimits, "There should be $permsCount permissions.");
$this->assertEquals(PERMS_PUBLIC, $stdlimits['view_stream']);
$this->assertEquals(PERMS_SPECIFIC, $stdlimits['send_stream']);
$this->assertEquals(PERMS_PUBLIC, $stdlimits['view_profile']);
$this->assertEquals(PERMS_PUBLIC, $stdlimits['view_contacts']);
$this->assertEquals(PERMS_PUBLIC, $stdlimits['view_storage']);
$this->assertEquals(PERMS_SPECIFIC, $stdlimits['write_storage']);
$this->assertEquals(PERMS_PUBLIC, $stdlimits['view_pages']);
$this->assertEquals(PERMS_PUBLIC, $stdlimits['view_wiki']);
$this->assertEquals(PERMS_SPECIFIC, $stdlimits['write_pages']);
$this->assertEquals(PERMS_SPECIFIC, $stdlimits['write_wiki']);
$this->assertEquals(PERMS_SPECIFIC, $stdlimits['post_wall']);
$this->assertEquals(PERMS_SPECIFIC, $stdlimits['post_comments']);
$this->assertEquals(PERMS_SPECIFIC, $stdlimits['post_mail']);
$this->assertEquals(PERMS_SPECIFIC, $stdlimits['post_like']);
$this->assertEquals(PERMS_SPECIFIC, $stdlimits['tag_deliver']);
$this->assertEquals(PERMS_SPECIFIC, $stdlimits['chat']);
$this->assertEquals(PERMS_SPECIFIC, $stdlimits['republish']);
$this->assertEquals(PERMS_SPECIFIC, $stdlimits['delegate']);
}
}

View file

@ -1,105 +0,0 @@
<?php
/*
* Copyright (c) 2017 Hubzilla
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
namespace Code\Tests\Unit\Access;
use Code\Tests\Unit\UnitTestCase;
use Code\Access\PermissionRoles;
use phpmock\phpunit\PHPMock;
use Code\Extend\Hook;
/**
* @brief Unit Test case for PermissionRoles class.
*
* @TODO Work around dependencies to static PermissionLimits methods.
*
* @covers Code\Access\PermissionRoles
*/
class PermissionRolesTest extends UnitTestCase
{
use PHPMock;
public function testVersion()
{
$expectedVersion = 3;
$this->assertEquals($expectedVersion, PermissionRoles::version());
$pr = new PermissionRoles();
$this->assertEquals($expectedVersion, $pr->version());
}
public function testRoles()
{
// Create a stub for global function t() with expectation
$t = $this->getFunctionMock('Code\Access', 't');
$t->expects($this->atLeastOnce())->willReturnCallback(
function ($string) {
return $string;
}
);
$roles = PermissionRoles::roles();
$r = new PermissionRoles();
$this->assertEquals($roles, $r->roles());
$socialNetworking = [
'social_federation' => 'Social - Federation',
'social' => 'Social - Mostly Public',
'social_restricted' => 'Social - Restricted',
'social_private' => 'Social - Private'
];
$this->assertArraySubset(['Social Networking' => $socialNetworking], $roles);
$this->assertEquals($socialNetworking, $roles['Social Networking']);
$this->assertCount(5, $roles, 'There should be 5 permission groups.');
$this->assertCount(1, $roles['Other'], "In the 'Other' group should be just one permission role");
}
/**
* @uses ::Hook::call
* @uses Code\Access\PermissionLimits::Std_Limits
* @uses Code\Access\Permissions::Perms
*/
public function testRole_perms()
{
// Create a stub for global function t()
$t = $this->getFunctionMock('Code\Access', 't');
$t = $this->getFunctionMock('Code\Access', 'get_config');
$rp_social = PermissionRoles::role_perms('social');
$this->assertEquals('social', $rp_social['role']);
$rp_custom = PermissionRoles::role_perms('custom');
$this->assertEquals(['role' => 'custom'], $rp_custom);
$rp_nonexistent = PermissionRoles::role_perms('nonexistent');
$this->assertEquals(['role' => 'nonexistent'], $rp_nonexistent);
}
}

View file

@ -1,336 +0,0 @@
<?php
/*
* Copyright (c) 2017 Hubzilla
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
namespace Code\Tests\Unit\Access;
use phpmock\phpunit\PHPMock;
use Code\Access\PermissionRoles;
use Code\Tests\Unit\UnitTestCase;
use Code\Access\Permissions;
use Code\Extend\Hook;
/**
* @brief Unit Test case for Permissions class.
*
* @covers Code\Access\Permissions
*/
class PermissionsTest extends UnitTestCase
{
use PHPMock;
public function testVersion()
{
$expectedVersion = 3;
// static call
$this->assertEquals($expectedVersion, Permissions::version());
// instance call
$p = new Permissions();
$this->assertEquals($expectedVersion, $p->version());
}
/**
* @coversNothing
*/
public function testVersionEqualsPermissionRoles()
{
$p = new Permissions();
$pr = new PermissionRoles();
$this->assertEquals($p->version(), $pr->version());
}
/**
* @uses ::Hook::call
*/
public function testPerms()
{
// There are 18 default perms
$permsCount = 18;
// Create a stub for global function t() with expectation
$t = $this->getFunctionMock('Code\Access', 't');
$t->expects($this->exactly(2 * $permsCount))->willReturnCallback(
function ($string) {
return $string;
}
);
// static method Perms()
$perms = Permissions::Perms();
$p = new Permissions();
$this->assertEquals($perms, $p->Perms());
$this->assertEquals($permsCount, count($perms), "There should be $permsCount permissions.");
$this->assertEquals('Can view my channel stream and posts', $perms['view_stream']);
// non existent perm should not be set
$this->assertFalse(isset($perms['invalid_perm']));
}
/**
* filter parmeter is only used in hook \b permissions_list. So the result
* in this test should be the same as if there was no filter parameter.
*
* @todo Stub Hook::call() function and also test filter
*
* @uses ::Hook::call
*/
public function testPermsFilter()
{
// There are 18 default perms
$permsCount = 18;
// Create a stub for global function t() with expectation
$t = $this->getFunctionMock('Code\Access', 't');
$t->expects($this->exactly(2 * $permsCount))->willReturnCallback(
function ($string) {
return $string;
}
);
$perms = Permissions::Perms('view_');
$this->assertEquals($permsCount, count($perms));
$this->assertEquals('Can view my channel stream and posts', $perms['view_stream']);
$perms = Permissions::Perms('invalid_perm');
$this->assertEquals($permsCount, count($perms));
}
/**
* Better should mock Permissions::Perms, but not possible with static methods.
*
* @uses ::Hook::call
*
* @dataProvider FilledPermsProvider
*
* @param array $permarr An indexed permissions array to pass
* @param array $expected The expected result perms array
*/
public function testFilledPerms($permarr, $expected)
{
// Create a stub for global function t()
$t = $this->getFunctionMock('Code\Access', 't');
$this->assertEquals($expected, Permissions::FilledPerms($permarr));
}
/**
* @return array An associative array with test values for FilledPerms()
* * \e array Indexed array which is passed as parameter to FilledPerms()
* * \e array Expected associative result array with filled perms
*/
public function FilledPermsProvider()
{
return [
'Empty param array' => [
[],
[
'view_stream' => 0,
'send_stream' => 0,
'view_profile' => 0,
'view_contacts' => 0,
'view_storage' => 0,
'write_storage' => 0,
'view_pages' => 0,
'view_wiki' => 0,
'write_pages' => 0,
'write_wiki' => 0,
'post_wall' => 0,
'post_comments' => 0,
'post_mail' => 0,
'post_like' => 0,
'tag_deliver' => 0,
'chat' => 0,
'republish' => 0,
'delegate' => 0
]
],
'provide view_stream and view_pages as param' => [
['view_stream', 'view_pages'],
[
'view_stream' => 1,
'send_stream' => 0,
'view_profile' => 0,
'view_contacts' => 0,
'view_storage' => 0,
'write_storage' => 0,
'view_pages' => 1,
'view_wiki' => 0,
'write_pages' => 0,
'write_wiki' => 0,
'post_wall' => 0,
'post_comments' => 0,
'post_mail' => 0,
'post_like' => 0,
'tag_deliver' => 0,
'chat' => 0,
'republish' => 0,
'delegate' => 0
]
],
'provide an unknown param' => [
['view_stream', 'unknown_perm'],
[
'view_stream' => 1,
'send_stream' => 0,
'view_profile' => 0,
'view_contacts' => 0,
'view_storage' => 0,
'write_storage' => 0,
'view_pages' => 0,
'view_wiki' => 0,
'write_pages' => 0,
'write_wiki' => 0,
'post_wall' => 0,
'post_comments' => 0,
'post_mail' => 0,
'post_like' => 0,
'tag_deliver' => 0,
'chat' => 0,
'republish' => 0,
'delegate' => 0
]
]
];
}
/**
* @uses ::Hook::call
*/
public function testFilledPermsNull()
{
// Create a stub for global function t() with expectation
$t = $this->getFunctionMock('Code\Access', 't');
$t->expects($this->atLeastOnce());
// Create a stub for global function bt() with expectations
$bt = $this->getFunctionMock('Code\Access', 'btlogger');
$bt->expects($this->once())->with($this->equalTo('FilledPerms: null'));
$result = [
'view_stream' => 0,
'send_stream' => 0,
'view_profile' => 0,
'view_contacts' => 0,
'view_storage' => 0,
'write_storage' => 0,
'view_pages' => 0,
'view_wiki' => 0,
'write_pages' => 0,
'write_wiki' => 0,
'post_wall' => 0,
'post_comments' => 0,
'post_mail' => 0,
'post_like' => 0,
'tag_deliver' => 0,
'chat' => 0,
'republish' => 0,
'delegate' => 0
];
$this->assertEquals($result, Permissions::FilledPerms(null));
}
/**
* @dataProvider OPermsProvider
*
* @param array $permarr The params to pass to the OPerms method
* @param array $expected The expected result
*/
public function testOPerms($permarr, $expected)
{
$this->assertEquals($expected, Permissions::OPerms($permarr));
}
/**
* @return array An associative array with test values for OPerms()
* * \e array Array with perms to test
* * \e array Expected result array
*/
public function OPermsProvider()
{
return [
'empty' => [
[],
[]
],
'valid' => [
['perm1' => 1, 'perm2' => 0],
[['name' => 'perm1', 'value' => 1], ['name' => 'perm2', 'value' => 0]]
],
'null array' => [
null,
[]
]
];
}
/**
* @dataProvider permsCompareProvider
*
* @param array $p1 The first permission
* @param array $p2 The second permission
* @param bool $expectedresult The expected result of the tested method
*/
public function testPermsCompare($p1, $p2, $expectedresult)
{
$this->assertEquals($expectedresult, Permissions::PermsCompare($p1, $p2));
}
/**
* @return array An associative array with test values for PermsCompare()
* * \e array 1st array with perms
* * \e array 2nd array with perms
* * \e boolean expected result for the perms comparison
*/
public function permsCompareProvider()
{
return [
'equal' => [
['perm1' => 1, 'perm2' => 0],
['perm1' => 1, 'perm2' => 0],
true
],
'different values' => [
['perm1' => 1, 'perm2' => 0],
['perm1' => 0, 'perm2' => 1],
false
],
'different order' => [
['perm1' => 1, 'perm2' => 0],
['perm2' => 0, 'perm1' => 1],
true
],
'partial first in second' => [
['perm1' => 1],
['perm1' => 1, 'perm2' => 0],
true
],
'partial second in first' => [
['perm1' => 1, 'perm2' => 0],
['perm1' => 1],
false
]
];
}
}

View file

@ -1,74 +0,0 @@
<?php
/* Copyright (c) 2017 Hubzilla
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
namespace Code\Tests\Unit;
use PDO;
use PHPUnit\DbUnit\Database\Connection;
use PHPUnit\DbUnit\TestCaseTrait;
use PHPUnit\Framework\TestCase;
use function getenv;
/**
* @brief Base class for our Database Unit Tests.
*
* @warning Never run these tests against a production database, because all
* tables will get truncated and there is no way to recover without a backup.
*
* @author Klaus Weidenbach
*/
abstract class DatabaseTestCase extends TestCase
{
use TestCaseTrait;
/**
* Only instantiate PDO once for test clean-up/fixture load.
*
* @var PDO
*/
private static $pdo = null;
/**
* Only instantiate \PHPUnit\DbUnit\Database\Connection once per test.
*
* @var Connection
*/
private $conn = null;
final public function getConnection()
{
if ($this->conn === null) {
if (self::$pdo === null) {
$dsn = getenv('hz_db_scheme') . ':host=' . getenv('hz_db_server')
. ';port=' . getenv('hz_db_port') . ';dbname=' . getenv('hz_db_database');
self::$pdo = new PDO($dsn, getenv('hz_db_user'), getenv('hz_db_pass'));
}
$this->conn = $this->createDefaultDBConnection(self::$pdo, getenv('hz_db_database'));
}
return $this->conn;
}
}

View file

@ -1,150 +0,0 @@
<?php
/*
* Copyright (c) 2017 Hubzilla
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
namespace Code\Tests\Unit\includes;
use Code\Tests\Unit\UnitTestCase;
use phpmock\phpunit\PHPMock;
use Code\Lib\Markdown;
/**
* @brief Unit Test case for markdown functions.
*/
class MarkdownTest extends UnitTestCase
{
use PHPMock;
/**
* @covers ::html2markdown
* @dataProvider html2markdownProvider
*/
public function testHtml2markdown($html, $markdown)
{
$this->assertEquals($markdown, Markdown::from_html($html));
}
public function html2markdownProvider()
{
return [
'empty text' => [
'',
''
],
'space and nbsp only' => [
' &nbsp;',
''
],
'strong, b, em, i, bib' => [
'<strong>strong</strong> <b>bold</b> <em>em</em> <i>italic</i> <b>bo<i>italic</i>ld</b>',
'**strong** **bold** *em* *italic* **bo*italic*ld**'
],
'empty tags' => [
'text1 <b></b> text2 <i></i>',
'text1 text2'
],
'HTML entities, lt does not work' => [
'& gt > lt <',
'& gt > lt'
],
'escaped HTML entities' => [
'&amp; lt &lt; gt &gt;',
'& lt < gt >'
],
'linebreak' => [
"line1<br>line2\nline3",
"line1 \nline2 line3"
],
'headlines' => [
'<h1>header1</h1><h3>Header 3</h3>',
"header1\n=======\n\n### Header 3"
],
'unordered list' => [
'<ul><li>Item 1</li><li>Item 2</li><li>Item <b>3</b></li></ul>',
"- Item 1\n- Item 2\n- Item **3**"
],
'ordered list' => [
'<ol><li>Item 1</li><li>Item 2</li><li>Item <b>3</b></li></ol>',
"1. Item 1\n2. Item 2\n3. Item **3**"
],
'nested lists' => [
'<ul><li>Item 1<ol><li>Item 1a</li><li>Item <b>1b</b></ol></li><li>Item 2</li></ul>',
"- Item 1\n 1. Item 1a\n 2. Item **1b**\n- Item 2"
],
'img' => [
'<img src="/path/to/img.png" alt="alt text" title="title text">',
'![alt text](/path/to/img.png "title text")'
],
'link' => [
'<a href="http://hubzilla.org" title="Hubzilla">link</a>',
'[link](http://hubzilla.org "Hubzilla")'
],
'img link' => [
'<a href="http://hubzilla.org" title="Hubzilla"><img src="/img/hubzilla.png" alt="alt img text" title="img title"></a>',
'[![alt img text](/img/hubzilla.png "img title")](http://hubzilla.org "Hubzilla")'
],
'script' => [
"<script>alert('test');</script>",
"<script>alert('test');</script>"
],
'blockquote, issue #793' => [
'<blockquote>something</blockquote>blah',
"> something\n\nblah"
],
'code' => [
'<code>&lt;p&gt;HTML text&lt;/p&gt;</code>',
'`<p>HTML text</p>`'
],
'pre' => [
'<pre> one line with spaces </pre>',
"```\n one line with spaces \n```"
],
'div p' => [
'<div>div</div><div><p>p</p></div>',
"<div>div</div><div>p\n\n</div>"
]
];
}
/*public function testHtml2markdownException() {
//$this->expectException(\InvalidArgumentException::class);
// need to stub logger() for this to work
$this->assertEquals('', Markdown::from_html('<<invalid'));
}*/
/* public function testBB2diasporaMardown() {
//stub bbcode() and return our HTML, we just need to test the HTML2Markdown library.
$html1 = 'test<b>bold</b><br><i>i</i><ul><li>li1</li><li>li2</li></ul><br>';
$bb1 = 'test';
// php-mock can not mock global functions which is called by a global function.
// If the calling function is in a namespace it does work.
$bbc = $this->getFunctionMock(__NAMESPACE__, "bbcode");
$bbc->expects($this->once())->willReturn('test<b>bold</b><br><i>i</i><ul><li>li1</li><li>li2</li></ul><br>');
$this->assertEquals($bb1, Markdown::from_bbcode($html1));
}
*/
}

View file

@ -1,102 +0,0 @@
<?php
/*
* Copyright (c) 2016-2017 Hubzilla
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
namespace Code\Tests\Unit\Lib;
use phpmock\phpunit\PHPMock;
use Code\Tests\Unit\UnitTestCase;
use Code\Lib\PermissionDescription;
/**
* @brief Unit Test case for PermissionDescription class.
*
* @covers Code\Lib\PermissionDescription
*/
class PermissionDescriptionTest extends UnitTestCase
{
use PHPMock;
public function testFromDescription()
{
$permDesc = PermissionDescription::fromDescription('test');
$permDesc2 = PermissionDescription::fromDescription('test');
$permDesc3 = PermissionDescription::fromDescription('test2');
$this->assertEquals($permDesc, $permDesc2);
$this->assertNotEquals($permDesc, $permDesc3);
}
public function testFromStandalonePermission()
{
// Create a stub for global function t()
$t = $this->getFunctionMock('Code\Lib', 't');
$t->expects($this->atLeastOnce())->willReturnCallback(
function ($string) {
return $string;
}
);
// Create a mock for global function logger()
$this->getFunctionMock('Code\Lib', 'logger');
$permDescUnknown = PermissionDescription::fromStandalonePermission(-1);
$permDescSelf = PermissionDescription::fromStandalonePermission(0);
$this->assertNull($permDescUnknown);
$this->assertNotNull($permDescSelf);
}
public function testFromGlobalPermission()
{
//$permDesc = PermissionDescription::fromGlobalPermission('view_profile');
$this->markTestIncomplete(
'The method fromGlobalPermission() is not yet testable ...'
);
}
public function testGetPermissionDescription()
{
// Create a stub for global function t()
$t = $this->getFunctionMock('Code\Lib', 't');
$t->expects($this->atLeastOnce())->willReturnCallback(
function ($string) {
return $string;
}
);
// Create a mock for global function logger()
$this->getFunctionMock('Code\Lib', 'logger');
// Create a stub for the PermissionDescription class
$stub = $this->createMock(PermissionDescription::class);
$stub->method('get_permission_description')
->will($this->returnArgument(0));
$permDescSelf = PermissionDescription::fromStandalonePermission(0);
$this->assertInstanceOf(PermissionDescription::class, $permDescSelf);
$this->assertEquals($permDescSelf->get_permission_description(), 'Only me');
$permDescPublic = PermissionDescription::fromStandalonePermission(PERMS_PUBLIC);
$this->assertEquals($permDescPublic->get_permission_description(), 'Public');
}
}

View file

@ -33,7 +33,7 @@ use Code\Web\HTTPSig;
*
* @covers Code\Web\HTTPSig
*/
class PermissionDescriptionTest extends UnitTestCase
class HttpSigTest extends UnitTestCase
{
use PHPMock;
@ -45,7 +45,7 @@ class PermissionDescriptionTest extends UnitTestCase
{
$this->assertSame(
$digest,
HTTPSig::generate_digest($text, false)
HTTPSig::generate_digest_header($text, 'sha256')
);
}
@ -54,15 +54,15 @@ class PermissionDescriptionTest extends UnitTestCase
return [
'empty body text' => [
'',
'47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU='
'SHA-256=47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU='
],
'sample body text' => [
'body text',
'2fu8kUkvuzuo5XyhWwORNOcJgDColXgxWkw1T5EXzPI='
'SHA-256=2fu8kUkvuzuo5XyhWwORNOcJgDColXgxWkw1T5EXzPI='
],
'NULL body text' => [
null,
'47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU='
'SHA-256=47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU='
],
];
}
@ -70,67 +70,10 @@ class PermissionDescriptionTest extends UnitTestCase
public function testGeneratedDigestsOfDifferentTextShouldNotBeEqual()
{
$this->assertNotSame(
HTTPSig::generate_digest('text1', false),
HTTPSig::generate_digest('text2', false)
HTTPSig::generate_digest_header('text1'),
HTTPSig::generate_digest_header('text2')
);
}
/**
* Process separation needed for header() check.
* @runInSeparateProcess
*/
public function testGenerate_digestSendsHttpHeader()
{
$ret = HTTPSig::generate_digest('body text', true);
$this->assertSame('2fu8kUkvuzuo5XyhWwORNOcJgDColXgxWkw1T5EXzPI=', $ret);
$this->assertContains(
'Digest: SHA-256=2fu8kUkvuzuo5XyhWwORNOcJgDColXgxWkw1T5EXzPI=',
xdebug_get_headers(),
'HTTP header Digest does not match'
);
}
/**
* @uses ::crypto_unencapsulate
*/
public function testDecrypt_sigheader()
{
$header = 'Header: iv="value_iv" key="value_key" alg="value_alg" data="value_data"';
$result = [
'iv' => 'value_iv',
'key' => 'value_key',
'alg' => 'value_alg',
'data' => 'value_data'
];
$this->assertSame($result, HTTPSig::decrypt_sigheader($header, 'site private key'));
}
/**
* @uses ::crypto_unencapsulate
*/
public function testDecrypt_sigheaderUseSitePrivateKey()
{
// Create a stub for global function get_config() with expectation
$t = $this->getFunctionMock('Code\Web', 'get_config');
$t->expects($this->once())->willReturn('system.prvkey');
$header = 'Header: iv="value_iv" key="value_key" alg="value_alg" data="value_data"';
$result = [
'iv' => 'value_iv',
'key' => 'value_key',
'alg' => 'value_alg',
'data' => 'value_data'
];
$this->assertSame($result, HTTPSig::decrypt_sigheader($header));
}
public function testDecrypt_sigheaderIncompleteHeaderShouldReturnEmptyString()
{
$header = 'Header: iv="value_iv" key="value_key"';
$this->assertEmpty(HTTPSig::decrypt_sigheader($header, 'site private key'));
}
}

View file

@ -1,174 +0,0 @@
<?php
/*
* Copyright (c) 2017 Hubzilla
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
namespace Code\Tests\Unit\includes;
use Code\Tests\Unit\UnitTestCase;
use Text_LanguageDetect;
//use phpmock\phpunit\PHPMock;
/**
* @brief Unit Test cases for include/language.php file.
*
* @author Klaus Weidenbach
*/
class LanguageTest extends UnitTestCase
{
//use PHPMock;
/**
* @dataProvider languageExamplesProvider
* @coversNothing
*/
public function testDetectLanguage($text, $langCode, $confidence)
{
require_once('library/text_languagedetect/Text/LanguageDetect.php');
// php-mock can not mock global functions which is called by a global function.
// If the calling function is in a namespace it would work.
//$gc = $this->getFunctionMock(__NAMESPACE__, 'get_config');
//$gc->expects($this->once())->willReturn(10)
//$cg = $this->getFunctionMock('Code\Lib\Config', 'Get');
//$cg->expects($this->once())->willReturn(10);
//$this->assertEquals($langCode, detect_language($text));
// Can not unit test detect_language(), therefore test the used library
// only for now to find regressions on library updates.
$l = new Text_LanguageDetect();
// return 2-letter ISO 639-1 (en) language code
$l->setNameMode(2);
$lng = $l->detectConfidence($text);
$this->assertEquals($langCode, $lng['language']);
$this->assertEquals($confidence, round($lng['confidence'], 6));
}
public function languageExamplesProvider()
{
return [
'empty text' => [
'',
'',
null
],
'English' => [
'English is a West Germanic language that was first spoken in early medieval England and is now a global lingua franca.[4][5] Named after the Angles, one of the Germanic tribes that migrated to England, it ultimately derives its name from the Anglia (Angeln) peninsula in the Baltic Sea. It is closely related to the Frisian languages, but its vocabulary has been significantly influenced by other Germanic languages, particularly Norse (a North Germanic language), as well as by Latin and Romance languages, especially French.',
'en',
0.078422
],
'German' => [
'Deutschland ist ein Bundesstaat in Mitteleuropa. Er besteht aus 16 Ländern und ist als freiheitlich-demokratischer und sozialer Rechtsstaat verfasst. Die Bundesrepublik Deutschland stellt die jüngste Ausprägung des deutschen Nationalstaates dar. Mit rund 82,8 Millionen Einwohnern (31. Dezember 2016) zählt Deutschland zu den dicht besiedelten Flächenstaaten.',
'de',
0.134339
],
'Norwegian' => [
'Kongeriket Norge er et nordisk, europeisk land og en selvstendig stat vest på Den skandinaviske halvøy. Landet er langt og smalt, og kysten strekker seg langs Nord-Atlanteren, hvor også Norges kjente fjorder befinner seg. Totalt dekker det relativt tynt befolkede landet 385 000 kvadratkilometer med litt over fem millioner innbyggere (2016).',
'no',
0.007076
]
];
}
/**
* @covers ::get_language_name
* @dataProvider getLanguageNameProvider
*/
public function testGetLanguageName($lang, $name, $trans)
{
$this->assertEquals($name, get_language_name($lang));
foreach ($trans as $k => $v) {
//echo "$k -> $v";
$this->assertEquals($v, get_language_name($lang, $k));
}
}
public function getLanguageNameProvider()
{
return [
'empty language code' => [
'',
'',
['de' => '']
],
'invalid language code' => [
'zz',
'zz',
['de' => 'zz']
],
'de' => [
'de',
'German',
[
'de' => 'Deutsch',
'nb' => 'tysk'
]
],
'de-de' => [
'de-de',
'German',
[
'de-de' => 'Deutsch',
'nb' => 'Deutsch' // should be tysk, seems to be a bug upstream
]
],
'en' => [
'en',
'English',
[
'de' => 'Englisch',
'nb' => 'engelsk'
]
],
'en-gb' => [
'en-gb',
'British English',
[
'de' => 'Britisches Englisch',
'nb' => 'engelsk (Storbritannia)'
]
],
'en-au' => [
'en-au',
'Australian English',
[
'de' => 'Australisches Englisch',
'nb' => 'engelsk (Australia)'
]
],
'nb' => [
'nb',
'Norwegian Bokmål',
[
'de' => 'Norwegisch Bokmål',
'nb' => 'norsk bokmål'
]
]
];
}
}

View file

@ -76,12 +76,12 @@ empty line above';
// test our own CSS configuration
$this->assertEquals('<div>position removed</div>', purify_html('<div style="position:absolut">position removed</div>'));
$this->assertEquals('<div style="position:fixed;">position preserved</div>', purify_html('<div style="position:fixed">position preserved</div>', true));
$this->assertEquals('<div>invalid position removed</div>', purify_html('<div style="position:invalid">invalid position removed</div>', true));
$this->assertEquals('<div style="position:fixed;">position preserved</div>', purify_html('<div style="position:fixed">position preserved</div>', ['allow_position']));
$this->assertEquals('<div>invalid position removed</div>', purify_html('<div style="position:invalid">invalid position removed</div>', ['allow_position']));
$this->assertEquals('<div>position removed</div>', purify_html('<div style="top:10px; left:3em;">position removed</div>'));
$this->assertEquals('<div style="top:10px;left:3em;right:50%;">position preserved</div>', purify_html('<div style="top:10px; left:3em; right:50%;">position preserved</div>', true));
$this->assertEquals('<div>invalid position removed</div>', purify_html('<div style="top:10p">invalid position removed</div>', true));
$this->assertEquals('<div style="top:10px;left:3em;right:50%;">position preserved</div>', purify_html('<div style="top:10px; left:3em; right:50%;">position preserved</div>', ['allow_position']));
$this->assertEquals('<div>invalid position removed</div>', purify_html('<div style="top:10p">invalid position removed</div>', ['allow_position']));
}
/**

View file

@ -1,71 +0,0 @@
<?php
/*
* Copyright (c) 2017 Hubzilla
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
namespace Code\Tests\Unit\includes;
use DBA;
use Code\Tests\Unit\UnitTestCase;
// required because of process isolation and no autoloading
require_once 'include/dba/dba_driver.php';
/**
* @brief Unit Test case for include/dba/DBA.php file.
*
* This test needs process isolation because of static \DBA.
* @runTestsInSeparateProcesses
*/
class DBATest extends UnitTestCase
{
public function testDbaFactoryMysql()
{
$this->assertNull(DBA::$dba);
$ret = DBA::dba_factory('server', 'port', 'user', 'pass', 'db', '0');
$this->assertInstanceOf('dba_pdo', $ret);
$this->assertFalse($ret->connected);
$this->assertSame('mysql', DBA::$scheme);
$this->assertSame('schema_mysql.sql', DBA::$install_script);
$this->assertSame('0001-01-01 00:00:00', DBA::$null_date);
$this->assertSame('UTC_TIMESTAMP()', DBA::$utc_now);
$this->assertSame('`', DBA::$tquot);
}
public function testDbaFactoryPostgresql()
{
$this->assertNull(DBA::$dba);
$ret = DBA::dba_factory('server', 'port', 'user', 'pass', 'db', '1');
$this->assertInstanceOf('dba_pdo', $ret);
$this->assertFalse($ret->connected);
$this->assertSame('pgsql', DBA::$scheme);
$this->assertSame('schema_postgres.sql', DBA::$install_script);
$this->assertSame('0001-01-01 00:00:00', DBA::$null_date);
$this->assertSame("now() at time zone 'UTC'", DBA::$utc_now);
$this->assertSame('"', DBA::$tquot);
}
}

View file

@ -1,9 +0,0 @@
account:
-
account_id: 42
account_email: "hubzilla@example.com"
account_language: "no"
-
account_id: 43
account_email: "hubzilla@example.org"
account_language: "de"

View file

@ -1,212 +0,0 @@
<?php
/*
* Copyright (c) 2017 Hubzilla
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
namespace Code\Tests\Unit\includes;
use dba_driver;
use dba_pdo;
use PHPUnit\DbUnit\DataSet\IDataSet;
use Code\Tests\Unit\DatabaseTestCase;
use PHPUnit\DbUnit\TestCaseTrait;
use PHPUnit\DbUnit\DataSet\YamlDataSet;
use function getenv;
require_once 'include/dba/dba_pdo.php';
/**
* @brief Unit Test case for include/dba/dba_pdo.php file.
*
* Some very basic tests to see if our database layer can connect to a real
* database.
*/
class dba_pdoTest extends DatabaseTestCase
{
use TestCaseTrait;
/**
* @var dba_driver
*/
protected $dba;
/**
* Set initial state of the database before each test is executed.
* Load database fixtures.
*
* @return IDataSet
*/
public function getDataSet()
{
return new YamlDataSet(dirname(__FILE__) . '/_files/account.yml');
}
protected function setUp()
{
// Will invoke getDataSet() to load fixtures into DB
parent::setUp();
$this->dba = new dba_pdo(
getenv('hz_db_server'),
getenv('hz_db_scheme'),
getenv('hz_db_port'),
getenv('hz_db_user'),
getenv('hz_db_pass'),
getenv('hz_db_database')
);
}
protected function assertPreConditions()
{
$this->assertSame('pdo', $this->dba->getdriver(), "Driver is expected to be 'pdo'.");
$this->assertInstanceOf('dba_driver', $this->dba);
$this->assertTrue($this->dba->connected, 'Pre condition failed, DB is not connected.');
$this->assertInstanceOf('PDO', $this->dba->db);
}
protected function tearDown()
{
$this->dba = null;
}
/**
* @group mysql
*/
public function testQuoteintervalOnMysql()
{
$this->assertSame('value', $this->dba->quote_interval('value'));
}
/**
* @group postgresql
*/
public function testQuoteintervalOnPostgresql()
{
$this->assertSame("'value'", $this->dba->quote_interval('value'));
}
/**
* @group mysql
*/
public function testGenerateMysqlConcatSql()
{
$this->assertSame('GROUP_CONCAT(DISTINCT field SEPARATOR \';\')', $this->dba->concat('field', ';'));
$this->assertSame('GROUP_CONCAT(DISTINCT field2 SEPARATOR \' \')', $this->dba->concat('field2', ' '));
}
/**
* @group postgresql
*/
public function testGeneratePostgresqlConcatSql()
{
$this->assertSame('string_agg(field,\';\')', $this->dba->concat('field', ';'));
$this->assertSame('string_agg(field2,\' \')', $this->dba->concat('field2', ' '));
}
public function testConnectToSqlServer()
{
// connect() is done in dba_pdo constructor which is called in setUp()
$this->assertTrue($this->dba->connected);
}
/**
* @depends testConnectToSqlServer
*/
public function testCloseSqlServerConnection()
{
$this->dba->close();
$this->assertNull($this->dba->db);
$this->assertFalse($this->dba->connected);
}
/**
* @depends testConnectToSqlServer
*/
public function testSelectQueryShouldReturnArray()
{
$ret = $this->dba->q('SELECT * FROM account');
$this->assertTrue(is_array($ret));
}
/**
* @depends testConnectToSqlServer
*/
public function testInsertQueryShouldReturnPdostatement()
{
// Fixture account.yml adds two entries to account table
$this->assertEquals(2, $this->getConnection()->getRowCount('account'), 'Pre-Condition');
$ret = $this->dba->q('INSERT INTO account
(account_id, account_email, account_language)
VALUES (100, \'insert@example.com\', \'de\')
');
$this->assertInstanceOf('PDOStatement', $ret);
$this->assertEquals(3, $this->getConnection()->getRowCount('account'), 'Inserting failed');
}
public function testConnectToWrongSqlServer()
{
$nodba = new dba_pdo(
'wrongserver',
getenv('hz_db_scheme'),
getenv('hz_db_port'),
getenv('hz_db_user'),
getenv('hz_db_pass'),
getenv('hz_db_database')
);
$this->assertSame('pdo', $nodba->getdriver());
$this->assertInstanceOf('dba_pdo', $nodba);
$this->assertFalse($nodba->connected);
$this->assertNull($nodba->db);
$this->assertFalse($nodba->q('SELECT * FROM account'));
}
/**
* @depends testConnectToSqlServer
*/
public function testSelectQueryToNonExistentTableShouldReturnFalse()
{
$ret = $this->dba->q('SELECT * FROM non_existent_table');
$this->assertFalse($ret);
}
/**
* @depends testConnectToSqlServer
*/
public function testInsertQueryToNonExistentTableShouldReturnEmptyArray()
{
$ret = $this->dba->q('INSERT INTO non_existent_table
(account_email, account_language)
VALUES (\'email@example.com\', \'en\')
');
$this->assertNotInstanceOf('PDOStatement', $ret);
$this->isEmpty($ret);
}
}