From 5e1addc75e73e84254e820fc67dba057a8728db6 Mon Sep 17 00:00:00 2001 From: Mario Date: Thu, 26 Nov 2020 11:14:40 +0000 Subject: revert folder renaming --- tests/README.md | 25 ++ tests/acceptance/behat.yml | 27 ++ .../acceptance/features/bootstrap/AdminContext.php | 23 ++ tests/acceptance/features/bootstrap/ApiContext.php | 23 ++ .../features/bootstrap/FeatureContext.php | 23 ++ tests/acceptance/features/login_local.feature | 18 ++ tests/infection.json.dist | 15 + tests/phpunit-pgsql.xml | 43 +++ tests/phpunit.xml | 37 +++ tests/phpunit.xml.dist | 49 ++++ tests/travis/gen_apidocs.sh | 69 +++++ tests/travis/prepare.sh | 35 +++ tests/travis/prepare_mysql.sh | 53 ++++ tests/travis/prepare_pgsql.sh | 54 ++++ tests/unit/Access/AccessListTest.php | 191 ++++++++++++ tests/unit/Access/PermissionLimitsTest.php | 78 +++++ tests/unit/Access/PermissionRolesTest.php | 101 +++++++ tests/unit/Access/PermissionsTest.php | 322 +++++++++++++++++++++ tests/unit/AntiXSSTest.php | 73 +++++ tests/unit/AutonameTest.php | 81 ++++++ tests/unit/ContainsAttributeTest.php | 53 ++++ tests/unit/Lib/PermissionDescriptionTest.php | 97 +++++++ tests/unit/Photo/PhotoGdTest.php | 147 ++++++++++ tests/unit/UnitTestCase.php | 38 +++ tests/unit/UploadTest.php | 31 ++ tests/unit/Web/HttpSigTest.php | 112 +++++++ tests/unit/expand_acl_test.php | 148 ++++++++++ tests/unit/get_tags_test.php | 317 ++++++++++++++++++++ tests/unit/includes/FeedutilsTest.php | 89 ++++++ tests/unit/includes/LanguageTest.php | 164 +++++++++++ tests/unit/includes/MarkdownTest.php | 147 ++++++++++ tests/unit/includes/PhotodriverTest.php | 39 +++ tests/unit/includes/TextTest.php | 120 ++++++++ tests/unit/includes/dba/_files/account.yml | 9 + tests/unit/template_test.php | 218 ++++++++++++++ 35 files changed, 3069 insertions(+) create mode 100644 tests/README.md create mode 100644 tests/acceptance/behat.yml create mode 100644 tests/acceptance/features/bootstrap/AdminContext.php create mode 100644 tests/acceptance/features/bootstrap/ApiContext.php create mode 100644 tests/acceptance/features/bootstrap/FeatureContext.php create mode 100644 tests/acceptance/features/login_local.feature create mode 100644 tests/infection.json.dist create mode 100644 tests/phpunit-pgsql.xml create mode 100644 tests/phpunit.xml create mode 100644 tests/phpunit.xml.dist create mode 100755 tests/travis/gen_apidocs.sh create mode 100755 tests/travis/prepare.sh create mode 100755 tests/travis/prepare_mysql.sh create mode 100755 tests/travis/prepare_pgsql.sh create mode 100644 tests/unit/Access/AccessListTest.php create mode 100644 tests/unit/Access/PermissionLimitsTest.php create mode 100644 tests/unit/Access/PermissionRolesTest.php create mode 100644 tests/unit/Access/PermissionsTest.php create mode 100644 tests/unit/AntiXSSTest.php create mode 100644 tests/unit/AutonameTest.php create mode 100644 tests/unit/ContainsAttributeTest.php create mode 100644 tests/unit/Lib/PermissionDescriptionTest.php create mode 100644 tests/unit/Photo/PhotoGdTest.php create mode 100644 tests/unit/UnitTestCase.php create mode 100644 tests/unit/UploadTest.php create mode 100644 tests/unit/Web/HttpSigTest.php create mode 100644 tests/unit/expand_acl_test.php create mode 100644 tests/unit/get_tags_test.php create mode 100644 tests/unit/includes/FeedutilsTest.php create mode 100644 tests/unit/includes/LanguageTest.php create mode 100644 tests/unit/includes/MarkdownTest.php create mode 100644 tests/unit/includes/PhotodriverTest.php create mode 100644 tests/unit/includes/TextTest.php create mode 100644 tests/unit/includes/dba/_files/account.yml create mode 100644 tests/unit/template_test.php (limited to 'tests') diff --git a/tests/README.md b/tests/README.md new file mode 100644 index 000000000..395333159 --- /dev/null +++ b/tests/README.md @@ -0,0 +1,25 @@ +The folder tests/ contains resources for automated testing tools. + +Here you will find PHPUnit, Behat, etc. files to test the functionaly +of Hubzilla. Right now it only contains some basic tests to see if feasable +this can help improve the project. + +# Contents + +* unit/ PHPUnit tests +These are unit tests to check the smallest parts, like single functions. +It uses the tool PHPUnit https://phpunit.de/ + +* acceptance/ functional/acceptance testing +These are behavioral or so called functional/acceptance testing. They +are used to test business logic. They are written in Gherkin and use +the tool Behat http://behat.org/ + +# How to use? +You need the dev tools which are defined in the composer.json in the +require-dev configuration. +Run ```composer install``` without --no-dev to install these tools. + +To run unit tests run ```vendor/bin/phpunit tests/unit/``` + +To run acceptance tests run ```vendor/bin/behat --config tests/acceptance/behat.yml``` diff --git a/tests/acceptance/behat.yml b/tests/acceptance/behat.yml new file mode 100644 index 000000000..933571e5e --- /dev/null +++ b/tests/acceptance/behat.yml @@ -0,0 +1,27 @@ +default: + suites: + default: + paths: + - %paths.base%/features + contexts: + - Behat\MinkExtension\Context\MinkContext + admin_features: + filters: { role: admin } + contexts: + - AdminContext + api_features: + paths: + - %paths.base%/features/api + filters: + tags: "@api" + contexts: + - ApiContext + gherkin: + filters: + tags: ~@wip + extensions: + Behat\MinkExtension: + base_url: 'http://localhost' + sessions: + default: + goutte: ~ diff --git a/tests/acceptance/features/bootstrap/AdminContext.php b/tests/acceptance/features/bootstrap/AdminContext.php new file mode 100644 index 000000000..aa4dced67 --- /dev/null +++ b/tests/acceptance/features/bootstrap/AdminContext.php @@ -0,0 +1,23 @@ + + + + + ../Zotlabs/ + ../include/ + + + + + + + + ./unit/ + + + ./unit/ + + + + + mysql + + + + + + + + + + + + + + + + + + + diff --git a/tests/phpunit.xml b/tests/phpunit.xml new file mode 100644 index 000000000..717d8fc8a --- /dev/null +++ b/tests/phpunit.xml @@ -0,0 +1,37 @@ + + + + + ../Zotlabs/ + ../include/ + + + + + + + + + + + + + + + + ./unit/ + + + ./unit/ + + + + + + + + postgresql + + + + diff --git a/tests/phpunit.xml.dist b/tests/phpunit.xml.dist new file mode 100644 index 000000000..97c84fb81 --- /dev/null +++ b/tests/phpunit.xml.dist @@ -0,0 +1,49 @@ + + + + ./unit/ + + + ./unit/ + + + + + + + postgresql + + + + + + ../Zotlabs/ + ../include/ + + + + + + + + + + + + + + + + + + diff --git a/tests/travis/gen_apidocs.sh b/tests/travis/gen_apidocs.sh new file mode 100755 index 000000000..e5938e1e8 --- /dev/null +++ b/tests/travis/gen_apidocs.sh @@ -0,0 +1,69 @@ +#!/usr/bin/env bash + +# +# Copyright (c) 2016 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. +# + +# Exit if anything fails +set -e + +# Only create and deploy API documentation once, on first build job. +# Waiting for upcoming 'Build Stages' Q1/Q2 2017 to make this cleaner. +# https://github.com/travis-ci/travis-ci/issues/929 +if [[ "$TRAVIS_JOB_NUMBER" != "${TRAVIS_BUILD_NUMBER}.1" ]]; then + echo "Not the first build job. Creating API documentation only once is enough." + echo "We are finished ..." + exit +fi + +echo "Doxygen version >= 1.8 is required" +doxygen --version + +# Check if newer version of Doxygen should be used +if [ ! -z "$DOXY_VER" ]; then + export DOXY_BINPATH=$HOME/doxygen/doxygen-$DOXY_VER/bin + if [ ! -e "$DOXY_BINPATH/doxygen" ]; then + echo "Installing newer Doxygen $DOXY_VER ..." + mkdir -p $HOME/doxygen && cd $HOME/doxygen + wget -O - http://ftp.stack.nl/pub/users/dimitri/doxygen-$DOXY_VER.linux.bin.tar.gz | tar xz + export PATH=$DOXY_BINPATH:$PATH + fi + echo "Doxygen version" + doxygen --version +fi + +echo "Generating Doxygen API documentation ..." +cd $TRAVIS_BUILD_DIR +mkdir -p ./doc/html +# Redirect stderr and stdout to log file and console to be able to review documentation errors +doxygen $DOXYFILE 2>&1 | tee ./doc/html/doxygen.log + +# Check if Doxygen successfully created the documentation +if [ -d "doc/html" ] && [ -f "doc/html/index.html" ]; then + echo "API documentation generated" + if [ -n "${TRAVIS_TAG}" ]; then + echo "Generate API documentation archive for release deployment ..." + zip -9 -r -q doc/hubzilla-api-documentation.zip doc/html/ + fi +else + echo "No API documentation files have been found" >&2 + exit 1 +fi diff --git a/tests/travis/prepare.sh b/tests/travis/prepare.sh new file mode 100755 index 000000000..267b4ec46 --- /dev/null +++ b/tests/travis/prepare.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash + +# +# Copyright (c) 2016 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. +# + +# Exit if anything fails +set -e + +# gd is required, show some info about the used one +php -r "var_dump(gd_info());" + + +echo "Creating required folders for Hubzilla ..." +mkdir -p ./store/\[data\]/smarty3 + +echo "TODO: create .htconfig" diff --git a/tests/travis/prepare_mysql.sh b/tests/travis/prepare_mysql.sh new file mode 100755 index 000000000..5b1c96d78 --- /dev/null +++ b/tests/travis/prepare_mysql.sh @@ -0,0 +1,53 @@ +#!/usr/bin/env bash + +# +# Copyright (c) 2016 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. +# + +# Exit if anything fails +set -e + +echo "Preparing for MySQL/MariaDB ..." + +if [[ "$MYSQL_VERSION" == "5.7" ]]; then + echo "Using MySQL 5.7 in Docker container, need to use TCP" + export PROTO="--protocol=TCP" +fi + +# Print out some MySQL information +mysql --version +mysql $PROTO -e "SELECT VERSION();" +mysql $PROTO -e "SHOW VARIABLES LIKE 'max_allowed_packet';" +mysql $PROTO -e "SHOW VARIABLES LIKE 'collation_%';" +mysql $PROTO -e "SHOW VARIABLES LIKE 'character_set%';" +mysql $PROTO -e "SELECT @@sql_mode;" + +# Create Hubzilla database +mysql $PROTO -u root -e "CREATE DATABASE IF NOT EXISTS travis_hubzilla;"; +mysql $PROTO -u root -e "CREATE USER 'travis_hz'@'%' IDENTIFIED BY 'hubzilla';" +mysql $PROTO -u root -e "GRANT ALL ON travis_hubzilla.* TO 'travis_hz'@'%';" + +# Import table structure +mysql $PROTO -u root travis_hubzilla < ./install/schema_mysql.sql + +# Show databases and tables +mysql $PROTO -u root -e "SHOW DATABASES;" +mysql $PROTO -u root -e "USE travis_hubzilla; SHOW TABLES;" diff --git a/tests/travis/prepare_pgsql.sh b/tests/travis/prepare_pgsql.sh new file mode 100755 index 000000000..c6b12e4d6 --- /dev/null +++ b/tests/travis/prepare_pgsql.sh @@ -0,0 +1,54 @@ +#!/usr/bin/env bash + +# +# Copyright (c) 2016 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. +# + +# Exit if anything fails +set -e + +echo "Preparing for PostgreSQL ..." + +if [[ "$POSTGRESQL_VERSION" == "10" ]]; then + echo "Using PostgreSQL in Docker container, need to use TCP" + export PROTO="-h localhost" +fi + +# Print out some PostgreSQL information +psql --version +# Why does this hang further execution of the job? +psql $PROTO -U postgres -c "SELECT VERSION();" + +# Create Hubzilla database +psql $PROTO -U postgres -c "DROP DATABASE IF EXISTS travis_hubzilla;" +psql $PROTO -U postgres -v ON_ERROR_STOP=1 <<-EOSQL + CREATE USER travis_hz WITH PASSWORD 'hubzilla'; + CREATE DATABASE travis_hubzilla; + ALTER DATABASE travis_hubzilla OWNER TO travis_hz; + GRANT ALL PRIVILEGES ON DATABASE travis_hubzilla TO travis_hz; +EOSQL + +# Import table structure +psql $PROTO -U travis_hz -v ON_ERROR_STOP=1 travis_hubzilla < ./install/schema_postgres.sql + +# Show databases and tables +psql $PROTO -U postgres -l +psql $PROTO -U postgres -d travis_hubzilla -c "\dt;" diff --git a/tests/unit/Access/AccessListTest.php b/tests/unit/Access/AccessListTest.php new file mode 100644 index 000000000..dbc19fabb --- /dev/null +++ b/tests/unit/Access/AccessListTest.php @@ -0,0 +1,191 @@ + '', + 'allow_gid' => '', + 'deny_cid' => '', + 'deny_gid' => '' + ]; + + + + public function testConstructor() { + $channel = [ + 'channel_allow_cid' => '', + 'channel_allow_gid' => '', + 'channel_deny_cid' => '', + 'channel_deny_gid' => '' + ]; + + $accessList = new AccessList($channel); + + $this->assertEquals($this->expectedResult, $accessList->get()); + $this->assertFalse($accessList->get_explicit()); + } + + /** + * @expectedException PHPUnit\Framework\Error\Error + */ + public function testPHPErrorOnInvalidConstructor() { + $accessList = new AccessList('invalid'); + // Causes: "Illegal string offset 'channel_allow_cid'" + } + + public function testDefaultGetExplicit() { + $accessList = new AccessList([]); + + $this->assertFalse($accessList->get_explicit()); + } + + public function testDefaultGet() { + $arr = [ + 'allow_cid' => '', + 'allow_gid' => '', + 'deny_cid' => '', + 'deny_gid' => '' + ]; + + $accessList = new AccessList([]); + + $this->assertEquals($arr, $accessList->get()); + } + + public function testSet() { + $arr = [ + 'allow_cid' => '', + 'allow_gid' => '', + 'deny_cid' => '', + 'deny_gid' => '' + ]; + $accessList = new AccessList([]); + + // 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 AccessList([]); + + $accessList->set('invalid'); + // Causes: "Illegal string offset 'allow_cid'" + } + + /** + * set_from_array() 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 AccessList([]); + $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 AccessList([]); + $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 AccessList([]); + $this->assertFalse($accessListPublic->is_private()); + + $accessListPrivate = new AccessList($channel); + $this->assertTrue($accessListPrivate->is_private()); + } + + public function isprivateProvider() { + return [ + 'all set' => [[ + 'channel_allow_cid' => '', + 'channel_allow_gid' => '', + 'channel_deny_cid' => '', + 'channel_deny_gid' => '' + ]], + 'only one set' => [[ + 'channel_allow_cid' => '', + 'channel_allow_gid' => '', + 'channel_deny_cid' => '', + 'channel_deny_gid' => '' + ]], + 'acid+null' => [[ + 'channel_allow_cid' => '', + 'channel_allow_gid' => null, + 'channel_deny_cid' => '', + 'channel_deny_gid' => '' + ]] + ]; + } + +} \ No newline at end of file diff --git a/tests/unit/Access/PermissionLimitsTest.php b/tests/unit/Access/PermissionLimitsTest.php new file mode 100644 index 000000000..57ad42a19 --- /dev/null +++ b/tests/unit/Access/PermissionLimitsTest.php @@ -0,0 +1,78 @@ +getFunctionMock('Zotlabs\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']); + } + +} \ No newline at end of file diff --git a/tests/unit/Access/PermissionRolesTest.php b/tests/unit/Access/PermissionRolesTest.php new file mode 100644 index 000000000..58fd88bb1 --- /dev/null +++ b/tests/unit/Access/PermissionRolesTest.php @@ -0,0 +1,101 @@ +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('Zotlabs\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 ::call_hooks + * @uses Zotlabs\Access\PermissionLimits::Std_Limits + * @uses Zotlabs\Access\Permissions::Perms + */ + public function testRole_perms() { + // Create a stub for global function t() + $t = $this->getFunctionMock('Zotlabs\Access', 't'); + $t = $this->getFunctionMock('Zotlabs\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); + } + +} diff --git a/tests/unit/Access/PermissionsTest.php b/tests/unit/Access/PermissionsTest.php new file mode 100644 index 000000000..40724fff8 --- /dev/null +++ b/tests/unit/Access/PermissionsTest.php @@ -0,0 +1,322 @@ +assertEquals($expectedVersion, Permissions::version()); + + // instance call + $p = new Permissions(); + $this->assertEquals($expectedVersion, $p->version()); + } + + /** + * @coversNothing + */ + public function testVersionEqualsPermissionRoles() { + $p = new Permissions(); + $pr = new \Zotlabs\Access\PermissionRoles(); + $this->assertEquals($p->version(), $pr->version()); + } + + /** + * @uses ::call_hooks + */ + public function testPerms() { + // There are 18 default perms + $permsCount = 18; + + // Create a stub for global function t() with expectation + $t = $this->getFunctionMock('Zotlabs\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 call_hooks() function and also test filter + * + * @uses ::call_hooks + */ + public function testPermsFilter() { + // There are 18 default perms + $permsCount = 18; + + // Create a stub for global function t() with expectation + $t = $this->getFunctionMock('Zotlabs\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 ::call_hooks + * + * @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('Zotlabs\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 ::call_hooks + */ + public function testFilledPermsNull() { + // Create a stub for global function t() with expectation + $t = $this->getFunctionMock('Zotlabs\Access', 't'); + $t->expects($this->atLeastOnce()); + // Create a stub for global function bt() with expectations + $bt = $this->getFunctionMock('Zotlabs\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 boolean $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 + ] + ]; + } +} diff --git a/tests/unit/AntiXSSTest.php b/tests/unit/AntiXSSTest.php new file mode 100644 index 000000000..b45042a1e --- /dev/null +++ b/tests/unit/AntiXSSTest.php @@ -0,0 +1,73 @@ +'; + + $validstring=notags($invalidstring); + $escapedString=escape_tags($invalidstring); + + $this->assertEquals('[submit type="button" onclick="alert(\'failed!\');" /]', $validstring); + $this->assertEquals("<submit type="button" onclick="alert('failed!');" />", $escapedString); + } + + /** + *xmlify and unxmlify + */ + public function testXmlify() { + $text="I want to break\n this!11!"; + $xml=xmlify($text); + $retext=unxmlify($text); + + $this->assertEquals($text, $retext); + } + + /** + * xmlify and put in a document + */ + public function testXmlifyDocument() { + $tag="I want to break"; + $xml=xmlify($tag); + $text=''.$xml.''; + + $xml_parser=xml_parser_create(); + //should be possible to parse it + $values=array(); $index=array(); + $this->assertEquals(1, xml_parse_into_struct($xml_parser, $text, $values, $index)); + + $this->assertEquals(array('TEXT'=>array(0)), + $index); + $this->assertEquals(array(array('tag'=>'TEXT', 'type'=>'complete', 'level'=>1, 'value'=>$tag)), + $values); + + xml_parser_free($xml_parser); + } + + /** + * test hex2bin and reverse + */ + public function testHex2Bin() { + $this->assertEquals(-3, hex2bin(bin2hex(-3))); + $this->assertEquals(0, hex2bin(bin2hex(0))); + $this->assertEquals(12, hex2bin(bin2hex(12))); + $this->assertEquals(PHP_INT_MAX, hex2bin(bin2hex(PHP_INT_MAX))); + } + + //function qp, quick and dirty?? + //get_mentions + //get_contact_block, bis Zeile 538 +} +?> diff --git a/tests/unit/AutonameTest.php b/tests/unit/AutonameTest.php new file mode 100644 index 000000000..566fe6149 --- /dev/null +++ b/tests/unit/AutonameTest.php @@ -0,0 +1,81 @@ +assertNotEquals($autoname1, $autoname2); + } + + /** + *autonames should be random, odd length + */ + public function testAutonameOdd() { + $autoname1=autoname(9); + $autoname2=autoname(9); + + $this->assertNotEquals($autoname1, $autoname2); + } + + /** + * try to fail autonames + */ + public function testAutonameNoLength() { + $autoname1=autoname(0); + $this->assertEquals(0, strlen($autoname1)); + } + + /** + * try to fail it with invalid input + * + * TODO: What's corect behaviour here? An exception? + */ + public function testAutonameNegativeLength() { + $autoname1=autoname(-23); + $this->assertEquals(0, strlen($autoname1)); + } + + // public function testAutonameMaxLength() { + // $autoname2=autoname(PHP_INT_MAX); + // $this->assertEquals(PHP_INT_MAX, strlen($autoname2)); + // } + + /** + * test with a length, that may be too short + * length is maximum - autoname can return something shorter. + */ + public function testAutonameLength1() { + $autoname1=autoname(1); + $test = ((strlen($autoname1) < 2) ? 1 : 0); + $this->assertEquals(1, $test); + + $autoname2=autoname(1); + $test = ((strlen($autoname2) < 2) ? 1 : 0); + $this->assertEquals(1, $test); + + // The following test is problematic, with only 26 possibilities + // generating the same thing twice happens often aka + // birthday paradox +// $this->assertFalse($autoname1==$autoname2); + } +} diff --git a/tests/unit/ContainsAttributeTest.php b/tests/unit/ContainsAttributeTest.php new file mode 100644 index 000000000..0930d9837 --- /dev/null +++ b/tests/unit/ContainsAttributeTest.php @@ -0,0 +1,53 @@ +assertTrue(attribute_contains($testAttr, "class3")); + $this->assertFalse(attribute_contains($testAttr, "class2")); + } + + /** + * test attribute contains + */ + public function testAttributeContains2() { + $testAttr="class1 not-class2 class3"; + $this->assertTrue(attribute_contains($testAttr, "class3")); + $this->assertFalse(attribute_contains($testAttr, "class2")); + } + + /** + * test with empty input + */ + public function testAttributeContainsEmpty() { + $testAttr=""; + $this->assertFalse(attribute_contains($testAttr, "class2")); + } + + /** + * test input with special chars + */ + public function testAttributeContainsSpecialChars() { + $testAttr="--... %\$ä() /(=?}"; + $this->assertFalse(attribute_contains($testAttr, "class2")); + } +} \ No newline at end of file diff --git a/tests/unit/Lib/PermissionDescriptionTest.php b/tests/unit/Lib/PermissionDescriptionTest.php new file mode 100644 index 000000000..96c381d0c --- /dev/null +++ b/tests/unit/Lib/PermissionDescriptionTest.php @@ -0,0 +1,97 @@ +assertEquals($permDesc, $permDesc2); + $this->assertNotEquals($permDesc, $permDesc3); + } + + public function testFromStandalonePermission() { + // Create a stub for global function t() + $t = $this->getFunctionMock('Zotlabs\Lib', 't'); + $t->expects($this->atLeastOnce())->willReturnCallback( + function ($string) { + return $string; + } + ); + // Create a mock for global function logger() + $this->getFunctionMock('Zotlabs\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('Zotlabs\Lib', 't'); + $t->expects($this->atLeastOnce())->willReturnCallback( + function ($string) { + return $string; + } + ); + // Create a mock for global function logger() + $this->getFunctionMock('Zotlabs\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'); + } +} diff --git a/tests/unit/Photo/PhotoGdTest.php b/tests/unit/Photo/PhotoGdTest.php new file mode 100644 index 000000000..ae7382c43 --- /dev/null +++ b/tests/unit/Photo/PhotoGdTest.php @@ -0,0 +1,147 @@ +photoGd = new PhotoGd($data, 'image/png'); + } + + /** + * Cleans up the environment after running a test. + */ + protected function tearDown(): void { + $this->photoGd = null; + + parent::tearDown(); + } + + /** + * Tests PhotoGd->supportedTypes() + * + * Without mocking gd this check is environment dependent. + * + public function testSupportedTypes() { + $sft = $this->photoGd->supportedTypes(); + + $this->assertArrayHasKey('image/jpeg', $sft); + $this->assertArrayHasKey('image/gif', $sft); + $this->assertArrayHasKey('image/png', $sft); + + $this->assertArrayNotHasKey('image/foo', $sft); + } + */ + + /** + * Tests PhotoGd->clearexif() + */ + public function testClearexifIsNotImplementedInGdAndDoesNotAlterImageOrReturnSomething() { + $data_before = $this->photoGd->getImage(); + $this->assertNull($this->photoGd->clearexif()); + $this->assertSame($data_before, $this->photoGd->getImage()); + } + + /** + * Tests PhotoGd->getImage() + */ + public function testGetimageReturnsAResource() { + $res = $this->photoGd->getImage(); + $this->assertIsResource($res); + $this->assertEquals('gd', get_resource_type($res)); + } + public function testGetimageReturnsFalseOnFailure() { + $this->photoGd = new PhotoGd(''); + $this->assertFalse($this->photoGd->getImage()); + } + + /** + * Tests PhotoGd->doScaleImage() + */ + public function testDoscaleImageSetsCorrectDimensions() { + $this->photoGd->doScaleImage(5, 8); + + $this->assertSame(5, $this->photoGd->getWidth()); + $this->assertSame(8, $this->photoGd->getHeight()); + } + + /** + * Tests PhotoGd->rotate() + */ + public function testRotate360DegreesCreatesANewImage() { + $data = $this->photoGd->getImage(); + $this->photoGd->rotate(360); + $this->assertNotEquals($data, $this->photoGd->getImage()); + } + + /** + * Tests PhotoGd->flip() + * + public function testFlip() { + // TODO Auto-generated PhotoGdTest->testFlip() + $this->markTestIncomplete("flip test not implemented"); + + $this->photoGd->flip(); + } + */ + + /** + * Tests PhotoGd->cropImageRect() + */ + public function testCropimagerectSetsCorrectDimensions() { + $this->photoGd->cropImageRect(10, 12, 1, 2, 11, 11); + + $this->assertSame(10, $this->photoGd->getWidth()); + $this->assertSame(12, $this->photoGd->getHeight()); + } + + /** + * Tests PhotoGd->imageString() + */ + public function testImagestringReturnsABinaryString() { + // Create a stub for global function get_config() + // get_config('system', 'png_quality') + // get_config('system', 'jpeg_quality'); + $gc = $this->getFunctionMock('Zotlabs\Photo', 'get_config'); + $gc->expects($this->once())->willReturnCallback( + function() { + switch($this->photoGd->getType()){ + case 'image/png': + return 7; + case 'image/jpeg': + default: + return 70; + } + } + ); + + $this->assertIsString($this->photoGd->imageString()); + } + +} diff --git a/tests/unit/UnitTestCase.php b/tests/unit/UnitTestCase.php new file mode 100644 index 000000000..7d706d5be --- /dev/null +++ b/tests/unit/UnitTestCase.php @@ -0,0 +1,38 @@ +assertEquals("audio/ogg", z_mime_content_type($multidots)); + $this->assertNotEquals("application/octet-stream", z_mime_content_type($multidots)); + } + + public function testFileNameOneDot() { + $multidots = "foo.ogg"; + $this->assertEquals("audio/ogg", z_mime_content_type($multidots)); + $this->assertNotEquals("application/octet-stream", z_mime_content_type($multidots)); + } +} \ No newline at end of file diff --git a/tests/unit/Web/HttpSigTest.php b/tests/unit/Web/HttpSigTest.php new file mode 100644 index 000000000..bd11b96c8 --- /dev/null +++ b/tests/unit/Web/HttpSigTest.php @@ -0,0 +1,112 @@ +assertSame( + $digest, + HTTPSig::generate_digest_header($text) + ); + } + public function generate_digestProvider() { + return [ + 'empty body text' => [ + '', + 'SHA-256=47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=' + ], + 'sample body text' => [ + 'body text', + 'SHA-256=2fu8kUkvuzuo5XyhWwORNOcJgDColXgxWkw1T5EXzPI=' + ], + 'NULL body text' => [ + null, + 'SHA-256=47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=' + ], + ]; + } + + function testGeneratedDigestsOfDifferentTextShouldNotBeEqual() { + $this->assertNotSame( + HTTPSig::generate_digest_header('text1'), + HTTPSig::generate_digest_header('text2') + ); + } + + /** + * @uses ::crypto_unencapsulate + */ + function testDecrypt_sigheader() { + $header = 'Header: iv="value_iv" key="value_key" alg="value_alg" data="value_data"'; + $result = [ + 'encrypted' => true, + '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 + */ + function testDecrypt_sigheaderUseSitePrivateKey() { + // Create a stub for global function get_config() with expectation + $t = $this->getFunctionMock('Zotlabs\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 = [ + 'encrypted' => true, + 'iv' => 'value_iv', + 'key' => 'value_key', + 'alg' => 'value_alg', + 'data' => 'value_data' + ]; + + $this->assertSame($result, HTTPSig::decrypt_sigheader($header)); + } + function testDecrypt_sigheaderIncompleteHeaderShouldReturnEmptyString() { + $header = 'Header: iv="value_iv" key="value_key"'; + + $this->assertEmpty(HTTPSig::decrypt_sigheader($header, 'site private key')); + } +} diff --git a/tests/unit/expand_acl_test.php b/tests/unit/expand_acl_test.php new file mode 100644 index 000000000..154bc921d --- /dev/null +++ b/tests/unit/expand_acl_test.php @@ -0,0 +1,148 @@ +<2><3>'; + $this->assertEquals(array(1, 2, 3), expand_acl($text)); + } + + /** + * test with a big number + */ + public function testExpandAclBigNumber() { + $text='<1><'.PHP_INT_MAX.'><15>'; + $this->assertEquals(array(1, PHP_INT_MAX, 15), expand_acl($text)); + } + + /** + * test with a string in it. + * + * TODO: is this valid input? Otherwise: should there be an exception? + */ + public function testExpandAclString() { + $text="<1><279012>"; + $this->assertEquals(array(1, 279012), expand_acl($text)); + } + + /** + * test with a ' ' in it. + * + * TODO: is this valid input? Otherwise: should there be an exception? + */ + public function testExpandAclSpace() { + $text="<1><279 012><32>"; + $this->assertEquals(array(1, "279", "32"), expand_acl($text)); + } + + /** + * test empty input + */ + public function testExpandAclEmpty() { + $text=""; + $this->assertEquals(array(), expand_acl($text)); + } + + /** + * test invalid input, no < at all + * + * TODO: should there be an exception? + */ + public function testExpandAclNoBrackets() { + $text="According to documentation, that's invalid. "; //should be invalid + $this->assertEquals(array(), expand_acl($text)); + } + + /** + * test invalid input, just open < + * + * TODO: should there be an exception? + */ + public function testExpandAclJustOneBracket1() { + $text="assertEquals(array(), expand_acl($text)); + } + + /** + * test invalid input, just close > + * + * TODO: should there be an exception? + */ + public function testExpandAclJustOneBracket2() { + $text="Another invalid> string"; //should be invalid + $this->assertEquals(array(), expand_acl($text)); + } + + /** + * test invalid input, just close > + * + * TODO: should there be an exception? + */ + public function testExpandAclCloseOnly() { + $text="Another> invalid> string>"; //should be invalid + $this->assertEquals(array(), expand_acl($text)); + } + + /** + * test invalid input, just open < + * + * TODO: should there be an exception? + */ + public function testExpandAclOpenOnly() { + $text="assertEquals(array(), expand_acl($text)); + } + + /** + * test invalid input, open and close do not match + * + * TODO: should there be an exception? + */ + public function testExpandAclNoMatching1() { + $text=" invalid "; //should be invalid + $this->assertEquals(array(), expand_acl($text)); + } + + /** + * test invalid input, open and close do not match + * + * TODO: should there be an exception? + */ + public function testExpandAclNoMatching2() { + $text="<1>2><3>"; +// The angles are delimiters which aren't important +// the important thing is the numeric content, this returns array(1,2,3) currently +// we may wish to eliminate 2 from the results, though it isn't harmful +// It would be a better test to figure out if there is any ACL input which can +// produce this $text and fix that instead. +// $this->assertEquals(array(), expand_acl($text)); + } + + /** + * test invalid input, empty <> + * + * TODO: should there be an exception? Or array(1, 3) + * (This should be array(1,3) - mike) + */ + public function testExpandAclEmptyMatch() { + $text="<1><><3>"; + $this->assertEquals(array(1,3), expand_acl($text)); + } +} \ No newline at end of file diff --git a/tests/unit/get_tags_test.php b/tests/unit/get_tags_test.php new file mode 100644 index 000000000..bdffd8311 --- /dev/null +++ b/tests/unit/get_tags_test.php @@ -0,0 +1,317 @@ +15, + 'attag'=>'', 'network'=>'dfrn', + 'name'=>'Mike Lastname', 'alias'=>'Mike', + 'nick'=>'Mike', 'url'=>"http://justatest.de")); + + $args=func_get_args(); + + //last parameter is always (in this test) uid, so, it should be 11 + if($args[count($args)-1]!=11) { + return; + } + + + if(3==count($args)) { + //first call in handle_body, id only + if($result[0]['id']==$args[1]) { + return $result; + } + //second call in handle_body, name + if($result[0]['name']===$args[1]) { + return $result; + } + } + //third call in handle_body, nick or attag + if($result[0]['nick']===$args[2] || $result[0]['attag']===$args[1]) { + return $result; + } +} + +/** + * replacement for dbesc. + * I don't want to test dbesc here, so + * I just return the input. It won't be a problem, because + * the test does not use a real database. + * + * DON'T USE HAT FUNCTION OUTSIDE A TEST! + * + * @param string $str + * @return input + */ +function dbesc($str) { + return $str; +} + +/** + * TestCase for tag handling. + * + * @author alexander + * @package test.util + */ +class GetTagsTest extends PHPUnit_Framework_TestCase { + /** the mock to use as app */ + private $a; + + /** + * initialize the test. That's a phpUnit function, + * don't change its name. + */ + public function setUp() { + $this->a=new MockApp(); + } + + /** + * test with one Person tag + */ + public function testGetTagsShortPerson() { + $text="hi @Mike"; + + $tags=get_tags($text); + + $str_tags=''; + foreach($tags as $tag) { + handle_tag($text, $str_tags, 11, $tag); + } + + //correct tags found? + $this->assertEquals(1, count($tags)); + $this->assertTrue(in_array("@Mike", $tags)); + + //correct output from handle_tag? + $this->assertEquals("@[url=http://justatest.de]Mike Lastname[/url]", $str_tags); + $this->assertEquals("hi @[url=http://justatest.de]Mike Lastname[/url]", $text); + } + + /** + * test with one Person tag. + * There's a minor spelling mistake... + */ + public function testGetTagsShortPersonSpelling() { + $text="hi @Mike.because"; + + $tags=get_tags($text); + + //correct tags found? + $this->assertEquals(1, count($tags)); + $this->assertTrue(in_array("@Mike.because", $tags)); + + $str_tags=''; + handle_tag($text, $str_tags, 11, $tags[0]); + + // (mike) - This is a tricky case. + // we support mentions as in @mike@example.com - which contains a period. + // This shouldn't match anything unless you have a contact named "Mike.because". + // We may need another test for "@Mike. because" - which should return the contact + // as we ignore trailing periods in tags. + +// $this->assertEquals("cid:15", $inform); +// $this->assertEquals("@[url=http://justatest.de]Mike Lastname[/url]", $str_tags); +// $this->assertEquals("hi @[url=http://justatest.de]Mike Lastname[/url].because", $text); + + $this->assertEquals("", $str_tags); + + } + + /** + * test with two Person tags. + * There's a minor spelling mistake... + */ + + public function testGetTagsPerson2Spelling() { + $text="hi @Mike@campino@friendica.eu"; + + $tags=get_tags($text); + +// This construct is not supported. Results are indeterminate +// $this->assertEquals(2, count($tags)); +// $this->assertTrue(in_array("@Mike", $tags)); +// $this->assertTrue(in_array("@campino@friendica.eu", $tags)); + } + + /** + * Test with one hash tag. + */ + public function testGetTagsShortTag() { + $text="This is a #test_case"; + + $tags=get_tags($text); + + $this->assertEquals(1, count($tags)); + $this->assertTrue(in_array("#test_case", $tags)); + } + + /** + * test with a person and a hash tag + */ + public function testGetTagsShortTagAndPerson() { + $text="hi @Mike This is a #test_case"; + + $tags=get_tags($text); + + $this->assertEquals(3, count($tags)); + $this->assertTrue(in_array("@Mike", $tags)); + $this->assertTrue(in_array("@Mike This", $tags)); + $this->assertTrue(in_array("#test_case", $tags)); + + $str_tags=''; + foreach($tags as $tag) { + handle_tag($text, $str_tags, 11, $tag); + } + + $this->assertEquals("@[url=http://justatest.de]Mike Lastname[/url],#[url=baseurl/search?tag=test%20case]test case[/url]", $str_tags); + $this->assertEquals("hi @[url=http://justatest.de]Mike Lastname[/url] This is a #[url=baseurl/search?tag=test%20case]test case[/url]", $text); + + } + + /** + * test with a person, a hash tag and some special chars. + */ + public function testGetTagsShortTagAndPersonSpecialChars() { + $text="hi @Mike, This is a #test_case."; + + $tags=get_tags($text); + + $this->assertEquals(2, count($tags)); + $this->assertTrue(in_array("@Mike", $tags)); + $this->assertTrue(in_array("#test_case", $tags)); + } + + /** + * Test with a person tag and text behind it. + */ + public function testGetTagsPersonOnly() { + $text="@Test I saw the Theme Dev group was created."; + + $tags=get_tags($text); + + $this->assertEquals(2, count($tags)); + $this->assertTrue(in_array("@Test I", $tags)); + $this->assertTrue(in_array("@Test", $tags)); + } + + /** + * this test demonstrates strange behaviour by intval. + * It makes the next test fail. + */ + public function testIntval() { + $this->assertEquals(15, intval("15 it")); + } + + /** + * test a tag with an id in it + */ + public function testIdTag() { + $text="Test with @mike+15 id tag"; + + $tags=get_tags($text); + + $this->assertEquals(2, count($tags)); + $this->assertTrue(in_array("@mike+15", $tags)); + + //happens right now, but it shouldn't be necessary + $this->assertTrue(in_array("@mike+15 id", $tags)); + + $str_tags=''; + foreach($tags as $tag) { + handle_tag($text, $str_tags, 11, $tag); + } + + $this->assertEquals("Test with @[url=http://justatest.de]Mike Lastname[/url] id tag", $text); + $this->assertEquals("@[url=http://justatest.de]Mike Lastname[/url]", $str_tags); + } + + /** + * test with two persons and one special tag. + */ + public function testGetTags2Persons1TagSpecialChars() { + $text="hi @Mike, I'm just writing #test_cases, so" + ." so @somebody@friendica.com may change #things."; + + $tags=get_tags($text); + + $this->assertEquals(5, count($tags)); + $this->assertTrue(in_array("@Mike", $tags)); + $this->assertTrue(in_array("#test_cases", $tags)); + $this->assertTrue(in_array("@somebody@friendica.com", $tags)); + $this->assertTrue(in_array("@somebody@friendica.com may", $tags)); + $this->assertTrue(in_array("#things", $tags)); + } + + /** + * test with a long text. + */ + public function testGetTags() { + $text="hi @Mike, I'm just writing #test_cases, " + ." so @somebody@friendica.com may change #things. Of course I " + ."look for a lot of #pitfalls, like #tags at the end of a sentence " + ."@comment. I hope noone forgets about @fullstops.because that might" + ." break #things. @Mike@campino@friendica.eu is also #nice, isn't it? " + ."Now, add a @first_last tag. "; + + $tags=get_tags($text); + + $this->assertTrue(in_array("@Mike", $tags)); + $this->assertTrue(in_array("#test_cases", $tags)); + $this->assertTrue(in_array("@somebody@friendica.com", $tags)); + $this->assertTrue(in_array("#things", $tags)); + $this->assertTrue(in_array("#pitfalls", $tags)); + $this->assertTrue(in_array("#tags", $tags)); + $this->assertTrue(in_array("@comment", $tags)); + $this->assertTrue(in_array("@fullstops.because", $tags)); + $this->assertTrue(in_array("#things", $tags)); + $this->assertTrue(in_array("@Mike", $tags)); + $this->assertTrue(in_array("#nice", $tags)); + $this->assertTrue(in_array("@first_last", $tags)); + + //right now, none of the is matched (unsupported) +// $this->assertFalse(in_array("@Mike@campino@friendica.eu", $tags)); +// $this->assertTrue(in_array("@campino@friendica.eu", $tags)); +// $this->assertTrue(in_array("@campino@friendica.eu is", $tags)); + } + + /** + * test with an empty string + */ + public function testGetTagsEmpty() { + $tags=get_tags(""); + $this->assertEquals(0, count($tags)); + } +} \ No newline at end of file diff --git a/tests/unit/includes/FeedutilsTest.php b/tests/unit/includes/FeedutilsTest.php new file mode 100644 index 000000000..e9826a73d --- /dev/null +++ b/tests/unit/includes/FeedutilsTest.php @@ -0,0 +1,89 @@ +assertEquals('id', normalise_id('id')); + $this->assertEquals('id', normalise_id('X-ZOT:id')); + $this->assertEquals('id id2', normalise_id('X-ZOT:id X-ZOT:id2')); + $this->assertEmpty(normalise_id('')); + } + + public function test_encode_rel_links() { + // invalid params return empty array + $this->assertEquals([], encode_rel_links('string')); + $this->assertEquals([], encode_rel_links([])); + + $b = ['attribs' => ['' => [ + 'rel' => 'rel_value', + 'type' => 'type_value', + 'href' => 'href_value', + 'length' => 'length_value', + 'title' => 'title_value' + ]]]; + $blink1 = ['link1' => $b]; + $bresult[] = $b['attribs']['']; + $this->assertEquals($bresult, encode_rel_links($blink1)); + } + +/* public function test_encode_rel_links_fail() { + $a = [ 'key' => 'value']; + $this->assertFalse(encode_rel_links($a)); + //Illegal string offset 'attribs' + }*/ + + /** + * @uses ::xmlify + */ + public function test_atom_author() { + $this->assertEquals('', atom_author('', 'nick', 'name', 'uri', 72, 72, 'png', 'photourl')); + + $a = ' + uri + nick + uri + + + nick + name +'; + + $this->assertXmlStringEqualsXmlString($a, atom_author('tag', 'nick', 'name', 'uri', 72, 72, 'png', 'http://photourl')); + } + + /** + * @uses ::xmlify + */ + public function test_atom_render_author() { + $xchan = [ + 'xchan_addr' => 'chan@hub', + 'xchan_url' => 'http://hub', + 'xchan_name' => 'Chan', + 'xchan_photo_l' => 'http://hub/img', + 'xchan_photo_mimetype' => 'mimetype' + ]; + // There is no input validation in atom_render_author + //$this->assertEquals('', atom_render_author('', $xchan)); + + $a = ' + http://activitystrea.ms/schema/1.0/person + http://hub + chan + http://hub + + + + chan + Chan +'; + + $this->assertXmlStringEqualsXmlString($a, atom_render_author('tag', $xchan)); + } +} diff --git a/tests/unit/includes/LanguageTest.php b/tests/unit/includes/LanguageTest.php new file mode 100644 index 000000000..0ca9eacd0 --- /dev/null +++ b/tests/unit/includes/LanguageTest.php @@ -0,0 +1,164 @@ +getFunctionMock(__NAMESPACE__, 'get_config'); + //$gc->expects($this->once())->willReturn(10) + //$cg = $this->getFunctionMock('Zotlabs\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' => 'Englisch (Vereinigtes Königreich)', + 'nb' => 'engelsk (Storbritannia)' + ] + ], + 'en-au' => [ + 'en-au', + 'Australian English', + [ + 'de' => 'Englisch (Australien)', + 'nb' => 'engelsk (Australia)' + ] + ], + 'nb' => [ + 'nb', + 'Norwegian Bokmål', + [ + 'de' => 'Norwegisch Bokmål', + 'nb' => 'norsk bokmål' + ] + ] + ]; + } +} diff --git a/tests/unit/includes/MarkdownTest.php b/tests/unit/includes/MarkdownTest.php new file mode 100644 index 000000000..2a92a58d2 --- /dev/null +++ b/tests/unit/includes/MarkdownTest.php @@ -0,0 +1,147 @@ +assertEquals($markdown, html2markdown($html)); + } + + public function html2markdownProvider() { + return [ + 'empty text' => [ + '', + '' + ], + 'space and nbsp only' => [ + '  ', + '' + ], + + 'strong, b, em, i, bib' => [ + 'strong bold em italic boitalicld', + '**strong** **bold** *em* *italic* **bo*italic*ld**' + ], + + 'empty tags' => [ + 'text1 text2 ', + 'text1 text2' + ], + 'HTML entities, lt does not work' => [ + '& gt > lt <', + '& gt > lt' + ], + 'escaped HTML entities' => [ + '& lt < gt >', + '& lt < gt >' + ], + 'linebreak' => [ + "line1
line2\nline3", + "line1 \nline2 line3" + ], + 'headlines' => [ + '

header1

Header 3

', + "header1\n=======\n\n### Header 3" + ], + 'unordered list' => [ + '
  • Item 1
  • Item 2
  • Item 3
', + "- Item 1\n- Item 2\n- Item **3**" + ], + 'ordered list' => [ + '
  1. Item 1
  2. Item 2
  3. Item 3
', + "1. Item 1\n2. Item 2\n3. Item **3**" + ], + 'nested lists' => [ + '
  • Item 1
    1. Item 1a
    2. Item 1b
  • Item 2
', + "- Item 1\n 1. Item 1a\n 2. Item **1b**\n- Item 2" + ], + 'img' => [ + 'alt text', + '![alt text](/path/to/img.png "title text")' + ], + 'link' => [ + 'link', + '[link](http://hubzilla.org "Hubzilla")' + ], + 'img link' => [ + 'alt img text', + '[![alt img text](/img/hubzilla.png "img title")](http://hubzilla.org "Hubzilla")' + ], + 'script' => [ + "", + "" + ], + 'blockquote, issue #793' => [ + '
something
blah', + "> something\n\nblah" + ], + 'code' => [ + '<p>HTML text</p>', + '`

HTML text

`' + ], + 'pre' => [ + '
  one line with spaces  
', + "```\n one line with spaces \n```" + ], + 'div p' => [ + '
div

p

', + "
div
p\n\n
" + ] + ]; + } + + /*public function testHtml2markdownException() { + //$this->expectException(\InvalidArgumentException::class); + // need to stub logger() for this to work + $this->assertEquals('', html2markdown('<getFunctionMock(__NAMESPACE__, "bbcode"); + $bbc->expects($this->once())->willReturn('testbold
i
  • li1
  • li2

'); + + $this->assertEquals($bb1, bb2diaspora($html1)); + } +*/ +} diff --git a/tests/unit/includes/PhotodriverTest.php b/tests/unit/includes/PhotodriverTest.php new file mode 100644 index 000000000..6f6ad0ffe --- /dev/null +++ b/tests/unit/includes/PhotodriverTest.php @@ -0,0 +1,39 @@ +getFunctionMock(__NAMESPACE__, 'logger'); + //$logger->expects($this->once()); + + //$ph = \photo_factory('', 'image/bmp'); + //$this->assertNull($ph); + + $this->markTestIncomplete('Need to mock logger(), otherwise not unit testable.'); + } + + public function testPhotofactoryReturnsPhotogdIfConfigIgnore_imagickIsSet() { + // 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'); + // simulate get_config('system', 'ignore_imagick') configured + //$gc->expects($this->once())->willReturn(1) + + //$ph = \photo_factory(file_get_contents('images/hz-16.png'), 'image/png'); + //$this->assertInstanceOf(PhotoGd::class, $ph); + + $this->markTestIncomplete('Need to mock get_config(), otherwise not unit testable.'); + } +} \ No newline at end of file diff --git a/tests/unit/includes/TextTest.php b/tests/unit/includes/TextTest.php new file mode 100644 index 000000000..97fa64895 --- /dev/null +++ b/tests/unit/includes/TextTest.php @@ -0,0 +1,120 @@ + + one tab preserved + +empty line above'; + $this->assertEquals($htmlbr, purify_html($htmlbr)); + + // HTML5 is not supported by HTMLPurifier yet, test our own configuration + $html5elements = '
section
footer
'; + $this->assertEquals($html5elements, purify_html($html5elements)); + $this->assertEquals('', purify_html('')); + + // unsupported HTML5 elements + $this->assertEquals('Your HTML parser does not support HTML5 video.', purify_html('')); + $this->assertEquals('Your HTML parser does not support HTML5 audio.', purify_html('')); + + // preserve f6 and bootstrap additional data attributes from our own configuration + $this->assertEquals('
text
', purify_html('
text
')); + $this->assertEquals('
  • item1
', purify_html('
  • item1
')); + $this->assertEquals('
  • item1
', purify_html('
  • item1
')); + } + + /** + * @covers ::purify_html + */ + public function testPurifyHTML_html() { + $this->assertEquals('

ids und classes

', purify_html('

ids und classes

')); + $this->assertEquals('

close missing tags

', purify_html('

close missing tags')); + $this->assertEquals('

deprecated tag
', purify_html('
deprecated tag
')); + $this->assertEquals('
illegal nesting
', purify_html('
illegal nesting
')); + $this->assertEquals('link with target', purify_html('link with target')); + $this->assertEquals('link with rel="nofollow"', purify_html('link with rel="nofollow"')); + $this->assertEquals('a b', purify_html('a b')); + $this->assertEquals('ä ä € €', purify_html('ä ä € €')); + $this->assertEquals('text', purify_html('text')); + $this->assertEquals('', purify_html('')); + } + + /** + * @covers ::purify_html + */ + public function testPurifyHTML_js() { + $this->assertEquals('
', purify_html('
')); + $this->assertEquals('link', purify_html('link')); + $this->assertEquals('', purify_html('')); + $this->assertEquals('', purify_html('')); + } + + /** + * @covers ::purify_html + */ + public function testPurifyHTML_css() { + $this->assertEquals('

red

', purify_html('

red

')); + $this->assertEquals('

invalid color

', purify_html('

invalid color

')); + $this->assertEquals('

invalid style

', purify_html('

invalid style

')); + + // test our own CSS configuration + $this->assertEquals('
position removed
', purify_html('
position removed
')); + $this->assertEquals('
position preserved
', purify_html('
position preserved
', true)); + $this->assertEquals('
invalid position removed
', purify_html('
invalid position removed
', true)); + + $this->assertEquals('
position removed
', purify_html('
position removed
')); + $this->assertEquals('
position preserved
', purify_html('
position preserved
', true)); + $this->assertEquals('
invalid position removed
', purify_html('
invalid position removed
', true)); + } + + /** + * @dataProvider notagsProvider + */ + public function testNotags($string, $expected) { + $this->assertEquals($expected, notags($string)); + } + public function notagsProvider() { + return [ + 'empty string' => ['', ''], + 'simple tag' => ['', '[value]'], + 'tag pair' => ['text', '[b]text[/b]'], + 'double angle bracket' => ['< ['>', '>'] + ]; + } + + /** + * @dataProvider sanitise_aclProvider + */ + public function testSanitise_acl($string, $expected) { + sanitise_acl($string); + $this->assertEquals($expected, $string); + } + public function sanitise_aclProvider() { + return [ + 'text' => ['value', ''], + 'text with angle bracket' => ['', '<[value]>'], + 'comma separated acls' => ['value1,value2', ''] + ]; + } + + public function testUnsetSanitise_acl() { + $empty = ''; + sanitise_acl($empty); + $this->assertTrue(isset($empty)); // unset() not working? Would expect false + $this->assertEmpty($empty); + } + +} diff --git a/tests/unit/includes/dba/_files/account.yml b/tests/unit/includes/dba/_files/account.yml new file mode 100644 index 000000000..344bdb799 --- /dev/null +++ b/tests/unit/includes/dba/_files/account.yml @@ -0,0 +1,9 @@ +account: + - + account_id: 42 + account_email: "hubzilla@example.com" + account_language: "no" + - + account_id: 43 + account_email: "hubzilla@example.org" + account_language: "de" diff --git a/tests/unit/template_test.php b/tests/unit/template_test.php new file mode 100644 index 000000000..dfaecb4a1 --- /dev/null +++ b/tests/unit/template_test.php @@ -0,0 +1,218 @@ +assertTrue(is_null($second)); + } + + public function testSimpleVariableString() { + $tpl='Hello $name!'; + + $text=replace_macros($tpl, array('$name'=>'Anna')); + + $this->assertEquals('Hello Anna!', $text); + } + + public function testSimpleVariableInt() { + $tpl='There are $num new messages!'; + + $text=replace_macros($tpl, array('$num'=>172)); + + $this->assertEquals('There are 172 new messages!', $text); + } + + public function testConditionalElse() { + $tpl='There{{ if $num!=1 }} are $num new messages{{ else }} is 1 new message{{ endif }}!'; + + $text1=replace_macros($tpl, array('$num'=>1)); + $text22=replace_macros($tpl, array('$num'=>22)); + + $this->assertEquals('There is 1 new message!', $text1); + $this->assertEquals('There are 22 new messages!', $text22); + } + + public function testConditionalNoElse() { + $tpl='{{ if $num!=0 }}There are $num new messages!{{ endif }}'; + + $text0=replace_macros($tpl, array('$num'=>0)); + $text22=replace_macros($tpl, array('$num'=>22)); + + $this->assertEquals('', $text0); + $this->assertEquals('There are 22 new messages!', $text22); + } + + public function testConditionalFail() { + $tpl='There {{ if $num!=1 }} are $num new messages{{ else }} is 1 new message{{ endif }}!'; + + $text1=replace_macros($tpl, array()); + + //$this->assertEquals('There is 1 new message!', $text1); + } + + public function testSimpleFor() { + $tpl='{{ for $messages as $message }} $message {{ endfor }}'; + + $text=replace_macros($tpl, array('$messages'=>array('message 1', 'message 2'))); + + $this->assertEquals(' message 1 message 2 ', $text); + } + + public function testFor() { + $tpl='{{ for $messages as $message }} from: $message.from to $message.to {{ endfor }}'; + + $text=replace_macros($tpl, array('$messages'=>array(array('from'=>'Mike', 'to'=>'Alex'), array('from'=>'Alex', 'to'=>'Mike')))); + + $this->assertEquals(' from: Mike to Alex from: Alex to Mike ', $text); + } + + public function testKeyedFor() { + $tpl='{{ for $messages as $from=>$to }} from: $from to $to {{ endfor }}'; + + $text=replace_macros($tpl, array('$messages'=>array('Mike'=>'Alex', 'Sven'=>'Mike'))); + + $this->assertEquals(' from: Mike to Alex from: Sven to Mike ', $text); + } + + public function testForEmpty() { + $tpl='messages: {{for $messages as $message}} from: $message.from to $message.to {{ endfor }}'; + + $text=replace_macros($tpl, array('$messages'=>array())); + + $this->assertEquals('messages: ', $text); + } + + public function testForWrongType() { + $tpl='messages: {{for $messages as $message}} from: $message.from to $message.to {{ endfor }}'; + + $text=replace_macros($tpl, array('$messages'=>11)); + + $this->assertEquals('messages: ', $text); + } + + public function testForConditional() { + $tpl='new messages: {{for $messages as $message}}{{ if $message.new }} $message.text{{endif}}{{ endfor }}'; + + $text=replace_macros($tpl, array('$messages'=>array( + array('new'=>true, 'text'=>'new message'), + array('new'=>false, 'text'=>'old message')))); + + $this->assertEquals('new messages: new message', $text); + } + + public function testConditionalFor() { + $tpl='{{ if $enabled }}new messages:{{for $messages as $message}} $message.text{{ endfor }}{{endif}}'; + + $text=replace_macros($tpl, array('$enabled'=>true, + '$messages'=>array( + array('new'=>true, 'text'=>'new message'), + array('new'=>false, 'text'=>'old message')))); + + $this->assertEquals('new messages: new message old message', $text); + } + + public function testFantasy() { + $tpl='Fantasy: {{fantasy $messages}}'; + + $text=replace_macros($tpl, array('$messages'=>'no no')); + + $this->assertEquals('Fantasy: {{fantasy no no}}', $text); + } + + public function testInc() { + $tpl='{{inc field_input.tpl with $field=$myvar}}{{ endinc }}'; + + $text=replace_macros($tpl, array('$myvar'=>array('myfield', 'label', 'value', 'help'))); + + $this->assertEquals(" \n" + ."
\n" + ." \n" + ." \n" + ." help\n" + ."
\n", $text); + } + + public function testIncNoVar() { + $tpl='{{inc field_input.tpl }}{{ endinc }}'; + + $text=replace_macros($tpl, array('$field'=>array('myfield', 'label', 'value', 'help'))); + + $this->assertEquals(" \n
\n \n" + ." \n" + ." help\n" + ."
\n", $text); + } + + public function testDoubleUse() { + $tpl='Hello $name! {{ if $enabled }} I love you! {{ endif }}'; + + $text=replace_macros($tpl, array('$name'=>'Anna', '$enabled'=>false)); + + $this->assertEquals('Hello Anna! ', $text); + + $tpl='Hey $name! {{ if $enabled }} I hate you! {{ endif }}'; + + $text=replace_macros($tpl, array('$name'=>'Max', '$enabled'=>true)); + + $this->assertEquals('Hey Max! I hate you! ', $text); + } + + public function testIncDouble() { + $tpl='{{inc field_input.tpl with $field=$var1}}{{ endinc }}' + .'{{inc field_input.tpl with $field=$var2}}{{ endinc }}'; + + $text=replace_macros($tpl, array('$var1'=>array('myfield', 'label', 'value', 'help'), + '$var2'=>array('myfield2', 'label2', 'value2', 'help2'))); + + $this->assertEquals(" \n" + ."
\n" + ." \n" + ." \n" + ." help\n" + ."
\n" + ." \n" + ."
\n" + ." \n" + ." \n" + ." help2\n" + ."
\n", $text); + } +} \ No newline at end of file -- cgit v1.2.3