diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index 185a2ca3c..580e59048 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -15,3 +15,6 @@ b2474ccd46f9374d52f00c8a195be2266463cf4f # Coding Style: Updated Spaces 73123a96d3fc055f08da036b0121b469a75e3371 + +# Tests indentation +f0216ce423bb133ce668774a5f75ca86455b7280 diff --git a/composer.json b/composer.json index 731bbea8f..feee95f89 100644 --- a/composer.json +++ b/composer.json @@ -100,7 +100,7 @@ ], "test": "phpunit", "test:codecov": "phpunit --coverage-clover ./build/logs/clover.xml", - "test:make-pot": "wp i18n make-pot src tests/languages/timber.pot --domain=", + "test:make-pot": "wp i18n make-pot src tests/languages/timber.pot --domain= && wp i18n make-pot ./tests/assets/translations ./tests/languages/timber-test.pot --domain=timber-test", "test:no-cov": "phpunit --no-coverage" } } diff --git a/tests/assets/Sport.php b/tests/assets/Sport.php index fa1897064..d581985d8 100644 --- a/tests/assets/Sport.php +++ b/tests/assets/Sport.php @@ -1,9 +1,9 @@ Get started here." -msgstr "" - -#: content-none.php:26 -msgid "" -"Sorry, but nothing matched your search terms. Please try again with some " -"different keywords." -msgstr "" - -#: content-none.php:31 -msgid "" -"It seems we can’t find what you’re looking for. Perhaps " -"searching can help." -msgstr "" - -#. Author URI of the plugin/theme -#: footer.php:25 -msgid "https://wordpress.org/" -msgstr "" - -#: footer.php:25 -msgid "Proudly powered by %s" -msgstr "" - -#: functions.php:85 -msgid "Primary Menu" -msgstr "" - -#: functions.php:86 -msgid "Social Links Menu" -msgstr "" - -#: functions.php:133 -msgid "Widget Area" -msgstr "" - -#: functions.php:135 -msgid "Add widgets here to appear in your sidebar." -msgstr "" - -#. translators: If there are characters in your language that are not supported -#. by Noto Sans, translate this to 'off'. Do not translate into your own -#. language. -#: functions.php:158 -msgctxt "Noto Sans font: on or off" -msgid "on" -msgstr "" - -#. translators: If there are characters in your language that are not supported -#. by Noto Serif, translate this to 'off'. Do not translate into your own -#. language. -#: functions.php:163 -msgctxt "Noto Serif font: on or off" -msgid "on" -msgstr "" - -#. translators: If there are characters in your language that are not supported -#. by Inconsolata, translate this to 'off'. Do not translate into your own -#. language. -#: functions.php:168 -msgctxt "Inconsolata font: on or off" -msgid "on" -msgstr "" - -#. translators: To add an additional character subset specific to your -#. language, translate this to 'greek', 'cyrillic', 'devanagari' or -#. 'vietnamese'. Do not translate into your own language. -#: functions.php:173 -msgctxt "Add new subset (greek, cyrillic, devanagari, vietnamese)" -msgid "no-subset" -msgstr "" - -#: functions.php:231 -msgid "expand child menu" -msgstr "" - -#: functions.php:232 -msgid "collapse child menu" -msgstr "" - -#: header.php:27 -msgid "Skip to content" -msgstr "" - -#: header.php:44 -msgid "Menu and widgets" -msgstr "" - -#: image.php:24 -msgid "Previous Image" -msgstr "" - -#: image.php:24 -msgid "Next Image" -msgstr "" - -#: image.php:84 -msgctxt "Parent post link" -msgid "" -"Published in" -"%title" -msgstr "" - -#: inc/back-compat.php:37 inc/back-compat.php:47 inc/back-compat.php:60 -msgid "" -"Twenty Fifteen requires at least WordPress version 4.1. You are running " -"version %s. Please upgrade and try again." -msgstr "" - -#: inc/customizer.php:36 -msgid "Base Color Scheme" -msgstr "" - -#: inc/customizer.php:51 -msgid "Header and Sidebar Text Color" -msgstr "" - -#: inc/customizer.php:52 inc/customizer.php:68 inc/customizer.php:73 -msgid "Applied to the header on small screens and the sidebar on wide screens." -msgstr "" - -#: inc/customizer.php:67 -msgid "Header and Sidebar Background Color" -msgstr "" - -#: inc/customizer.php:97 -msgid "Default" -msgstr "" - -#: inc/customizer.php:108 -msgid "Dark" -msgstr "" - -#: inc/customizer.php:119 -msgid "Yellow" -msgstr "" - -#: inc/customizer.php:130 -msgid "Pink" -msgstr "" - -#: inc/customizer.php:141 -msgid "Purple" -msgstr "" - -#: inc/customizer.php:152 -msgid "Blue" -msgstr "" - -#: inc/template-tags.php:23 -msgid "Comment navigation" -msgstr "" - -#: inc/template-tags.php:26 -msgid "Older Comments" -msgstr "" - -#: inc/template-tags.php:30 -msgid "Newer Comments" -msgstr "" - -#: inc/template-tags.php:49 -msgid "Featured" -msgstr "" - -#: inc/template-tags.php:55 -msgctxt "Used before post format." -msgid "Format" -msgstr "" - -#: inc/template-tags.php:76 -msgctxt "Used before publish date." -msgid "Posted on" -msgstr "" - -#: inc/template-tags.php:85 -msgctxt "Used before post author name." -msgid "Author" -msgstr "" - -#: inc/template-tags.php:91 inc/template-tags.php:99 -msgctxt "Used between list items, there is a space after the comma." -msgid ", " -msgstr "" - -#: inc/template-tags.php:94 -msgctxt "Used before category names." -msgid "Categories" -msgstr "" - -#: inc/template-tags.php:102 -msgctxt "Used before tag names." -msgid "Tags" -msgstr "" - -#: inc/template-tags.php:113 -msgctxt "Used before full size attachment link." -msgid "Full size" -msgstr "" - -#: inc/template-tags.php:122 -msgid "Leave a comment" -msgstr "" - -#: inc/template-tags.php:122 -msgid "1 Comment" -msgstr "" - -#: inc/template-tags.php:122 -msgid "% Comments" -msgstr "" - -#: search.php:18 -msgid "Search Results for: %s" -msgstr "" - -#: single.php:33 -msgid "Next" -msgstr "" - -#: single.php:34 -msgid "Next post:" -msgstr "" - -#: single.php:36 -msgid "Previous" -msgstr "" - -#: single.php:37 -msgid "Previous post:" -msgstr "" - -#. Theme Name of the plugin/theme -msgid "Twenty Fifteen" -msgstr "" - -#. Theme URI of the plugin/theme -msgid "https://wordpress.org/themes/twentyfifteen" -msgstr "" - -#. Description of the plugin/theme -msgid "" -"Our 2015 default theme is clean, blog-focused, and designed for clarity. " -"Twenty Fifteen's simple, straightforward typography is readable on a wide " -"variety of screen sizes, and suitable for multiple languages. We designed it " -"using a mobile-first approach, meaning your content takes center-stage, " -"regardless of whether your visitors arrive by smartphone, tablet, laptop, or " -"desktop computer." -msgstr "" - -#. Author of the plugin/theme -msgid "the WordPress team" -msgstr "" - -#. Test -msgid "thingy" -msgstr "Cheesy Poofs" diff --git a/tests/assets/my-sidebar.php b/tests/assets/my-sidebar.php index e5d877606..98311c23d 100644 --- a/tests/assets/my-sidebar.php +++ b/tests/assets/my-sidebar.php @@ -1,5 +1,5 @@ get_loader(); - } + $TimberLoader = new Timber\Loader(); + for ($i = 0; $i < 5000; $i++) { + $loader = $TimberLoader->get_loader(); } + } - public static function testImageResize() - { - $img = 'arch.jpg'; + public static function testImageResize() + { + $img = 'arch.jpg'; + $upload_dir = wp_upload_dir(); + $destination = $upload_dir['path'] . '/' . $img; + if (!file_exists($destination)) { + copy(__DIR__ . '/../assets/' . $img, $destination); + } + for ($i = 0; $i < 20; $i++) { $upload_dir = wp_upload_dir(); - $destination = $upload_dir['path'] . '/' . $img; - if (!file_exists($destination)) { - copy(__DIR__ . '/../assets/' . $img, $destination); - } - for ($i = 0; $i < 20; $i++) { - $upload_dir = wp_upload_dir(); - $img = Timber\ImageHelper::resize($upload_dir['url'] . '/arch.jpg', 500, 200, 'default', true); - } + $img = Timber\ImageHelper::resize($upload_dir['url'] . '/arch.jpg', 500, 200, 'default', true); } + } - public static function run($function) - { - $start_time = microtime(true); - self::$function(); - $end_time = microtime(true); - echo $end_time - $start_time; - } + public static function run($function) + { + $start_time = microtime(true); + self::$function(); + $end_time = microtime(true); + echo $end_time - $start_time; } +} diff --git a/tests/benchmark/benchmark-timber.php b/tests/benchmark/benchmark-timber.php index 47aa36d15..15e9e7a27 100644 --- a/tests/benchmark/benchmark-timber.php +++ b/tests/benchmark/benchmark-timber.php @@ -1,20 +1,20 @@ get_loader(); - } + $TimberLoader = new Timber\Loader(); + for ($i = 0; $i < 5000; $i++) { + $loader = $TimberLoader->get_loader(); } + } - public static function run($function) - { - $start_time = microtime(true); - self::$function(); - $end_time = microtime(true); - echo $end_time - $start_time; - } + public static function run($function) + { + $start_time = microtime(true); + self::$function(); + $end_time = microtime(true); + echo $end_time - $start_time; } +} diff --git a/tests/bootstrap.php b/tests/bootstrap.php index f9fcab486..9e02d079a 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -33,6 +33,18 @@ function _manually_load_plugin() // WPML integration define('ICL_LANGUAGE_CODE', 'en'); +/** + * Mocked function for testing menus in WPML + */ +function wpml_object_id_filter($element_id, $element_type = 'post', $return_original_if_missing = false, $language_code = null) +{ + $locations = get_nav_menu_locations(); + if (isset($locations['extra-menu'])) { + return $locations['extra-menu']; + } + return $element_id; +} + /** * Bootstrap the CLI dependencies. * diff --git a/tests/languages/timber-test-en_US.mo b/tests/languages/timber-test-en_US.mo new file mode 100644 index 000000000..274869038 Binary files /dev/null and b/tests/languages/timber-test-en_US.mo differ diff --git a/tests/languages/timber-test-en_US.po b/tests/languages/timber-test-en_US.po new file mode 100644 index 000000000..f2fa46175 --- /dev/null +++ b/tests/languages/timber-test-en_US.po @@ -0,0 +1,19 @@ +msgid "" +msgstr "" +"Project-Id-Version: \n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2022-07-29T08:43:31+02:00\n" +"PO-Revision-Date: 2022-07-29 08:47+0200\n" +"Last-Translator: Lukas Gächter \n" +"Language-Team: \n" +"Language: en_US\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"X-Generator: Poedit 3.1.1\n" +"X-Domain: timber-test\n" + +#: timber-test.php:8 +msgid "thingy" +msgstr "Cheesy Poofs" diff --git a/tests/languages/timber-test.pot b/tests/languages/timber-test.pot new file mode 100644 index 000000000..a3d0b7af2 --- /dev/null +++ b/tests/languages/timber-test.pot @@ -0,0 +1,17 @@ +msgid "" +msgstr "" +"Project-Id-Version: \n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: FULL NAME \n" +"Language-Team: LANGUAGE \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"POT-Creation-Date: 2022-07-29T08:43:31+02:00\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"X-Generator: WP-CLI 2.6.0\n" +"X-Domain: timber-test\n" + +#: timber-test.php:8 +msgid "thingy" +msgstr "" diff --git a/tests/languages/timber.pot b/tests/languages/timber.pot index ee9fae176..c22ed6bfc 100644 --- a/tests/languages/timber.pot +++ b/tests/languages/timber.pot @@ -7,7 +7,7 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"POT-Creation-Date: 2022-07-26T11:04:33+00:00\n" +"POT-Creation-Date: 2022-07-29T08:43:31+02:00\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "X-Generator: WP-CLI 2.6.0\n" @@ -15,10 +15,6 @@ msgstr "" msgid "%1$s %2$d" msgstr "" -#: Archives.php:190 -msgid "%1$s" -msgstr "" - #. translators: %s: Human-readable time difference. #: DateTimeHelper.php:73 msgid "%s ago" diff --git a/tests/php/timber-custom-comment.php b/tests/php/timber-custom-comment.php index e2f41645f..87ff1893f 100644 --- a/tests/php/timber-custom-comment.php +++ b/tests/php/timber-custom-comment.php @@ -1,9 +1,9 @@ factory->post->create([ - 'post_date' => $date . ' 19:46:41', - ]); - } - $this->go_to('/'); - $archives = new Timber\Archives([ - 'type' => 'monthly', - 'show_year' => false, - 'limit' => 3, + $dates = ['2013-11-08', '2013-12-08', '2013-11-09', '2013-06-08', '2013-03-03']; + foreach ($dates as $date) { + $this->factory->post->create([ + 'post_date' => $date . ' 19:46:41', ]); - $this->assertEquals(3, count($archives->items)); - $this->assertEquals(2, $archives->items[1]['post_count']); } + $this->go_to('/'); + $archives = new Timber\Archives([ + 'type' => 'monthly', + 'show_year' => false, + 'limit' => 3, + ]); + $this->assertEquals(3, count($archives->items)); + $this->assertEquals(2, $archives->items[1]['post_count']); + } - public function testArchiveMonthly() - { - $dates = ['2013-11-08', '2013-12-08', '2013-11-09', '2013-06-08']; - foreach ($dates as $date) { - $this->factory->post->create([ - 'post_date' => $date . ' 19:46:41', - ]); - } - $this->go_to('/'); - $archives = new Timber\Archives([ - 'type' => 'monthly', - 'show_year' => false, - ]); - $this->assertEquals('December', $archives->items[0]['name']); - $this->assertEquals(3, count($archives->items)); - $this->assertEquals(2, $archives->items[1]['post_count']); - $archives = new Timber\Archives([ - 'type' => 'monthly', - 'show_year' => true, + public function testArchiveMonthly() + { + $dates = ['2013-11-08', '2013-12-08', '2013-11-09', '2013-06-08']; + foreach ($dates as $date) { + $this->factory->post->create([ + 'post_date' => $date . ' 19:46:41', ]); - $this->assertEquals('December 2013', $archives->items[0]['name']); } + $this->go_to('/'); + $archives = new Timber\Archives([ + 'type' => 'monthly', + 'show_year' => false, + ]); + $this->assertEquals('December', $archives->items[0]['name']); + $this->assertEquals(3, count($archives->items)); + $this->assertEquals(2, $archives->items[1]['post_count']); + $archives = new Timber\Archives([ + 'type' => 'monthly', + 'show_year' => true, + ]); + $this->assertEquals('December 2013', $archives->items[0]['name']); + } - public function testArchiveYearly() - { - $dates = ['2011-11-08', '2011-12-08', '2013-11-09', '2014-07-04']; - foreach ($dates as $date) { - $this->factory->post->create([ - 'post_date' => $date . ' 19:46:41', - ]); - } - $this->go_to('/'); - $archives = new Timber\Archives([ - 'type' => 'yearly', - 'show_year' => false, + public function testArchiveYearly() + { + $dates = ['2011-11-08', '2011-12-08', '2013-11-09', '2014-07-04']; + foreach ($dates as $date) { + $this->factory->post->create([ + 'post_date' => $date . ' 19:46:41', ]); - $this->assertEquals(3, count($archives->items)); - $this->assertEquals(2, $archives->items[2]['post_count']); } + $this->go_to('/'); + $archives = new Timber\Archives([ + 'type' => 'yearly', + 'show_year' => false, + ]); + $this->assertEquals(3, count($archives->items)); + $this->assertEquals(2, $archives->items[2]['post_count']); + } - public function testArchiveDaily() - { - $dates = ['2013-11-08', '2013-12-08', '2013-11-09', '2013-11-09', '2013-06-08', '2014-01-08', - ]; - foreach ($dates as $date) { - $this->factory->post->create([ - 'post_date' => $date . ' 19:46:41', - ]); - } - $this->go_to('/'); - $archives = new Timber\Archives([ - 'type' => 'daily', + public function testArchiveDaily() + { + $dates = ['2013-11-08', '2013-12-08', '2013-11-09', '2013-11-09', '2013-06-08', '2014-01-08', + ]; + foreach ($dates as $date) { + $this->factory->post->create([ + 'post_date' => $date . ' 19:46:41', ]); - $this->assertEquals(5, count($archives->items)); - $this->assertEquals(2, $archives->items[2]['post_count']); } + $this->go_to('/'); + $archives = new Timber\Archives([ + 'type' => 'daily', + ]); + $this->assertEquals(5, count($archives->items)); + $this->assertEquals(2, $archives->items[2]['post_count']); + } - public function testArchiveYearlyMonthly() - { - $dates = ['2013-11-08', '2013-12-08', '2013-11-09', '2013-06-08', '2014-01-08', - ]; - foreach ($dates as $date) { - $this->factory->post->create([ - 'post_date' => $date . ' 19:46:41', - ]); - } - $this->go_to('/'); - $archives = new Timber\Archives([ - 'type' => 'monthly-nested', - ]); - $this->assertEquals(2, count($archives->items)); - $this->assertEquals(4, $archives->items[1]['post_count']); - $this->assertEquals(2, $archives->items[1]['children'][1]['post_count']); - $archives = new Timber\Archives([ - 'type' => 'yearlymonthly', + public function testArchiveYearlyMonthly() + { + $dates = ['2013-11-08', '2013-12-08', '2013-11-09', '2013-06-08', '2014-01-08', + ]; + foreach ($dates as $date) { + $this->factory->post->create([ + 'post_date' => $date . ' 19:46:41', ]); - $this->assertEquals(2, count($archives->items)); - $this->assertEquals(4, $archives->items[1]['post_count']); - $this->assertEquals(2, $archives->items[1]['children'][1]['post_count']); } + $this->go_to('/'); + $archives = new Timber\Archives([ + 'type' => 'monthly-nested', + ]); + $this->assertEquals(2, count($archives->items)); + $this->assertEquals(4, $archives->items[1]['post_count']); + $this->assertEquals(2, $archives->items[1]['children'][1]['post_count']); + $archives = new Timber\Archives([ + 'type' => 'yearlymonthly', + ]); + $this->assertEquals(2, count($archives->items)); + $this->assertEquals(4, $archives->items[1]['post_count']); + $this->assertEquals(2, $archives->items[1]['children'][1]['post_count']); + } - public function testArchiveWeekly() - { - $dates = ['2015-03-02', '2015-03-09', '2015-03-16', '2015-03-21', '2015-03-22', - ]; - foreach ($dates as $date) { - $this->factory->post->create([ - 'post_date' => $date . ' 19:46:41', - ]); - } - $this->go_to('/'); - $archives = new Timber\Archives([ - 'type' => 'weekly', + public function testArchiveWeekly() + { + $dates = ['2015-03-02', '2015-03-09', '2015-03-16', '2015-03-21', '2015-03-22', + ]; + foreach ($dates as $date) { + $this->factory->post->create([ + 'post_date' => $date . ' 19:46:41', ]); - $this->assertEquals(3, count($archives->items)); - $this->assertEquals(3, $archives->items[0]['post_count']); } + $this->go_to('/'); + $archives = new Timber\Archives([ + 'type' => 'weekly', + ]); + $this->assertEquals(3, count($archives->items)); + $this->assertEquals(3, $archives->items[0]['post_count']); + } - public function testArchiveAlpha() - { - $posts = [ - [ - 'date' => '2015-03-02', - 'post_title' => 'Jared loves Lauren', - ], - [ - 'date' => '2015-03-02', - 'post_title' => 'Another fantastic post', - ], - [ - 'date' => '2015-03-02', - 'post_title' => 'Foobar', - ], - [ - 'date' => '2015-03-02', - 'post_title' => 'Quack Quack', - ], - ]; - foreach ($posts as $post) { - $this->factory->post->create([ - 'post_date' => $post['date'] . ' 19:46:41', - 'post_title' => $post['post_title'], - ]); - } - $this->go_to('/'); - $archives = new Timber\Archives([ - 'type' => 'alpha', + public function testArchiveAlpha() + { + $posts = [ + [ + 'date' => '2015-03-02', + 'post_title' => 'Jared loves Lauren', + ], + [ + 'date' => '2015-03-02', + 'post_title' => 'Another fantastic post', + ], + [ + 'date' => '2015-03-02', + 'post_title' => 'Foobar', + ], + [ + 'date' => '2015-03-02', + 'post_title' => 'Quack Quack', + ], + ]; + foreach ($posts as $post) { + $this->factory->post->create([ + 'post_date' => $post['date'] . ' 19:46:41', + 'post_title' => $post['post_title'], ]); - $this->assertEquals(4, count($archives->items)); - $this->assertEquals('Quack Quack', $archives->items[3]['name']); } + $this->go_to('/'); + $archives = new Timber\Archives([ + 'type' => 'alpha', + ]); + $this->assertEquals(4, count($archives->items)); + $this->assertEquals('Quack Quack', $archives->items[3]['name']); + } - public function testArchivesWithArgs() - { - register_post_type('book'); - $dates = ['2013-11-08', '2013-12-08', '2013-11-09', '2013-06-08', '2014-01-08', - ]; - foreach ($dates as $date) { - $this->factory->post->create([ - 'post_date' => $date . ' 19:46:41', - ]); - } - $dates = ['2014-11-08', '2014-12-08', '2014-11-09', '2014-06-08', '2015-01-08', '2015-02-14', - ]; - foreach ($dates as $date) { - $this->factory->post->create([ - 'post_date' => $date . ' 19:46:41', - 'post_type' => 'book', - ]); - } - $this->go_to('/'); - $archives = new Timber\Archives(); - - $this->assertEquals(2, count($archives->items)); - $archives = new Timber\Archives([ + public function testArchivesWithArgs() + { + register_post_type('book'); + $dates = ['2013-11-08', '2013-12-08', '2013-11-09', '2013-06-08', '2014-01-08', + ]; + foreach ($dates as $date) { + $this->factory->post->create([ + 'post_date' => $date . ' 19:46:41', + ]); + } + $dates = ['2014-11-08', '2014-12-08', '2014-11-09', '2014-06-08', '2015-01-08', '2015-02-14', + ]; + foreach ($dates as $date) { + $this->factory->post->create([ + 'post_date' => $date . ' 19:46:41', 'post_type' => 'book', - 'type' => 'monthly', ]); - $this->assertEquals(5, count($archives->items)); } + $this->go_to('/'); + $archives = new Timber\Archives(); + + $this->assertEquals(2, count($archives->items)); + $archives = new Timber\Archives([ + 'post_type' => 'book', + 'type' => 'monthly', + ]); + $this->assertEquals(5, count($archives->items)); } +} diff --git a/tests/test-timber-cache.php b/tests/test-timber-cache.php index a6047d20a..90e1592e4 100644 --- a/tests/test-timber-cache.php +++ b/tests/test-timber-cache.php @@ -1,528 +1,528 @@ _generate_transient_name(); - Timber\Helper::_lock_transient($transient, 5); - $this->assertTrue(Timber\Helper::_is_transient_locked($transient)); - } +use Timber\Cache\TimberKeyGeneratorInterface; + +/** + * @group called-post-constructor + */ +class TestTimberCache extends Timber_UnitTestCase +{ + private function _generate_transient_name() + { + static $i = 0; + $i++; + return 'timber_test_transient_' . $i; + } - public function testTransientUnlock() - { - $transient = $this->_generate_transient_name(); - Timber\Helper::_lock_transient($transient, 5); - Timber\Helper::_unlock_transient($transient, 5); - $this->assertFalse(Timber\Helper::_is_transient_locked($transient)); - } + public function testTransientLock() + { + $transient = $this->_generate_transient_name(); + Timber\Helper::_lock_transient($transient, 5); + $this->assertTrue(Timber\Helper::_is_transient_locked($transient)); + } - public function testTransientExpire() - { - $transient = $this->_generate_transient_name(); + public function testTransientUnlock() + { + $transient = $this->_generate_transient_name(); + Timber\Helper::_lock_transient($transient, 5); + Timber\Helper::_unlock_transient($transient, 5); + $this->assertFalse(Timber\Helper::_is_transient_locked($transient)); + } - Timber\Helper::_lock_transient($transient, 1); - sleep(2); - $this->assertFalse(Timber\Helper::_is_transient_locked($transient)); - } + public function testTransientExpire() + { + $transient = $this->_generate_transient_name(); - public function testTransientLocksInternal() - { - $transient = $this->_generate_transient_name(); + Timber\Helper::_lock_transient($transient, 1); + sleep(2); + $this->assertFalse(Timber\Helper::_is_transient_locked($transient)); + } - $is_locked = Timber\Helper::transient($transient, function () use ($transient) { - return Timber\Helper::_is_transient_locked($transient); - }, 30); + public function testTransientLocksInternal() + { + $transient = $this->_generate_transient_name(); - $this->assertTrue($is_locked); - } + $is_locked = Timber\Helper::transient($transient, function () use ($transient) { + return Timber\Helper::_is_transient_locked($transient); + }, 30); - public function testTransientLocksExternal() - { - $transient = $this->_generate_transient_name(); + $this->assertTrue($is_locked); + } - Timber\Helper::_lock_transient($transient, 30); - $get_transient = Timber\Helper::transient($transient, '__return_true', 30); + public function testTransientLocksExternal() + { + $transient = $this->_generate_transient_name(); - $this->assertFalse($get_transient); - } + Timber\Helper::_lock_transient($transient, 30); + $get_transient = Timber\Helper::transient($transient, '__return_true', 30); - public function testTransientAsAnonymousFunction() - { - $transient = $this->_generate_transient_name(); + $this->assertFalse($get_transient); + } - $result = Timber\Helper::transient($transient, function () { - return 'pooptime'; - }, 200); - $this->assertEquals($result, 'pooptime'); - } + public function testTransientAsAnonymousFunction() + { + $transient = $this->_generate_transient_name(); - public function testSetTransient() - { - $transient = $this->_generate_transient_name(); + $result = Timber\Helper::transient($transient, function () { + return 'pooptime'; + }, 200); + $this->assertEquals($result, 'pooptime'); + } - $first_value = Timber\Helper::transient($transient, function () { - return 'first_value'; - }, 30); + public function testSetTransient() + { + $transient = $this->_generate_transient_name(); - $second_value = Timber\Helper::transient($transient, function () { - return 'second_value'; - }, 30); + $first_value = Timber\Helper::transient($transient, function () { + return 'first_value'; + }, 30); - $this->assertEquals('first_value', $second_value); - } + $second_value = Timber\Helper::transient($transient, function () { + return 'second_value'; + }, 30); - public function testDisableTransients() - { - $transient = $this->_generate_transient_name(); + $this->assertEquals('first_value', $second_value); + } - $first_value = Timber\Helper::transient($transient, function () { - return 'first_value'; - }, 30); + public function testDisableTransients() + { + $transient = $this->_generate_transient_name(); - $second_value = Timber\Helper::transient($transient, function () { - return 'second_value'; - }, false); + $first_value = Timber\Helper::transient($transient, function () { + return 'first_value'; + }, 30); - $this->assertEquals('second_value', $second_value); - } + $second_value = Timber\Helper::transient($transient, function () { + return 'second_value'; + }, false); - public function testTransientAsString() - { - $transient = $this->_generate_transient_name(); + $this->assertEquals('second_value', $second_value); + } - $result = Timber\Helper::transient($transient, 'my_test_callback', 200); - $this->assertEquals($result, 'lbj'); - } + public function testTransientAsString() + { + $transient = $this->_generate_transient_name(); - public function testTransientLocked() - { - $transient = $this->_generate_transient_name(); + $result = Timber\Helper::transient($transient, 'my_test_callback', 200); + $this->assertEquals($result, 'lbj'); + } - Timber\Helper::_lock_transient($transient, 30); + public function testTransientLocked() + { + $transient = $this->_generate_transient_name(); - // Transient is locked and won't be forced, so it should return false - $get_transient = Timber\Helper::transient($transient, '__return_true'); + Timber\Helper::_lock_transient($transient, 30); - $this->assertFalse($get_transient); - } + // Transient is locked and won't be forced, so it should return false + $get_transient = Timber\Helper::transient($transient, '__return_true'); - public function testTransientForce() - { - $transient = $this->_generate_transient_name(); + $this->assertFalse($get_transient); + } - Timber\Helper::_lock_transient($transient, 30); - $get_transient = Timber\Helper::transient($transient, '__return_true', 0, 5, true); + public function testTransientForce() + { + $transient = $this->_generate_transient_name(); - $this->assertTrue($get_transient); - } + Timber\Helper::_lock_transient($transient, 30); + $get_transient = Timber\Helper::transient($transient, '__return_true', 0, 5, true); - public function testTransientForceAllFilter() - { - $transient = $this->_generate_transient_name(); + $this->assertTrue($get_transient); + } - Timber\Helper::_lock_transient($transient, 30); + public function testTransientForceAllFilter() + { + $transient = $this->_generate_transient_name(); - add_filter('timber/transient/force_transients', '__return_true'); - $get_transient = Timber\Helper::transient($transient, '__return_true'); - remove_filter('timber/transient/force_transients', '__return_true'); + Timber\Helper::_lock_transient($transient, 30); - $this->assertTrue($get_transient); - } + add_filter('timber/transient/force_transients', '__return_true'); + $get_transient = Timber\Helper::transient($transient, '__return_true'); + remove_filter('timber/transient/force_transients', '__return_true'); - public function testKeyGenerator() - { - $post_id = $this->factory->post->create([ - 'post_title' => 'My Test Post', - ]); - $post = Timber::get_post($post_id); + $this->assertTrue($get_transient); + } - $kg = new Timber\Cache\KeyGenerator(); - $key = $kg->generateKey($post); + public function testKeyGenerator() + { + $post_id = $this->factory->post->create([ + 'post_title' => 'My Test Post', + ]); + $post = Timber::get_post($post_id); - $this->assertStringStartsWith('Timber;Post;', $key); - } + $kg = new Timber\Cache\KeyGenerator(); + $key = $kg->generateKey($post); - public function testKeyGeneratorWithTimberKeyGeneratorInterface() - { - $kg = new Timber\Cache\KeyGenerator(); - $thing = new MyFakeThing(); - $key = $kg->generateKey($thing); - $this->assertEquals('iamakey', $key); - } + $this->assertStringStartsWith('Timber;Post;', $key); + } - public function testKeyGeneratorWithArray() - { - $kg = new Timber\Cache\KeyGenerator(); - $thing = [ - '_cache_key' => 'iAmAKeyButInAnArray', - ]; - $key = $kg->generateKey($thing); - $this->assertEquals('iAmAKeyButInAnArray', $key); - } + public function testKeyGeneratorWithTimberKeyGeneratorInterface() + { + $kg = new Timber\Cache\KeyGenerator(); + $thing = new MyFakeThing(); + $key = $kg->generateKey($thing); + $this->assertEquals('iamakey', $key); + } - public function testTransientForceFilter() - { - $transient = $this->_generate_transient_name(); + public function testKeyGeneratorWithArray() + { + $kg = new Timber\Cache\KeyGenerator(); + $thing = [ + '_cache_key' => 'iAmAKeyButInAnArray', + ]; + $key = $kg->generateKey($thing); + $this->assertEquals('iAmAKeyButInAnArray', $key); + } - Timber\Helper::_lock_transient($transient, 30); + public function testTransientForceFilter() + { + $transient = $this->_generate_transient_name(); - add_filter('timber_force_transient_' . $transient, '__return_true'); - $get_transient = Timber\Helper::transient($transient, '__return_true'); - remove_filter('timber_force_transient_' . $transient, '__return_true'); + Timber\Helper::_lock_transient($transient, 30); - $this->assertTrue($get_transient); - } + add_filter('timber_force_transient_' . $transient, '__return_true'); + $get_transient = Timber\Helper::transient($transient, '__return_true'); + remove_filter('timber_force_transient_' . $transient, '__return_true'); - public function testExpireTransient() - { - $transient = $this->_generate_transient_name(); + $this->assertTrue($get_transient); + } - $first_value = Timber\Helper::transient($transient, function () { - return 'first_value'; - }, 1); + public function testExpireTransient() + { + $transient = $this->_generate_transient_name(); - sleep(2); + $first_value = Timber\Helper::transient($transient, function () { + return 'first_value'; + }, 1); - $second_value = Timber\Helper::transient($transient, function () { - return 'second_value'; - }, 1); + sleep(2); - $this->assertEquals('second_value', $second_value); - } + $second_value = Timber\Helper::transient($transient, function () { + return 'second_value'; + }, 1); - /** - * @expectedDeprecated Timber::$cache and Timber::$twig_cache - */ - public function testTwigCacheDeprecated() - { - $cache_dir = __DIR__ . '/../cache/twig'; - if (is_dir($cache_dir)) { - Timber\Loader::rrmdir($cache_dir); - } - $this->assertFileDoesNotExist($cache_dir); - Timber::$twig_cache = true; - $pid = $this->factory->post->create(); - $post = Timber::get_post($pid); - Timber::compile('assets/single-post.twig', [ - 'post' => $post, - ]); - sleep(1); - $this->assertFileExists($cache_dir); - $loader = new Timber\Loader(); - $loader->clear_cache_twig(); - Timber::$twig_cache = false; - $this->assertFileDoesNotExist($cache_dir); - } + $this->assertEquals('second_value', $second_value); + } - /** - * @expectedDeprecated Timber::$cache and Timber::$twig_cache - */ - public function testTwigCacheAliasDeprecated() - { - $cache_dir = __DIR__ . '/../cache/twig'; - if (is_dir($cache_dir)) { - Timber\Loader::rrmdir($cache_dir); - } - $this->assertFileDoesNotExist($cache_dir); - Timber::$cache = true; - $pid = $this->factory->post->create(); - $post = Timber::get_post($pid); - Timber::compile('assets/single-post.twig', [ - 'post' => $post, - ]); - //sleep(1); - $this->assertFileExists($cache_dir); - $loader = new Timber\Loader(); - $loader->clear_cache_twig(); - Timber::$cache = false; - Timber::$twig_cache = false; - $this->assertFileDoesNotExist($cache_dir); - } + /** + * @expectedDeprecated Timber::$cache and Timber::$twig_cache + */ + public function testTwigCacheDeprecated() + { + $cache_dir = __DIR__ . '/../cache/twig'; + if (is_dir($cache_dir)) { + Timber\Loader::rrmdir($cache_dir); + } + $this->assertFileDoesNotExist($cache_dir); + Timber::$twig_cache = true; + $pid = $this->factory->post->create(); + $post = Timber::get_post($pid); + Timber::compile('assets/single-post.twig', [ + 'post' => $post, + ]); + sleep(1); + $this->assertFileExists($cache_dir); + $loader = new Timber\Loader(); + $loader->clear_cache_twig(); + Timber::$twig_cache = false; + $this->assertFileDoesNotExist($cache_dir); + } - public function testTwigCache() - { - $cache_dir = __DIR__ . '/../cache/twig'; + /** + * @expectedDeprecated Timber::$cache and Timber::$twig_cache + */ + public function testTwigCacheAliasDeprecated() + { + $cache_dir = __DIR__ . '/../cache/twig'; + if (is_dir($cache_dir)) { + Timber\Loader::rrmdir($cache_dir); + } + $this->assertFileDoesNotExist($cache_dir); + Timber::$cache = true; + $pid = $this->factory->post->create(); + $post = Timber::get_post($pid); + Timber::compile('assets/single-post.twig', [ + 'post' => $post, + ]); + //sleep(1); + $this->assertFileExists($cache_dir); + $loader = new Timber\Loader(); + $loader->clear_cache_twig(); + Timber::$cache = false; + Timber::$twig_cache = false; + $this->assertFileDoesNotExist($cache_dir); + } - if (is_dir($cache_dir)) { - Timber\Loader::rrmdir($cache_dir); - } + public function testTwigCache() + { + $cache_dir = __DIR__ . '/../cache/twig'; - $this->assertFileDoesNotExist($cache_dir); + if (is_dir($cache_dir)) { + Timber\Loader::rrmdir($cache_dir); + } - $cache_enabler = function ($options) { - $options['cache'] = true; + $this->assertFileDoesNotExist($cache_dir); - return $options; - }; + $cache_enabler = function ($options) { + $options['cache'] = true; - add_filter('timber/twig/environment/options', $cache_enabler); + return $options; + }; - $pid = $this->factory->post->create(); - $post = Timber::get_post($pid); - Timber::compile('assets/single-post.twig', [ - 'post' => $post, - ]); - sleep(1); + add_filter('timber/twig/environment/options', $cache_enabler); - $this->assertFileExists($cache_dir); + $pid = $this->factory->post->create(); + $post = Timber::get_post($pid); + Timber::compile('assets/single-post.twig', [ + 'post' => $post, + ]); + sleep(1); - $loader = new Timber\Loader(); - $loader->clear_cache_twig(); - $this->assertFileDoesNotExist($cache_dir); + $this->assertFileExists($cache_dir); - remove_filter('timber/twig/environment/options', $cache_enabler); - } + $loader = new Timber\Loader(); + $loader->clear_cache_twig(); + $this->assertFileDoesNotExist($cache_dir); - public function testTimberLoaderCache() - { - $pid = $this->factory->post->create(); - $post = Timber::get_post($pid); - $str_old = Timber::compile('assets/single-post.twig', [ - 'post' => $post, - ], 600); - $str_another = Timber::compile('assets/single-parent.twig', [ - 'post' => $post, - 'rand' => rand(0, 99), - ], 500); - //sleep(1); - $str_new = Timber::compile('assets/single-post.twig', [ - 'post' => $post, - ], 600); - $this->assertEquals($str_old, $str_new); - $loader = new Timber\Loader(); - $clear = $loader->clear_cache_timber(); - $this->assertGreaterThan(0, $clear); - global $wpdb; - $query = "SELECT * FROM $wpdb->options WHERE option_name LIKE '_transient_timberloader_%'"; - $wpdb->query($query); - $this->assertEquals(0, $wpdb->num_rows); - } + remove_filter('timber/twig/environment/options', $cache_enabler); + } - public function testTimberLoaderCacheObject() - { - global $_wp_using_ext_object_cache; - global $wp_object_cache; - $_wp_using_ext_object_cache = true; - $pid = $this->factory->post->create(); - $post = Timber::get_post($pid); - $str_old = Timber::compile('assets/single-post.twig', [ - 'post' => $post, - ], 600, \Timber\Loader::CACHE_OBJECT); - //sleep(1); - $str_new = Timber::compile('assets/single-post.twig', [ - 'post' => $post, - ], 600, \Timber\Loader::CACHE_OBJECT); - $this->assertEquals($str_old, $str_new); - $loader = new Timber\Loader(); - $clear = $loader->clear_cache_timber(\Timber\Loader::CACHE_OBJECT); - $this->assertTrue($clear); - $works = true; - if (isset($wp_object_cache->cache[\Timber\Loader::CACHEGROUP]) - && !empty($wp_object_cache->cache[\Timber\Loader::CACHEGROUP])) { - $works = false; - } - $this->assertTrue($works); - } + public function testTimberLoaderCache() + { + $pid = $this->factory->post->create(); + $post = Timber::get_post($pid); + $str_old = Timber::compile('assets/single-post.twig', [ + 'post' => $post, + ], 600); + $str_another = Timber::compile('assets/single-parent.twig', [ + 'post' => $post, + 'rand' => rand(0, 99), + ], 500); + //sleep(1); + $str_new = Timber::compile('assets/single-post.twig', [ + 'post' => $post, + ], 600); + $this->assertEquals($str_old, $str_new); + $loader = new Timber\Loader(); + $clear = $loader->clear_cache_timber(); + $this->assertGreaterThan(0, $clear); + global $wpdb; + $query = "SELECT * FROM $wpdb->options WHERE option_name LIKE '_transient_timberloader_%'"; + $wpdb->query($query); + $this->assertEquals(0, $wpdb->num_rows); + } - public function tear_down() - { - global $_wp_using_ext_object_cache; - $_wp_using_ext_object_cache = false; - global $wpdb; - $query = "DELETE FROM $wpdb->options WHERE option_name LIKE '_transient_timberloader_%'"; - $wpdb->query($query); - parent::tear_down(); - } + public function testTimberLoaderCacheObject() + { + global $_wp_using_ext_object_cache; + global $wp_object_cache; + $_wp_using_ext_object_cache = true; + $pid = $this->factory->post->create(); + $post = Timber::get_post($pid); + $str_old = Timber::compile('assets/single-post.twig', [ + 'post' => $post, + ], 600, \Timber\Loader::CACHE_OBJECT); + //sleep(1); + $str_new = Timber::compile('assets/single-post.twig', [ + 'post' => $post, + ], 600, \Timber\Loader::CACHE_OBJECT); + $this->assertEquals($str_old, $str_new); + $loader = new Timber\Loader(); + $clear = $loader->clear_cache_timber(\Timber\Loader::CACHE_OBJECT); + $this->assertTrue($clear); + $works = true; + if (isset($wp_object_cache->cache[\Timber\Loader::CACHEGROUP]) + && !empty($wp_object_cache->cache[\Timber\Loader::CACHEGROUP])) { + $works = false; + } + $this->assertTrue($works); + } - public function testTimberLoaderCacheTransients() - { - $time = 1; - $pid = $this->factory->post->create(); - $post = Timber::get_post($pid); - $str_old = Timber::compile('assets/single-post.twig', [ - 'post' => $post, - 'rand' => rand(0, 99999), - ], $time); - sleep(2); - $str_new = Timber::compile('assets/single-post.twig', [ - 'post' => $post, - 'rand' => rand(0, 99999), - ], $time); - $this->assertEquals($str_old, $str_new); - global $wpdb; - $query = "SELECT * FROM $wpdb->options WHERE option_name LIKE '_transient_timberloader_%'"; - $data = $wpdb->get_results($query); - $this->assertEquals(1, $wpdb->num_rows); - } + public function tear_down() + { + global $_wp_using_ext_object_cache; + $_wp_using_ext_object_cache = false; + global $wpdb; + $query = "DELETE FROM $wpdb->options WHERE option_name LIKE '_transient_timberloader_%'"; + $wpdb->query($query); + parent::tear_down(); + } - public function testTimberLoaderCacheTransientsAdminLoggedIn() - { - wp_set_current_user(1); - $time = 1; - $pid = $this->factory->post->create(); - $post = Timber::get_post($pid); - $r1 = rand(0, 999999); - $r2 = rand(0, 999999); - $str_old = Timber::compile('assets/single-post-rand.twig', [ - 'post' => $post, - 'rand' => $r1, - ], [600, false]); - self::_swapFiles(); - $str_new = Timber::compile('assets/single-post-rand.twig', [ - 'post' => $post, - 'rand' => $r2, - ], [600, false]); - $this->assertNotEquals($str_old, $str_new); - self::_unswapFiles(); - } + public function testTimberLoaderCacheTransients() + { + $time = 1; + $pid = $this->factory->post->create(); + $post = Timber::get_post($pid); + $str_old = Timber::compile('assets/single-post.twig', [ + 'post' => $post, + 'rand' => rand(0, 99999), + ], $time); + sleep(2); + $str_new = Timber::compile('assets/single-post.twig', [ + 'post' => $post, + 'rand' => rand(0, 99999), + ], $time); + $this->assertEquals($str_old, $str_new); + global $wpdb; + $query = "SELECT * FROM $wpdb->options WHERE option_name LIKE '_transient_timberloader_%'"; + $data = $wpdb->get_results($query); + $this->assertEquals(1, $wpdb->num_rows); + } - public function _swapFiles() - { - rename(__DIR__ . '/assets/single-post-rand.twig', __DIR__ . '/assets/single-post-rand.twig.tmp'); - rename(__DIR__ . '/assets/relative.twig', __DIR__ . '/assets/single-post-rand.twig'); - } + public function testTimberLoaderCacheTransientsAdminLoggedIn() + { + wp_set_current_user(1); + $time = 1; + $pid = $this->factory->post->create(); + $post = Timber::get_post($pid); + $r1 = rand(0, 999999); + $r2 = rand(0, 999999); + $str_old = Timber::compile('assets/single-post-rand.twig', [ + 'post' => $post, + 'rand' => $r1, + ], [600, false]); + self::_swapFiles(); + $str_new = Timber::compile('assets/single-post-rand.twig', [ + 'post' => $post, + 'rand' => $r2, + ], [600, false]); + $this->assertNotEquals($str_old, $str_new); + self::_unswapFiles(); + } - public function _unswapFiles() - { - rename(__DIR__ . '/assets/single-post-rand.twig', __DIR__ . '/assets/relative.twig'); - rename(__DIR__ . '/assets/single-post-rand.twig.tmp', __DIR__ . '/assets/single-post-rand.twig'); - } + public function _swapFiles() + { + rename(__DIR__ . '/assets/single-post-rand.twig', __DIR__ . '/assets/single-post-rand.twig.tmp'); + rename(__DIR__ . '/assets/relative.twig', __DIR__ . '/assets/single-post-rand.twig'); + } - public function testTimberLoaderCacheTransientsAdminLoggedOut() - { - $time = 1; - $pid = $this->factory->post->create(); - $post = Timber::get_post($pid); - $r1 = rand(0, 999999); - $str_old = Timber::compile('assets/single-post-rand.twig', [ - 'post' => $post, - 'rand' => $r1, - ], [600, false]); - self::_swapFiles(); - $str_new = Timber::compile('assets/single-post-rand.twig', [ - 'post' => $post, - 'rand' => $r1, - ], [600, false]); - $this->assertEquals($str_old, $str_new); - self::_unswapFiles(); - } + public function _unswapFiles() + { + rename(__DIR__ . '/assets/single-post-rand.twig', __DIR__ . '/assets/relative.twig'); + rename(__DIR__ . '/assets/single-post-rand.twig.tmp', __DIR__ . '/assets/single-post-rand.twig'); + } - public function testTimberLoaderCacheTransientsAdminLoggedOutWithSiteCache() - { - $time = 1; - $pid = $this->factory->post->create(); - $post = Timber::get_post($pid); - $r1 = rand(0, 999999); - $str_old = Timber::compile('assets/single-post-rand.twig', [ - 'post' => $post, - 'rand' => $r1, - ], [600, false], \Timber\Loader::CACHE_SITE_TRANSIENT); - self::_swapFiles(); - $str_new = Timber::compile('assets/single-post-rand.twig', [ - 'post' => $post, - 'rand' => $r1, - ], [600, false], \Timber\Loader::CACHE_SITE_TRANSIENT); - $this->assertEquals($str_old, $str_new); - self::_unswapFiles(); - } + public function testTimberLoaderCacheTransientsAdminLoggedOut() + { + $time = 1; + $pid = $this->factory->post->create(); + $post = Timber::get_post($pid); + $r1 = rand(0, 999999); + $str_old = Timber::compile('assets/single-post-rand.twig', [ + 'post' => $post, + 'rand' => $r1, + ], [600, false]); + self::_swapFiles(); + $str_new = Timber::compile('assets/single-post-rand.twig', [ + 'post' => $post, + 'rand' => $r1, + ], [600, false]); + $this->assertEquals($str_old, $str_new); + self::_unswapFiles(); + } - public function testTimberLoaderCacheTransientsAdminLoggedOutWithObjectCache() - { - global $_wp_using_ext_object_cache; - $_wp_using_ext_object_cache = true; - $time = 1; - $pid = $this->factory->post->create(); - $post = Timber::get_post($pid); - $r1 = rand(0, 999999); - $str_old = Timber::compile('assets/single-post-rand.twig', [ - 'post' => $post, - 'rand' => $r1, - ], [600, false], \Timber\Loader::CACHE_OBJECT); - self::_swapFiles(); - $str_new = Timber::compile('assets/single-post-rand.twig', [ - 'post' => $post, - 'rand' => $r1, - ], [600, false], \Timber\Loader::CACHE_OBJECT); - $this->assertEquals($str_old, $str_new); - self::_unswapFiles(); - $_wp_using_ext_object_cache = false; - } + public function testTimberLoaderCacheTransientsAdminLoggedOutWithSiteCache() + { + $time = 1; + $pid = $this->factory->post->create(); + $post = Timber::get_post($pid); + $r1 = rand(0, 999999); + $str_old = Timber::compile('assets/single-post-rand.twig', [ + 'post' => $post, + 'rand' => $r1, + ], [600, false], \Timber\Loader::CACHE_SITE_TRANSIENT); + self::_swapFiles(); + $str_new = Timber::compile('assets/single-post-rand.twig', [ + 'post' => $post, + 'rand' => $r1, + ], [600, false], \Timber\Loader::CACHE_SITE_TRANSIENT); + $this->assertEquals($str_old, $str_new); + self::_unswapFiles(); + } - public function testTimberLoaderCacheTransientsWithExtObjectCache() - { - global $_wp_using_ext_object_cache; - $_wp_using_ext_object_cache = true; - $time = 1; - $pid = $this->factory->post->create(); - $post = Timber::get_post($pid); - $r1 = rand(0, 999999); - $r2 = rand(0, 999999); - $str_old = Timber::compile('assets/single-post.twig', [ - 'post' => $post, - 'rand' => $r1, - ], $time); - $str_new = Timber::compile('assets/single-post.twig', [ - 'post' => $post, - 'rand' => $r2, - ], $time); - $this->assertEquals($str_old, $str_new); - global $wpdb; - $query = "SELECT * FROM $wpdb->options WHERE option_name LIKE '_transient_timberloader_%'"; - $data = $wpdb->get_results($query); - $this->assertEquals(0, $wpdb->num_rows); - $_wp_using_ext_object_cache = false; - } + public function testTimberLoaderCacheTransientsAdminLoggedOutWithObjectCache() + { + global $_wp_using_ext_object_cache; + $_wp_using_ext_object_cache = true; + $time = 1; + $pid = $this->factory->post->create(); + $post = Timber::get_post($pid); + $r1 = rand(0, 999999); + $str_old = Timber::compile('assets/single-post-rand.twig', [ + 'post' => $post, + 'rand' => $r1, + ], [600, false], \Timber\Loader::CACHE_OBJECT); + self::_swapFiles(); + $str_new = Timber::compile('assets/single-post-rand.twig', [ + 'post' => $post, + 'rand' => $r1, + ], [600, false], \Timber\Loader::CACHE_OBJECT); + $this->assertEquals($str_old, $str_new); + self::_unswapFiles(); + $_wp_using_ext_object_cache = false; + } - public function testTimberLoaderCacheTransientsButKeepOtherTransients() - { - $time = 1; - $pid = $this->factory->post->create(); - $post = Timber::get_post($pid); - set_transient('random_600', 'foo', 600); - $random_post = Timber::compile('assets/single-post.twig', [ - 'post' => $post, - 'rand' => rand(0, 99999), - ], 600); - $str_old = Timber::compile('assets/single-post.twig', [ - 'post' => $post, - 'rand' => rand(0, 99999), - ], $time); - sleep(2); - $str_new = Timber::compile('assets/single-post.twig', [ - 'post' => $post, - 'rand' => rand(0, 99999), - ], $time); - $this->assertEquals($str_old, $str_new); - global $wpdb; - $query = "SELECT * FROM $wpdb->options WHERE option_name LIKE '_transient_timberloader_%'"; - $data = $wpdb->get_results($query); - $this->assertEquals(2, $wpdb->num_rows); - $this->assertEquals('foo', get_transient('random_600')); - } + public function testTimberLoaderCacheTransientsWithExtObjectCache() + { + global $_wp_using_ext_object_cache; + $_wp_using_ext_object_cache = true; + $time = 1; + $pid = $this->factory->post->create(); + $post = Timber::get_post($pid); + $r1 = rand(0, 999999); + $r2 = rand(0, 999999); + $str_old = Timber::compile('assets/single-post.twig', [ + 'post' => $post, + 'rand' => $r1, + ], $time); + $str_new = Timber::compile('assets/single-post.twig', [ + 'post' => $post, + 'rand' => $r2, + ], $time); + $this->assertEquals($str_old, $str_new); + global $wpdb; + $query = "SELECT * FROM $wpdb->options WHERE option_name LIKE '_transient_timberloader_%'"; + $data = $wpdb->get_results($query); + $this->assertEquals(0, $wpdb->num_rows); + $_wp_using_ext_object_cache = false; } - class MyFakeThing implements TimberKeyGeneratorInterface + public function testTimberLoaderCacheTransientsButKeepOtherTransients() { - public function _get_cache_key() - { - return 'iamakey'; - } + $time = 1; + $pid = $this->factory->post->create(); + $post = Timber::get_post($pid); + set_transient('random_600', 'foo', 600); + $random_post = Timber::compile('assets/single-post.twig', [ + 'post' => $post, + 'rand' => rand(0, 99999), + ], 600); + $str_old = Timber::compile('assets/single-post.twig', [ + 'post' => $post, + 'rand' => rand(0, 99999), + ], $time); + sleep(2); + $str_new = Timber::compile('assets/single-post.twig', [ + 'post' => $post, + 'rand' => rand(0, 99999), + ], $time); + $this->assertEquals($str_old, $str_new); + global $wpdb; + $query = "SELECT * FROM $wpdb->options WHERE option_name LIKE '_transient_timberloader_%'"; + $data = $wpdb->get_results($query); + $this->assertEquals(2, $wpdb->num_rows); + $this->assertEquals('foo', get_transient('random_600')); } +} - function my_test_callback() +class MyFakeThing implements TimberKeyGeneratorInterface +{ + public function _get_cache_key() { - return "lbj"; + return 'iamakey'; } +} + +function my_test_callback() +{ + return "lbj"; +} diff --git a/tests/test-timber-comment-avatar.php b/tests/test-timber-comment-avatar.php index 01a2538da..9438993f7 100644 --- a/tests/test-timber-comment-avatar.php +++ b/tests/test-timber-comment-avatar.php @@ -1,168 +1,168 @@ markTestSkipped('Cannot test avatar images when not connected to internet'); - } - $post_id = $this->factory->post->create(); - $comment_id = $this->factory->comment->create([ - 'comment_post_ID' => $post_id, - ]); - $comment = Timber\Timber::get_comment($comment_id); - - # test default gravatr holding image - $avatar = $comment->avatar("mystery"); - - $this->assertTrue(substr($avatar, 0, 5) == "http:"); + if (!TestTimberImage::is_connected()) { + $this->markTestSkipped('Cannot test avatar images when not connected to internet'); } + $post_id = $this->factory->post->create(); + $comment_id = $this->factory->comment->create([ + 'comment_post_ID' => $post_id, + ]); + $comment = Timber\Timber::get_comment($comment_id); - public function testAvatarFalse() - { - update_option('show_avatars', false); - $post_id = $this->factory->post->create(); - $comment_id = $this->factory->comment->create([ - 'comment_post_ID' => $post_id, - ]); - $comment = Timber\Timber::get_comment($comment_id); + # test default gravatr holding image + $avatar = $comment->avatar("mystery"); - # test default gravatr holding image - $avatar = $comment->avatar(); + $this->assertTrue(substr($avatar, 0, 5) == "http:"); + } - $this->assertFalse($avatar); - } + public function testAvatarFalse() + { + update_option('show_avatars', false); + $post_id = $this->factory->post->create(); + $comment_id = $this->factory->comment->create([ + 'comment_post_ID' => $post_id, + ]); + $comment = Timber\Timber::get_comment($comment_id); - public function testAvatarBlank() - { - if (!TestTimberImage::is_connected()) { - $this->markTestSkipped('Cannot test avatar images when not connected to internet'); - } - $post_id = $this->factory->post->create(); - $comment_id = $this->factory->comment->create([ - 'comment_post_ID' => $post_id, - ]); - $comment = Timber\Timber::get_comment($comment_id); - - # test default gravatr holding image - $avatar = $comment->avatar(92, "blank"); - - $this->assertTrue(substr($avatar, 0, 5) == "http:"); - } + # test default gravatr holding image + $avatar = $comment->avatar(); + + $this->assertFalse($avatar); + } - public function testAvatarGravatarDefault() - { - if (!TestTimberImage::is_connected()) { - $this->markTestSkipped('Cannot test avatar images when not connected to internet'); - } - $post_id = $this->factory->post->create(); - $comment_id = $this->factory->comment->create([ - 'comment_post_ID' => $post_id, - ]); - $comment = Timber\Timber::get_comment($comment_id); - - # test default gravatr holding image - $avatar = $comment->avatar(92, "gravatar_default"); - - $this->assertTrue(substr($avatar, 0, 5) == "http:"); + public function testAvatarBlank() + { + if (!TestTimberImage::is_connected()) { + $this->markTestSkipped('Cannot test avatar images when not connected to internet'); } + $post_id = $this->factory->post->create(); + $comment_id = $this->factory->comment->create([ + 'comment_post_ID' => $post_id, + ]); + $comment = Timber\Timber::get_comment($comment_id); + + # test default gravatr holding image + $avatar = $comment->avatar(92, "blank"); + + $this->assertTrue(substr($avatar, 0, 5) == "http:"); + } - public function testGravatar() - { - if (!TestTimberImage::is_connected()) { - $this->markTestSkipped('Cannot test avatar images when not connected to internet'); - } - $post_id = $this->factory->post->create(); - $comment_id = $this->factory->comment->create([ - 'comment_post_ID' => $post_id, - 'comment_author' => 'jarednova', - 'comment_author_email' => 'jarednova@upstatement.com', - ]); - $comment = Timber\Timber::get_comment($comment_id); - $gravatar = md5(file_get_contents($comment->avatar())); - /* this keeps changing b/c of compression tweaks on WP.org, disabling the test */ - //$this->assertEquals($gravatar, md5(file_get_contents(dirname(__FILE__).'/assets/jarednova.jpeg'))); - - $comment_id = $this->factory->comment->create([ - 'comment_post_ID' => $post_id, - 'comment_author' => 'jarednova', - 'comment_author_email' => 'notjared@upstatement.com', - ]); - $comment = Timber\Timber::get_comment($comment_id); - $not_gravatar = md5(file_get_contents($comment->avatar())); - $this->assertNotEquals($not_gravatar, md5(file_get_contents(dirname(__FILE__) . '/assets/jarednova.jpeg'))); + public function testAvatarGravatarDefault() + { + if (!TestTimberImage::is_connected()) { + $this->markTestSkipped('Cannot test avatar images when not connected to internet'); } + $post_id = $this->factory->post->create(); + $comment_id = $this->factory->comment->create([ + 'comment_post_ID' => $post_id, + ]); + $comment = Timber\Timber::get_comment($comment_id); + + # test default gravatr holding image + $avatar = $comment->avatar(92, "gravatar_default"); - public function testAvatarSimple() - { - if (!TestTimberImage::is_connected()) { - $this->markTestSkipped('Cannot test avatar images when not connected to internet'); - } - $theme_url = get_theme_root_uri() . '/' . get_stylesheet(); - $post_id = $this->factory->post->create(); - $comment_id = $this->factory->comment->create([ - 'comment_post_ID' => $post_id, - ]); - $comment = Timber\Timber::get_comment($comment_id); - - # test default gravatr holding image - $avatar = $comment->avatar(32, "mystery"); - - $this->assertTrue(substr($avatar, 0, 5) == "http:"); - - # does it work if its SSL? - $_SERVER['HTTPS'] = 'on'; - $avatar = $comment->avatar(32, "mystery"); - $this->assertTrue(200 === $this->crawl($avatar)); - $this->assertTrue(substr($avatar, 0, 6) == "https:"); - $_SERVER['HTTPS'] = 'off'; - - # pass custom url on different domain. can't check by crawling as - # i get a 302 regardless of default url - # so just check it comes back with it in the url - $this->valid_avatar($comment, "http://upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png"); - - # same domain. - $this->valid_avatar($comment, $theme_url . "/images/default.png"); - - #relative - $default_url = "/images/default.png"; - $avatar = $comment->avatar(32, $default_url); - if (strstr($avatar, '?')) { - list($url, $params) = explode('?', $avatar); - $default_url = $theme_url . $default_url; - # you get back the absoulte url to default in the avatar url? - $this->assertEquals($params, "d=$default_url&s=32"); - } - # you get back url? - $this->assertTrue(substr($theme_url . $avatar, 0, 5) == "http:"); + $this->assertTrue(substr($avatar, 0, 5) == "http:"); + } + + public function testGravatar() + { + if (!TestTimberImage::is_connected()) { + $this->markTestSkipped('Cannot test avatar images when not connected to internet'); } + $post_id = $this->factory->post->create(); + $comment_id = $this->factory->comment->create([ + 'comment_post_ID' => $post_id, + 'comment_author' => 'jarednova', + 'comment_author_email' => 'jarednova@upstatement.com', + ]); + $comment = Timber\Timber::get_comment($comment_id); + $gravatar = md5(file_get_contents($comment->avatar())); + /* this keeps changing b/c of compression tweaks on WP.org, disabling the test */ + //$this->assertEquals($gravatar, md5(file_get_contents(dirname(__FILE__).'/assets/jarednova.jpeg'))); + + $comment_id = $this->factory->comment->create([ + 'comment_post_ID' => $post_id, + 'comment_author' => 'jarednova', + 'comment_author_email' => 'notjared@upstatement.com', + ]); + $comment = Timber\Timber::get_comment($comment_id); + $not_gravatar = md5(file_get_contents($comment->avatar())); + $this->assertNotEquals($not_gravatar, md5(file_get_contents(dirname(__FILE__) . '/assets/jarednova.jpeg'))); + } - public function valid_avatar($comment, $default_url) - { - $avatar = $comment->avatar(32, $default_url); - if (strstr($avatar, '?')) { - list($url, $params) = explode('?', $avatar); - # you get back the default in the avatar url? - $this->assertEquals($params, "d=$default_url&s=32"); - } - # you get back url? - $this->assertTrue(substr($avatar, 0, 5) == "http:"); + public function testAvatarSimple() + { + if (!TestTimberImage::is_connected()) { + $this->markTestSkipped('Cannot test avatar images when not connected to internet'); + } + $theme_url = get_theme_root_uri() . '/' . get_stylesheet(); + $post_id = $this->factory->post->create(); + $comment_id = $this->factory->comment->create([ + 'comment_post_ID' => $post_id, + ]); + $comment = Timber\Timber::get_comment($comment_id); + + # test default gravatr holding image + $avatar = $comment->avatar(32, "mystery"); + + $this->assertTrue(substr($avatar, 0, 5) == "http:"); + + # does it work if its SSL? + $_SERVER['HTTPS'] = 'on'; + $avatar = $comment->avatar(32, "mystery"); + $this->assertTrue(200 === $this->crawl($avatar)); + $this->assertTrue(substr($avatar, 0, 6) == "https:"); + $_SERVER['HTTPS'] = 'off'; + + # pass custom url on different domain. can't check by crawling as + # i get a 302 regardless of default url + # so just check it comes back with it in the url + $this->valid_avatar($comment, "http://upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png"); + + # same domain. + $this->valid_avatar($comment, $theme_url . "/images/default.png"); + + #relative + $default_url = "/images/default.png"; + $avatar = $comment->avatar(32, $default_url); + if (strstr($avatar, '?')) { + list($url, $params) = explode('?', $avatar); + $default_url = $theme_url . $default_url; + # you get back the absoulte url to default in the avatar url? + $this->assertEquals($params, "d=$default_url&s=32"); } + # you get back url? + $this->assertTrue(substr($theme_url . $avatar, 0, 5) == "http:"); + } - public function crawl($url) - { - $handle = curl_init($url); - curl_setopt($handle, CURLOPT_RETURNTRANSFER, true); - /* Get the HTML or whatever is linked in $url. */ - $response = curl_exec($handle); - /* Check for 404 (file not found). */ - $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE); - curl_close($handle); - return $httpCode; + public function valid_avatar($comment, $default_url) + { + $avatar = $comment->avatar(32, $default_url); + if (strstr($avatar, '?')) { + list($url, $params) = explode('?', $avatar); + # you get back the default in the avatar url? + $this->assertEquals($params, "d=$default_url&s=32"); } + # you get back url? + $this->assertTrue(substr($avatar, 0, 5) == "http:"); + } + + public function crawl($url) + { + $handle = curl_init($url); + curl_setopt($handle, CURLOPT_RETURNTRANSFER, true); + /* Get the HTML or whatever is linked in $url. */ + $response = curl_exec($handle); + /* Check for 404 (file not found). */ + $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE); + curl_close($handle); + return $httpCode; } +} diff --git a/tests/test-timber-comment-thread.php b/tests/test-timber-comment-thread.php index 0498a65c2..11484f3f0 100644 --- a/tests/test-timber-comment-thread.php +++ b/tests/test-timber-comment-thread.php @@ -1,63 +1,63 @@ factory->post->create([ - 'post_title' => 'Gobbles', - ]); - $comment_id_array = $this->factory->comment->create_many(5, [ - 'comment_post_ID' => $post_id, - ]); - $args = []; - $ct = new Timber\CommentThread($post_id, $args); - $this->assertEquals(5, count($ct)); - } + $post_id = $this->factory->post->create([ + 'post_title' => 'Gobbles', + ]); + $comment_id_array = $this->factory->comment->create_many(5, [ + 'comment_post_ID' => $post_id, + ]); + $args = []; + $ct = new Timber\CommentThread($post_id, $args); + $this->assertEquals(5, count($ct)); + } - public function testCommentThreadCountMethod() - { - $post_id = $this->factory->post->create([ - 'post_title' => 'Gobbles', - ]); - $comment_id_array = $this->factory->comment->create_many(5, [ - 'comment_post_ID' => $post_id, - ]); - $args = []; - $ct = new Timber\CommentThread($post_id, $args); - $this->assertEquals(5, $ct->count()); - } + public function testCommentThreadCountMethod() + { + $post_id = $this->factory->post->create([ + 'post_title' => 'Gobbles', + ]); + $comment_id_array = $this->factory->comment->create_many(5, [ + 'comment_post_ID' => $post_id, + ]); + $args = []; + $ct = new Timber\CommentThread($post_id, $args); + $this->assertEquals(5, $ct->count()); + } + + public function testShowUnmoderatedCommentIfByAnon() + { + global $wp_version; + $post_id = $this->factory->post->create(); - public function testShowUnmoderatedCommentIfByAnon() - { - global $wp_version; - $post_id = $this->factory->post->create(); + $quote = "And in that moment, I was a marine biologist"; + $comment_id = $this->factory->comment->create([ + 'comment_post_ID' => $post_id, + 'comment_content' => $quote, + 'comment_approved' => 0, + 'comment_author_email' => 'jarednova@upstatement.com', + ]); - $quote = "And in that moment, I was a marine biologist"; - $comment_id = $this->factory->comment->create([ - 'comment_post_ID' => $post_id, - 'comment_content' => $quote, - 'comment_approved' => 0, - 'comment_author_email' => 'jarednova@upstatement.com', - ]); + $comment = get_comment($comment_id); - $comment = get_comment($comment_id); + $post = Timber::get_post($post_id); + $this->assertEquals(0, count($post->comments())); - $post = Timber::get_post($post_id); + $_GET['unapproved'] = $comment->comment_ID; + $_GET['moderation-hash'] = wp_hash($comment->comment_date_gmt); + $post = Timber::get_post($post_id); + if (!function_exists('wp_get_unapproved_comment_author_email')) { $this->assertEquals(0, count($post->comments())); - - $_GET['unapproved'] = $comment->comment_ID; - $_GET['moderation-hash'] = wp_hash($comment->comment_date_gmt); - $post = Timber::get_post($post_id); - if (!function_exists('wp_get_unapproved_comment_author_email')) { - $this->assertEquals(0, count($post->comments())); - } else { - $timber_comment = $post->comments()[0]; - $this->assertEquals($quote, $timber_comment->comment_content); - } + } else { + $timber_comment = $post->comments()[0]; + $this->assertEquals($quote, $timber_comment->comment_content); } } +} diff --git a/tests/test-timber-debug.php b/tests/test-timber-debug.php index f8f7f4eeb..49c8aca8c 100644 --- a/tests/test-timber-debug.php +++ b/tests/test-timber-debug.php @@ -1,6 +1,5 @@ markTestSkipped('It belongs to the ages now'); - } + $this->markTestSkipped('It belongs to the ages now'); + } - public function testGetPostsByMeta() - { - $this->markTestSkipped('It belongs to the ages now'); - } + public function testGetPostsByMeta() + { + $this->markTestSkipped('It belongs to the ages now'); + } - public function testTwitterify() - { - $this->markTestSkipped('It belongs to the ages now'); - } + public function testTwitterify() + { + $this->markTestSkipped('It belongs to the ages now'); } +} diff --git a/tests/test-timber-helper.php b/tests/test-timber-helper.php index 61ed491a6..57449d1a4 100644 --- a/tests/test-timber-helper.php +++ b/tests/test-timber-helper.php @@ -2,390 +2,389 @@ require_once(__DIR__ . '/php/timber-post-subclass.php'); +/** + * @group posts-api + * @group terms-api + * @group users-api + */ +class TestTimberHelper extends Timber_UnitTestCase +{ + public function testPluckArray() + { + $arr = []; + $arr[] = [ + 'name' => 'Bill', + 'number' => 42, + ]; + $arr[] = [ + 'name' => 'Barack', + 'number' => 44, + ]; + $arr[] = [ + 'name' => 'Hillary', + 'number' => 45, + ]; + $names = \Timber\Helper::pluck($arr, 'name'); + $this->assertEquals(['Bill', 'Barack', 'Hillary'], $names); + } + + public function testPluckArrayMissing() + { + $arr = []; + $arr[] = [ + 'name' => 'Bill', + 'number' => 42, + ]; + $arr[] = [ + 'name' => 'Barack', + 'number' => 44, + ]; + $arr[] = [ + 'name' => 'Hillary', + 'number' => 45, + ]; + $arr[] = [ + 'name' => 'Donald', + ]; + $names = \Timber\Helper::pluck($arr, 'number'); + $this->assertEquals([42, 44, 45], $names); + } + + public function testPluckObject() + { + $billy = new stdClass(); + $billy->name = 'Billy Corgan'; + $billy->instrument = 'guitar'; + $jimmy = new stdClass(); + $jimmy->name = 'Jimmy Chamberlin'; + $jimmy->instrument = 'drums'; + $pumpkins = [$billy, $jimmy]; + $instruments = \Timber\Helper::pluck($pumpkins, 'instrument'); + $this->assertEquals(['guitar', 'drums'], $instruments); + } + + public function testPluckObjectWithMethod() + { + $this->register_post_classmap_temporarily([ + 'post' => TimberPostSubclass::class, + ]); + + $tps = Timber::get_post($this->factory->post->create()); + $jimmy = new stdClass(); + $jimmy->name = 'Jimmy'; + $pumpkins = [$tps, $jimmy]; + $bar = \Timber\Helper::pluck($pumpkins, 'foo'); + $this->assertEquals(['bar'], $bar); + } + + public function testTrimCharacters() + { + $text = "Sometimes you need to do such weird things like remove all comments from your project."; + $trimmed = \Timber\TextHelper::trim_characters($text, 20); + $this->assertEquals("Sometimes yo…", $trimmed); + } + + public function testCloseTagsWithSelfClosingTags() + { + $p = '

My thing is this


Whatever'; + $html = \Timber\TextHelper::close_tags($p); + $this->assertEquals('

My thing is this


Whatever

', $html); + } + + public function testCommentForm() + { + $post_id = $this->factory->post->create(); + global $post; + $post = get_post($post_id); + $form = Timber\Helper::ob_function('comment_form', [[], $post_id]); + $form = trim($form); + $this->assertStringStartsWith('
assertEquals('', Timber\Helper::get_wp_title()); + } + + public function testWPTitleSingle() + { + //since we're testing with twentyfourteen -- need to remove its filters on wp_title + remove_all_filters('wp_title'); + $post_id = $this->factory->post->create([ + 'post_title' => 'My New Post', + ]); + $post = get_post($post_id); + $this->go_to(site_url('?p=' . $post_id)); + $this->assertEquals('My New Post', Timber\Helper::get_wp_title()); + } + + public function testCloseTags() + { + $str = 'Hi!'; + $closed = Timber\TextHelper::close_tags($str); + $this->assertEquals($str . '', $closed); + } + + public function testArrayToObject() + { + $arr = [ + 'jared' => 'super cool', + ]; + $obj = Timber\Helper::array_to_object($arr); + $this->assertEquals('super cool', $obj->jared); + } + + public function testArrayArrayToObject() + { + $arr = [ + 'jared' => 'super cool', + 'prefs' => [ + 'food' => 'spicy', + 'women' => 'spicier', + + ], + ]; + $obj = Timber\Helper::array_to_object($arr); + $this->assertEquals('spicy', $obj->prefs->food); + } + + public function testGetObjectIndexByProperty() + { + $obj1 = new stdClass(); + $obj1->name = 'mark'; + $obj1->skill = 'acro yoga'; + $obj2 = new stdClass(); + $obj2->name = 'austin'; + $obj2->skill = 'cooking'; + $arr = [$obj1, $obj2]; + $index = Timber\Helper::get_object_index_by_property($arr, 'skill', 'cooking'); + $this->assertEquals(1, $index); + $obj = Timber\Helper::get_object_by_property($arr, 'skill', 'cooking'); + $this->assertEquals('austin', $obj->name); + } + + public function testGetObjectByPropertyButNoMatch() + { + $obj1 = new stdClass(); + $obj1->name = 'mark'; + $obj1->skill = 'acro yoga'; + $arr = [$obj1]; + $result = Timber\Helper::get_object_by_property($arr, 'skill', 'cooking'); + $this->assertFalse($result); + } + + public function testGetArrayIndexByProperty() + { + $obj1 = []; + $obj1['name'] = 'mark'; + $obj1['skill'] = 'acro yoga'; + $obj2 = []; + $obj2['name'] = 'austin'; + $obj2['skill'] = 'cooking'; + $arr = [$obj1, $obj2]; + $index = \Timber\Helper::get_object_index_by_property($arr, 'skill', 'cooking'); + $this->assertEquals(1, $index); + $this->assertFalse(\Timber\Helper::get_object_index_by_property('butts', 'skill', 'cooking')); + } + + public function testGetObjectByPropertyButNo() + { + $this->expectException(InvalidArgumentException::class); + $obj1 = new stdClass(); + $obj1->name = 'mark'; + $obj1->skill = 'acro yoga'; + $obj = Timber\Helper::get_object_by_property($obj1, 'skill', 'cooking'); + } + + public function testTimers() + { + $start = Timber\Helper::start_timer(); + sleep(1); + $end = Timber\Helper::stop_timer($start); + $this->assertStringContainsString(' seconds.', $end); + $time = str_replace(' seconds.', '', $end); + $this->assertGreaterThan(1, $time); + } + + public function testArrayTruncate() + { + $arr = ['Buster', 'GOB', 'Michael', 'Lindsay']; + $arr = Timber\Helper::array_truncate($arr, 2); + $this->assertContains('Buster', $arr); + $this->assertEquals(2, count($arr)); + $this->assertFalse(in_array('Lindsay', $arr)); + } + + public function testIsTrue() + { + $true = Timber\Helper::is_true('true'); + $this->assertTrue($true); + $false = Timber\Helper::is_true('false'); + $this->assertFalse($false); + $estelleGetty = Timber\Helper::is_true('Estelle Getty'); + $this->assertTrue($estelleGetty); + } + + public function testIsEven() + { + $this->assertTrue(Timber\Helper::iseven(2)); + $this->assertFalse(Timber\Helper::iseven(7)); + } + + public function testIsOdd() + { + $this->assertFalse(Timber\Helper::isodd(2)); + $this->assertTrue(Timber\Helper::isodd(7)); + } + + public function testErrorLog() + { + ob_start(); + $this->assertTrue(Timber\Helper::error_log('foo')); + $this->assertTrue(Timber\Helper::error_log(['Dark Helmet', 'Barf'])); + $data = ob_get_flush(); + } + + public function testOSort() + { + $michael = new stdClass(); + $michael->name = 'Michael'; + $michael->year = 1981; + $lauren = new stdClass(); + $lauren->name = 'Lauren'; + $lauren->year = 1984; + $boo = new stdClass(); + $boo->name = 'Robbie'; + $boo->year = 1989; + $people = [$lauren, $michael, $boo]; + Timber\Helper::osort($people, 'year'); + $this->assertEquals('Michael', $people[0]->name); + $this->assertEquals('Lauren', $people[1]->name); + $this->assertEquals('Robbie', $people[2]->name); + $this->assertEquals(1984, $people[1]->year); + } + + /** + * Updated to new syntax + * @ticket #2124 + */ + public function testNewArrayFilter() + { + $posts = []; + $posts[] = $this->factory->post->create([ + 'post_title' => 'Stringer Bell', + 'post_content' => 'Idris Elba', + ]); + $posts[] = $this->factory->post->create([ + 'post_title' => 'Snoop', + 'post_content' => 'Felicia Pearson', + ]); + $posts[] = $this->factory->post->create([ + 'post_title' => 'Cheese', + 'post_content' => 'Method Man', + ]); + $posts = Timber::get_posts($posts); + $template = '{% for post in posts | wp_list_filter("snoop")%}{{ post.content|striptags }}{% endfor %}'; + $str = Timber::compile_string($template, [ + 'posts' => $posts, + ]); + $this->assertEquals('Felicia Pearson', trim($str)); + } + + public function testIsArrayAssoc() + { + $arr = [14, 21, 'thing']; + $this->assertFalse(Timber\Helper::is_array_assoc($arr)); + + $assoc_array = [ + 'thing' => 'yeah', + 'foo' => 'bar', + ]; + $this->assertTrue(Timber\Helper::is_array_assoc($assoc_array)); + } + + public function testTwigFilterFilter() + { + $template = "{% set sizes = [34, 36, 38, 40, 42] %}{{ sizes|filter(v => v > 38)|join(', ') }}"; + $str = Timber::compile_string($template); + $this->assertEquals("40, 42", $str); + } + + /** + * Test for when we're filtering something that's not an array. + */ + public function testArrayFilterWithBogusArray() + { + $this->expectException(Twig\Error\RuntimeError::class); + $template = '{% for post in posts | filter({slug:"snoop", post_content:"Idris Elba"}, "OR")%}{{ post.title }} {% endfor %}'; + $str = Timber::compile_string($template, [ + 'posts' => 'foobar', + ]); + $this->assertEquals('', $str); + } + + public function testConvertWPObject() + { + + // Test WP_Post -> \Timber\Post + $post_id = $this->factory->post->create(); + $wp_post = get_post($post_id); + $timber_post = \Timber\Helper::convert_wp_object($wp_post); + $this->assertTrue($timber_post instanceof \Timber\Post); + + // Test WP_Term -> \Timber\Term + $term_id = $this->factory->term->create(); + $wp_term = get_term($term_id); + $timber_term = \Timber\Helper::convert_wp_object($wp_term); + $this->assertTrue($timber_term instanceof \Timber\Term); + + // Test WP_User -> \Timber\User + $user_id = $this->factory->user->create(); + $wp_user = get_user_by('id', $user_id); + $timber_user = \Timber\Helper::convert_wp_object($wp_user); + $this->assertTrue($timber_user instanceof \Timber\User); + + // Test strange input + $random_int = 2018; + $convert_int = \Timber\Helper::convert_wp_object($random_int); + $this->assertTrue($convert_int === $random_int); + + $array = []; + $convert_array = \Timber\Helper::convert_wp_object($array); + $this->assertTrue(is_array($convert_array)); + } + + public function testConvertPostWithClassMap() + { + register_post_type('sport'); + require_once('assets/Sport.php'); + + $this->register_post_classmap_temporarily([ + 'sport' => Sport::class, + ]); + + $sport_id = $this->factory->post->create([ + 'post_type' => 'sport', + 'post_title' => 'Basketball Player', + ]); + $wp_post = get_post($sport_id); + $sport_post = \Timber\Helper::convert_wp_object($wp_post); + $this->assertInstanceOf(Sport::class, $sport_post); + $this->assertEquals('ESPN', $sport_post->channel()); + } /** - * @group posts-api - * @group terms-api - * @group users-api + * @expectedIncorrectUsage Accessing the thumbnail ID through {{ post._thumbnail_id }} */ - class TestTimberHelper extends Timber_UnitTestCase + public function testDoingItWrong() { - public function testPluckArray() - { - $arr = []; - $arr[] = [ - 'name' => 'Bill', - 'number' => 42, - ]; - $arr[] = [ - 'name' => 'Barack', - 'number' => 44, - ]; - $arr[] = [ - 'name' => 'Hillary', - 'number' => 45, - ]; - $names = \Timber\Helper::pluck($arr, 'name'); - $this->assertEquals(['Bill', 'Barack', 'Hillary'], $names); - } - - public function testPluckArrayMissing() - { - $arr = []; - $arr[] = [ - 'name' => 'Bill', - 'number' => 42, - ]; - $arr[] = [ - 'name' => 'Barack', - 'number' => 44, - ]; - $arr[] = [ - 'name' => 'Hillary', - 'number' => 45, - ]; - $arr[] = [ - 'name' => 'Donald', - ]; - $names = \Timber\Helper::pluck($arr, 'number'); - $this->assertEquals([42, 44, 45], $names); - } - - public function testPluckObject() - { - $billy = new stdClass(); - $billy->name = 'Billy Corgan'; - $billy->instrument = 'guitar'; - $jimmy = new stdClass(); - $jimmy->name = 'Jimmy Chamberlin'; - $jimmy->instrument = 'drums'; - $pumpkins = [$billy, $jimmy]; - $instruments = \Timber\Helper::pluck($pumpkins, 'instrument'); - $this->assertEquals(['guitar', 'drums'], $instruments); - } - - public function testPluckObjectWithMethod() - { - $this->register_post_classmap_temporarily([ - 'post' => TimberPostSubclass::class, - ]); - - $tps = Timber::get_post($this->factory->post->create()); - $jimmy = new stdClass(); - $jimmy->name = 'Jimmy'; - $pumpkins = [$tps, $jimmy]; - $bar = \Timber\Helper::pluck($pumpkins, 'foo'); - $this->assertEquals(['bar'], $bar); - } - - public function testTrimCharacters() - { - $text = "Sometimes you need to do such weird things like remove all comments from your project."; - $trimmed = \Timber\TextHelper::trim_characters($text, 20); - $this->assertEquals("Sometimes yo…", $trimmed); - } - - public function testCloseTagsWithSelfClosingTags() - { - $p = '

My thing is this


Whatever'; - $html = \Timber\TextHelper::close_tags($p); - $this->assertEquals('

My thing is this


Whatever

', $html); - } - - public function testCommentForm() - { - $post_id = $this->factory->post->create(); - global $post; - $post = get_post($post_id); - $form = Timber\Helper::ob_function('comment_form', [[], $post_id]); - $form = trim($form); - $this->assertStringStartsWith('
assertEquals('', Timber\Helper::get_wp_title()); - } - - public function testWPTitleSingle() - { - //since we're testing with twentyfourteen -- need to remove its filters on wp_title - remove_all_filters('wp_title'); - $post_id = $this->factory->post->create([ - 'post_title' => 'My New Post', - ]); - $post = get_post($post_id); - $this->go_to(site_url('?p=' . $post_id)); - $this->assertEquals('My New Post', Timber\Helper::get_wp_title()); - } - - public function testCloseTags() - { - $str = 'Hi!'; - $closed = Timber\TextHelper::close_tags($str); - $this->assertEquals($str . '', $closed); - } - - public function testArrayToObject() - { - $arr = [ - 'jared' => 'super cool', - ]; - $obj = Timber\Helper::array_to_object($arr); - $this->assertEquals('super cool', $obj->jared); - } - - public function testArrayArrayToObject() - { - $arr = [ - 'jared' => 'super cool', - 'prefs' => [ - 'food' => 'spicy', - 'women' => 'spicier', - - ], - ]; - $obj = Timber\Helper::array_to_object($arr); - $this->assertEquals('spicy', $obj->prefs->food); - } - - public function testGetObjectIndexByProperty() - { - $obj1 = new stdClass(); - $obj1->name = 'mark'; - $obj1->skill = 'acro yoga'; - $obj2 = new stdClass(); - $obj2->name = 'austin'; - $obj2->skill = 'cooking'; - $arr = [$obj1, $obj2]; - $index = Timber\Helper::get_object_index_by_property($arr, 'skill', 'cooking'); - $this->assertEquals(1, $index); - $obj = Timber\Helper::get_object_by_property($arr, 'skill', 'cooking'); - $this->assertEquals('austin', $obj->name); - } - - public function testGetObjectByPropertyButNoMatch() - { - $obj1 = new stdClass(); - $obj1->name = 'mark'; - $obj1->skill = 'acro yoga'; - $arr = [$obj1]; - $result = Timber\Helper::get_object_by_property($arr, 'skill', 'cooking'); - $this->assertFalse($result); - } - - public function testGetArrayIndexByProperty() - { - $obj1 = []; - $obj1['name'] = 'mark'; - $obj1['skill'] = 'acro yoga'; - $obj2 = []; - $obj2['name'] = 'austin'; - $obj2['skill'] = 'cooking'; - $arr = [$obj1, $obj2]; - $index = \Timber\Helper::get_object_index_by_property($arr, 'skill', 'cooking'); - $this->assertEquals(1, $index); - $this->assertFalse(\Timber\Helper::get_object_index_by_property('butts', 'skill', 'cooking')); - } - - public function testGetObjectByPropertyButNo() - { - $this->expectException(InvalidArgumentException::class); - $obj1 = new stdClass(); - $obj1->name = 'mark'; - $obj1->skill = 'acro yoga'; - $obj = Timber\Helper::get_object_by_property($obj1, 'skill', 'cooking'); - } - - public function testTimers() - { - $start = Timber\Helper::start_timer(); - sleep(1); - $end = Timber\Helper::stop_timer($start); - $this->assertStringContainsString(' seconds.', $end); - $time = str_replace(' seconds.', '', $end); - $this->assertGreaterThan(1, $time); - } - - public function testArrayTruncate() - { - $arr = ['Buster', 'GOB', 'Michael', 'Lindsay']; - $arr = Timber\Helper::array_truncate($arr, 2); - $this->assertContains('Buster', $arr); - $this->assertEquals(2, count($arr)); - $this->assertFalse(in_array('Lindsay', $arr)); - } - - public function testIsTrue() - { - $true = Timber\Helper::is_true('true'); - $this->assertTrue($true); - $false = Timber\Helper::is_true('false'); - $this->assertFalse($false); - $estelleGetty = Timber\Helper::is_true('Estelle Getty'); - $this->assertTrue($estelleGetty); - } - - public function testIsEven() - { - $this->assertTrue(Timber\Helper::iseven(2)); - $this->assertFalse(Timber\Helper::iseven(7)); - } - - public function testIsOdd() - { - $this->assertFalse(Timber\Helper::isodd(2)); - $this->assertTrue(Timber\Helper::isodd(7)); - } - - public function testErrorLog() - { - ob_start(); - $this->assertTrue(Timber\Helper::error_log('foo')); - $this->assertTrue(Timber\Helper::error_log(['Dark Helmet', 'Barf'])); - $data = ob_get_flush(); - } - - public function testOSort() - { - $michael = new stdClass(); - $michael->name = 'Michael'; - $michael->year = 1981; - $lauren = new stdClass(); - $lauren->name = 'Lauren'; - $lauren->year = 1984; - $boo = new stdClass(); - $boo->name = 'Robbie'; - $boo->year = 1989; - $people = [$lauren, $michael, $boo]; - Timber\Helper::osort($people, 'year'); - $this->assertEquals('Michael', $people[0]->name); - $this->assertEquals('Lauren', $people[1]->name); - $this->assertEquals('Robbie', $people[2]->name); - $this->assertEquals(1984, $people[1]->year); - } - - /** - * Updated to new syntax - * @ticket #2124 - */ - public function testNewArrayFilter() - { - $posts = []; - $posts[] = $this->factory->post->create([ - 'post_title' => 'Stringer Bell', - 'post_content' => 'Idris Elba', - ]); - $posts[] = $this->factory->post->create([ - 'post_title' => 'Snoop', - 'post_content' => 'Felicia Pearson', - ]); - $posts[] = $this->factory->post->create([ - 'post_title' => 'Cheese', - 'post_content' => 'Method Man', - ]); - $posts = Timber::get_posts($posts); - $template = '{% for post in posts | wp_list_filter("snoop")%}{{ post.content|striptags }}{% endfor %}'; - $str = Timber::compile_string($template, [ - 'posts' => $posts, - ]); - $this->assertEquals('Felicia Pearson', trim($str)); - } - - public function testIsArrayAssoc() - { - $arr = [14, 21, 'thing']; - $this->assertFalse(Timber\Helper::is_array_assoc($arr)); - - $assoc_array = [ - 'thing' => 'yeah', - 'foo' => 'bar', - ]; - $this->assertTrue(Timber\Helper::is_array_assoc($assoc_array)); - } - - public function testTwigFilterFilter() - { - $template = "{% set sizes = [34, 36, 38, 40, 42] %}{{ sizes|filter(v => v > 38)|join(', ') }}"; - $str = Timber::compile_string($template); - $this->assertEquals("40, 42", $str); - } - - /** - * Test for when we're filtering something that's not an array. - */ - public function testArrayFilterWithBogusArray() - { - $this->expectException(Twig\Error\RuntimeError::class); - $template = '{% for post in posts | filter({slug:"snoop", post_content:"Idris Elba"}, "OR")%}{{ post.title }} {% endfor %}'; - $str = Timber::compile_string($template, [ - 'posts' => 'foobar', - ]); - $this->assertEquals('', $str); - } - - public function testConvertWPObject() - { - - // Test WP_Post -> \Timber\Post - $post_id = $this->factory->post->create(); - $wp_post = get_post($post_id); - $timber_post = \Timber\Helper::convert_wp_object($wp_post); - $this->assertTrue($timber_post instanceof \Timber\Post); - - // Test WP_Term -> \Timber\Term - $term_id = $this->factory->term->create(); - $wp_term = get_term($term_id); - $timber_term = \Timber\Helper::convert_wp_object($wp_term); - $this->assertTrue($timber_term instanceof \Timber\Term); - - // Test WP_User -> \Timber\User - $user_id = $this->factory->user->create(); - $wp_user = get_user_by('id', $user_id); - $timber_user = \Timber\Helper::convert_wp_object($wp_user); - $this->assertTrue($timber_user instanceof \Timber\User); - - // Test strange input - $random_int = 2018; - $convert_int = \Timber\Helper::convert_wp_object($random_int); - $this->assertTrue($convert_int === $random_int); - - $array = []; - $convert_array = \Timber\Helper::convert_wp_object($array); - $this->assertTrue(is_array($convert_array)); - } - - public function testConvertPostWithClassMap() - { - register_post_type('sport'); - require_once('assets/Sport.php'); - - $this->register_post_classmap_temporarily([ - 'sport' => Sport::class, - ]); - - $sport_id = $this->factory->post->create([ - 'post_type' => 'sport', - 'post_title' => 'Basketball Player', - ]); - $wp_post = get_post($sport_id); - $sport_post = \Timber\Helper::convert_wp_object($wp_post); - $this->assertInstanceOf(Sport::class, $sport_post); - $this->assertEquals('ESPN', $sport_post->channel()); - } - - /** - * @expectedIncorrectUsage Accessing the thumbnail ID through {{ post._thumbnail_id }} - */ - public function testDoingItWrong() - { - $post_id = $this->factory->post->create(); - $posts = Timber::get_posts(); - update_post_meta($post_id, '_thumbnail_id', '707'); - $post = Timber::get_post($post_id); - $thumbnail_id = $post->_thumbnail_id; - } + $post_id = $this->factory->post->create(); + $posts = Timber::get_posts(); + update_post_meta($post_id, '_thumbnail_id', '707'); + $post = Timber::get_post($post_id); + $thumbnail_id = $post->_thumbnail_id; } +} diff --git a/tests/test-timber-hooks.php b/tests/test-timber-hooks.php index 325e46f79..1cc82f865 100644 --- a/tests/test-timber-hooks.php +++ b/tests/test-timber-hooks.php @@ -1,14 +1,14 @@ assertEquals('Nathan Hass', $context['person']); - } + add_filter('timber/context', function ($context) { + $context['person'] = "Nathan Hass"; + return $context; + }); + $context = Timber::context(); + $this->assertEquals('Nathan Hass', $context['person']); } +} diff --git a/tests/test-timber-image-helper.php b/tests/test-timber-image-helper.php index ac205d417..ebeb6ad1a 100644 --- a/tests/test-timber-image-helper.php +++ b/tests/test-timber-image-helper.php @@ -1,201 +1,201 @@ assertEquals('/2017/06', $info['subdir']); - } + $url = 'http://example.org/wp-content/uploads/2017/06/dog.jpg'; + $info = Timber\ImageHelper::analyze_url($url); + $this->assertEquals('/2017/06', $info['subdir']); + } - public function testHTTPSAnalyze() - { - $url = 'https://example.org/wp-content/uploads/2017/06/dog.jpg'; - $info = Timber\ImageHelper::analyze_url($url); - $this->assertEquals('/2017/06', $info['subdir']); - } + public function testHTTPSAnalyze() + { + $url = 'https://example.org/wp-content/uploads/2017/06/dog.jpg'; + $info = Timber\ImageHelper::analyze_url($url); + $this->assertEquals('/2017/06', $info['subdir']); + } - public function testIsAnimatedGif() - { - $image = TestTimberImage::copyTestAttachment('robocop.gif'); - $this->assertTrue(Timber\ImageHelper::is_animated_gif($image)); - } + public function testIsAnimatedGif() + { + $image = TestTimberImage::copyTestAttachment('robocop.gif'); + $this->assertTrue(Timber\ImageHelper::is_animated_gif($image)); + } - public function testIsRegularGif() - { - $image = TestTimberImage::copyTestAttachment('boyer.gif'); - $this->assertFalse(Timber\ImageHelper::is_animated_gif($image)); - } + public function testIsRegularGif() + { + $image = TestTimberImage::copyTestAttachment('boyer.gif'); + $this->assertFalse(Timber\ImageHelper::is_animated_gif($image)); + } - public function testIsNotGif() - { - $arch = TestTimberImage::copyTestAttachment('arch.jpg'); - $this->assertFalse(Timber\ImageHelper::is_animated_gif($arch)); - } + public function testIsNotGif() + { + $arch = TestTimberImage::copyTestAttachment('arch.jpg'); + $this->assertFalse(Timber\ImageHelper::is_animated_gif($arch)); + } - public function testIsSVG() - { - $image = TestTimberImage::copyTestAttachment('timber-logo.svg'); - $this->assertTrue(Timber\ImageHelper::is_svg($image)); - } + public function testIsSVG() + { + $image = TestTimberImage::copyTestAttachment('timber-logo.svg'); + $this->assertTrue(Timber\ImageHelper::is_svg($image)); + } - public function testServerLocation() - { - $arch = TestTimberImage::copyTestAttachment('arch.jpg'); - $this->assertEquals($arch, \Timber\ImageHelper::get_server_location($arch)); - } + public function testServerLocation() + { + $arch = TestTimberImage::copyTestAttachment('arch.jpg'); + $this->assertEquals($arch, \Timber\ImageHelper::get_server_location($arch)); + } - /** - * @dataProvider customDirectoryData - */ - public function testCustomWordPressDirectoryStructure($template, $size) - { - $this->setupCustomWPDirectoryStructure(); - - $upload_dir = wp_upload_dir(); - $post_id = $this->factory->post->create(); - $filename = TestTimberImage::copyTestAttachment('flag.png'); - $destination_url = str_replace(ABSPATH, 'http://' . $_SERVER['HTTP_HOST'] . '/', $filename); - $wp_filetype = wp_check_filetype(basename($filename), null); - $attachment = [ - 'post_mime_type' => $wp_filetype['type'], - 'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)), - 'post_content' => '', - 'post_status' => 'inherit', - ]; - $attach_id = wp_insert_attachment($attachment, $filename, $post_id); - add_post_meta($post_id, '_thumbnail_id', $attach_id, true); - $data = []; - $data['post'] = Timber::get_post($post_id); - $data['size'] = $size; - $data['crop'] = 'default'; - Timber::compile($template, $data); - - $this->tearDownCustomWPDirectoryStructure(); - - $exists = file_exists($filename); - $this->assertTrue($exists); - $resized_path = $upload_dir['path'] . '/flag-' . $data['size']['width'] . 'x' . $data['size']['height'] . '-c-' . $data['crop'] . '.png'; - $exists = file_exists($resized_path); - $this->assertTrue($exists); - } + /** + * @dataProvider customDirectoryData + */ + public function testCustomWordPressDirectoryStructure($template, $size) + { + $this->setupCustomWPDirectoryStructure(); + + $upload_dir = wp_upload_dir(); + $post_id = $this->factory->post->create(); + $filename = TestTimberImage::copyTestAttachment('flag.png'); + $destination_url = str_replace(ABSPATH, 'http://' . $_SERVER['HTTP_HOST'] . '/', $filename); + $wp_filetype = wp_check_filetype(basename($filename), null); + $attachment = [ + 'post_mime_type' => $wp_filetype['type'], + 'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)), + 'post_content' => '', + 'post_status' => 'inherit', + ]; + $attach_id = wp_insert_attachment($attachment, $filename, $post_id); + add_post_meta($post_id, '_thumbnail_id', $attach_id, true); + $data = []; + $data['post'] = Timber::get_post($post_id); + $data['size'] = $size; + $data['crop'] = 'default'; + Timber::compile($template, $data); + + $this->tearDownCustomWPDirectoryStructure(); + + $exists = file_exists($filename); + $this->assertTrue($exists); + $resized_path = $upload_dir['path'] . '/flag-' . $data['size']['width'] . 'x' . $data['size']['height'] . '-c-' . $data['crop'] . '.png'; + $exists = file_exists($resized_path); + $this->assertTrue($exists); + } - public function testSideloadImageFolder() - { - $filename = 'acGwPDj4_400x400'; - $url = Timber\ImageHelper::sideload_image( - 'https://pbs.twimg.com/profile_images/768086933310476288/' . $filename . '.jpg' - ); + public function testSideloadImageFolder() + { + $filename = 'acGwPDj4_400x400'; + $url = Timber\ImageHelper::sideload_image( + 'https://pbs.twimg.com/profile_images/768086933310476288/' . $filename . '.jpg' + ); - $base_url = str_replace(basename($url), '', $url); + $base_url = str_replace(basename($url), '', $url); - $this->assertEquals('http://example.org/wp-content/uploads/external/', $base_url); - } + $this->assertEquals('http://example.org/wp-content/uploads/external/', $base_url); + } - public function testSideloadImageFolderChanged() - { - $this->add_filter_temporarily('timber/sideload_image/subdir', function ($subdir) { - return 'external'; - }); + public function testSideloadImageFolderChanged() + { + $this->add_filter_temporarily('timber/sideload_image/subdir', function ($subdir) { + return 'external'; + }); - $filename = 'acGwPDj4_400x400'; - $url = Timber\ImageHelper::sideload_image( - 'https://pbs.twimg.com/profile_images/768086933310476288/' . $filename . '.jpg' - ); + $filename = 'acGwPDj4_400x400'; + $url = Timber\ImageHelper::sideload_image( + 'https://pbs.twimg.com/profile_images/768086933310476288/' . $filename . '.jpg' + ); - $base_url = str_replace(basename($url), '', $url); + $base_url = str_replace(basename($url), '', $url); - $this->assertEquals('http://example.org/wp-content/uploads/external/', $base_url); - } + $this->assertEquals('http://example.org/wp-content/uploads/external/', $base_url); + } - public function testSideloadImageFolderEmpty() - { - $this->add_filter_temporarily('timber/sideload_image/subdir', function ($subdir) { - return ''; - }); + public function testSideloadImageFolderEmpty() + { + $this->add_filter_temporarily('timber/sideload_image/subdir', function ($subdir) { + return ''; + }); - $filename = 'acGwPDj4_400x400'; - $url = Timber\ImageHelper::sideload_image( - 'https://pbs.twimg.com/profile_images/768086933310476288/' . $filename . '.jpg' - ); + $filename = 'acGwPDj4_400x400'; + $url = Timber\ImageHelper::sideload_image( + 'https://pbs.twimg.com/profile_images/768086933310476288/' . $filename . '.jpg' + ); - $base_url = untrailingslashit(str_replace(basename($url), '', $url)); - $upload_dir = wp_upload_dir(); + $base_url = untrailingslashit(str_replace(basename($url), '', $url)); + $upload_dir = wp_upload_dir(); - $this->assertEquals($upload_dir['url'], $base_url); - } + $this->assertEquals($upload_dir['url'], $base_url); + } - public function testSideloadImageFolderFalse() - { - $this->add_filter_temporarily('timber/sideload_image/subdir', '__return_false'); + public function testSideloadImageFolderFalse() + { + $this->add_filter_temporarily('timber/sideload_image/subdir', '__return_false'); - $filename = 'acGwPDj4_400x400'; - $url = Timber\ImageHelper::sideload_image( - 'https://pbs.twimg.com/profile_images/768086933310476288/' . $filename . '.jpg' - ); + $filename = 'acGwPDj4_400x400'; + $url = Timber\ImageHelper::sideload_image( + 'https://pbs.twimg.com/profile_images/768086933310476288/' . $filename . '.jpg' + ); - $base_url = untrailingslashit(str_replace(basename($url), '', $url)); - $upload_dir = wp_upload_dir(); + $base_url = untrailingslashit(str_replace(basename($url), '', $url)); + $upload_dir = wp_upload_dir(); - $this->assertEquals($upload_dir['url'], $base_url); - } + $this->assertEquals($upload_dir['url'], $base_url); + } - public function testDeleteSideloadedFile() - { - $filename = 'acGwPDj4_400x400'; - $img = Timber\ImageHelper::sideload_image('https://pbs.twimg.com/profile_images/768086933310476288/' . $filename . '.jpg'); - $files = scandir('/tmp'); - $matches = false; - foreach ($files as $file) { - $substr = substr($file, 0, strlen($filename)); - if ($substr == $filename) { - $matches = true; - } + public function testDeleteSideloadedFile() + { + $filename = 'acGwPDj4_400x400'; + $img = Timber\ImageHelper::sideload_image('https://pbs.twimg.com/profile_images/768086933310476288/' . $filename . '.jpg'); + $files = scandir('/tmp'); + $matches = false; + foreach ($files as $file) { + $substr = substr($file, 0, strlen($filename)); + if ($substr == $filename) { + $matches = true; } - $this->assertFalse($matches); } + $this->assertFalse($matches); + } - /** - * @doesNotPerformAssertions - */ - public function testDeleteFalseFile() - { - Timber\ImageHelper::delete_generated_files('/etc/www/image.jpg'); - } + /** + * @doesNotPerformAssertions + */ + public function testDeleteFalseFile() + { + Timber\ImageHelper::delete_generated_files('/etc/www/image.jpg'); + } - public function testLetterbox() - { - $file_loc = TestTimberImage::copyTestAttachment('eastern.jpg'); - $upload_dir = wp_upload_dir(); - $image = $upload_dir['url'] . '/eastern.jpg'; - $new_file = Timber\ImageHelper::letterbox($image, 500, 500, '#CCC', true); - $location_of_image = Timber\ImageHelper::get_server_location($new_file); - $this->addFile($location_of_image); - $this->assertTrue(TestTimberImage::checkSize($location_of_image, 500, 500)); - //whats the bg/color of the image - $this->assertTrue(TestTimberImage::checkPixel($location_of_image, 1, 1, "#CCC")); - } + public function testLetterbox() + { + $file_loc = TestTimberImage::copyTestAttachment('eastern.jpg'); + $upload_dir = wp_upload_dir(); + $image = $upload_dir['url'] . '/eastern.jpg'; + $new_file = Timber\ImageHelper::letterbox($image, 500, 500, '#CCC', true); + $location_of_image = Timber\ImageHelper::get_server_location($new_file); + $this->addFile($location_of_image); + $this->assertTrue(TestTimberImage::checkSize($location_of_image, 500, 500)); + //whats the bg/color of the image + $this->assertTrue(TestTimberImage::checkPixel($location_of_image, 1, 1, "#CCC")); + } - public function customDirectoryData() - { - return [ + public function customDirectoryData() + { + return [ + [ + 'assets/thumb-test.twig', [ - 'assets/thumb-test.twig', - [ - 'width' => 100, - 'height' => 50, - ], - ], [ - 'assets/thumb-test-relative.twig', - [ - 'width' => 50, - 'height' => 100, - ], + 'width' => 100, + 'height' => 50, ], - ]; - } + ], [ + 'assets/thumb-test-relative.twig', + [ + 'width' => 50, + 'height' => 100, + ], + ], + ]; } +} diff --git a/tests/test-timber-image-multisite.php b/tests/test-timber-image-multisite.php index 2350e9e04..74d81fd68 100644 --- a/tests/test-timber-image-multisite.php +++ b/tests/test-timber-image-multisite.php @@ -1,39 +1,39 @@ markTestSkipped('Test is only for Multisite'); - return; - } - $blog_id = TestTimberMultisite::createSubDomainSite(); - $this->assertGreaterThan(1, $blog_id); - $pretend_image = 'http://example.org/wp-content/2015/08/fake-pic.jpg'; - $is_external = Timber\URLHelper::is_external_content($pretend_image); - $this->assertFalse($is_external); + public function testSubDomainImageLocaion() + { + if (!is_multisite()) { + $this->markTestSkipped('Test is only for Multisite'); + return; } + $blog_id = TestTimberMultisite::createSubDomainSite(); + $this->assertGreaterThan(1, $blog_id); + $pretend_image = 'http://example.org/wp-content/2015/08/fake-pic.jpg'; + $is_external = Timber\URLHelper::is_external_content($pretend_image); + $this->assertFalse($is_external); + } - public function testSubDirectoryImageLocaion() - { - if (!is_multisite()) { - $this->markTestSkipped('Test is only for Multisite'); - return; - } - $blog_id = TestTimberMultisite::createSubDirectorySite(); - $this->assertGreaterThan(1, $blog_id); - $blog_details = get_blog_details($blog_id); - $pretend_image = 'http://example.org/wp-content/2015/08/fake-pic.jpg'; - $is_external = Timber\URLHelper::is_external_content($pretend_image); - $this->assertFalse($is_external); + public function testSubDirectoryImageLocaion() + { + if (!is_multisite()) { + $this->markTestSkipped('Test is only for Multisite'); + return; } + $blog_id = TestTimberMultisite::createSubDirectorySite(); + $this->assertGreaterThan(1, $blog_id); + $blog_details = get_blog_details($blog_id); + $pretend_image = 'http://example.org/wp-content/2015/08/fake-pic.jpg'; + $is_external = Timber\URLHelper::is_external_content($pretend_image); + $this->assertFalse($is_external); } +} diff --git a/tests/test-timber-image-path-helper.php b/tests/test-timber-image-path-helper.php index 75794964a..0ce9ca54d 100644 --- a/tests/test-timber-image-path-helper.php +++ b/tests/test-timber-image-path-helper.php @@ -1,48 +1,48 @@ addFile($location_of_image); - $this->assertTrue(TestTimberImage::checkSize($location_of_image, 500, 500)); - //whats the bg/color of the image - $this->assertTrue(TestTimberImage::checkPixel($location_of_image, 1, 1, "#CCC")); - } + $hebrew = self::copyTestAttachment('hebrew.jpg', 'איתין-נוף-נוסף.jpg'); + $upload_dir = wp_upload_dir(); + $image = $upload_dir['url'] . '/איתין-נוף-נוסף.jpg'; + $new_file = Timber\ImageHelper::letterbox($image, 500, 500, '#CCC', true); + $location_of_image = Timber\ImageHelper::get_server_location($new_file); + $this->addFile($location_of_image); + $this->assertTrue(TestTimberImage::checkSize($location_of_image, 500, 500)); + //whats the bg/color of the image + $this->assertTrue(TestTimberImage::checkPixel($location_of_image, 1, 1, "#CCC")); + } - public function testImagePathStartsWithSpecialChar() - { - require_once('wp-overrides.php'); - $filename = self::copyTestAttachment('robocop.jpg', '©Robocop.jpg'); - $filesize = filesize($filename); - $data = [ - 'tmp_name' => $filename, - 'name' => '©Robocop.jpg', - 'type' => 'image/jpg', - 'size' => $filesize, - 'error' => 0, - ]; - $this->assertTrue(file_exists($filename)); - $_FILES['tester'] = $data; - $file_id = WP_Overrides::media_handle_upload('tester', 0, [], [ - 'test_form' => false, - ]); - if (!is_int($file_id)) { - error_log(print_r($file_id, true)); - } - $image = Timber::get_post($file_id); - $str = ''; - $result = Timber::compile_string($str, [ - 'image' => $image, - ]); - $upload_dir = wp_upload_dir(); - $this->assertEquals('', trim($result)); + public function testImagePathStartsWithSpecialChar() + { + require_once('wp-overrides.php'); + $filename = self::copyTestAttachment('robocop.jpg', '©Robocop.jpg'); + $filesize = filesize($filename); + $data = [ + 'tmp_name' => $filename, + 'name' => '©Robocop.jpg', + 'type' => 'image/jpg', + 'size' => $filesize, + 'error' => 0, + ]; + $this->assertTrue(file_exists($filename)); + $_FILES['tester'] = $data; + $file_id = WP_Overrides::media_handle_upload('tester', 0, [], [ + 'test_form' => false, + ]); + if (!is_int($file_id)) { + error_log(print_r($file_id, true)); } + $image = Timber::get_post($file_id); + $str = ''; + $result = Timber::compile_string($str, [ + 'image' => $image, + ]); + $upload_dir = wp_upload_dir(); + $this->assertEquals('', trim($result)); } +} diff --git a/tests/test-timber-image-tojpg.php b/tests/test-timber-image-tojpg.php index 64fc7fe55..8fbf9c05e 100644 --- a/tests/test-timber-image-tojpg.php +++ b/tests/test-timber-image-tojpg.php @@ -1,97 +1,97 @@ $filename, - ]); - $this->assertEquals($filename, $str); - unlink($filename); - } + /** + * This should fail silently as opposed to throwing an exception + * see #1383 and #1192 + */ + public function testTIFtoJPG() + { + $filename = TestTimberImage::copyTestAttachment('white-castle.tif'); + $str = Timber::compile_string('{{file|tojpg}}', [ + 'file' => $filename, + ]); + $this->assertEquals($filename, $str); + unlink($filename); + } - public function testPNGtoJPG() - { - $filename = TestTimberImage::copyTestAttachment('flag.png'); - $str = Timber::compile_string('{{file|tojpg}}', [ - 'file' => $filename, - ]); - $renamed = str_replace('.png', '.jpg', $filename); - $this->assertFileExists($renamed); - $this->assertGreaterThan(1000, filesize($renamed)); - $this->assertEquals('image/png', mime_content_type($filename)); - $this->assertEquals('image/jpeg', mime_content_type($renamed)); - unlink($filename); - unlink($renamed); - } + public function testPNGtoJPG() + { + $filename = TestTimberImage::copyTestAttachment('flag.png'); + $str = Timber::compile_string('{{file|tojpg}}', [ + 'file' => $filename, + ]); + $renamed = str_replace('.png', '.jpg', $filename); + $this->assertFileExists($renamed); + $this->assertGreaterThan(1000, filesize($renamed)); + $this->assertEquals('image/png', mime_content_type($filename)); + $this->assertEquals('image/jpeg', mime_content_type($renamed)); + unlink($filename); + unlink($renamed); + } - public function testGIFtoJPG() - { - $filename = TestTimberImage::copyTestAttachment('boyer.gif'); - $str = Timber::compile_string('{{file|tojpg}}', [ - 'file' => $filename, - ]); - $renamed = str_replace('.gif', '.jpg', $filename); - $this->assertFileExists($renamed); - $this->assertGreaterThan(1000, filesize($renamed)); - $this->assertEquals('image/gif', mime_content_type($filename)); - $this->assertEquals('image/jpeg', mime_content_type($renamed)); - unlink($filename); - unlink($renamed); - } + public function testGIFtoJPG() + { + $filename = TestTimberImage::copyTestAttachment('boyer.gif'); + $str = Timber::compile_string('{{file|tojpg}}', [ + 'file' => $filename, + ]); + $renamed = str_replace('.gif', '.jpg', $filename); + $this->assertFileExists($renamed); + $this->assertGreaterThan(1000, filesize($renamed)); + $this->assertEquals('image/gif', mime_content_type($filename)); + $this->assertEquals('image/jpeg', mime_content_type($renamed)); + unlink($filename); + unlink($renamed); + } - public function testJPGtoJPG() - { - $filename = TestTimberImage::copyTestAttachment('stl.jpg'); - $original_size = filesize($filename); - $str = Timber::compile_string('{{file|tojpg}}', [ - 'file' => $filename, - ]); - $new_size = filesize($filename); - $this->assertEquals($original_size, $new_size); - $this->assertEquals('image/jpeg', mime_content_type($filename)); - unlink($filename); - } + public function testJPGtoJPG() + { + $filename = TestTimberImage::copyTestAttachment('stl.jpg'); + $original_size = filesize($filename); + $str = Timber::compile_string('{{file|tojpg}}', [ + 'file' => $filename, + ]); + $new_size = filesize($filename); + $this->assertEquals($original_size, $new_size); + $this->assertEquals('image/jpeg', mime_content_type($filename)); + unlink($filename); + } - public function testJPEGtoJPG() - { - $filename = TestTimberImage::copyTestAttachment('jarednova.jpeg'); - $str = Timber::compile_string('{{file|tojpg}}', [ - 'file' => $filename, - ]); - $renamed = str_replace('.jpeg', '.jpg', $filename); - $this->assertFileExists($renamed); - $this->assertGreaterThan(1000, filesize($renamed)); - $this->assertEquals('image/jpeg', mime_content_type($filename)); - $this->assertEquals('image/jpeg', mime_content_type($renamed)); - unlink($filename); - unlink($renamed); - } + public function testJPEGtoJPG() + { + $filename = TestTimberImage::copyTestAttachment('jarednova.jpeg'); + $str = Timber::compile_string('{{file|tojpg}}', [ + 'file' => $filename, + ]); + $renamed = str_replace('.jpeg', '.jpg', $filename); + $this->assertFileExists($renamed); + $this->assertGreaterThan(1000, filesize($renamed)); + $this->assertEquals('image/jpeg', mime_content_type($filename)); + $this->assertEquals('image/jpeg', mime_content_type($renamed)); + unlink($filename); + unlink($renamed); + } - public function testSideloadedPNGToJPG() - { - $url = 'https://user-images.githubusercontent.com/2084481/31230351-116569a8-a9e4-11e7-8310-48b7f679892b.png'; - $sideloaded = Timber::compile_string('{{ file|tojpg }}', [ - 'file' => $url, - ]); + public function testSideloadedPNGToJPG() + { + $url = 'https://user-images.githubusercontent.com/2084481/31230351-116569a8-a9e4-11e7-8310-48b7f679892b.png'; + $sideloaded = Timber::compile_string('{{ file|tojpg }}', [ + 'file' => $url, + ]); - $base_url = str_replace(basename($sideloaded), '', $sideloaded); - $expected = $base_url . md5($url) . '.jpg'; + $base_url = str_replace(basename($sideloaded), '', $sideloaded); + $expected = $base_url . md5($url) . '.jpg'; - $this->assertEquals($expected, $sideloaded); - } + $this->assertEquals($expected, $sideloaded); } +} diff --git a/tests/test-timber-image-towebp.php b/tests/test-timber-image-towebp.php index 282f8ba52..f127ab6af 100644 --- a/tests/test-timber-image-towebp.php +++ b/tests/test-timber-image-towebp.php @@ -1,111 +1,111 @@ $filename, - ]); - $this->assertEquals($filename, $str); - } + public function testTIFtoWEBP() + { + $filename = TestTimberImage::copyTestAttachment('white-castle.tif'); + $str = Timber::compile_string('{{file|towebp}}', [ + 'file' => $filename, + ]); + $this->assertEquals($filename, $str); + } - public function testPNGtoWEBP() - { - $filename = TestTimberImage::copyTestAttachment('flag.png'); - $str = Timber::compile_string('{{file|towebp}}', [ - 'file' => $filename, - ]); - $renamed = str_replace('.png', '.webp', $filename); - $this->assertFileExists($renamed); - $this->assertGreaterThan(1000, filesize($renamed)); - $this->assertEquals('image/png', mime_content_type($filename)); - $this->assertEquals('image/webp', mime_content_type($renamed)); - } + public function testPNGtoWEBP() + { + $filename = TestTimberImage::copyTestAttachment('flag.png'); + $str = Timber::compile_string('{{file|towebp}}', [ + 'file' => $filename, + ]); + $renamed = str_replace('.png', '.webp', $filename); + $this->assertFileExists($renamed); + $this->assertGreaterThan(1000, filesize($renamed)); + $this->assertEquals('image/png', mime_content_type($filename)); + $this->assertEquals('image/webp', mime_content_type($renamed)); + } - public function testGIFtoJPG() - { - $filename = TestTimberImage::copyTestAttachment('boyer.gif'); - $str = Timber::compile_string('{{file|towebp}}', [ - 'file' => $filename, - ]); - $renamed = str_replace('.gif', '.webp', $filename); - $this->assertFileExists($renamed); - $this->assertGreaterThan(1000, filesize($renamed)); - $this->assertEquals('image/gif', mime_content_type($filename)); - $this->assertEquals('image/webp', mime_content_type($renamed)); - } + public function testGIFtoJPG() + { + $filename = TestTimberImage::copyTestAttachment('boyer.gif'); + $str = Timber::compile_string('{{file|towebp}}', [ + 'file' => $filename, + ]); + $renamed = str_replace('.gif', '.webp', $filename); + $this->assertFileExists($renamed); + $this->assertGreaterThan(1000, filesize($renamed)); + $this->assertEquals('image/gif', mime_content_type($filename)); + $this->assertEquals('image/webp', mime_content_type($renamed)); + } - public function testJPGtoWEBP() - { - $filename = TestTimberImage::copyTestAttachment('stl.jpg'); - $original_size = filesize($filename); - $str = Timber::compile_string('{{file|towebp(100)}}', [ - 'file' => $filename, - ]); - $renamed = str_replace('.jpg', '.webp', $filename); - $this->assertGreaterThan(1000, filesize($renamed)); - $this->assertEquals('image/jpeg', mime_content_type($filename)); - $this->assertEquals('image/webp', mime_content_type($renamed)); - } + public function testJPGtoWEBP() + { + $filename = TestTimberImage::copyTestAttachment('stl.jpg'); + $original_size = filesize($filename); + $str = Timber::compile_string('{{file|towebp(100)}}', [ + 'file' => $filename, + ]); + $renamed = str_replace('.jpg', '.webp', $filename); + $this->assertGreaterThan(1000, filesize($renamed)); + $this->assertEquals('image/jpeg', mime_content_type($filename)); + $this->assertEquals('image/webp', mime_content_type($renamed)); + } - public function testJPEGtoJPG() - { - $filename = TestTimberImage::copyTestAttachment('jarednova.jpeg'); - $str = Timber::compile_string('{{file|towebp}}', [ - 'file' => $filename, - ]); - $renamed = str_replace('.jpeg', '.webp', $filename); - $this->assertFileExists($renamed); - $this->assertGreaterThan(1000, filesize($renamed)); - $this->assertEquals('image/jpeg', mime_content_type($filename)); - $this->assertEquals('image/webp', mime_content_type($renamed)); - } + public function testJPEGtoJPG() + { + $filename = TestTimberImage::copyTestAttachment('jarednova.jpeg'); + $str = Timber::compile_string('{{file|towebp}}', [ + 'file' => $filename, + ]); + $renamed = str_replace('.jpeg', '.webp', $filename); + $this->assertFileExists($renamed); + $this->assertGreaterThan(1000, filesize($renamed)); + $this->assertEquals('image/jpeg', mime_content_type($filename)); + $this->assertEquals('image/webp', mime_content_type($renamed)); + } - public function testWEBPtoWEBP() - { - $filename = TestTimberImage::copyTestAttachment('mountains.webp'); - $original_size = filesize($filename); - $str = Timber::compile_string('{{file|towebp}}', [ - 'file' => $filename, - ]); - $new_size = filesize($filename); - $this->assertEquals($original_size, $new_size); - $this->assertEquals('image/webp', mime_content_type($filename)); - } + public function testWEBPtoWEBP() + { + $filename = TestTimberImage::copyTestAttachment('mountains.webp'); + $original_size = filesize($filename); + $str = Timber::compile_string('{{file|towebp}}', [ + 'file' => $filename, + ]); + $new_size = filesize($filename); + $this->assertEquals($original_size, $new_size); + $this->assertEquals('image/webp', mime_content_type($filename)); + } - public function testSideloadedJPGToWEBP() - { - $url = 'https://pbs.twimg.com/profile_images/768086933310476288/acGwPDj4_400x400.jpg'; - $sideloaded = Timber::compile_string('{{ file|towebp }}', [ - 'file' => $url, - ]); + public function testSideloadedJPGToWEBP() + { + $url = 'https://pbs.twimg.com/profile_images/768086933310476288/acGwPDj4_400x400.jpg'; + $sideloaded = Timber::compile_string('{{ file|towebp }}', [ + 'file' => $url, + ]); - $base_url = str_replace(basename($sideloaded), '', $sideloaded); - $expected = $base_url . md5($url) . '.webp'; + $base_url = str_replace(basename($sideloaded), '', $sideloaded); + $expected = $base_url . md5($url) . '.webp'; - $this->assertEquals($expected, $sideloaded); - } + $this->assertEquals($expected, $sideloaded); + } - public function testSideloadedPNGToWEBP() - { - $url = 'https://user-images.githubusercontent.com/2084481/31230351-116569a8-a9e4-11e7-8310-48b7f679892b.png'; - $sideloaded = Timber::compile_string('{{ file|towebp }}', [ - 'file' => $url, - ]); + public function testSideloadedPNGToWEBP() + { + $url = 'https://user-images.githubusercontent.com/2084481/31230351-116569a8-a9e4-11e7-8310-48b7f679892b.png'; + $sideloaded = Timber::compile_string('{{ file|towebp }}', [ + 'file' => $url, + ]); - $base_url = str_replace(basename($sideloaded), '', $sideloaded); - $expected = $base_url . md5($url) . '.webp'; + $base_url = str_replace(basename($sideloaded), '', $sideloaded); + $expected = $base_url . md5($url) . '.webp'; - $this->assertEquals($expected, $sideloaded); - } + $this->assertEquals($expected, $sideloaded); } +} diff --git a/tests/test-timber-image.php b/tests/test-timber-image.php index cc3dde6df..7cc8de9d0 100644 --- a/tests/test-timber-image.php +++ b/tests/test-timber-image.php @@ -547,7 +547,7 @@ public static function checkPixel($file, $x, $y, $color = false, $upper_color = if (self::checkChannel('red', $test_colors, $colors_of_file, $upper_colors) && self::checkChannel('green', $test_colors, $colors_of_file, $upper_colors) && self::checkChannel('blue', $test_colors, $colors_of_file, $upper_colors) - ) { + ) { return true; } return false; diff --git a/tests/test-timber-integrations-coauthors.php b/tests/test-timber-integrations-coauthors.php index faac8d8b7..d757cd565 100644 --- a/tests/test-timber-integrations-coauthors.php +++ b/tests/test-timber-integrations-coauthors.php @@ -2,236 +2,236 @@ use Timber\Integration\CoAuthorsPlus\CoAuthorsPlusUser; +/** + * @group posts-api + * @group integrations + */ +class TestTimberIntegrationsCoAuthors extends Timber_UnitTestCase +{ /** - * @group posts-api - * @group integrations + * Overload WP_UnitTestcase to ignore deprecated notices + * thrown by use of wp_title() in Timber */ - class TestTimberIntegrationsCoAuthors extends Timber_UnitTestCase + public function expectedDeprecated() { - /** - * Overload WP_UnitTestcase to ignore deprecated notices - * thrown by use of wp_title() in Timber - */ - public function expectedDeprecated() - { - if (false !== ($key = array_search('WP_User->id', $this->caught_deprecated))) { - unset($this->caught_deprecated[$key]); - } - parent::expectedDeprecated(); + if (false !== ($key = array_search('WP_User->id', $this->caught_deprecated))) { + unset($this->caught_deprecated[$key]); } + parent::expectedDeprecated(); + } - public function set_up() - { - if (!class_exists('CoAuthors_Plus')) { - return $this->markTestSkipped('CoAuthors_Plus plugin not loaded'); - } - parent::set_up(); + public function set_up() + { + if (!class_exists('CoAuthors_Plus')) { + return $this->markTestSkipped('CoAuthors_Plus plugin not loaded'); } + parent::set_up(); + } - /* ---------------- - * Helper functions - ---------------- */ + /* ---------------- + * Helper functions + ---------------- */ - public static function create_guest_author($args) - { - $cap = new CoAuthors_Guest_Authors(); - $guest_id = $cap->create($args); + public static function create_guest_author($args) + { + $cap = new CoAuthors_Guest_Authors(); + $guest_id = $cap->create($args); - return $guest_id; - } + return $guest_id; + } - public static function attach_featured_image($guest_id, $thumb) - { - $filename = self::copyTestImage($thumb); - $wp_filetype = wp_check_filetype(basename($filename), null); - $attachment = [ - 'post_mime_type' => $wp_filetype['type'], - 'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)), - 'post_excerpt' => '', - 'post_status' => 'inherit', - ]; - $attach_id = wp_insert_attachment($attachment, $filename, $guest_id); - add_post_meta($guest_id, '_thumbnail_id', $attach_id, true); - return $attach_id; - } + public static function attach_featured_image($guest_id, $thumb) + { + $filename = self::copyTestImage($thumb); + $wp_filetype = wp_check_filetype(basename($filename), null); + $attachment = [ + 'post_mime_type' => $wp_filetype['type'], + 'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)), + 'post_excerpt' => '', + 'post_status' => 'inherit', + ]; + $attach_id = wp_insert_attachment($attachment, $filename, $guest_id); + add_post_meta($guest_id, '_thumbnail_id', $attach_id, true); + return $attach_id; + } - public static function copyTestImage($img = 'avt-1.jpg', $dest_name = null) - { - $upload_dir = wp_upload_dir(); - if (is_null($dest_name)) { - $dest_name = $img; - } - $destination = $upload_dir['path'] . '/' . $dest_name; - copy(__DIR__ . '/assets/' . $img, $destination); - return $destination; - } - /* ---------------- - * Tests - ---------------- */ - - public function testAuthors() - { - $uid = $this->factory->user->create([ - 'display_name' => 'Jen Weinman', - 'user_login' => 'aquajenus', - ]); - $pid = $this->factory->post->create([ - 'post_author' => $uid, - ]); - $post = Timber::get_post($pid); - $template_string = '{% for author in post.authors %}{{author.name}}{% endfor %}'; - $str = Timber::compile_string($template_string, [ - 'post' => $post, - ]); - $this->assertEquals('Jen Weinman', $str); + public static function copyTestImage($img = 'avt-1.jpg', $dest_name = null) + { + $upload_dir = wp_upload_dir(); + if (is_null($dest_name)) { + $dest_name = $img; } + $destination = $upload_dir['path'] . '/' . $dest_name; + copy(__DIR__ . '/assets/' . $img, $destination); + return $destination; + } + /* ---------------- + * Tests + ---------------- */ - public function testGuestAuthor() - { - $pid = $this->factory->post->create(); - $post = Timber::get_post($pid); - - $user_login = 'bmotia'; - $display_name = 'Motia'; - $guest_id = self::create_guest_author( - [ - 'user_login' => $user_login, - 'display_name' => $display_name, - ] - ); - - global $coauthors_plus; - $coauthors_plus->add_coauthors($pid, [$user_login]); - - $authors = $post->authors(); - $author = $authors[0]; - $this->assertEquals($display_name, $author->display_name); - $this->assertInstanceOf(CoAuthorsPlusUser::class, $author); - } + public function testAuthors() + { + $uid = $this->factory->user->create([ + 'display_name' => 'Jen Weinman', + 'user_login' => 'aquajenus', + ]); + $pid = $this->factory->post->create([ + 'post_author' => $uid, + ]); + $post = Timber::get_post($pid); + $template_string = '{% for author in post.authors %}{{author.name}}{% endfor %}'; + $str = Timber::compile_string($template_string, [ + 'post' => $post, + ]); + $this->assertEquals('Jen Weinman', $str); + } - public function testGuestAuthorWithRegularAuthor() - { - $uid = $this->factory->user->create([ - 'display_name' => 'Alexander Hamilton', - 'user_login' => 'ahamilton', - ]); - $pid = $this->factory->post->create([ - 'post_author' => $uid, - ]); - $post = Timber::get_post($pid); - - $user_login = 'bmotia'; - $display_name = 'Motia'; - $guest_id = self::create_guest_author( - [ - 'user_login' => $user_login, - 'display_name' => $display_name, - ] - ); - - global $coauthors_plus; - $coauthors_plus->add_coauthors($pid, ['ahamilton', $user_login]); - - $authors = $post->authors(); - $author = $authors[1]; - $this->assertEquals($display_name, $author->display_name); - $this->assertInstanceOf(CoAuthorsPlusUser::class, $author); - $template_string = '{% for author in post.authors %}{{author.name}}, {% endfor %}'; - $str = Timber::compile_string($template_string, [ - 'post' => $post, - ]); - $this->assertEquals('Alexander Hamilton, Motia,', trim($str)); - } + public function testGuestAuthor() + { + $pid = $this->factory->post->create(); + $post = Timber::get_post($pid); - /** - * Co-Authors originally created as guests can be linked to a real WordPress user account. In these instances, we want to use the linked account's information - */ - public function testLinkedGuestAuthor() - { - global $coauthors_plus; + $user_login = 'bmotia'; + $display_name = 'Motia'; + $guest_id = self::create_guest_author( + [ + 'user_login' => $user_login, + 'display_name' => $display_name, + ] + ); - $pid = $this->factory->post->create(); - $post = Timber::get_post($pid); + global $coauthors_plus; + $coauthors_plus->add_coauthors($pid, [$user_login]); - $user_login = 'truelogin'; - $display_name = 'True Name'; + $authors = $post->authors(); + $author = $authors[0]; + $this->assertEquals($display_name, $author->display_name); + $this->assertInstanceOf(CoAuthorsPlusUser::class, $author); + } - $uid = $this->factory->user->create([ - 'display_name' => $display_name, + public function testGuestAuthorWithRegularAuthor() + { + $uid = $this->factory->user->create([ + 'display_name' => 'Alexander Hamilton', + 'user_login' => 'ahamilton', + ]); + $pid = $this->factory->post->create([ + 'post_author' => $uid, + ]); + $post = Timber::get_post($pid); + + $user_login = 'bmotia'; + $display_name = 'Motia'; + $guest_id = self::create_guest_author( + [ 'user_login' => $user_login, - ]); - $user = Timber::get_user($uid); - - $guest_login = 'linkguestlogin'; - $guest_display_name = 'LGuest D Name'; - $guest_id = self::create_guest_author( - [ - 'user_login' => $guest_login, - 'display_name' => $guest_display_name, - ] - ); - add_post_meta($guest_id, 'cap-linked_account', $user_login, true); - - $coauthors_plus->add_coauthors($pid, [$user_login]); - - $coauthors_plus->force_guest_authors = false; - $authors = $post->authors(); - - /** - * Here we're testing to see if we get the LINKED guest author account ("Mr. True Name") - * instead of the temporary guest name ("LGuest D Name") that was created. - */ - $author = $authors[0]; - $this->assertEquals("True Name", $author->name()); - $this->assertInstanceOf('Timber\User', $author); - $this->assertInstanceOf(CoAuthorsPlusUser::class, $author); - - /** - * Here we're testing that when we FORCE guest authors, it uses the original guest author - * account ("LGuest D Name") when reporting the user's name. - */ - $coauthors_plus->force_guest_authors = true; - $authors = $post->authors(); - $author = $authors[0]; - $this->assertEquals($guest_display_name, $author->name()); - $this->assertInstanceOf('Timber\User', $author); - $this->assertInstanceOf(CoAuthorsPlusUser::class, $author); - } + 'display_name' => $display_name, + ] + ); + + global $coauthors_plus; + $coauthors_plus->add_coauthors($pid, ['ahamilton', $user_login]); + + $authors = $post->authors(); + $author = $authors[1]; + $this->assertEquals($display_name, $author->display_name); + $this->assertInstanceOf(CoAuthorsPlusUser::class, $author); + $template_string = '{% for author in post.authors %}{{author.name}}, {% endfor %}'; + $str = Timber::compile_string($template_string, [ + 'post' => $post, + ]); + $this->assertEquals('Alexander Hamilton, Motia,', trim($str)); + } + + /** + * Co-Authors originally created as guests can be linked to a real WordPress user account. In these instances, we want to use the linked account's information + */ + public function testLinkedGuestAuthor() + { + global $coauthors_plus; + + $pid = $this->factory->post->create(); + $post = Timber::get_post($pid); + + $user_login = 'truelogin'; + $display_name = 'True Name'; + + $uid = $this->factory->user->create([ + 'display_name' => $display_name, + 'user_login' => $user_login, + ]); + $user = Timber::get_user($uid); + + $guest_login = 'linkguestlogin'; + $guest_display_name = 'LGuest D Name'; + $guest_id = self::create_guest_author( + [ + 'user_login' => $guest_login, + 'display_name' => $guest_display_name, + ] + ); + add_post_meta($guest_id, 'cap-linked_account', $user_login, true); + + $coauthors_plus->add_coauthors($pid, [$user_login]); + + $coauthors_plus->force_guest_authors = false; + $authors = $post->authors(); /** - * @group attachments + * Here we're testing to see if we get the LINKED guest author account ("Mr. True Name") + * instead of the temporary guest name ("LGuest D Name") that was created. */ - public function testGuestAuthorAvatar() - { - $pid = $this->factory->post->create(); - $post = Timber::get_post($pid); - $user_login = 'withfeaturedimage'; - $display_name = 'Have Featured'; - $email = 'admin@admin.com'; - $guest_id = self::create_guest_author( - [ - 'user_email' => $email, - 'user_login' => $user_login, - 'display_name' => $display_name, - ] - ); - $attach_id = self::attach_featured_image($guest_id, 'avt-1.jpg'); - $image = Timber::get_post($attach_id); - - global $coauthors_plus; - $coauthors_plus->add_coauthors($pid, [$user_login]); - - // NOTE: this used to be `{{author.avatar.src}}` but now avatar() just returns a string - $template_string = '{% for author in post.authors %}{{author.avatar}}{% endfor %}'; - $str1 = Timber::compile_string($template_string, [ - 'post' => $post, - ]); - $this->assertEquals($image->src(), $str1); - - add_filter('timber/co_authors_plus/prefer_gravatar', '__return_true'); - $str2 = Timber::compile_string($template_string, [ - 'post' => $post, - ]); - $this->assertEquals(get_avatar_url($email), $str2); - } + $author = $authors[0]; + $this->assertEquals("True Name", $author->name()); + $this->assertInstanceOf('Timber\User', $author); + $this->assertInstanceOf(CoAuthorsPlusUser::class, $author); + + /** + * Here we're testing that when we FORCE guest authors, it uses the original guest author + * account ("LGuest D Name") when reporting the user's name. + */ + $coauthors_plus->force_guest_authors = true; + $authors = $post->authors(); + $author = $authors[0]; + $this->assertEquals($guest_display_name, $author->name()); + $this->assertInstanceOf('Timber\User', $author); + $this->assertInstanceOf(CoAuthorsPlusUser::class, $author); + } + + /** + * @group attachments + */ + public function testGuestAuthorAvatar() + { + $pid = $this->factory->post->create(); + $post = Timber::get_post($pid); + $user_login = 'withfeaturedimage'; + $display_name = 'Have Featured'; + $email = 'admin@admin.com'; + $guest_id = self::create_guest_author( + [ + 'user_email' => $email, + 'user_login' => $user_login, + 'display_name' => $display_name, + ] + ); + $attach_id = self::attach_featured_image($guest_id, 'avt-1.jpg'); + $image = Timber::get_post($attach_id); + + global $coauthors_plus; + $coauthors_plus->add_coauthors($pid, [$user_login]); + + // NOTE: this used to be `{{author.avatar.src}}` but now avatar() just returns a string + $template_string = '{% for author in post.authors %}{{author.avatar}}{% endfor %}'; + $str1 = Timber::compile_string($template_string, [ + 'post' => $post, + ]); + $this->assertEquals($image->src(), $str1); + + add_filter('timber/co_authors_plus/prefer_gravatar', '__return_true'); + $str2 = Timber::compile_string($template_string, [ + 'post' => $post, + ]); + $this->assertEquals(get_avatar_url($email), $str2); } +} diff --git a/tests/test-timber-loader.php b/tests/test-timber-loader.php index 0de242da8..31bd3dd78 100644 --- a/tests/test-timber-loader.php +++ b/tests/test-timber-loader.php @@ -1,307 +1,307 @@ assertInstanceOf('Twig\Loader\LoaderInterface', $loader); - return $loader; - }); - $str = Timber::compile('assets/single.twig', []); - } + $php_unit = $this; + add_filter('timber/loader/loader', function ($loader) use ($php_unit) { + $php_unit->assertInstanceOf('Twig\Loader\LoaderInterface', $loader); + return $loader; + }); + $str = Timber::compile('assets/single.twig', []); + } - public function testBogusTemplate() - { - $str = Timber::compile('assets/darkhelmet.twig'); - $this->assertFalse($str); - } + public function testBogusTemplate() + { + $str = Timber::compile('assets/darkhelmet.twig'); + $this->assertFalse($str); + } - public function testBogusTemplates() - { - $str = Timber::compile(['assets/barf.twig', 'assets/lonestar.twig']); - $this->assertFalse($str); - } + public function testBogusTemplates() + { + $str = Timber::compile(['assets/barf.twig', 'assets/lonestar.twig']); + $this->assertFalse($str); + } - public function testTemplateChainWithMissingTwigFiles() - { - $str = Timber::compile(['assets/lonestar.twig', 'assets/single.twig']); - $this->assertEquals('I am single.twig', trim($str)); - } + public function testTemplateChainWithMissingTwigFiles() + { + $str = Timber::compile(['assets/lonestar.twig', 'assets/single.twig']); + $this->assertEquals('I am single.twig', trim($str)); + } - public function testWhitespaceTrimForTemplate() - { - $str = Timber::compile('assets/single.twig ', []); - $this->assertEquals('I am single.twig', trim($str)); - } + public function testWhitespaceTrimForTemplate() + { + $str = Timber::compile('assets/single.twig ', []); + $this->assertEquals('I am single.twig', trim($str)); + } - /** - * @expectedDeprecated timber/loader/paths - * @expectedDeprecated add_filter( 'timber/loader/paths', ['path/to/my/templates'] ) in a non-associative array - */ - public function testTwigPathFilterAdded() - { - $php_unit = $this; - add_filter('timber/loader/paths', function ($paths) use ($php_unit) { - $paths[] = __DIR__ . '/october/'; - return $paths; - }); - $str = Timber::compile('spooky.twig', []); - $this->assertEquals('Boo!', $str); - } + /** + * @expectedDeprecated timber/loader/paths + * @expectedDeprecated add_filter( 'timber/loader/paths', ['path/to/my/templates'] ) in a non-associative array + */ + public function testTwigPathFilterAdded() + { + $php_unit = $this; + add_filter('timber/loader/paths', function ($paths) use ($php_unit) { + $paths[] = __DIR__ . '/october/'; + return $paths; + }); + $str = Timber::compile('spooky.twig', []); + $this->assertEquals('Boo!', $str); + } - /** - * @expectedDeprecated timber/loader/paths - */ - public function testUpdatedTwigPathFilterAdded() - { - $php_unit = $this; - add_filter('timber/loader/paths', function ($paths) use ($php_unit) { - $paths[] = [__DIR__ . '/october/']; - return $paths; - }); - $str = Timber::compile('spooky.twig', []); - $this->assertEquals('Boo!', $str); - } + /** + * @expectedDeprecated timber/loader/paths + */ + public function testUpdatedTwigPathFilterAdded() + { + $php_unit = $this; + add_filter('timber/loader/paths', function ($paths) use ($php_unit) { + $paths[] = [__DIR__ . '/october/']; + return $paths; + }); + $str = Timber::compile('spooky.twig', []); + $this->assertEquals('Boo!', $str); + } - /** - * @expectedDeprecated timber/loader/paths - * @expectedDeprecated add_filter( 'timber/loader/paths', ['path/to/my/templates'] ) in a non-associative array - */ - public function testTwigPathFilter() - { - $php_unit = $this; - add_filter('timber/loader/paths', function ($paths) use ($php_unit) { - $paths = call_user_func_array('array_merge', array_values($paths)); - $count = count($paths); - $php_unit->assertEquals(3, count($paths)); - $pos = array_search('/', $paths); - unset($paths[$pos]); - $php_unit->assertEquals(2, count($paths)); - return $paths; - }); - $str = Timber::compile('assets/single.twig', []); - } + /** + * @expectedDeprecated timber/loader/paths + * @expectedDeprecated add_filter( 'timber/loader/paths', ['path/to/my/templates'] ) in a non-associative array + */ + public function testTwigPathFilter() + { + $php_unit = $this; + add_filter('timber/loader/paths', function ($paths) use ($php_unit) { + $paths = call_user_func_array('array_merge', array_values($paths)); + $count = count($paths); + $php_unit->assertEquals(3, count($paths)); + $pos = array_search('/', $paths); + unset($paths[$pos]); + $php_unit->assertEquals(2, count($paths)); + return $paths; + }); + $str = Timber::compile('assets/single.twig', []); + } - public function testTimberLocationsFilterAdded() - { - $php_unit = $this; - add_filter('timber/locations', function ($paths) use ($php_unit) { - $paths[] = [__DIR__ . '/october/']; - return $paths; - }); - $str = Timber::compile('spooky.twig', []); - $this->assertEquals('Boo!', $str); - } + public function testTimberLocationsFilterAdded() + { + $php_unit = $this; + add_filter('timber/locations', function ($paths) use ($php_unit) { + $paths[] = [__DIR__ . '/october/']; + return $paths; + }); + $str = Timber::compile('spooky.twig', []); + $this->assertEquals('Boo!', $str); + } - public function testTwigLoadsFromChildTheme() - { - $this->_setupParentTheme(); - $this->_setupChildTheme(); - $this->assertFileExists(WP_CONTENT_DIR . '/themes/fake-child-theme/style.css'); - switch_theme('fake-child-theme'); - $child_theme = get_stylesheet_directory_uri(); - $this->assertEquals(WP_CONTENT_URL . '/themes/fake-child-theme', $child_theme); - $context = []; - $str = Timber::compile('single.twig', $context); - $this->assertEquals('I am single.twig', trim($str)); - } + public function testTwigLoadsFromChildTheme() + { + $this->_setupParentTheme(); + $this->_setupChildTheme(); + $this->assertFileExists(WP_CONTENT_DIR . '/themes/fake-child-theme/style.css'); + switch_theme('fake-child-theme'); + $child_theme = get_stylesheet_directory_uri(); + $this->assertEquals(WP_CONTENT_URL . '/themes/fake-child-theme', $child_theme); + $context = []; + $str = Timber::compile('single.twig', $context); + $this->assertEquals('I am single.twig', trim($str)); + } - public static function _setupChildTheme() - { - $dest_dir = WP_CONTENT_DIR . '/themes/fake-child-theme'; - if (!file_exists($dest_dir)) { - mkdir($dest_dir, 0777, true); - } - if (!file_exists($dest_dir . '/views')) { - mkdir($dest_dir . '/views', 0777, true); - } - copy(__DIR__ . '/assets/style.css', $dest_dir . '/style.css'); - copy(__DIR__ . '/assets/single.twig', $dest_dir . '/views/single.twig'); + public static function _setupChildTheme() + { + $dest_dir = WP_CONTENT_DIR . '/themes/fake-child-theme'; + if (!file_exists($dest_dir)) { + mkdir($dest_dir, 0777, true); } - - public static function _setupParentTheme() - { - $dest_dir = WP_CONTENT_DIR . '/themes/twentyfifteen'; - if (!file_exists($dest_dir . '/views')) { - mkdir($dest_dir . '/views', 0777, true); - } - copy(__DIR__ . '/assets/single-parent.twig', $dest_dir . '/views/single.twig'); - copy(__DIR__ . '/assets/single-parent.twig', $dest_dir . '/views/single-parent.twig'); + if (!file_exists($dest_dir . '/views')) { + mkdir($dest_dir . '/views', 0777, true); } + copy(__DIR__ . '/assets/style.css', $dest_dir . '/style.css'); + copy(__DIR__ . '/assets/single.twig', $dest_dir . '/views/single.twig'); + } - public function testTwigLoadsFromParentTheme() - { - $this->_setupParentTheme(); - $this->_setupChildTheme(); - switch_theme('fake-child-theme'); - $templates = ['single-parent.twig']; - $str = Timber::compile($templates, []); - $this->assertEquals('I am single.twig in parent theme', trim($str)); + public static function _setupParentTheme() + { + $dest_dir = WP_CONTENT_DIR . '/themes/twentyfifteen'; + if (!file_exists($dest_dir . '/views')) { + mkdir($dest_dir . '/views', 0777, true); } + copy(__DIR__ . '/assets/single-parent.twig', $dest_dir . '/views/single.twig'); + copy(__DIR__ . '/assets/single-parent.twig', $dest_dir . '/views/single-parent.twig'); + } - public function _setupRelativeViews() - { - if (!file_exists(__DIR__ . '/views')) { - mkdir(__DIR__ . '/views', 0777, true); - } - copy(__DIR__ . '/assets/relative.twig', __DIR__ . '/views/single.twig'); - } + public function testTwigLoadsFromParentTheme() + { + $this->_setupParentTheme(); + $this->_setupChildTheme(); + switch_theme('fake-child-theme'); + $templates = ['single-parent.twig']; + $str = Timber::compile($templates, []); + $this->assertEquals('I am single.twig in parent theme', trim($str)); + } - public function _teardownRelativeViews() - { - if (file_exists(__DIR__ . '/views/single.twig')) { - unlink(__DIR__ . '/views/single.twig'); - } - if (file_exists(__DIR__ . '/views')) { - rmdir(__DIR__ . '/views'); - } + public function _setupRelativeViews() + { + if (!file_exists(__DIR__ . '/views')) { + mkdir(__DIR__ . '/views', 0777, true); } + copy(__DIR__ . '/assets/relative.twig', __DIR__ . '/views/single.twig'); + } - public function testTwigLoadsFromRelativeToScript() - { - $this->_setupRelativeViews(); - $str = Timber::compile('single.twig'); - $this->assertEquals('I am in the assets directory', trim($str)); - $this->_teardownRelativeViews(); + public function _teardownRelativeViews() + { + if (file_exists(__DIR__ . '/views/single.twig')) { + unlink(__DIR__ . '/views/single.twig'); } - - public function testTwigLoadsFromAbsolutePathOnServer() - { - $str = Timber::compile(__DIR__ . '/assets/image-test.twig'); - $this->assertEquals('', trim($str)); + if (file_exists(__DIR__ . '/views')) { + rmdir(__DIR__ . '/views'); } + } - public function _testTwigLoadsFromAbsolutePathOnServerWithSecurityRestriction() - { - $str = Timber::compile('assets/single-foo.twig'); - } + public function testTwigLoadsFromRelativeToScript() + { + $this->_setupRelativeViews(); + $str = Timber::compile('single.twig'); + $this->assertEquals('I am in the assets directory', trim($str)); + $this->_teardownRelativeViews(); + } - public function testTwigLoadsFromAlternateDirName() - { - Timber::$dirname = [ - \Timber\Loader::MAIN_NAMESPACE => ['foo', 'views'], - ]; - if (!file_exists(get_template_directory() . '/foo')) { - mkdir(get_template_directory() . '/foo', 0777, true); - } - copy(__DIR__ . '/assets/single-foo.twig', get_template_directory() . '/foo/single-foo.twig'); - $str = Timber::compile('single-foo.twig'); - $this->assertEquals('I am single-foo', trim($str)); - } + public function testTwigLoadsFromAbsolutePathOnServer() + { + $str = Timber::compile(__DIR__ . '/assets/image-test.twig'); + $this->assertEquals('', trim($str)); + } - public function testTwigLoadsFromAlternateDirNameWithoutNamespace() - { - Timber::$dirname = [['foo', 'views']]; - if (!file_exists(get_template_directory() . '/foo')) { - mkdir(get_template_directory() . '/foo', 0777, true); - } - copy(__DIR__ . '/assets/single-foo.twig', get_template_directory() . '/foo/single-foo.twig'); - $str = Timber::compile('single-foo.twig'); - $this->assertEquals('I am single-foo', trim($str)); - } + public function _testTwigLoadsFromAbsolutePathOnServerWithSecurityRestriction() + { + $str = Timber::compile('assets/single-foo.twig'); + } - public function testTwigLoadsFromAlternateDirNameWithoutNamespaceAndSimpleArray() - { - Timber::$dirname = ['foo', 'views']; - if (!file_exists(get_template_directory() . '/foo')) { - mkdir(get_template_directory() . '/foo', 0777, true); - } - copy(__DIR__ . '/assets/single-foo.twig', get_template_directory() . '/foo/single-foo.twig'); - $str = Timber::compile('single-foo.twig'); - $this->assertEquals('I am single-foo', trim($str)); + public function testTwigLoadsFromAlternateDirName() + { + Timber::$dirname = [ + \Timber\Loader::MAIN_NAMESPACE => ['foo', 'views'], + ]; + if (!file_exists(get_template_directory() . '/foo')) { + mkdir(get_template_directory() . '/foo', 0777, true); } + copy(__DIR__ . '/assets/single-foo.twig', get_template_directory() . '/foo/single-foo.twig'); + $str = Timber::compile('single-foo.twig'); + $this->assertEquals('I am single-foo', trim($str)); + } - public function testTwigLoadsFromLocation() - { - Timber::$locations = __DIR__ . '/assets'; - $str = Timber::compile('thumb-test.twig'); - $this->assertEquals('', trim($str)); + public function testTwigLoadsFromAlternateDirNameWithoutNamespace() + { + Timber::$dirname = [['foo', 'views']]; + if (!file_exists(get_template_directory() . '/foo')) { + mkdir(get_template_directory() . '/foo', 0777, true); } + copy(__DIR__ . '/assets/single-foo.twig', get_template_directory() . '/foo/single-foo.twig'); + $str = Timber::compile('single-foo.twig'); + $this->assertEquals('I am single-foo', trim($str)); + } - public function testTwigLoadsFromLocationWithNamespace() - { - Timber::$locations = [ - __DIR__ . '/assets' => 'assets', - ]; - $str = Timber::compile('@assets/thumb-test.twig'); - $this->assertEquals('', trim($str)); + public function testTwigLoadsFromAlternateDirNameWithoutNamespaceAndSimpleArray() + { + Timber::$dirname = ['foo', 'views']; + if (!file_exists(get_template_directory() . '/foo')) { + mkdir(get_template_directory() . '/foo', 0777, true); } + copy(__DIR__ . '/assets/single-foo.twig', get_template_directory() . '/foo/single-foo.twig'); + $str = Timber::compile('single-foo.twig'); + $this->assertEquals('I am single-foo', trim($str)); + } - public function testTwigLoadsFromLocationWithNestedNamespace() - { - Timber::$locations = [ - __DIR__ . '/namespaced' => 'namespaced', - ]; - $str = Timber::compile('@namespaced/test-nested.twig'); - $this->assertEquals('This is a namespaced template.', trim($str)); - } + public function testTwigLoadsFromLocation() + { + Timber::$locations = __DIR__ . '/assets'; + $str = Timber::compile('thumb-test.twig'); + $this->assertEquals('', trim($str)); + } - public function testTwigLoadsFromLocationWithAndWithoutNamespaces() - { - Timber::$locations = [ - __DIR__ . '/namespaced' => 'namespaced', - __DIR__ . '/assets', - ]; + public function testTwigLoadsFromLocationWithNamespace() + { + Timber::$locations = [ + __DIR__ . '/assets' => 'assets', + ]; + $str = Timber::compile('@assets/thumb-test.twig'); + $this->assertEquals('', trim($str)); + } - // Namespaced location - $str = Timber::compile('@namespaced/test-namespaced.twig'); - $this->assertEquals('This is a namespaced template.', trim($str)); + public function testTwigLoadsFromLocationWithNestedNamespace() + { + Timber::$locations = [ + __DIR__ . '/namespaced' => 'namespaced', + ]; + $str = Timber::compile('@namespaced/test-nested.twig'); + $this->assertEquals('This is a namespaced template.', trim($str)); + } - // Non namespaced location - $str = Timber::compile('thumb-test.twig'); - $this->assertEquals('', trim($str)); - } + public function testTwigLoadsFromLocationWithAndWithoutNamespaces() + { + Timber::$locations = [ + __DIR__ . '/namespaced' => 'namespaced', + __DIR__ . '/assets', + ]; + + // Namespaced location + $str = Timber::compile('@namespaced/test-namespaced.twig'); + $this->assertEquals('This is a namespaced template.', trim($str)); + + // Non namespaced location + $str = Timber::compile('thumb-test.twig'); + $this->assertEquals('', trim($str)); + } - public function testTwigLoadsFromLocationWithAndWithoutNamespacesAndDirs() - { - Timber::$dirname = [ - \Timber\Loader::MAIN_NAMESPACE => ['foo', 'views'], - ]; - Timber::$locations = [ - __DIR__ . '/namespaced' => 'namespaced', - __DIR__ . '/assets', - ]; - - // Namespaced location - $str = Timber::compile('@namespaced/test-namespaced.twig'); - $this->assertEquals('This is a namespaced template.', trim($str)); - - // Non namespaced location - $str = Timber::compile('thumb-test.twig'); - $this->assertEquals('', trim($str)); - - if (!file_exists(get_template_directory() . '/foo')) { - mkdir(get_template_directory() . '/foo', 0777, true); - } - copy(__DIR__ . '/assets/single-foo.twig', get_template_directory() . '/foo/single-foo.twig'); - - // Dir - $str = Timber::compile('single-foo.twig'); - $this->assertEquals('I am single-foo', trim($str)); + public function testTwigLoadsFromLocationWithAndWithoutNamespacesAndDirs() + { + Timber::$dirname = [ + \Timber\Loader::MAIN_NAMESPACE => ['foo', 'views'], + ]; + Timber::$locations = [ + __DIR__ . '/namespaced' => 'namespaced', + __DIR__ . '/assets', + ]; + + // Namespaced location + $str = Timber::compile('@namespaced/test-namespaced.twig'); + $this->assertEquals('This is a namespaced template.', trim($str)); + + // Non namespaced location + $str = Timber::compile('thumb-test.twig'); + $this->assertEquals('', trim($str)); + + if (!file_exists(get_template_directory() . '/foo')) { + mkdir(get_template_directory() . '/foo', 0777, true); } + copy(__DIR__ . '/assets/single-foo.twig', get_template_directory() . '/foo/single-foo.twig'); - public function testTwigLoadsFromMultipleLocationsWithNamespace() - { - Timber::$locations = [ - __DIR__ . '/assets' => 'assets', - __DIR__ . '/namespaced' => 'assets', - ]; - $str = Timber::compile('@assets/thumb-test.twig'); - $this->assertEquals('', trim($str)); - - $str = Timber::compile('@assets/test-namespaced.twig'); - $this->assertEquals('This is a namespaced template.', trim($str)); - } + // Dir + $str = Timber::compile('single-foo.twig'); + $this->assertEquals('I am single-foo', trim($str)); + } - public function testTwigLoadsFirstTemplateWhenMultipleLocationsWithSameNamespace() - { - Timber::$locations = [ - __DIR__ . '/assets' => 'assets', - __DIR__ . '/namespaced' => 'assets', - ]; - $str = Timber::compile('@assets/thumb-test.twig'); - $this->assertEquals('', trim($str)); - } + public function testTwigLoadsFromMultipleLocationsWithNamespace() + { + Timber::$locations = [ + __DIR__ . '/assets' => 'assets', + __DIR__ . '/namespaced' => 'assets', + ]; + $str = Timber::compile('@assets/thumb-test.twig'); + $this->assertEquals('', trim($str)); + + $str = Timber::compile('@assets/test-namespaced.twig'); + $this->assertEquals('This is a namespaced template.', trim($str)); + } + + public function testTwigLoadsFirstTemplateWhenMultipleLocationsWithSameNamespace() + { + Timber::$locations = [ + __DIR__ . '/assets' => 'assets', + __DIR__ . '/namespaced' => 'assets', + ]; + $str = Timber::compile('@assets/thumb-test.twig'); + $this->assertEquals('', trim($str)); } +} diff --git a/tests/test-timber-parent-child.php b/tests/test-timber-parent-child.php index 4007c6119..b146bd416 100644 --- a/tests/test-timber-parent-child.php +++ b/tests/test-timber-parent-child.php @@ -1,24 +1,24 @@ factory->post->create(); - $post = Timber::get_post($pid); - $str = Timber::compile(['single-course.twig', 'single.twig'], [ - 'post' => $post, - ]); - $this->assertEquals('I am single course', $str); - } + TestTimberLoader::_setupParentTheme(); + TestTimberLoader::_setupChildTheme(); + switch_theme('fake-child-theme'); + register_post_type('course'); + //copy a specific file to the PARENT directory + $dest_dir = WP_CONTENT_DIR . '/themes/twentyfifteen'; + copy(__DIR__ . '/assets/single-course.twig', $dest_dir . '/views/single-course.twig'); + $pid = $this->factory->post->create(); + $post = Timber::get_post($pid); + $str = Timber::compile(['single-course.twig', 'single.twig'], [ + 'post' => $post, + ]); + $this->assertEquals('I am single course', $str); } +} diff --git a/tests/test-timber-post-comments.php b/tests/test-timber-post-comments.php index 6a20aa2bd..c0809c6f5 100644 --- a/tests/test-timber-post-comments.php +++ b/tests/test-timber-post-comments.php @@ -2,210 +2,210 @@ require_once __DIR__ . '/php/timber-custom-comment.php'; - /** - * @group posts-api - * @group comments-api - * @group called-post-constructor - */ - class TestTimberPostComments extends Timber_UnitTestCase +/** + * @group posts-api + * @group comments-api + * @group called-post-constructor + */ +class TestTimberPostComments extends Timber_UnitTestCase +{ + public function testComments() { - public function testComments() - { - $post_id = $this->factory->post->create([ - 'post_title' => 'Gobbles', - ]); - $comment_id_array = $this->factory->comment->create_many(5, [ - 'comment_post_ID' => $post_id, - ]); - $post = Timber::get_post($post_id); - $this->assertEquals(5, count($post->comments())); - $this->assertEquals(5, $post->comment_count()); - } + $post_id = $this->factory->post->create([ + 'post_title' => 'Gobbles', + ]); + $comment_id_array = $this->factory->comment->create_many(5, [ + 'comment_post_ID' => $post_id, + ]); + $post = Timber::get_post($post_id); + $this->assertEquals(5, count($post->comments())); + $this->assertEquals(5, $post->comment_count()); + } - public function testCommentCount() - { - $post_id = $this->factory->post->create([ - 'post_title' => 'Gobbles', - ]); - $comment_id_array = $this->factory->comment->create_many(5, [ - 'comment_post_ID' => $post_id, - ]); - $post = Timber::get_post($post_id); - $this->assertEquals(2, count($post->comments(2))); - $this->assertEquals(5, count($post->comments())); - } + public function testCommentCount() + { + $post_id = $this->factory->post->create([ + 'post_title' => 'Gobbles', + ]); + $comment_id_array = $this->factory->comment->create_many(5, [ + 'comment_post_ID' => $post_id, + ]); + $post = Timber::get_post($post_id); + $this->assertEquals(2, count($post->comments(2))); + $this->assertEquals(5, count($post->comments())); + } - public function testCommentCountZero() - { - $quote = 'Named must your fear be before banish it you can.'; - $post_id = $this->factory->post->create([ - 'post_content' => $quote, - ]); - $post = Timber::get_post($post_id); - $this->assertEquals(0, $post->get_comment_count()); - } + public function testCommentCountZero() + { + $quote = 'Named must your fear be before banish it you can.'; + $post_id = $this->factory->post->create([ + 'post_content' => $quote, + ]); + $post = Timber::get_post($post_id); + $this->assertEquals(0, $post->get_comment_count()); + } - public function testShowUnmoderatedCommentIfByLoggedInUser() - { - $post_id = $this->factory->post->create(); - $uid = $this->factory->user->create(); - wp_set_current_user($uid); - $quote = "You know, I always wanted to pretend I was an architect"; - $comment_id = $this->factory->comment->create([ - 'comment_post_ID' => $post_id, - 'comment_content' => $quote, - 'user_id' => $uid, - 'comment_approved' => 0, - ]); - $post = Timber::get_post($post_id); - $this->assertEquals(1, count($post->comments())); - wp_set_current_user(0); - $post = Timber::get_post($post_id); - $this->assertEquals(0, count($post->comments())); - } + public function testShowUnmoderatedCommentIfByLoggedInUser() + { + $post_id = $this->factory->post->create(); + $uid = $this->factory->user->create(); + wp_set_current_user($uid); + $quote = "You know, I always wanted to pretend I was an architect"; + $comment_id = $this->factory->comment->create([ + 'comment_post_ID' => $post_id, + 'comment_content' => $quote, + 'user_id' => $uid, + 'comment_approved' => 0, + ]); + $post = Timber::get_post($post_id); + $this->assertEquals(1, count($post->comments())); + wp_set_current_user(0); + $post = Timber::get_post($post_id); + $this->assertEquals(0, count($post->comments())); + } - public function testPostWithCustomCommentClass() - { - $post_id = $this->factory->post->create([ - 'post_title' => 'Gobbles', - ]); - $comment_id_array = $this->factory->comment->create_many(5, [ - 'comment_post_ID' => $post_id, - ]); - $post = Timber::get_post($post_id); + public function testPostWithCustomCommentClass() + { + $post_id = $this->factory->post->create([ + 'post_title' => 'Gobbles', + ]); + $comment_id_array = $this->factory->comment->create_many(5, [ + 'comment_post_ID' => $post_id, + ]); + $post = Timber::get_post($post_id); - $filter = function () { - return [ - 'post' => CustomComment::class, - ]; - }; - add_filter('timber/comment/classmap', $filter); + $filter = function () { + return [ + 'post' => CustomComment::class, + ]; + }; + add_filter('timber/comment/classmap', $filter); - $comments = $post->comments(null, 'wp', 'comment', 'approve', 'CustomComment'); - $this->assertEquals(CustomComment::class, get_class($comments[0])); + $comments = $post->comments(null, 'wp', 'comment', 'approve', 'CustomComment'); + $this->assertEquals(CustomComment::class, get_class($comments[0])); - remove_filter('timber/comment/classmap', $filter); - } + remove_filter('timber/comment/classmap', $filter); + } - public function testShowUnmoderatedCommentIfByCurrentUser() - { - $post_id = $this->factory->post->create(); - add_filter('wp_get_current_commenter', function ($author_data) { - $author_data['comment_author_email'] = 'jarednova@upstatement.com'; - return $author_data; - }); - $commenter = wp_get_current_commenter(); - $quote = "And in that moment, I was a marine biologist"; - $comment_id = $this->factory->comment->create([ - 'comment_post_ID' => $post_id, - 'comment_content' => $quote, - 'comment_approved' => 0, - 'comment_author_email' => 'jarednova@upstatement.com', - ]); - $post = Timber::get_post($post_id); - $this->assertEquals(1, count($post->comments())); - } + public function testShowUnmoderatedCommentIfByCurrentUser() + { + $post_id = $this->factory->post->create(); + add_filter('wp_get_current_commenter', function ($author_data) { + $author_data['comment_author_email'] = 'jarednova@upstatement.com'; + return $author_data; + }); + $commenter = wp_get_current_commenter(); + $quote = "And in that moment, I was a marine biologist"; + $comment_id = $this->factory->comment->create([ + 'comment_post_ID' => $post_id, + 'comment_content' => $quote, + 'comment_approved' => 0, + 'comment_author_email' => 'jarednova@upstatement.com', + ]); + $post = Timber::get_post($post_id); + $this->assertEquals(1, count($post->comments())); + } - public function testMultilevelThreadedComments() - { - update_option('comment_order', 'ASC'); - $post_id = $this->factory->post->create([ - 'post_title' => 'Gobbles', - ]); - $comment_id = $this->factory->comment->create([ - 'comment_post_ID' => $post_id, - ]); - $child_id = $this->factory->comment->create([ - 'comment_post_ID' => $post_id, - 'comment_parent' => $comment_id, - ]); - $grandchild_id = $this->factory->comment->create([ - 'comment_post_ID' => $post_id, - 'comment_parent' => $child_id, - ]); - $grandchild_id = $this->factory->comment->create([ - 'comment_post_ID' => $post_id, - 'comment_parent' => $child_id, - ]); - $post = Timber::get_post($post_id); - $comments = $post->comments(); - $this->assertEquals(1, count($comments)); - $children = $comments[0]->children(); - $this->assertEquals(1, count($children)); - $grand_children = $children[0]->children(); - $this->assertEquals(2, count($grand_children)); - } + public function testMultilevelThreadedComments() + { + update_option('comment_order', 'ASC'); + $post_id = $this->factory->post->create([ + 'post_title' => 'Gobbles', + ]); + $comment_id = $this->factory->comment->create([ + 'comment_post_ID' => $post_id, + ]); + $child_id = $this->factory->comment->create([ + 'comment_post_ID' => $post_id, + 'comment_parent' => $comment_id, + ]); + $grandchild_id = $this->factory->comment->create([ + 'comment_post_ID' => $post_id, + 'comment_parent' => $child_id, + ]); + $grandchild_id = $this->factory->comment->create([ + 'comment_post_ID' => $post_id, + 'comment_parent' => $child_id, + ]); + $post = Timber::get_post($post_id); + $comments = $post->comments(); + $this->assertEquals(1, count($comments)); + $children = $comments[0]->children(); + $this->assertEquals(1, count($children)); + $grand_children = $children[0]->children(); + $this->assertEquals(2, count($grand_children)); + } - public function testMultilevelThreadedCommentsCorrectParents() - { - update_option('comment_order', 'ASC'); - $post_id = $this->factory->post->create([ - 'post_title' => 'Gobbles', - 'post_date' => '2016-11-28 12:00:00', - ]); - $uncle_id = $this->factory->comment->create([ - 'comment_post_ID' => $post_id, - 'comment_date' => '2016-11-28 13:00:00', - 'comment_content' => 'i am the UNCLE', - ]); - $parent_id = $this->factory->comment->create([ - 'comment_post_ID' => $post_id, - 'comment_date' => '2016-11-28 14:00:00', - 'comment_content' => 'i am the Parent', - ]); - $child_id = $this->factory->comment->create([ - 'comment_post_ID' => $post_id, - 'comment_parent' => $parent_id, - 'comment_date' => '2016-11-28 15:00:00', - 'comment_content' => 'I am the child', - ]); - $grandchild_id = $this->factory->comment->create([ - 'comment_post_ID' => $post_id, - 'comment_parent' => $child_id, - 'comment_date' => '2016-11-28 16:00:00', - 'comment_content' => 'I am the GRANDchild', - ]); - $post = Timber::get_post($post_id); - $comments = $post->comments(); - $children = $comments[1]->children(); - $this->assertEquals($parent_id, $children[0]->comment_parent); - $grand_children = $children[0]->children(); - $grandchild = $grand_children[0]; - $this->assertEquals($child_id, $grandchild->comment_parent); - } + public function testMultilevelThreadedCommentsCorrectParents() + { + update_option('comment_order', 'ASC'); + $post_id = $this->factory->post->create([ + 'post_title' => 'Gobbles', + 'post_date' => '2016-11-28 12:00:00', + ]); + $uncle_id = $this->factory->comment->create([ + 'comment_post_ID' => $post_id, + 'comment_date' => '2016-11-28 13:00:00', + 'comment_content' => 'i am the UNCLE', + ]); + $parent_id = $this->factory->comment->create([ + 'comment_post_ID' => $post_id, + 'comment_date' => '2016-11-28 14:00:00', + 'comment_content' => 'i am the Parent', + ]); + $child_id = $this->factory->comment->create([ + 'comment_post_ID' => $post_id, + 'comment_parent' => $parent_id, + 'comment_date' => '2016-11-28 15:00:00', + 'comment_content' => 'I am the child', + ]); + $grandchild_id = $this->factory->comment->create([ + 'comment_post_ID' => $post_id, + 'comment_parent' => $child_id, + 'comment_date' => '2016-11-28 16:00:00', + 'comment_content' => 'I am the GRANDchild', + ]); + $post = Timber::get_post($post_id); + $comments = $post->comments(); + $children = $comments[1]->children(); + $this->assertEquals($parent_id, $children[0]->comment_parent); + $grand_children = $children[0]->children(); + $grandchild = $grand_children[0]; + $this->assertEquals($child_id, $grandchild->comment_parent); + } - public function testThreadedCommentsWithTemplate() - { - $post_id = $this->factory->post->create([ - 'post_title' => 'Gobbles', - ]); - $comment_id = $this->factory->comment->create([ - 'comment_post_ID' => $post_id, - 'comment_content' => 'oldest!', - 'comment_date' => '2016-11-28 12:58:18', - ]); - $comment2_id = $this->factory->comment->create([ - 'comment_post_ID' => $post_id, - 'comment_content' => 'newest!', - 'comment_date' => '2016-11-28 13:58:18', - ]); - $comment2_child_id = $this->factory->comment->create([ - 'comment_post_ID' => $post_id, - 'comment_parent' => $comment2_id, - 'comment_content' => 'response', - 'comment_date' => '2016-11-28 14:58:18', - ]); - $comment2_grandchild_id = $this->factory->comment->create([ - 'comment_post_ID' => $post_id, - 'comment_parent' => $comment2_child_id, - 'comment_content' => 'Respond2Respond', - 'comment_date' => '2016-11-28 15:58:18', - ]); - $post = Timber::get_post($post_id); - $str = Timber::compile('assets/comments-thread.twig', [ - 'post' => $post, - ]); - $str = preg_replace('/\s+/', ' ', $str); - $this->assertEquals('

newest!

response

Respond2Respond

oldest!

', trim($str)); - } + public function testThreadedCommentsWithTemplate() + { + $post_id = $this->factory->post->create([ + 'post_title' => 'Gobbles', + ]); + $comment_id = $this->factory->comment->create([ + 'comment_post_ID' => $post_id, + 'comment_content' => 'oldest!', + 'comment_date' => '2016-11-28 12:58:18', + ]); + $comment2_id = $this->factory->comment->create([ + 'comment_post_ID' => $post_id, + 'comment_content' => 'newest!', + 'comment_date' => '2016-11-28 13:58:18', + ]); + $comment2_child_id = $this->factory->comment->create([ + 'comment_post_ID' => $post_id, + 'comment_parent' => $comment2_id, + 'comment_content' => 'response', + 'comment_date' => '2016-11-28 14:58:18', + ]); + $comment2_grandchild_id = $this->factory->comment->create([ + 'comment_post_ID' => $post_id, + 'comment_parent' => $comment2_child_id, + 'comment_content' => 'Respond2Respond', + 'comment_date' => '2016-11-28 15:58:18', + ]); + $post = Timber::get_post($post_id); + $str = Timber::compile('assets/comments-thread.twig', [ + 'post' => $post, + ]); + $str = preg_replace('/\s+/', ' ', $str); + $this->assertEquals('

newest!

response

Respond2Respond

oldest!

', trim($str)); } +} diff --git a/tests/test-timber-post-content.php b/tests/test-timber-post-content.php index 73758fc89..4ff473a7a 100644 --- a/tests/test-timber-post-content.php +++ b/tests/test-timber-post-content.php @@ -1,71 +1,71 @@ factory->post->create(); - $post = Timber::get_post($post_id); - $post->post_content = $quote; - wp_update_post($post); - $this->assertEquals($quote, trim(strip_tags($post->content()))); - } + $quote = 'The way to do well is to do well.'; + $post_id = $this->factory->post->create(); + $post = Timber::get_post($post_id); + $post->post_content = $quote; + wp_update_post($post); + $this->assertEquals($quote, trim(strip_tags($post->content()))); + } - public function testContentPaged() - { - $quote = $page1 = 'The way to do well is to do well.'; - $quote .= ''; - $quote .= $page2 = "And do not let your tongue get ahead of your mind."; + public function testContentPaged() + { + $quote = $page1 = 'The way to do well is to do well.'; + $quote .= ''; + $quote .= $page2 = "And do not let your tongue get ahead of your mind."; - $post_id = $this->factory->post->create(); - $post = Timber::get_post($post_id); - $post->post_content = $quote; - wp_update_post($post); + $post_id = $this->factory->post->create(); + $post = Timber::get_post($post_id); + $post->post_content = $quote; + wp_update_post($post); - $this->assertEquals($page1, trim(strip_tags($post->content(1)))); - $this->assertEquals($page2, trim(strip_tags($post->content(2)))); - } + $this->assertEquals($page1, trim(strip_tags($post->content(1)))); + $this->assertEquals($page2, trim(strip_tags($post->content(2)))); + } - public function testPagedContent() - { - $quote = $page1 = 'Named must your fear be before banish it you can.'; - $quote .= ''; - $quote .= $page2 = "No, try not. Do or do not. There is no try."; + public function testPagedContent() + { + $quote = $page1 = 'Named must your fear be before banish it you can.'; + $quote .= ''; + $quote .= $page2 = "No, try not. Do or do not. There is no try."; - $post_id = $this->factory->post->create([ - 'post_content' => $quote, - ]); + $post_id = $this->factory->post->create([ + 'post_content' => $quote, + ]); - $this->go_to(get_permalink($post_id)); + $this->go_to(get_permalink($post_id)); - setup_postdata(get_post($post_id)); + setup_postdata(get_post($post_id)); - $post = Timber::get_post(); - $this->assertEquals($page1, trim(strip_tags($post->paged_content()))); + $post = Timber::get_post(); + $this->assertEquals($page1, trim(strip_tags($post->paged_content()))); - $pagination = $post->pagination(); - $this->go_to($pagination['pages'][1]['link']); + $pagination = $post->pagination(); + $this->go_to($pagination['pages'][1]['link']); - setup_postdata(get_post($post_id)); - $post = Timber::get_post(); + setup_postdata(get_post($post_id)); + $post = Timber::get_post(); - $this->assertEquals($page2, trim(strip_tags($post->paged_content()))); - } + $this->assertEquals($page2, trim(strip_tags($post->paged_content()))); + } - /** - * @ticket 2218 - */ - public function testGutenbergExcerptOption() - { - global $wp_version; - if ($wp_version < 5.0) { - $this->markTestSkipped('Only applies to Block editor which is avaialble in WP 5.x'); - } - $content_1 = ' + /** + * @ticket 2218 + */ + public function testGutenbergExcerptOption() + { + global $wp_version; + if ($wp_version < 5.0) { + $this->markTestSkipped('Only applies to Block editor which is avaialble in WP 5.x'); + } + $content_1 = '

Heres the start to a thing

@@ -77,11 +77,11 @@ public function testGutenbergExcerptOption()

Heres the read more stuff that we shant see!

'; - $post_id = $this->factory->post->create([ - 'post_content' => $content_1, - ]); - $post = Timber::get_post($post_id); + $post_id = $this->factory->post->create([ + 'post_content' => $content_1, + ]); + $post = Timber::get_post($post_id); - $this->assertEquals('

Heres the read more stuff that we shant see!

', trim($post->content())); - } + $this->assertEquals('

Heres the read more stuff that we shant see!

', trim($post->content())); } +} diff --git a/tests/test-timber-post-convert.php b/tests/test-timber-post-convert.php index 4e45ad6bf..bdeb1a1d7 100644 --- a/tests/test-timber-post-convert.php +++ b/tests/test-timber-post-convert.php @@ -1,73 +1,73 @@ factory->post->create(); - $post = Timber::get_post($post_id); - $post_id = $this->factory->post->create([ - 'post_title' => 'Maybe Child Post', - ]); - $posts = get_posts([ - 'post__in' => [$post_id], - ]); - $converted = $post->convert($posts[0]); - $this->assertEquals($post_id, $converted->id); - $this->assertEquals('Timber\Post', get_class($converted)); - } + $post_id = $this->factory->post->create(); + $post = Timber::get_post($post_id); + $post_id = $this->factory->post->create([ + 'post_title' => 'Maybe Child Post', + ]); + $posts = get_posts([ + 'post__in' => [$post_id], + ]); + $converted = $post->convert($posts[0]); + $this->assertEquals($post_id, $converted->id); + $this->assertEquals('Timber\Post', get_class($converted)); + } - public function testConvertSingleItemArray() - { - $post_id = $this->factory->post->create(); - $post = Timber::get_post($post_id); - $post_id = $this->factory->post->create([ - 'post_title' => 'Maybe Child Post', - ]); - $posts = get_posts([ - 'post__in' => [$post_id], - ]); - $converted = $post->convert($posts); - $this->assertEquals($post_id, $converted[0]->id); - $this->assertEquals('Timber\Post', get_class($converted[0])); - } + public function testConvertSingleItemArray() + { + $post_id = $this->factory->post->create(); + $post = Timber::get_post($post_id); + $post_id = $this->factory->post->create([ + 'post_title' => 'Maybe Child Post', + ]); + $posts = get_posts([ + 'post__in' => [$post_id], + ]); + $converted = $post->convert($posts); + $this->assertEquals($post_id, $converted[0]->id); + $this->assertEquals('Timber\Post', get_class($converted[0])); + } - public function testConvertArray() - { - $post_ids = $this->factory->post->create_many(8, [ - 'post_title' => 'Sample Post ' . rand(1, 999), - ]); + public function testConvertArray() + { + $post_ids = $this->factory->post->create_many(8, [ + 'post_title' => 'Sample Post ' . rand(1, 999), + ]); - $post_id = $this->factory->post->create(); - $post = Timber::get_post($post_id); - $posts = get_posts([ - 'post__in' => $post_ids, - 'orderby' => 'post__in', - ]); - $converted = $post->convert($posts); - $this->assertEquals($post_ids[2], $converted[2]->id); - $this->assertEquals('Timber\Post', get_class($converted[3])); - } + $post_id = $this->factory->post->create(); + $post = Timber::get_post($post_id); + $posts = get_posts([ + 'post__in' => $post_ids, + 'orderby' => 'post__in', + ]); + $converted = $post->convert($posts); + $this->assertEquals($post_ids[2], $converted[2]->id); + $this->assertEquals('Timber\Post', get_class($converted[3])); + } - public function testNestedArray() - { - $post_ids = $this->factory->post->create_many(8, [ - 'post_title' => 'Sample Post ' . rand(1, 999), - ]); + public function testNestedArray() + { + $post_ids = $this->factory->post->create_many(8, [ + 'post_title' => 'Sample Post ' . rand(1, 999), + ]); - $post_id = $this->factory->post->create(); - $post = Timber::get_post($post_id); - $posts = get_posts([ - 'post__in' => $post_ids, - 'orderby' => 'post__in', - ]); - $arr = [$post, $posts]; + $post_id = $this->factory->post->create(); + $post = Timber::get_post($post_id); + $posts = get_posts([ + 'post__in' => $post_ids, + 'orderby' => 'post__in', + ]); + $arr = [$post, $posts]; - $converted = $post->convert($arr); - $this->assertEquals($post_ids[2], $converted[1][2]->id); - $this->assertEquals('Timber\Post', get_class($converted[1][3])); - } + $converted = $post->convert($arr); + $this->assertEquals($post_ids[2], $converted[1][2]->id); + $this->assertEquals('Timber\Post', get_class($converted[1][3])); } +} diff --git a/tests/test-timber-post-excerpt-object.php b/tests/test-timber-post-excerpt-object.php index 726424075..67240b5f5 100644 --- a/tests/test-timber-post-excerpt-object.php +++ b/tests/test-timber-post-excerpt-object.php @@ -1,418 +1,418 @@ Govenment:

  • of the people
  • by the people
  • for the people
'; + $post_id = $this->factory->post->create([ + 'post_content' => $expected . '
Lincoln
', + 'post_excerpt' => false, + ]); + $post = Timber::get_post($post_id); + $template = "{{ post.excerpt( {strip:'


    1. '}) }}"; + $str = Timber::compile_string($template, [ + 'post' => $post, + ]); + $this->assertEquals($expected . '

      Lincoln

      Read More', $str); + } + + public function test1886ErrorWithForce() + { + $expected = '

      Government:

      • of the people
      • by the people
      • for the people
      '; + $post_id = $this->factory->post->create([ + 'post_excerpt' => $expected, + 'post_content' => $this->gettysburg, + ]); + $post = Timber::get_post($post_id); + $template = '{{ post.excerpt({ + strip: "
      • ", + words:10, + force:true }) + }}'; + $str = Timber::compile_string($template, [ + 'post' => $post, + ]); + $this->assertEquals('Government:
        • of the people
        • by the people
        • for the
        Read More', $str); + } + + public function testExcerptConstructorWithWords() + { + $post_id = $this->factory->post->create([ + 'post_excerpt' => $this->gettysburg, + ]); + $post = Timber::get_post($post_id); + $excerpt = $post->excerpt([ + 'words' => 4, + 'force' => true, + 'read_more' => false, + ]); + + // Coerce excerpt to a string and test it. + $this->assertEquals('Four score and seven…', '' . $excerpt); + } + + public function testExcerptConstructorWithChars() + { + $post_id = $this->factory->post->create([ + 'post_excerpt' => $this->gettysburg, + ]); + $post = Timber::get_post($post_id); + $excerpt = $post->excerpt([ + 'chars' => 20, + 'force' => true, + 'read_more' => false, + ]); + + // Coerce excerpt to a string and test it. + $this->assertEquals('Four score and seven…', '' . $excerpt); + } + + public function testExcerptConstructorWithEnd() + { + $post_id = $this->factory->post->create([ + 'post_excerpt' => $this->gettysburg, + ]); + $post = Timber::get_post($post_id); + $excerpt = $post->excerpt([ + 'chars' => 20, + 'force' => true, + 'read_more' => false, + 'end' => ' - kthxbi', + ]); + + // Coerce excerpt to a string and test it. + $this->assertEquals('Four score and seven - kthxbi', '' . $excerpt); + } + + public function testExcerptConstructorWithHtml() + { + $post_id = $this->factory->post->create([ + 'post_excerpt' => 'Yo' + . ' CLICK' + . ' STRONG ' + . $this->gettysburg, + ]); + $post = Timber::get_post($post_id); + $excerpt = $post->excerpt([ + 'chars' => 26, + 'read_more' => false, + 'force' => true, + ]); + + // Coerce excerpt to a string and test it. + $this->assertEquals('Yo CLICK STRONG Four score…', '' . $excerpt); + } + + public function testExcerptConstructorStrippingSomeTags() + { + $post_id = $this->factory->post->create([ + 'post_excerpt' => 'Yo' + . ' CLICK' + . ' STRONG ' + . $this->gettysburg, + ]); + $post = Timber::get_post($post_id); + $excerpt = $post->excerpt([ + 'words' => 5, + 'read_more' => false, + 'force' => true, + 'strip' => '', + ]); + + // Coerce excerpt to a string and test it. + $this->assertEquals( + 'Yo CLICK STRONG Four…', + '' . $excerpt + ); + } + + public function testExcerptConstructorWithReadMore() + { + $post_id = $this->factory->post->create([ + 'post_excerpt' => $this->gettysburg, + ]); + $post = Timber::get_post($post_id); + $readmore = 'read more! if you dare...'; + $excerpt = $post->excerpt([ + 'chars' => 20, + 'force' => true, + 'read_more' => 'read more! if you dare...', + ]); + + $expected = sprintf( + 'Four score and seven… %s', + $post->link(), + $readmore + ); + + // Coerce excerpt to a string and test it. + $this->assertEquals($expected, '' . $excerpt); + } + + public function testExcerptWithStyleTags() + { + global $wpdb; + $style = 'Yo. '; + $id = $wpdb->insert( + $wpdb->posts, + [ + 'post_author' => '1', + 'post_content' => $style . $this->gettysburg, + 'post_title' => 'Thing', + 'post_date' => '2017-03-01 00:21:40', + 'post_date_gmt' => '2017-03-01 00:21:40', + ] + ); + $post_id = $wpdb->insert_id; + $post = Timber::get_post($post_id); + $template = '{{ post.excerpt.length(9).read_more(false).strip(true) }}'; + $str = Timber::compile_string($template, [ + 'post' => $post, + ]); + $this->assertEquals('Yo. Four score and seven years ago our fathers…', $str); + } + + public function testExcerptTags() + { + $post_id = $this->factory->post->create([ + 'post_excerpt' => 'It turned out that just about anyone in authority — cops, judges, city leaders — was in on the game.', + ]); + $post = Timber::get_post($post_id); + $template = '{{ post.excerpt.length(3).read_more(false).strip(false) }}'; + $str = Timber::compile_string($template, [ + 'post' => $post, + ]); + $this->assertStringNotContainsString('

        ', $str); + } + + public function testPostExcerptObjectWithCharAndWordLengthWordsWin() + { + $pid = $this->factory->post->create([ + 'post_content' => $this->gettysburg, + 'post_excerpt' => '', + ]); + $template = '{{ post.excerpt.length(2).chars(20) }}'; + $post = Timber::get_post($pid); + $str = Timber::compile_string($template, [ + 'post' => $post, + ]); + $this->assertEquals('Four score… Read More', $str); + } + + public function testPostExcerptObjectWithCharAndWordLengthCharsWin() + { + $pid = $this->factory->post->create([ + 'post_content' => $this->gettysburg, + 'post_excerpt' => '', + ]); + $template = '{{ post.excerpt.length(20).chars(20) }}'; + $post = Timber::get_post($pid); + $str = Timber::compile_string($template, [ + 'post' => $post, + ]); + $this->assertEquals('Four score and seven… Read More', $str); + } + + public function testPostExcerptObjectWithCharLength() + { + $pid = $this->factory->post->create([ + 'post_content' => $this->gettysburg, + 'post_excerpt' => '', + ]); + $template = '{{ post.excerpt.chars(20) }}'; + $post = Timber::get_post($pid); + $str = Timber::compile_string($template, [ + 'post' => $post, + ]); + $this->assertEquals('Four score and seven… Read More', $str); + } + + public function testPostExcerptObjectWithLength() + { + $pid = $this->factory->post->create([ + 'post_content' => 'Lauren is a duck she a big ole duck!', + 'post_excerpt' => '', + ]); + $template = '{{ post.excerpt.length(4) }}'; + $post = Timber::get_post($pid); + $str = Timber::compile_string($template, [ + 'post' => $post, + ]); + $this->assertEquals('Lauren is a duck… Read More', $str); + } + + public function testPostExcerptObjectWithForcedLength() + { + $pid = $this->factory->post->create([ + 'post_content' => 'Great Gatsby', + 'post_excerpt' => 'In my younger and more vulnerable years my father gave me some advice that I’ve been turning over in my mind ever since.', + ]); + $template = '{{ post.excerpt.force.length(3) }}'; + $post = Timber::get_post($pid); + $str = Timber::compile_string($template, [ + 'post' => $post, + ]); + $this->assertEquals('In my younger… Read More', $str); + } + + public function testPostExcerptObject() + { + $pid = $this->factory->post->create([ + 'post_content' => 'Great Gatsby', + 'post_excerpt' => 'In my younger and more vulnerable years my father gave me some advice that I’ve been turning over in my mind ever since.', + ]); + $template = '{{ post.excerpt }}'; + $post = Timber::get_post($pid); + $str = Timber::compile_string($template, [ + 'post' => $post, + ]); + $this->assertEquals('In my younger and more vulnerable years my father gave me some advice that I’ve been turning over in my mind ever since. Read More', $str); + } + + public function testPostExcerptObjectStrip() + { + $pid = $this->factory->post->create([ + 'post_content' => 'Great Gatsby', + 'post_excerpt' => 'In my younger and more vulnerable years my father gave me some advice that I’ve been turning over in my mind ever since.', + ]); + $template = '{{ post.excerpt.strip(false) }}'; + $post = Timber::get_post($pid); + $str = Timber::compile_string($template, [ + 'post' => $post, + ]); + $this->assertEquals('In my younger and more vulnerable years my father gave me some advice that I’ve been turning over in my mind ever since. Read More', $str); + } + + public function testPostExcerptObjectWithReadMore() + { + $pid = $this->factory->post->create([ + 'post_content' => 'Great Gatsby', + 'post_excerpt' => 'In my younger and more vulnerable years my father gave me some advice that I’ve been turning over in my mind ever since.', + ]); + $template = '{{ post.excerpt.read_more("Keep Reading") }}'; + $post = Timber::get_post($pid); + $str = Timber::compile_string($template, [ + 'post' => $post, + ]); + $this->assertEquals('In my younger and more vulnerable years my father gave me some advice that I’ve been turning over in my mind ever since. Keep Reading', $str); + } + + public function testPostExcerptObjectWithEverything() + { + $pid = $this->factory->post->create([ + 'post_content' => 'Great Gatsby', + 'post_excerpt' => 'In my younger and more vulnerable years my father gave me some advice that I’ve been turning over in my mind ever since.', + ]); + $template = '{{ post.excerpt.length(6).force.end("-->").read_more("Keep Reading") }}'; + $post = Timber::get_post($pid); + $str = Timber::compile_string($template, [ + 'post' => $post, + ]); + $this->assertEquals('In my younger and more vulnerable--> Keep Reading', $str); + } + + public function testExcerptWithMoreTagAndForcedLength() + { + $pid = $this->factory->post->create([ + 'post_content' => 'Lauren is a duck Lauren is not a duck', + 'post_excerpt' => '', + ]); + $post = Timber::get_post($pid); + + $this->assertEquals( + 'Lauren is a duck Read More', + (string) $post->excerpt() + ); + } + + public function testExcerptWithCustomMoreTag() + { + $pid = $this->factory->post->create([ + 'post_content' => 'Eric is a polar bear Lauren is not a duck', + 'post_excerpt' => '', + ]); + $post = Timber::get_post($pid); + $this->assertEquals('Eric is a polar bear But what is Elaina?', $post->excerpt()); + } + + public function testExcerptWithSpaceInMoreTag() + { + $pid = $this->factory->post->create([ + 'post_content' => 'Lauren is a duck, but a great duck let me tell you why Lauren is not a duck', + 'post_excerpt' => '', + ]); + $post = Timber::get_post($pid); + $template = '{{post.excerpt.length(3).force}}'; + $str = Timber::compile_string($template, [ + 'post' => $post, + ]); + $this->assertEquals('Lauren is a… Read More', $str); + } + + public function testExcerptWithStripAndClosingPTag() + { + $pid = $this->factory->post->create([ + 'post_excerpt' => '

        Lauren is a duck, but a great duck let me tell you why

        ', + ]); + $post = Timber::get_post($pid); + $template = '{{post.excerpt.strip(false)}}'; + $str = Timber::compile_string($template, [ + 'post' => $post, + ]); + $this->assertEquals('

        Lauren is a duck, but a great duck let me tell you why Read More

        ', $str); + } + + public function testExcerptWithStripAndClosingPTagForced() + { + $pid = $this->factory->post->create([ + 'post_excerpt' => '

        Lauren is a duck, but a great duck let me tell you why

        ', + ]); + $post = Timber::get_post($pid); + $template = '{{post.excerpt.strip(false).force(4)}}'; + $str = Timber::compile_string($template, [ + 'post' => $post, + ]); + $this->assertEquals('

        Lauren is a duck, but a great duck let me tell you why… Read More

        ', $str); + } + + public function testEmptyExcerpt() + { + $pid = $this->factory->post->create([ + 'post_excerpt' => '', + 'post_content' => '', + ]); + $post = Timber::get_post($pid); + $template = '{{ post.excerpt }}'; + $str = Timber::compile_string($template, [ + 'post' => $post, + ]); + $this->assertEquals('', $str); + } + /** - * @group posts-api + * @ticket #2045 */ - class TestTimberPostExcerptObject extends Timber_UnitTestCase + public function testPageExcerptOnSearch() { - protected $gettysburg = 'Four score and seven years ago our fathers brought forth on this continent a new nation, conceived in liberty, and dedicated to the proposition that all men are created equal.'; - - public function test1886Error() - { - $expected = '

        Govenment:

        • of the people
        • by the people
        • for the people
        '; - $post_id = $this->factory->post->create([ - 'post_content' => $expected . '
        Lincoln
        ', - 'post_excerpt' => false, - ]); - $post = Timber::get_post($post_id); - $template = "{{ post.excerpt( {strip:'


          1. '}) }}"; - $str = Timber::compile_string($template, [ - 'post' => $post, - ]); - $this->assertEquals($expected . '

            Lincoln

            Read More', $str); - } - - public function test1886ErrorWithForce() - { - $expected = '

            Government:

            • of the people
            • by the people
            • for the people
            '; - $post_id = $this->factory->post->create([ - 'post_excerpt' => $expected, - 'post_content' => $this->gettysburg, - ]); - $post = Timber::get_post($post_id); - $template = '{{ post.excerpt({ - strip: "
            • ", - words:10, - force:true }) - }}'; - $str = Timber::compile_string($template, [ - 'post' => $post, - ]); - $this->assertEquals('Government:
              • of the people
              • by the people
              • for the
              Read More', $str); - } - - public function testExcerptConstructorWithWords() - { - $post_id = $this->factory->post->create([ - 'post_excerpt' => $this->gettysburg, - ]); - $post = Timber::get_post($post_id); - $excerpt = $post->excerpt([ - 'words' => 4, - 'force' => true, - 'read_more' => false, - ]); - - // Coerce excerpt to a string and test it. - $this->assertEquals('Four score and seven…', '' . $excerpt); - } - - public function testExcerptConstructorWithChars() - { - $post_id = $this->factory->post->create([ - 'post_excerpt' => $this->gettysburg, - ]); - $post = Timber::get_post($post_id); - $excerpt = $post->excerpt([ - 'chars' => 20, - 'force' => true, - 'read_more' => false, - ]); - - // Coerce excerpt to a string and test it. - $this->assertEquals('Four score and seven…', '' . $excerpt); - } - - public function testExcerptConstructorWithEnd() - { - $post_id = $this->factory->post->create([ - 'post_excerpt' => $this->gettysburg, - ]); - $post = Timber::get_post($post_id); - $excerpt = $post->excerpt([ - 'chars' => 20, - 'force' => true, - 'read_more' => false, - 'end' => ' - kthxbi', - ]); - - // Coerce excerpt to a string and test it. - $this->assertEquals('Four score and seven - kthxbi', '' . $excerpt); - } - - public function testExcerptConstructorWithHtml() - { - $post_id = $this->factory->post->create([ - 'post_excerpt' => 'Yo' - . ' CLICK' - . ' STRONG ' - . $this->gettysburg, - ]); - $post = Timber::get_post($post_id); - $excerpt = $post->excerpt([ - 'chars' => 26, - 'read_more' => false, - 'force' => true, - ]); - - // Coerce excerpt to a string and test it. - $this->assertEquals('Yo CLICK STRONG Four score…', '' . $excerpt); - } - - public function testExcerptConstructorStrippingSomeTags() - { - $post_id = $this->factory->post->create([ - 'post_excerpt' => 'Yo' - . ' CLICK' - . ' STRONG ' - . $this->gettysburg, - ]); - $post = Timber::get_post($post_id); - $excerpt = $post->excerpt([ - 'words' => 5, - 'read_more' => false, - 'force' => true, - 'strip' => '', - ]); - - // Coerce excerpt to a string and test it. - $this->assertEquals( - 'Yo CLICK STRONG Four…', - '' . $excerpt - ); - } - - public function testExcerptConstructorWithReadMore() - { - $post_id = $this->factory->post->create([ - 'post_excerpt' => $this->gettysburg, - ]); - $post = Timber::get_post($post_id); - $readmore = 'read more! if you dare...'; - $excerpt = $post->excerpt([ - 'chars' => 20, - 'force' => true, - 'read_more' => 'read more! if you dare...', - ]); - - $expected = sprintf( - 'Four score and seven… %s', - $post->link(), - $readmore - ); - - // Coerce excerpt to a string and test it. - $this->assertEquals($expected, '' . $excerpt); - } - - public function testExcerptWithStyleTags() - { - global $wpdb; - $style = 'Yo. '; - $id = $wpdb->insert( - $wpdb->posts, - [ - 'post_author' => '1', - 'post_content' => $style . $this->gettysburg, - 'post_title' => 'Thing', - 'post_date' => '2017-03-01 00:21:40', - 'post_date_gmt' => '2017-03-01 00:21:40', - ] - ); - $post_id = $wpdb->insert_id; - $post = Timber::get_post($post_id); - $template = '{{ post.excerpt.length(9).read_more(false).strip(true) }}'; - $str = Timber::compile_string($template, [ - 'post' => $post, - ]); - $this->assertEquals('Yo. Four score and seven years ago our fathers…', $str); - } - - public function testExcerptTags() - { - $post_id = $this->factory->post->create([ - 'post_excerpt' => 'It turned out that just about anyone in authority — cops, judges, city leaders — was in on the game.', - ]); - $post = Timber::get_post($post_id); - $template = '{{ post.excerpt.length(3).read_more(false).strip(false) }}'; - $str = Timber::compile_string($template, [ - 'post' => $post, - ]); - $this->assertStringNotContainsString('

              ', $str); - } - - public function testPostExcerptObjectWithCharAndWordLengthWordsWin() - { - $pid = $this->factory->post->create([ - 'post_content' => $this->gettysburg, - 'post_excerpt' => '', - ]); - $template = '{{ post.excerpt.length(2).chars(20) }}'; - $post = Timber::get_post($pid); - $str = Timber::compile_string($template, [ - 'post' => $post, - ]); - $this->assertEquals('Four score… Read More', $str); - } - - public function testPostExcerptObjectWithCharAndWordLengthCharsWin() - { - $pid = $this->factory->post->create([ - 'post_content' => $this->gettysburg, - 'post_excerpt' => '', - ]); - $template = '{{ post.excerpt.length(20).chars(20) }}'; - $post = Timber::get_post($pid); - $str = Timber::compile_string($template, [ - 'post' => $post, - ]); - $this->assertEquals('Four score and seven… Read More', $str); - } - - public function testPostExcerptObjectWithCharLength() - { - $pid = $this->factory->post->create([ - 'post_content' => $this->gettysburg, - 'post_excerpt' => '', - ]); - $template = '{{ post.excerpt.chars(20) }}'; - $post = Timber::get_post($pid); - $str = Timber::compile_string($template, [ - 'post' => $post, - ]); - $this->assertEquals('Four score and seven… Read More', $str); - } - - public function testPostExcerptObjectWithLength() - { - $pid = $this->factory->post->create([ - 'post_content' => 'Lauren is a duck she a big ole duck!', - 'post_excerpt' => '', - ]); - $template = '{{ post.excerpt.length(4) }}'; - $post = Timber::get_post($pid); - $str = Timber::compile_string($template, [ - 'post' => $post, - ]); - $this->assertEquals('Lauren is a duck… Read More', $str); - } - - public function testPostExcerptObjectWithForcedLength() - { - $pid = $this->factory->post->create([ - 'post_content' => 'Great Gatsby', - 'post_excerpt' => 'In my younger and more vulnerable years my father gave me some advice that I’ve been turning over in my mind ever since.', - ]); - $template = '{{ post.excerpt.force.length(3) }}'; - $post = Timber::get_post($pid); - $str = Timber::compile_string($template, [ - 'post' => $post, - ]); - $this->assertEquals('In my younger… Read More', $str); - } - - public function testPostExcerptObject() - { - $pid = $this->factory->post->create([ - 'post_content' => 'Great Gatsby', - 'post_excerpt' => 'In my younger and more vulnerable years my father gave me some advice that I’ve been turning over in my mind ever since.', - ]); - $template = '{{ post.excerpt }}'; - $post = Timber::get_post($pid); - $str = Timber::compile_string($template, [ - 'post' => $post, - ]); - $this->assertEquals('In my younger and more vulnerable years my father gave me some advice that I’ve been turning over in my mind ever since. Read More', $str); - } - - public function testPostExcerptObjectStrip() - { - $pid = $this->factory->post->create([ - 'post_content' => 'Great Gatsby', - 'post_excerpt' => 'In my younger and more vulnerable years my father gave me some advice that I’ve been turning over in my mind ever since.', - ]); - $template = '{{ post.excerpt.strip(false) }}'; - $post = Timber::get_post($pid); - $str = Timber::compile_string($template, [ - 'post' => $post, - ]); - $this->assertEquals('In my younger and more vulnerable years my father gave me some advice that I’ve been turning over in my mind ever since. Read More', $str); - } - - public function testPostExcerptObjectWithReadMore() - { - $pid = $this->factory->post->create([ - 'post_content' => 'Great Gatsby', - 'post_excerpt' => 'In my younger and more vulnerable years my father gave me some advice that I’ve been turning over in my mind ever since.', - ]); - $template = '{{ post.excerpt.read_more("Keep Reading") }}'; - $post = Timber::get_post($pid); - $str = Timber::compile_string($template, [ - 'post' => $post, - ]); - $this->assertEquals('In my younger and more vulnerable years my father gave me some advice that I’ve been turning over in my mind ever since. Keep Reading', $str); - } - - public function testPostExcerptObjectWithEverything() - { - $pid = $this->factory->post->create([ - 'post_content' => 'Great Gatsby', - 'post_excerpt' => 'In my younger and more vulnerable years my father gave me some advice that I’ve been turning over in my mind ever since.', - ]); - $template = '{{ post.excerpt.length(6).force.end("-->").read_more("Keep Reading") }}'; - $post = Timber::get_post($pid); - $str = Timber::compile_string($template, [ - 'post' => $post, - ]); - $this->assertEquals('In my younger and more vulnerable--> Keep Reading', $str); - } - - public function testExcerptWithMoreTagAndForcedLength() - { - $pid = $this->factory->post->create([ - 'post_content' => 'Lauren is a duck Lauren is not a duck', - 'post_excerpt' => '', - ]); - $post = Timber::get_post($pid); - - $this->assertEquals( - 'Lauren is a duck Read More', - (string) $post->excerpt() - ); - } - - public function testExcerptWithCustomMoreTag() - { - $pid = $this->factory->post->create([ - 'post_content' => 'Eric is a polar bear Lauren is not a duck', - 'post_excerpt' => '', - ]); - $post = Timber::get_post($pid); - $this->assertEquals('Eric is a polar bear But what is Elaina?', $post->excerpt()); - } - - public function testExcerptWithSpaceInMoreTag() - { - $pid = $this->factory->post->create([ - 'post_content' => 'Lauren is a duck, but a great duck let me tell you why Lauren is not a duck', - 'post_excerpt' => '', - ]); - $post = Timber::get_post($pid); - $template = '{{post.excerpt.length(3).force}}'; - $str = Timber::compile_string($template, [ - 'post' => $post, - ]); - $this->assertEquals('Lauren is a… Read More', $str); - } - - public function testExcerptWithStripAndClosingPTag() - { - $pid = $this->factory->post->create([ - 'post_excerpt' => '

              Lauren is a duck, but a great duck let me tell you why

              ', - ]); - $post = Timber::get_post($pid); - $template = '{{post.excerpt.strip(false)}}'; - $str = Timber::compile_string($template, [ - 'post' => $post, - ]); - $this->assertEquals('

              Lauren is a duck, but a great duck let me tell you why Read More

              ', $str); - } - - public function testExcerptWithStripAndClosingPTagForced() - { - $pid = $this->factory->post->create([ - 'post_excerpt' => '

              Lauren is a duck, but a great duck let me tell you why

              ', - ]); - $post = Timber::get_post($pid); - $template = '{{post.excerpt.strip(false).force(4)}}'; - $str = Timber::compile_string($template, [ - 'post' => $post, - ]); - $this->assertEquals('

              Lauren is a duck, but a great duck let me tell you why… Read More

              ', $str); - } - - public function testEmptyExcerpt() - { - $pid = $this->factory->post->create([ - 'post_excerpt' => '', - 'post_content' => '', - ]); - $post = Timber::get_post($pid); - $template = '{{ post.excerpt }}'; - $str = Timber::compile_string($template, [ - 'post' => $post, - ]); - $this->assertEquals('', $str); - } - - /** - * @ticket #2045 - */ - public function testPageExcerptOnSearch() - { - $pid = $this->factory->post->create([ - 'post_type' => 'page', - 'post_content' => 'What a beautiful day for a ballgame!', - 'post_excerpt' => '', - ]); - $post = Timber::get_post($pid); - $template = '{{ post.excerpt }}'; - $str = Timber::compile_string($template, [ - 'post' => $post, - ]); - $this->assertEquals( - 'What a beautiful day for a ballgame!', - $str - ); - } + $pid = $this->factory->post->create([ + 'post_type' => 'page', + 'post_content' => 'What a beautiful day for a ballgame!', + 'post_excerpt' => '', + ]); + $post = Timber::get_post($pid); + $template = '{{ post.excerpt }}'; + $str = Timber::compile_string($template, [ + 'post' => $post, + ]); + $this->assertEquals( + 'What a beautiful day for a ballgame!', + $str + ); } +} diff --git a/tests/test-timber-post-password.php b/tests/test-timber-post-password.php index 10fec7632..82f0288bf 100644 --- a/tests/test-timber-post-password.php +++ b/tests/test-timber-post-password.php @@ -1,56 +1,56 @@ factory->post->create(); - $post = Timber::get_post($post_id); - $post->post_content = $quote; - $post->post_password = 'burrito'; - wp_update_post($post); - $password_form = get_the_password_form($post->ID); - $this->assertEquals(wpautop($quote), $post->content()); - } + $quote = 'The way to do well is to do well.'; + $post_id = $this->factory->post->create(); + $post = Timber::get_post($post_id); + $post->post_content = $quote; + $post->post_password = 'burrito'; + wp_update_post($post); + $password_form = get_the_password_form($post->ID); + $this->assertEquals(wpautop($quote), $post->content()); + } - public function testPasswordedContentWhenEnabled() - { - add_filter('timber/post/content/show_password_form_for_protected', function ($maybe_show) { - return true; - }); - $quote = 'The way to do well is to do well.'; - $post_id = $this->factory->post->create(); - $post = Timber::get_post($post_id); - $post->post_content = $quote; - $post->post_password = 'burrito'; - wp_update_post($post); - $password_form = get_the_password_form($post->ID); - $this->assertEquals($password_form, $post->content()); - } + public function testPasswordedContentWhenEnabled() + { + add_filter('timber/post/content/show_password_form_for_protected', function ($maybe_show) { + return true; + }); + $quote = 'The way to do well is to do well.'; + $post_id = $this->factory->post->create(); + $post = Timber::get_post($post_id); + $post->post_content = $quote; + $post->post_password = 'burrito'; + wp_update_post($post); + $password_form = get_the_password_form($post->ID); + $this->assertEquals($password_form, $post->content()); + } - public function testPasswordedContentWhenEnabledWithCustomForm() - { - add_filter('timber/post/content/show_password_form_for_protected', function ($maybe_show) { - return true; - }); - add_filter('timber/post/content/password_form', function ($form, $post) { - return Timber::compile('assets/password-form.twig', [ - 'post' => $post, - ]); - }, 10, 2); - $quote = 'The way to do well is to do well.'; - $post_id = $this->factory->post->create([ - 'post_title' => 'Secrets!', + public function testPasswordedContentWhenEnabledWithCustomForm() + { + add_filter('timber/post/content/show_password_form_for_protected', function ($maybe_show) { + return true; + }); + add_filter('timber/post/content/password_form', function ($form, $post) { + return Timber::compile('assets/password-form.twig', [ + 'post' => $post, ]); - $post = Timber::get_post($post_id); - $post->post_content = $quote; - $post->post_password = 'burrito'; - wp_update_post($post); - $password_form = '
              Enter password to see Secrets!
              '; - $this->assertEquals($password_form, $post->content()); - } + }, 10, 2); + $quote = 'The way to do well is to do well.'; + $post_id = $this->factory->post->create([ + 'post_title' => 'Secrets!', + ]); + $post = Timber::get_post($post_id); + $post->post_content = $quote; + $post->post_password = 'burrito'; + wp_update_post($post); + $password_form = '
              Enter password to see Secrets!
              '; + $this->assertEquals($password_form, $post->content()); } +} diff --git a/tests/test-timber-post-terms.php b/tests/test-timber-post-terms.php index 84f36b2a0..2662d1fc4 100644 --- a/tests/test-timber-post-terms.php +++ b/tests/test-timber-post-terms.php @@ -1,176 +1,176 @@ factory->post->create(); - $post = Timber::get_post($pid); - - // create a new tag and associate it with the post - $dummy_tag = wp_insert_term('whatever', 'post_tag'); - wp_set_object_terms($pid, $dummy_tag['term_id'], 'post_tag', true); - - $this->add_filter_temporarily('timber/term/classmap', function () { - return [ - 'post_tag' => MyTimberTerm::class, - ]; - }); - - $terms = $post->terms([ - 'query' => [ - 'taxonomy' => 'post_tag', - ], - ]); - $this->assertInstanceOf(MyTimberTerm::class, $terms[0]); - - $post = Timber::get_post($pid); - $terms = $post->terms([ - 'query' => [ - 'taxonomy' => 'post_tag', - ], - 'merge' => true, - ]); - $this->assertInstanceOf(MyTimberTerm::class, $terms[0]); - } - - /** - * @ticket #2203 - */ - public function testPostTermsUsingUsingFactories() - { - $pid = $this->factory->post->create(); - $post = Timber::get_post($pid); + $pid = $this->factory->post->create(); + $post = Timber::get_post($pid); - // create a new tag and associate it with the post - $dummy_tag = wp_insert_term('whatever', 'post_tag'); - $dummy_cat = wp_insert_term('news', 'category'); - wp_set_object_terms($pid, $dummy_tag['term_id'], 'post_tag', true); + // create a new tag and associate it with the post + $dummy_tag = wp_insert_term('whatever', 'post_tag'); + wp_set_object_terms($pid, $dummy_tag['term_id'], 'post_tag', true); - wp_set_object_terms($pid, $dummy_cat['term_id'], 'category', true); + $this->add_filter_temporarily('timber/term/classmap', function () { + return [ + 'post_tag' => MyTimberTerm::class, + ]; + }); - $this->add_filter_temporarily('timber/term/classmap', function () { - return [ - 'post_tag' => MyTimberTerm::class, - ]; - }); - - $terms = $post->terms([ + $terms = $post->terms([ + 'query' => [ 'taxonomy' => 'post_tag', - ]); - $this->assertInstanceOf(MyTimberTerm::class, $terms[0]); - - $post = Timber::get_post($pid); - $terms = $post->terms([], [ - 'merge' => false, - ]); - $this->assertEquals('whatever', $terms['post_tag'][0]->name); - - $terms = $post->terms([], [ - 'merge' => true, - ]); - $this->assertEquals(3, count($terms)); - } + ], + ]); + $this->assertInstanceOf(MyTimberTerm::class, $terms[0]); - /** - * @ticket #2163 - * This test confirms that term ordering works when sent through the query parameter of - * arguments. - */ - public function testPostTermOrder() - { - $pid = $this->factory->post->create(); - register_taxonomy('cars', 'post'); - $cars[] = $this->factory->term->create([ - 'name' => 'Honda Civic', - 'taxonomy' => 'cars', - ]); - $cars[] = $this->factory->term->create([ - 'name' => 'Toyota Corolla', - 'taxonomy' => 'cars', - ]); - $cars[] = $this->factory->term->create([ - 'name' => 'Toyota Camry', - 'taxonomy' => 'cars', - ]); - $cars[] = $this->factory->term->create([ - 'name' => 'Dodge Intrepid', - 'taxonomy' => 'cars', - ]); - foreach ($cars as $tid) { - $car = Timber::get_term($tid); - } - wp_set_object_terms($pid, $cars, 'cars', false); - $post = Timber::get_post($pid); - $template = "{% for term_item in post.terms({query : {taxonomy: 'cars', orderby: 'term_id', order: 'ASC'}}) %}{{ term_item.name }} {% endfor %}"; - $str = Timber::compile_string($template, [ - 'post' => $post, - ]); - $this->assertEquals('Honda Civic Toyota Corolla Toyota Camry Dodge Intrepid ', $str); - } + $post = Timber::get_post($pid); + $terms = $post->terms([ + 'query' => [ + 'taxonomy' => 'post_tag', + ], + 'merge' => true, + ]); + $this->assertInstanceOf(MyTimberTerm::class, $terms[0]); + } - /** - * This should return an error because the "dfasdf" taxonomy doesn't exist - * NOTE: In Timber 1.x this returned a WP_Error. - */ - public function testTermExceptions() - { - self::enable_error_log(false); - $pid = $this->factory->post->create(); - $post = Timber::get_post($pid); - $terms = $post->terms('dfasdf'); - $this->assertEmpty($terms); - self::enable_error_log(true); - } + /** + * @ticket #2203 + */ + public function testPostTermsUsingUsingFactories() + { + $pid = $this->factory->post->create(); + $post = Timber::get_post($pid); + + // create a new tag and associate it with the post + $dummy_tag = wp_insert_term('whatever', 'post_tag'); + $dummy_cat = wp_insert_term('news', 'category'); + wp_set_object_terms($pid, $dummy_tag['term_id'], 'post_tag', true); + + wp_set_object_terms($pid, $dummy_cat['term_id'], 'category', true); + + $this->add_filter_temporarily('timber/term/classmap', function () { + return [ + 'post_tag' => MyTimberTerm::class, + ]; + }); + + $terms = $post->terms([ + 'taxonomy' => 'post_tag', + ]); + $this->assertInstanceOf(MyTimberTerm::class, $terms[0]); + + $post = Timber::get_post($pid); + $terms = $post->terms([], [ + 'merge' => false, + ]); + $this->assertEquals('whatever', $terms['post_tag'][0]->name); + + $terms = $post->terms([], [ + 'merge' => true, + ]); + $this->assertEquals(3, count($terms)); + } - /** - * This shouldn't return an error because the "foobar" taxonomy DOES exist - */ - public function testTermFromNonExistentTaxonomy() - { - self::enable_error_log(false); - register_taxonomy('foobar', 'post'); - $pid = $this->factory->post->create(); - $post = Timber::get_post($pid); - $terms = $post->terms('foobar'); - $this->assertEmpty($terms); - self::enable_error_log(true); + /** + * @ticket #2163 + * This test confirms that term ordering works when sent through the query parameter of + * arguments. + */ + public function testPostTermOrder() + { + $pid = $this->factory->post->create(); + register_taxonomy('cars', 'post'); + $cars[] = $this->factory->term->create([ + 'name' => 'Honda Civic', + 'taxonomy' => 'cars', + ]); + $cars[] = $this->factory->term->create([ + 'name' => 'Toyota Corolla', + 'taxonomy' => 'cars', + ]); + $cars[] = $this->factory->term->create([ + 'name' => 'Toyota Camry', + 'taxonomy' => 'cars', + ]); + $cars[] = $this->factory->term->create([ + 'name' => 'Dodge Intrepid', + 'taxonomy' => 'cars', + ]); + foreach ($cars as $tid) { + $car = Timber::get_term($tid); } + wp_set_object_terms($pid, $cars, 'cars', false); + $post = Timber::get_post($pid); + $template = "{% for term_item in post.terms({query : {taxonomy: 'cars', orderby: 'term_id', order: 'ASC'}}) %}{{ term_item.name }} {% endfor %}"; + $str = Timber::compile_string($template, [ + 'post' => $post, + ]); + $this->assertEquals('Honda Civic Toyota Corolla Toyota Camry Dodge Intrepid ', $str); + } - public function testTermNotMerged() - { - $pid = $this->factory->post->create(); + /** + * This should return an error because the "dfasdf" taxonomy doesn't exist + * NOTE: In Timber 1.x this returned a WP_Error. + */ + public function testTermExceptions() + { + self::enable_error_log(false); + $pid = $this->factory->post->create(); + $post = Timber::get_post($pid); + $terms = $post->terms('dfasdf'); + $this->assertEmpty($terms); + self::enable_error_log(true); + } - // create a new tag and category and associate each with the post - $tag_id = $this->factory->term->create([ - 'name' => 'whatever', - 'taxonomy' => 'post_tag', - ]); - $cat_id = $this->factory->term->create([ - 'name' => 'thingy', - 'taxonomy' => 'category', - ]); - wp_set_object_terms($pid, $tag_id, 'post_tag', true); - wp_set_object_terms($pid, $cat_id, 'category', true); - - $post = Timber::get_post($pid); - $terms = $post->terms([ - 'query' => [ - 'taxonomy' => 'all', - ], - 'merge' => false, - ]); - - $this->assertEquals($terms['post_tag'][0]->name, 'whatever'); - $this->assertEquals($terms['category'][0]->name, 'thingy'); - } + /** + * This shouldn't return an error because the "foobar" taxonomy DOES exist + */ + public function testTermFromNonExistentTaxonomy() + { + self::enable_error_log(false); + register_taxonomy('foobar', 'post'); + $pid = $this->factory->post->create(); + $post = Timber::get_post($pid); + $terms = $post->terms('foobar'); + $this->assertEmpty($terms); + self::enable_error_log(true); } - class MyTimberTerm extends Timber\Term + public function testTermNotMerged() { + $pid = $this->factory->post->create(); + + // create a new tag and category and associate each with the post + $tag_id = $this->factory->term->create([ + 'name' => 'whatever', + 'taxonomy' => 'post_tag', + ]); + $cat_id = $this->factory->term->create([ + 'name' => 'thingy', + 'taxonomy' => 'category', + ]); + wp_set_object_terms($pid, $tag_id, 'post_tag', true); + wp_set_object_terms($pid, $cat_id, 'category', true); + + $post = Timber::get_post($pid); + $terms = $post->terms([ + 'query' => [ + 'taxonomy' => 'all', + ], + 'merge' => false, + ]); + + $this->assertEquals($terms['post_tag'][0]->name, 'whatever'); + $this->assertEquals($terms['category'][0]->name, 'thingy'); } +} + +class MyTimberTerm extends Timber\Term +{ +} diff --git a/tests/test-timber-post-title.php b/tests/test-timber-post-title.php index 8420532c5..138f46f1d 100644 --- a/tests/test-timber-post-title.php +++ b/tests/test-timber-post-title.php @@ -1,17 +1,17 @@ factory->post->create([ - 'post_title' => 'Jared & Lauren', - ]); - $post = Timber::get_post($post_id); - $this->assertEquals(get_the_title($post_id), $post->title()); - $this->assertEquals(get_the_title($post_id), $post->post_title); - } + $post_id = $this->factory->post->create([ + 'post_title' => 'Jared & Lauren', + ]); + $post = Timber::get_post($post_id); + $this->assertEquals(get_the_title($post_id), $post->title()); + $this->assertEquals(get_the_title($post_id), $post->post_title); } +} diff --git a/tests/test-timber-post-type.php b/tests/test-timber-post-type.php index 643fa3d26..be2c4be5c 100644 --- a/tests/test-timber-post-type.php +++ b/tests/test-timber-post-type.php @@ -1,64 +1,64 @@ restore_locale(); - $obj = get_post_type_object('post'); - $this->assertEquals('Posts', $obj->labels->name); - } + restore_current_locale(); + $obj = get_post_type_object('post'); + $this->assertEquals('Posts', $obj->labels->name); + } - public function testPostTypeProperty() - { - $post_id = $this->factory->post->create(); - $post = Timber::get_post($post_id); - $this->assertEquals('post', $post->post_type); - } + public function testPostTypeProperty() + { + $post_id = $this->factory->post->create(); + $post = Timber::get_post($post_id); + $this->assertEquals('post', $post->post_type); + } - /** - * @ticket #2111 - */ - public function testNonExistentPostType() - { - $post_type = new Timber\PostType('foobar'); - $this->assertEquals('foobar', $post_type); - $this->assertEquals('Timber\PostType', get_class($post_type)); - } + /** + * @ticket #2111 + */ + public function testNonExistentPostType() + { + $post_type = new Timber\PostType('foobar'); + $this->assertEquals('foobar', $post_type); + $this->assertEquals('Timber\PostType', get_class($post_type)); + } - public function testPostTypeMethodInTwig() - { - $post_id = $this->factory->post->create(); - $post = Timber::get_post($post_id); - $template = '{{post.post_type}}'; - $str = Timber::compile_string($template, [ - 'post' => $post, - ]); - $this->assertEquals('post', $str); - } + public function testPostTypeMethodInTwig() + { + $post_id = $this->factory->post->create(); + $post = Timber::get_post($post_id); + $template = '{{post.post_type}}'; + $str = Timber::compile_string($template, [ + 'post' => $post, + ]); + $this->assertEquals('post', $str); + } - public function testTypeMethodInTwig() - { - $post_id = $this->factory->post->create(); - $post = Timber::get_post($post_id); - $template = '{{post.type}}'; - $str = Timber::compile_string($template, [ - 'post' => $post, - ]); - $this->assertEquals('post', $str); - } + public function testTypeMethodInTwig() + { + $post_id = $this->factory->post->create(); + $post = Timber::get_post($post_id); + $template = '{{post.type}}'; + $str = Timber::compile_string($template, [ + 'post' => $post, + ]); + $this->assertEquals('post', $str); + } - public function testTypeMethodInTwigLabels() - { - $post_id = $this->factory->post->create(); - $post = Timber::get_post($post_id); - $template = '{{post.type.labels.name}}'; - $str = Timber::compile_string($template, [ - 'post' => $post, - ]); - $this->assertEquals('Posts', $str); - } + public function testTypeMethodInTwigLabels() + { + $post_id = $this->factory->post->create(); + $post = Timber::get_post($post_id); + $template = '{{post.type.labels.name}}'; + $str = Timber::compile_string($template, [ + 'post' => $post, + ]); + $this->assertEquals('Posts', $str); } +} diff --git a/tests/test-timber-revisions.php b/tests/test-timber-revisions.php index 579abc057..51834e200 100644 --- a/tests/test-timber-revisions.php +++ b/tests/test-timber-revisions.php @@ -1,366 +1,366 @@ queried_object_id = $post_id; - $wp_query->queried_object = get_post($post_id); - $_GET['preview'] = true; - $_GET['preview_nonce'] = wp_create_nonce('post_preview_' . $post_id); - } - - public function testParentOfPost() - { - // Register Custom Post Type - - $args = [ - 'label' => __('Box', 'text_domain'), - 'description' => __('Post Type Description', 'text_domain'), - 'supports' => ['title', 'editor', 'revisions'], - 'taxonomies' => ['category', 'post_tag'], - 'hierarchical' => true, - 'public' => true, - 'show_ui' => true, - 'show_in_menu' => true, - 'menu_position' => 5, - 'show_in_admin_bar' => true, - 'show_in_nav_menus' => true, - 'can_export' => true, - 'has_archive' => true, - 'exclude_from_search' => false, - 'publicly_queryable' => true, - 'capability_type' => 'page', - ]; - register_post_type('box', $args); - - global $current_user; - global $wp_query; - - $uid = $this->factory->user->create([ - 'user_login' => 'timber', - 'user_pass' => 'timber', - ]); - $user = wp_set_current_user($uid); - $user->add_role('administrator'); - - $parent_id = $this->factory->post->create([ - 'post_content' => 'I am parent', - 'post_type' => 'box', - 'post_author' => $uid, - ]); - - $post_id = $this->factory->post->create([ - 'post_content' => 'I am child', - 'post_type' => 'box', - 'post_author' => $uid, - 'post_parent' => $parent_id, - ]); - - $revision_id = $this->factory->post->create([ - 'post_type' => 'revision', - 'post_status' => 'inherit', - 'post_parent' => $post_id, - 'post_content' => 'I am revised', - ]); - - $post = Timber::get_post($post_id); - $parent = Timber::get_post($parent_id); - - //$this->assertEquals($parent_id, $post->parent()->id); - - self::setRevision($post_id); - $revision = Timber::get_post(); - - $this->assertEquals('I am revised', trim(strip_tags($revision->content()))); - - $revision_parent = $revision->parent(); - $this->assertEquals($parent_id, $revision_parent->id); - $this->assertEquals('I am parent', trim(strip_tags($revision_parent->content()))); - } - - public function testPreviewClass() - { - global $current_user; - global $wp_query; - - $quote = 'The way to do well is to do well.'; - $post_id = $this->factory->post->create([ - 'post_content' => $quote, - 'post_author' => 5, - ]); - $revision_id = $this->factory->post->create([ - 'post_type' => 'revision', - 'post_status' => 'inherit', - 'post_parent' => $post_id, - 'post_content' => $quote . 'Yes', - ]); - - $uid = $this->factory->user->create([ - 'user_login' => 'timber', - 'user_pass' => 'timber', - ]); - - $original_post = Timber::get_post($post_id); - $user = wp_set_current_user($uid); - - $user->add_role('administrator'); - $wp_query->queried_object_id = $post_id; - $wp_query->queried_object = get_post($post_id); - $_GET['preview'] = true; - $_GET['preview_nonce'] = wp_create_nonce('post_preview_' . $post_id); - $post = Timber::get_post(); - $this->assertEquals($original_post->class(), $post->class()); - } - - public function testPreviewTitleWithID() - { - global $current_user; - global $wp_query; - - $post_id = $this->factory->post->create([ - 'post_title' => 'I call it banana bread', - 'post_author' => 5, - ]); - $revision_id = $this->factory->post->create([ - 'post_type' => 'revision', - 'post_status' => 'inherit', - 'post_parent' => $post_id, - 'post_title' => 'I call it fromage', - ]); - - $uid = $this->factory->user->create([ - 'user_login' => 'timber', - 'user_pass' => 'timber', - ]); - $user = wp_set_current_user($uid); - - $user->add_role('administrator'); - $wp_query->queried_object_id = $post_id; - $wp_query->queried_object = get_post($post_id); - $_GET['preview'] = true; - $_GET['preview_nonce'] = wp_create_nonce('post_preview_' . $post_id); - $post = Timber::get_post($post_id); - $this->assertEquals('I call it fromage', $post->title()); - } - - public function testPreviewContentWithID() - { - global $current_user; - global $wp_query; - - $quote = 'The way to do well is to do well.'; - $post_id = $this->factory->post->create([ - 'post_content' => $quote, - 'post_author' => 5, - ]); - $revision_id = $this->factory->post->create([ - 'post_type' => 'revision', - 'post_status' => 'inherit', - 'post_parent' => $post_id, - 'post_content' => $quote . 'Yes', - ]); - - $uid = $this->factory->user->create([ - 'user_login' => 'timber', - 'user_pass' => 'timber', - ]); - $user = wp_set_current_user($uid); - - $user->add_role('administrator'); - $wp_query->queried_object_id = $post_id; - $wp_query->queried_object = get_post($post_id); - $_GET['preview'] = true; - $_GET['preview_nonce'] = wp_create_nonce('post_preview_' . $post_id); - $post = Timber::get_post($post_id); - $this->assertEquals($quote . 'Yes', trim(strip_tags($post->content()))); - } - - public function testPreviewContent() - { - global $current_user; - global $wp_query; - - $quote = 'The way to do well is to do well.'; - $post_id = $this->factory->post->create([ - 'post_content' => $quote, - 'post_author' => 5, - ]); - $revision_id = $this->factory->post->create([ - 'post_type' => 'revision', - 'post_status' => 'inherit', - 'post_parent' => $post_id, - 'post_content' => $quote . 'Yes', - ]); - - $uid = $this->factory->user->create([ - 'user_login' => 'timber', - 'user_pass' => 'timber', - ]); - $user = wp_set_current_user($uid); - - $user->add_role('administrator'); - $wp_query->queried_object_id = $post_id; - $wp_query->queried_object = get_post($post_id); - $_GET['preview'] = true; - $_GET['preview_nonce'] = wp_create_nonce('post_preview_' . $post_id); - $post = Timber::get_post(); - $this->assertEquals($quote . 'Yes', trim(strip_tags($post->content()))); - } - - public function testMultiPreviewRevisions() - { - global $current_user; - global $wp_query; - - $quote = 'The way to do well is to do well.'; - $post_id = $this->factory->post->create([ - 'post_content' => $quote, - 'post_author' => 5, - ]); - $old_revision_id = $this->factory->post->create([ - 'post_type' => 'revision', - 'post_status' => 'inherit', - 'post_parent' => $post_id, - 'post_content' => $quote . 'Yes', - ]); - - $revision_id = $this->factory->post->create([ - 'post_type' => 'revision', - 'post_status' => 'inherit', - 'post_parent' => $post_id, - 'post_content' => 'I am the one', - ]); - - $uid = $this->factory->user->create([ - 'user_login' => 'timber', - 'user_pass' => 'timber', - ]); - $user = wp_set_current_user($uid); - - $user->add_role('administrator'); - $wp_query->queried_object_id = $post_id; - $wp_query->queried_object = get_post($post_id); - $_GET['preview'] = true; - $_GET['preview_nonce'] = wp_create_nonce('post_preview_' . $post_id); - $post = Timber::get_post(); - $this->assertEquals('I am the one', trim(strip_tags($post->content()))); - } - - public function testCustomFieldPreviewRevisionMethod() - { - global $current_user; - global $wp_query; - - $post_id = $this->factory->post->create([ - 'post_author' => 5, - ]); - update_field('test_field', 'The custom field content', $post_id); - - $assertCustomFieldVal = 'This has been revised'; - $revision_id = $this->factory->post->create([ - 'post_type' => 'revision', - 'post_status' => 'inherit', - 'post_parent' => $post_id, - ]); - update_field('test_field', $assertCustomFieldVal, $revision_id); - - $uid = $this->factory->user->create([ - 'user_login' => 'timber', - 'user_pass' => 'timber', - ]); - $user = wp_set_current_user($uid); - $user->add_role('administrator'); - - $wp_query->queried_object_id = $post_id; - $wp_query->queried_object = get_post($post_id); - $_GET['preview'] = true; - $_GET['preview_nonce'] = wp_create_nonce('post_preview_' . $post_id); - $post = Timber::get_post($post_id); - $str_getfield = Timber::compile_string('{{post.meta(\'test_field\')}}', [ - 'post' => $post, - ]); - $this->assertEquals($assertCustomFieldVal, $str_getfield); - } - - public function testCustomFieldPreviewRevisionImported() - { - global $current_user; - global $wp_query; - - $post_id = $this->factory->post->create([ - 'post_author' => 5, - ]); - update_field('test_field', 'The custom field content', $post_id); - - $assertCustomFieldVal = 'This has been revised'; - $revision_id = $this->factory->post->create([ - 'post_type' => 'revision', - 'post_status' => 'inherit', - 'post_parent' => $post_id, - ]); - update_field('test_field', $assertCustomFieldVal, $revision_id); - - $uid = $this->factory->user->create([ - 'user_login' => 'timber', - 'user_pass' => 'timber', - ]); - $user = wp_set_current_user($uid); - $user->add_role('administrator'); - - $wp_query->queried_object_id = $post_id; - $wp_query->queried_object = get_post($post_id); - $_GET['preview'] = true; - $_GET['preview_nonce'] = wp_create_nonce('post_preview_' . $post_id); - $post = Timber::get_post($post_id); - $str_direct = Timber::compile_string('{{ post.meta("test_field") }}', [ - 'post' => $post, - ]); - $this->assertEquals($assertCustomFieldVal, $str_direct); - } - - public function testCustomFieldPreviewNotRevision() - { - global $current_user; - global $wp_query; - $original_content = 'The custom field content'; - - $post_id = $this->factory->post->create([ - 'post_author' => 5, - ]); - update_field('test_field', $original_content, $post_id); - - $assertCustomFieldVal = 'This has been revised'; - $revision_id = $this->factory->post->create([ - 'post_type' => 'revision', - 'post_status' => 'inherit', - 'post_parent' => $post_id, - ]); - update_field('test_field', $assertCustomFieldVal, $revision_id); - - $uid = $this->factory->user->create([ - 'user_login' => 'timber', - 'user_pass' => 'timber', - ]); - $user = wp_set_current_user($uid); - $user->add_role('administrator'); - - $wp_query->queried_object_id = $post_id; - $wp_query->queried_object = get_post($post_id); - $post = Timber::get_post($post_id); - - $str_direct = Timber::compile_string('{{post.test_field}}', [ - 'post' => $post, - ]); - $str_getfield = Timber::compile_string('{{post.meta(\'test_field\')}}', [ - 'post' => $post, - ]); - - $this->assertEquals($original_content, $str_direct); - $this->assertEquals($original_content, $str_getfield); - } + global $wp_query; + $wp_query->queried_object_id = $post_id; + $wp_query->queried_object = get_post($post_id); + $_GET['preview'] = true; + $_GET['preview_nonce'] = wp_create_nonce('post_preview_' . $post_id); } + + public function testParentOfPost() + { + // Register Custom Post Type + + $args = [ + 'label' => __('Box', 'text_domain'), + 'description' => __('Post Type Description', 'text_domain'), + 'supports' => ['title', 'editor', 'revisions'], + 'taxonomies' => ['category', 'post_tag'], + 'hierarchical' => true, + 'public' => true, + 'show_ui' => true, + 'show_in_menu' => true, + 'menu_position' => 5, + 'show_in_admin_bar' => true, + 'show_in_nav_menus' => true, + 'can_export' => true, + 'has_archive' => true, + 'exclude_from_search' => false, + 'publicly_queryable' => true, + 'capability_type' => 'page', + ]; + register_post_type('box', $args); + + global $current_user; + global $wp_query; + + $uid = $this->factory->user->create([ + 'user_login' => 'timber', + 'user_pass' => 'timber', + ]); + $user = wp_set_current_user($uid); + $user->add_role('administrator'); + + $parent_id = $this->factory->post->create([ + 'post_content' => 'I am parent', + 'post_type' => 'box', + 'post_author' => $uid, + ]); + + $post_id = $this->factory->post->create([ + 'post_content' => 'I am child', + 'post_type' => 'box', + 'post_author' => $uid, + 'post_parent' => $parent_id, + ]); + + $revision_id = $this->factory->post->create([ + 'post_type' => 'revision', + 'post_status' => 'inherit', + 'post_parent' => $post_id, + 'post_content' => 'I am revised', + ]); + + $post = Timber::get_post($post_id); + $parent = Timber::get_post($parent_id); + + //$this->assertEquals($parent_id, $post->parent()->id); + + self::setRevision($post_id); + $revision = Timber::get_post(); + + $this->assertEquals('I am revised', trim(strip_tags($revision->content()))); + + $revision_parent = $revision->parent(); + $this->assertEquals($parent_id, $revision_parent->id); + $this->assertEquals('I am parent', trim(strip_tags($revision_parent->content()))); + } + + public function testPreviewClass() + { + global $current_user; + global $wp_query; + + $quote = 'The way to do well is to do well.'; + $post_id = $this->factory->post->create([ + 'post_content' => $quote, + 'post_author' => 5, + ]); + $revision_id = $this->factory->post->create([ + 'post_type' => 'revision', + 'post_status' => 'inherit', + 'post_parent' => $post_id, + 'post_content' => $quote . 'Yes', + ]); + + $uid = $this->factory->user->create([ + 'user_login' => 'timber', + 'user_pass' => 'timber', + ]); + + $original_post = Timber::get_post($post_id); + $user = wp_set_current_user($uid); + + $user->add_role('administrator'); + $wp_query->queried_object_id = $post_id; + $wp_query->queried_object = get_post($post_id); + $_GET['preview'] = true; + $_GET['preview_nonce'] = wp_create_nonce('post_preview_' . $post_id); + $post = Timber::get_post(); + $this->assertEquals($original_post->class(), $post->class()); + } + + public function testPreviewTitleWithID() + { + global $current_user; + global $wp_query; + + $post_id = $this->factory->post->create([ + 'post_title' => 'I call it banana bread', + 'post_author' => 5, + ]); + $revision_id = $this->factory->post->create([ + 'post_type' => 'revision', + 'post_status' => 'inherit', + 'post_parent' => $post_id, + 'post_title' => 'I call it fromage', + ]); + + $uid = $this->factory->user->create([ + 'user_login' => 'timber', + 'user_pass' => 'timber', + ]); + $user = wp_set_current_user($uid); + + $user->add_role('administrator'); + $wp_query->queried_object_id = $post_id; + $wp_query->queried_object = get_post($post_id); + $_GET['preview'] = true; + $_GET['preview_nonce'] = wp_create_nonce('post_preview_' . $post_id); + $post = Timber::get_post($post_id); + $this->assertEquals('I call it fromage', $post->title()); + } + + public function testPreviewContentWithID() + { + global $current_user; + global $wp_query; + + $quote = 'The way to do well is to do well.'; + $post_id = $this->factory->post->create([ + 'post_content' => $quote, + 'post_author' => 5, + ]); + $revision_id = $this->factory->post->create([ + 'post_type' => 'revision', + 'post_status' => 'inherit', + 'post_parent' => $post_id, + 'post_content' => $quote . 'Yes', + ]); + + $uid = $this->factory->user->create([ + 'user_login' => 'timber', + 'user_pass' => 'timber', + ]); + $user = wp_set_current_user($uid); + + $user->add_role('administrator'); + $wp_query->queried_object_id = $post_id; + $wp_query->queried_object = get_post($post_id); + $_GET['preview'] = true; + $_GET['preview_nonce'] = wp_create_nonce('post_preview_' . $post_id); + $post = Timber::get_post($post_id); + $this->assertEquals($quote . 'Yes', trim(strip_tags($post->content()))); + } + + public function testPreviewContent() + { + global $current_user; + global $wp_query; + + $quote = 'The way to do well is to do well.'; + $post_id = $this->factory->post->create([ + 'post_content' => $quote, + 'post_author' => 5, + ]); + $revision_id = $this->factory->post->create([ + 'post_type' => 'revision', + 'post_status' => 'inherit', + 'post_parent' => $post_id, + 'post_content' => $quote . 'Yes', + ]); + + $uid = $this->factory->user->create([ + 'user_login' => 'timber', + 'user_pass' => 'timber', + ]); + $user = wp_set_current_user($uid); + + $user->add_role('administrator'); + $wp_query->queried_object_id = $post_id; + $wp_query->queried_object = get_post($post_id); + $_GET['preview'] = true; + $_GET['preview_nonce'] = wp_create_nonce('post_preview_' . $post_id); + $post = Timber::get_post(); + $this->assertEquals($quote . 'Yes', trim(strip_tags($post->content()))); + } + + public function testMultiPreviewRevisions() + { + global $current_user; + global $wp_query; + + $quote = 'The way to do well is to do well.'; + $post_id = $this->factory->post->create([ + 'post_content' => $quote, + 'post_author' => 5, + ]); + $old_revision_id = $this->factory->post->create([ + 'post_type' => 'revision', + 'post_status' => 'inherit', + 'post_parent' => $post_id, + 'post_content' => $quote . 'Yes', + ]); + + $revision_id = $this->factory->post->create([ + 'post_type' => 'revision', + 'post_status' => 'inherit', + 'post_parent' => $post_id, + 'post_content' => 'I am the one', + ]); + + $uid = $this->factory->user->create([ + 'user_login' => 'timber', + 'user_pass' => 'timber', + ]); + $user = wp_set_current_user($uid); + + $user->add_role('administrator'); + $wp_query->queried_object_id = $post_id; + $wp_query->queried_object = get_post($post_id); + $_GET['preview'] = true; + $_GET['preview_nonce'] = wp_create_nonce('post_preview_' . $post_id); + $post = Timber::get_post(); + $this->assertEquals('I am the one', trim(strip_tags($post->content()))); + } + + public function testCustomFieldPreviewRevisionMethod() + { + global $current_user; + global $wp_query; + + $post_id = $this->factory->post->create([ + 'post_author' => 5, + ]); + update_field('test_field', 'The custom field content', $post_id); + + $assertCustomFieldVal = 'This has been revised'; + $revision_id = $this->factory->post->create([ + 'post_type' => 'revision', + 'post_status' => 'inherit', + 'post_parent' => $post_id, + ]); + update_field('test_field', $assertCustomFieldVal, $revision_id); + + $uid = $this->factory->user->create([ + 'user_login' => 'timber', + 'user_pass' => 'timber', + ]); + $user = wp_set_current_user($uid); + $user->add_role('administrator'); + + $wp_query->queried_object_id = $post_id; + $wp_query->queried_object = get_post($post_id); + $_GET['preview'] = true; + $_GET['preview_nonce'] = wp_create_nonce('post_preview_' . $post_id); + $post = Timber::get_post($post_id); + $str_getfield = Timber::compile_string('{{post.meta(\'test_field\')}}', [ + 'post' => $post, + ]); + $this->assertEquals($assertCustomFieldVal, $str_getfield); + } + + public function testCustomFieldPreviewRevisionImported() + { + global $current_user; + global $wp_query; + + $post_id = $this->factory->post->create([ + 'post_author' => 5, + ]); + update_field('test_field', 'The custom field content', $post_id); + + $assertCustomFieldVal = 'This has been revised'; + $revision_id = $this->factory->post->create([ + 'post_type' => 'revision', + 'post_status' => 'inherit', + 'post_parent' => $post_id, + ]); + update_field('test_field', $assertCustomFieldVal, $revision_id); + + $uid = $this->factory->user->create([ + 'user_login' => 'timber', + 'user_pass' => 'timber', + ]); + $user = wp_set_current_user($uid); + $user->add_role('administrator'); + + $wp_query->queried_object_id = $post_id; + $wp_query->queried_object = get_post($post_id); + $_GET['preview'] = true; + $_GET['preview_nonce'] = wp_create_nonce('post_preview_' . $post_id); + $post = Timber::get_post($post_id); + $str_direct = Timber::compile_string('{{ post.meta("test_field") }}', [ + 'post' => $post, + ]); + $this->assertEquals($assertCustomFieldVal, $str_direct); + } + + public function testCustomFieldPreviewNotRevision() + { + global $current_user; + global $wp_query; + $original_content = 'The custom field content'; + + $post_id = $this->factory->post->create([ + 'post_author' => 5, + ]); + update_field('test_field', $original_content, $post_id); + + $assertCustomFieldVal = 'This has been revised'; + $revision_id = $this->factory->post->create([ + 'post_type' => 'revision', + 'post_status' => 'inherit', + 'post_parent' => $post_id, + ]); + update_field('test_field', $assertCustomFieldVal, $revision_id); + + $uid = $this->factory->user->create([ + 'user_login' => 'timber', + 'user_pass' => 'timber', + ]); + $user = wp_set_current_user($uid); + $user->add_role('administrator'); + + $wp_query->queried_object_id = $post_id; + $wp_query->queried_object = get_post($post_id); + $post = Timber::get_post($post_id); + + $str_direct = Timber::compile_string('{{post.test_field}}', [ + 'post' => $post, + ]); + $str_getfield = Timber::compile_string('{{post.meta(\'test_field\')}}', [ + 'post' => $post, + ]); + + $this->assertEquals($original_content, $str_direct); + $this->assertEquals($original_content, $str_getfield); + } +} diff --git a/tests/test-timber-shortcodes.php b/tests/test-timber-shortcodes.php index 92965ad4a..202773e2c 100644 --- a/tests/test-timber-shortcodes.php +++ b/tests/test-timber-shortcodes.php @@ -1,34 +1,34 @@ assertEquals('hello timber foo', trim($return)); - } + add_shortcode('timber_shortcode', function ($text) { + return 'timber ' . $text[0]; + }); + $return = Timber::compile('assets/test-shortcodes.twig'); + $this->assertEquals('hello timber foo', trim($return)); + } - /** - * @ticket #2268 - */ - public function testCustomFieldShortcode() - { - add_shortcode('foobar', function ($atts) { - return 'barfoo'; - }); + /** + * @ticket #2268 + */ + public function testCustomFieldShortcode() + { + add_shortcode('foobar', function ($atts) { + return 'barfoo'; + }); - $post_id = $this->factory->post->create(); - update_post_meta($post_id, 'customfield', '[foobar]'); - $template = '{{ post.customfield | shortcodes }}'; + $post_id = $this->factory->post->create(); + update_post_meta($post_id, 'customfield', '[foobar]'); + $template = '{{ post.customfield | shortcodes }}'; - $post = Timber::get_post($post_id); - $compiled = Timber::compile_string($template, [ - 'post' => $post, - ]); + $post = Timber::get_post($post_id); + $compiled = Timber::compile_string($template, [ + 'post' => $post, + ]); - $this->assertEquals('barfoo', $compiled); - } + $this->assertEquals('barfoo', $compiled); } +} diff --git a/tests/test-timber-sidebar.php b/tests/test-timber-sidebar.php index 569ac33c9..4d02c05b8 100644 --- a/tests/test-timber-sidebar.php +++ b/tests/test-timber-sidebar.php @@ -1,31 +1,31 @@ factory->post->create([ - 'post_title' => 'Sidebar post content', - ]); - $sidebar_context = []; - $sidebar_context['post'] = Timber::get_post($sidebar_post); - $context['sidebar'] = Timber::get_sidebar('assets/sidebar.twig', $sidebar_context); - $result = Timber::compile('assets/main-w-sidebar.twig', $context); - $this->assertEquals('I am the main stuff

              Sidebar post content

              ', trim($result)); - } + $context = Timber::context(); + $sidebar_post = $this->factory->post->create([ + 'post_title' => 'Sidebar post content', + ]); + $sidebar_context = []; + $sidebar_context['post'] = Timber::get_post($sidebar_post); + $context['sidebar'] = Timber::get_sidebar('assets/sidebar.twig', $sidebar_context); + $result = Timber::compile('assets/main-w-sidebar.twig', $context); + $this->assertEquals('I am the main stuff

              Sidebar post content

              ', trim($result)); + } - public function testPHPSidebar() - { - add_filter('timber/context', function ($context) { - $context['sidebar'] = Timber::get_sidebar('assets/my-sidebar.php'); - return $context; - }); - $context = Timber::context(); - $result = Timber::compile('assets/main-w-sidebar-php.twig', $context); - $this->assertEquals("A Fever You Can't Sweat Out by Panic! at the Disco from 2005", trim($result)); - } + public function testPHPSidebar() + { + add_filter('timber/context', function ($context) { + $context['sidebar'] = Timber::get_sidebar('assets/my-sidebar.php'); + return $context; + }); + $context = Timber::context(); + $result = Timber::compile('assets/main-w-sidebar-php.twig', $context); + $this->assertEquals("A Fever You Can't Sweat Out by Panic! at the Disco from 2005", trim($result)); } +} diff --git a/tests/test-timber-site.php b/tests/test-timber-site.php index 54848c457..eaf046f52 100644 --- a/tests/test-timber-site.php +++ b/tests/test-timber-site.php @@ -12,7 +12,7 @@ public function testStandardThemeLocation() public function testLanguageAttributes() { - $this->restore_locale(); + restore_current_locale(); $site = new \Timber\Site(); $lang = $site->language_attributes(); $this->assertEquals('lang="en-US"', $lang); diff --git a/tests/test-timber-term.php b/tests/test-timber-term.php index f34299686..ab2868db3 100644 --- a/tests/test-timber-term.php +++ b/tests/test-timber-term.php @@ -6,629 +6,629 @@ class TermTestPage extends Post { } +/** +* @group terms-api +*/ +class TestTimberTerm extends Timber_UnitTestCase +{ + public function testTermFrom() + { + register_taxonomy('baseball', ['post']); + register_taxonomy('hockey', ['post']); + $this->factory->term->create([ + 'name' => 'Rangers', + 'taxonomy' => 'baseball', + ]); + $this->factory->term->create([ + 'name' => 'Cardinals', + 'taxonomy' => 'baseball', + ]); + $this->factory->term->create([ + 'name' => 'Rangers', + 'taxonomy' => 'hockey', + ]); + + $wp_terms = get_terms([ + 'taxonomy' => 'baseball', + 'hide_empty' => false, + ]); + $baseball_teams = Timber::get_terms($wp_terms); + + $this->assertCount(2, $baseball_teams); + + $this->assertEquals('Cardinals', $baseball_teams[0]->title()); + $this->assertEquals('Rangers', $baseball_teams[1]->title()); + } + /** - * @group terms-api - */ - class TestTimberTerm extends Timber_UnitTestCase + * @ticket #2362 + */ + public function testMultiTermsWithSameSlug() { - public function testTermFrom() - { - register_taxonomy('baseball', ['post']); - register_taxonomy('hockey', ['post']); - $this->factory->term->create([ - 'name' => 'Rangers', - 'taxonomy' => 'baseball', - ]); - $this->factory->term->create([ - 'name' => 'Cardinals', - 'taxonomy' => 'baseball', - ]); - $this->factory->term->create([ - 'name' => 'Rangers', - 'taxonomy' => 'hockey', - ]); - - $wp_terms = get_terms([ - 'taxonomy' => 'baseball', - 'hide_empty' => false, - ]); - $baseball_teams = Timber::get_terms($wp_terms); - - $this->assertCount(2, $baseball_teams); - - $this->assertEquals('Cardinals', $baseball_teams[0]->title()); - $this->assertEquals('Rangers', $baseball_teams[1]->title()); - } + $post_tag_id = $this->factory->term->create([ + 'name' => 'Security', + 'taxonomy' => 'post_tag', + ]); + $category_id = $this->factory->term->create([ + 'name' => 'Security', + 'taxonomy' => 'category', + ]); + $post_id = $this->factory->post->create(); + wp_set_object_terms($post_id, $post_tag_id, 'post_tag', true); + wp_set_object_terms($post_id, $category_id, 'category', true); + + $term_default = Timber::get_term_by('slug', 'security'); + $this->assertEquals('post_tag', $term_default->taxonomy); + $this->assertEquals('Security', $term_default->title()); + + $term_category = Timber::get_term_by('slug', 'security', 'category'); + $this->assertEquals('category', $term_category->taxonomy); + $this->assertEquals('Security', $term_category->title()); + } - /** - * @ticket #2362 - */ - public function testMultiTermsWithSameSlug() - { - $post_tag_id = $this->factory->term->create([ - 'name' => 'Security', - 'taxonomy' => 'post_tag', - ]); - $category_id = $this->factory->term->create([ - 'name' => 'Security', - 'taxonomy' => 'category', - ]); - $post_id = $this->factory->post->create(); - wp_set_object_terms($post_id, $post_tag_id, 'post_tag', true); - wp_set_object_terms($post_id, $category_id, 'category', true); - - $term_default = Timber::get_term_by('slug', 'security'); - $this->assertEquals('post_tag', $term_default->taxonomy); - $this->assertEquals('Security', $term_default->title()); - - $term_category = Timber::get_term_by('slug', 'security', 'category'); - $this->assertEquals('category', $term_category->taxonomy); - $this->assertEquals('Security', $term_category->title()); - } + public function testTermFromInvalidObject() + { + $this->expectException(\InvalidArgumentException::class); + + register_taxonomy('baseball', ['post']); + $term_id = $this->factory->term->create([ + 'name' => 'Cardinals', + 'taxonomy' => 'baseball', + ]); + $post_id = $this->factory->post->create([ + 'post_title' => 'Test Post', + ]); + $post = get_post($post_id); + $test = Timber::get_terms($post); + } - public function testTermFromInvalidObject() - { - $this->expectException(\InvalidArgumentException::class); - - register_taxonomy('baseball', ['post']); - $term_id = $this->factory->term->create([ - 'name' => 'Cardinals', - 'taxonomy' => 'baseball', - ]); - $post_id = $this->factory->post->create([ - 'post_title' => 'Test Post', - ]); - $post = get_post($post_id); - $test = Timber::get_terms($post); - } + public function testGetTerm() + { + register_taxonomy('arts', ['post']); + + $term_id = $this->factory->term->create([ + 'name' => 'Zong', + 'taxonomy' => 'arts', + ]); + // @todo #2087 get this to work w/o $taxonomy param + $term = Timber::get_term($term_id, ''); + $this->assertEquals('Zong', $term->title()); + $template = '{% set zp_term = get_term("' . $term->ID . '", "arts") %}{{ zp_term.name }}'; + $string = Timber::compile_string($template); + $this->assertEquals('Zong', $string); + } - public function testGetTerm() - { - register_taxonomy('arts', ['post']); - - $term_id = $this->factory->term->create([ - 'name' => 'Zong', - 'taxonomy' => 'arts', - ]); - // @todo #2087 get this to work w/o $taxonomy param - $term = Timber::get_term($term_id, ''); - $this->assertEquals('Zong', $term->title()); - $template = '{% set zp_term = get_term("' . $term->ID . '", "arts") %}{{ zp_term.name }}'; - $string = Timber::compile_string($template); - $this->assertEquals('Zong', $string); - } + public function testTerm() + { + $term_id = $this->factory->term->create(); + $term = Timber::get_term($term_id); + $this->assertEquals('Timber\Term', get_class($term)); + } - public function testTerm() - { - $term_id = $this->factory->term->create(); - $term = Timber::get_term($term_id); - $this->assertEquals('Timber\Term', get_class($term)); - } + public function testGetTermWithObject() + { + $term_id = $this->factory->term->create([ + 'name' => 'Famous Commissioners', + ]); + $term_data = get_term($term_id, 'post_tag'); + $this->assertTrue(in_array(get_class($term_data), ['WP_Term', 'stdClass'])); + $term = Timber::get_term($term_id); + $this->assertEquals('Famous Commissioners', $term->title()); + $this->assertEquals('Timber\Term', get_class($term)); + } - public function testGetTermWithObject() - { - $term_id = $this->factory->term->create([ - 'name' => 'Famous Commissioners', - ]); - $term_data = get_term($term_id, 'post_tag'); - $this->assertTrue(in_array(get_class($term_data), ['WP_Term', 'stdClass'])); - $term = Timber::get_term($term_id); - $this->assertEquals('Famous Commissioners', $term->title()); - $this->assertEquals('Timber\Term', get_class($term)); - } + public function testTermToString() + { + $term_id = $this->factory->term->create([ + 'name' => 'New England Patriots', + ]); + $term = Timber::get_term($term_id); + $str = Timber::compile_string('{{term}}', [ + 'term' => $term, + ]); + $this->assertEquals('New England Patriots', $str); + } - public function testTermToString() - { - $term_id = $this->factory->term->create([ - 'name' => 'New England Patriots', - ]); - $term = Timber::get_term($term_id); - $str = Timber::compile_string('{{term}}', [ - 'term' => $term, - ]); - $this->assertEquals('New England Patriots', $str); - } + public function testTermDescription() + { + $desc = 'An honest football team'; + $term_id = $this->factory->term->create([ + 'name' => 'New England Patriots', + 'description' => $desc, + ]); + $term = Timber::get_term($term_id, 'post_tag'); + $this->assertEquals($desc, $term->description()); + } - public function testTermDescription() - { - $desc = 'An honest football team'; - $term_id = $this->factory->term->create([ - 'name' => 'New England Patriots', - 'description' => $desc, - ]); - $term = Timber::get_term($term_id, 'post_tag'); - $this->assertEquals($desc, $term->description()); - } + public function testTermInitObject() + { + $term_id = $this->factory->term->create(); + $term = get_term($term_id, 'post_tag'); + $term = Timber::get_term($term); + $this->assertEquals($term->ID, $term_id); + } - public function testTermInitObject() - { - $term_id = $this->factory->term->create(); - $term = get_term($term_id, 'post_tag'); - $term = Timber::get_term($term); - $this->assertEquals($term->ID, $term_id); - } + public function testTermLink() + { + $term_id = $this->factory->term->create(); + $term = Timber::get_term($term_id); + $this->assertStringContainsString('http://', $term->link()); + } - public function testTermLink() - { - $term_id = $this->factory->term->create(); - $term = Timber::get_term($term_id); - $this->assertStringContainsString('http://', $term->link()); - } + public function testTermPath() + { + $term_id = $this->factory->term->create(); + $term = Timber::get_term($term_id); + $this->assertFalse(strstr($term->path(), 'http://')); + } - public function testTermPath() - { - $term_id = $this->factory->term->create(); - $term = Timber::get_term($term_id); - $this->assertFalse(strstr($term->path(), 'http://')); - } + /* + * Term::posts() tests + */ - /* - * Term::posts() tests - */ - - public function testPostsDefault() - { - register_post_type('portfolio', [ - 'taxonomies' => ['arts'], - 'public' => true, - ]); - register_taxonomy('arts', ['portfolio', 'post']); - - // Create a term, and some posts to assign it to. - $term_id = $this->factory->term->create([ - 'name' => 'Zong', - 'taxonomy' => 'arts', - ]); - - // Create 12 posts total. - // NOTE: Neither post_type has enough to satisfy the assertion below on its own, - // but together they should exceed the default posts_per_page and we should get - // exactly posts_per_page (10) back. - $posts = array_merge( - $this->factory->post->create_many(5), - $this->factory->post->create_many(7, [ - 'post_type' => 'portfolio', - ]) - ); - - // assign the term to each of our new posts - foreach ($posts as $post_id) { - wp_set_object_terms($post_id, $term_id, 'arts', true); - } - - $other_id = $this->factory->term->create([ - 'name' => 'Other', - 'taxonomy' => 'arts', - ]); - $other_posts = $this->factory->post->create_many(10); - foreach ($other_posts as $id) { - wp_set_object_terms($id, $other_id, 'arts', true); - } - - $term = Timber::get_term($term_id); - - // Expect the default posts_per_page, with posts of all types. - $this->assertCount(10, $term->posts()); - // Passing an empty array should behave exactly the same. - $this->assertCount(10, $term->posts([])); - } + public function testPostsDefault() + { + register_post_type('portfolio', [ + 'taxonomies' => ['arts'], + 'public' => true, + ]); + register_taxonomy('arts', ['portfolio', 'post']); + + // Create a term, and some posts to assign it to. + $term_id = $this->factory->term->create([ + 'name' => 'Zong', + 'taxonomy' => 'arts', + ]); + + // Create 12 posts total. + // NOTE: Neither post_type has enough to satisfy the assertion below on its own, + // but together they should exceed the default posts_per_page and we should get + // exactly posts_per_page (10) back. + $posts = array_merge( + $this->factory->post->create_many(5), + $this->factory->post->create_many(7, [ + 'post_type' => 'portfolio', + ]) + ); - public function testPostsDefaultPostType() - { - register_post_type('portfolio', [ - 'taxonomies' => ['arts'], - 'public' => true, - ]); - register_taxonomy('arts', ['portfolio', 'post']); - - // Create a term, and some posts to assign it to. - $term_id = $this->factory->term->create([ - 'name' => 'Zong', - 'taxonomy' => 'arts', - ]); - - // Create 12 posts total. - // NOTE: Neither post_type has enough to satisfy the assertion below on its own, - // but together they should exceed the 8 we ask for so we should get exactly 8 back. - // This is because, according to the docs, post_type defaults to "any" when using - // tax_query. - // https://developer.wordpress.org/reference/classes/WP_Query/parse_query/ - $posts = array_merge( - $this->factory->post->create_many(5), - $this->factory->post->create_many(7, [ - 'post_type' => 'portfolio', - ]) - ); - - // assign the term to each of our new posts - foreach ($posts as $post_id) { - wp_set_object_terms($post_id, $term_id, 'arts', true); - } - - $term = Timber::get_term($term_id); - - // Expect exactly the count we asked for. - $this->assertCount(8, $term->posts([ - 'posts_per_page' => 8, - ])); + // assign the term to each of our new posts + foreach ($posts as $post_id) { + wp_set_object_terms($post_id, $term_id, 'arts', true); } - public function testPostsWithPostTypeQuery() - { - register_post_type('portfolio', [ - 'taxonomies' => ['arts'], - 'public' => true, - ]); - register_taxonomy('arts', ['portfolio', 'post']); - - // Create a term, and some posts to assign it to. - $term_id = $this->factory->term->create([ - 'name' => 'Zong', - 'taxonomy' => 'arts', - ]); - - // Create 12 posts total. But we should only get 7 back below even though posts_per_page - // defaults to 10, because we limit by post_type. - $posts = array_merge( - $this->factory->post->create_many(5), - $this->factory->post->create_many(7, [ - 'post_type' => 'portfolio', - ]) - ); - - // assign the term to each of our new posts - foreach ($posts as $post_id) { - wp_set_object_terms($post_id, $term_id, 'arts', true); - } - - $term = Timber::get_term($term_id); - - // Expect the default posts_per_page, with posts of all types. - $this->assertCount(7, $term->posts([ - 'post_type' => 'portfolio', - ])); + $other_id = $this->factory->term->create([ + 'name' => 'Other', + 'taxonomy' => 'arts', + ]); + $other_posts = $this->factory->post->create_many(10); + foreach ($other_posts as $id) { + wp_set_object_terms($id, $other_id, 'arts', true); } - public function testPostsWithTaxQuery() - { - register_post_type('portfolio', [ - 'taxonomies' => ['arts'], - 'public' => true, - ]); - register_taxonomy('arts', ['portfolio', 'post']); - - // Create a term, and some posts to assign it to. - $term_id = $this->factory->term->create([ - 'taxonomy' => 'arts', - ]); - - // Create 12 posts total. - // NOTE: Neither post_type has enough to satisfy the assertion below on its own, - // but together they should exceed the 8 we ask for so we should get exactly 8 back. - // This is because, according to the docs, post_type defaults to "any" when using - // tax_query. - // https://developer.wordpress.org/reference/classes/WP_Query/parse_query/ - $posts = array_merge( - $this->factory->post->create_many(5), - $this->factory->post->create_many(7, [ - 'post_type' => 'portfolio', - ]) - ); - - // assign the term to each of our new posts - foreach ($posts as $post_id) { - wp_set_object_terms($post_id, $term_id, 'arts', true); - } - - // Tag one post and one portfolio with a special crafts term, too. - register_taxonomy('crafts', ['portfolio', 'post']); - $craft_id = $this->factory->term->create([ - 'taxonomy' => 'crafts', - ]); - wp_set_object_terms($posts[0], $craft_id, 'crafts', true); - wp_set_object_terms($posts[5], $craft_id, 'crafts', true); - - $term = Timber::get_term($term_id); - - // Expect the intersection of arts & crafts. - $this->assertCount(2, $term->posts([ - 'tax_query' => [ - [ - 'field' => 'id', - 'terms' => $craft_id, - 'taxonomy' => 'crafts', - ], - // This should get overridden; we don't want users to be able to - // override the Term we're querying for. - 'relation' => 'OR', - ], - ])); - } + $term = Timber::get_term($term_id); - /** - * @expectedIncorrectUsage Passing a query string to Term::posts() - */ - public function testGetPostsWithQueryString() - { - register_post_type('portfolio', [ - 'taxonomies' => ['post_tag'], - 'public' => true, - ]); - $term_id = $this->factory->term->create([ - 'name' => 'Zong', - ]); - $this->factory->post->create_many(3, [ - 'post_type' => 'post', - 'tags_input' => 'zong', - ]); - $this->factory->post->create_many(5, [ + // Expect the default posts_per_page, with posts of all types. + $this->assertCount(10, $term->posts()); + // Passing an empty array should behave exactly the same. + $this->assertCount(10, $term->posts([])); + } + + public function testPostsDefaultPostType() + { + register_post_type('portfolio', [ + 'taxonomies' => ['arts'], + 'public' => true, + ]); + register_taxonomy('arts', ['portfolio', 'post']); + + // Create a term, and some posts to assign it to. + $term_id = $this->factory->term->create([ + 'name' => 'Zong', + 'taxonomy' => 'arts', + ]); + + // Create 12 posts total. + // NOTE: Neither post_type has enough to satisfy the assertion below on its own, + // but together they should exceed the 8 we ask for so we should get exactly 8 back. + // This is because, according to the docs, post_type defaults to "any" when using + // tax_query. + // https://developer.wordpress.org/reference/classes/WP_Query/parse_query/ + $posts = array_merge( + $this->factory->post->create_many(5), + $this->factory->post->create_many(7, [ 'post_type' => 'portfolio', - 'tags_input' => 'zong', - ]); + ]) + ); - // Count is mismatched because string-based queries default to a post_type of "post". - $term = Timber::get_term($term_id); - $this->assertFalse($term->posts('posts_per_page=8')); + // assign the term to each of our new posts + foreach ($posts as $post_id) { + wp_set_object_terms($post_id, $term_id, 'arts', true); } - /** - * @expectedDeprecated Passing post_type_or_class - * This test *partially* honors the logic described in - * https://github.com/timber/timber/issues/799#issuecomment-192445207, - * although that behavior is not deprecated. - */ - public function testGetPostsWithPostTypeArg() - { - register_post_type('portfolio', [ - 'taxonomies' => ['post_tag'], - 'public' => true, - ]); - $term_id = $this->factory->term->create([ - 'name' => 'Zong', - ]); - $this->factory->post->create_many(3, [ - 'post_type' => 'post', - 'tags_input' => 'zong', - ]); - $this->factory->post->create_many(5, [ + $term = Timber::get_term($term_id); + + // Expect exactly the count we asked for. + $this->assertCount(8, $term->posts([ + 'posts_per_page' => 8, + ])); + } + + public function testPostsWithPostTypeQuery() + { + register_post_type('portfolio', [ + 'taxonomies' => ['arts'], + 'public' => true, + ]); + register_taxonomy('arts', ['portfolio', 'post']); + + // Create a term, and some posts to assign it to. + $term_id = $this->factory->term->create([ + 'name' => 'Zong', + 'taxonomy' => 'arts', + ]); + + // Create 12 posts total. But we should only get 7 back below even though posts_per_page + // defaults to 10, because we limit by post_type. + $posts = array_merge( + $this->factory->post->create_many(5), + $this->factory->post->create_many(7, [ 'post_type' => 'portfolio', - 'tags_input' => 'zong', - ]); + ]) + ); - $term = Timber::get_term($term_id); - $this->assertCount(3, $term->posts([ - 'orderby' => 'menu_order', - ], 'post')); + // assign the term to each of our new posts + foreach ($posts as $post_id) { + wp_set_object_terms($post_id, $term_id, 'arts', true); } - /** - * @expectedIncorrectUsage Passing a post class - */ - public function testGetPostsWithPostClassArg() - { - register_post_type('portfolio', [ - 'taxonomies' => ['post_tag'], - 'public' => true, - ]); - $term_id = $this->factory->term->create([ - 'name' => 'Zong', - ]); - $this->factory->post->create_many(3, [ - 'post_type' => 'post', - 'tags_input' => 'zong', - ]); - $this->factory->post->create_many(5, [ + $term = Timber::get_term($term_id); + + // Expect the default posts_per_page, with posts of all types. + $this->assertCount(7, $term->posts([ + 'post_type' => 'portfolio', + ])); + } + + public function testPostsWithTaxQuery() + { + register_post_type('portfolio', [ + 'taxonomies' => ['arts'], + 'public' => true, + ]); + register_taxonomy('arts', ['portfolio', 'post']); + + // Create a term, and some posts to assign it to. + $term_id = $this->factory->term->create([ + 'taxonomy' => 'arts', + ]); + + // Create 12 posts total. + // NOTE: Neither post_type has enough to satisfy the assertion below on its own, + // but together they should exceed the 8 we ask for so we should get exactly 8 back. + // This is because, according to the docs, post_type defaults to "any" when using + // tax_query. + // https://developer.wordpress.org/reference/classes/WP_Query/parse_query/ + $posts = array_merge( + $this->factory->post->create_many(5), + $this->factory->post->create_many(7, [ 'post_type' => 'portfolio', - 'tags_input' => 'zong', - ]); + ]) + ); - $term = Timber::get_term($term_id); - $this->assertCount(3, $term->posts([ - 'orderby' => 'menu_order', - ], null, 'INCORRECT')); + // assign the term to each of our new posts + foreach ($posts as $post_id) { + wp_set_object_terms($post_id, $term_id, 'arts', true); } - /** - * @expectedDeprecated {{ term.get_posts }} - */ - public function testGetPostsDeprecated() - { - $term_id = $this->factory->term->create([ - 'name' => 'Rad', - ]); - $posts = $this->factory->post->create_many(3, [ - 'tags_input' => 'rad', - ]); - $term = Timber::get_term($term_id); + // Tag one post and one portfolio with a special crafts term, too. + register_taxonomy('crafts', ['portfolio', 'post']); + $craft_id = $this->factory->term->create([ + 'taxonomy' => 'crafts', + ]); + wp_set_object_terms($posts[0], $craft_id, 'crafts', true); + wp_set_object_terms($posts[5], $craft_id, 'crafts', true); + + $term = Timber::get_term($term_id); + + // Expect the intersection of arts & crafts. + $this->assertCount(2, $term->posts([ + 'tax_query' => [ + [ + 'field' => 'id', + 'terms' => $craft_id, + 'taxonomy' => 'crafts', + ], + // This should get overridden; we don't want users to be able to + // override the Term we're querying for. + 'relation' => 'OR', + ], + ])); + } - $this->assertCount(3, $term->get_posts()); + /** + * @expectedIncorrectUsage Passing a query string to Term::posts() + */ + public function testGetPostsWithQueryString() + { + register_post_type('portfolio', [ + 'taxonomies' => ['post_tag'], + 'public' => true, + ]); + $term_id = $this->factory->term->create([ + 'name' => 'Zong', + ]); + $this->factory->post->create_many(3, [ + 'post_type' => 'post', + 'tags_input' => 'zong', + ]); + $this->factory->post->create_many(5, [ + 'post_type' => 'portfolio', + 'tags_input' => 'zong', + ]); + + // Count is mismatched because string-based queries default to a post_type of "post". + $term = Timber::get_term($term_id); + $this->assertFalse($term->posts('posts_per_page=8')); + } + + /** + * @expectedDeprecated Passing post_type_or_class + * This test *partially* honors the logic described in + * https://github.com/timber/timber/issues/799#issuecomment-192445207, + * although that behavior is not deprecated. + */ + public function testGetPostsWithPostTypeArg() + { + register_post_type('portfolio', [ + 'taxonomies' => ['post_tag'], + 'public' => true, + ]); + $term_id = $this->factory->term->create([ + 'name' => 'Zong', + ]); + $this->factory->post->create_many(3, [ + 'post_type' => 'post', + 'tags_input' => 'zong', + ]); + $this->factory->post->create_many(5, [ + 'post_type' => 'portfolio', + 'tags_input' => 'zong', + ]); + + $term = Timber::get_term($term_id); + $this->assertCount(3, $term->posts([ + 'orderby' => 'menu_order', + ], 'post')); + } + + /** + * @expectedIncorrectUsage Passing a post class + */ + public function testGetPostsWithPostClassArg() + { + register_post_type('portfolio', [ + 'taxonomies' => ['post_tag'], + 'public' => true, + ]); + $term_id = $this->factory->term->create([ + 'name' => 'Zong', + ]); + $this->factory->post->create_many(3, [ + 'post_type' => 'post', + 'tags_input' => 'zong', + ]); + $this->factory->post->create_many(5, [ + 'post_type' => 'portfolio', + 'tags_input' => 'zong', + ]); + + $term = Timber::get_term($term_id); + $this->assertCount(3, $term->posts([ + 'orderby' => 'menu_order', + ], null, 'INCORRECT')); + } + + /** + * @expectedDeprecated {{ term.get_posts }} + */ + public function testGetPostsDeprecated() + { + $term_id = $this->factory->term->create([ + 'name' => 'Rad', + ]); + $posts = $this->factory->post->create_many(3, [ + 'tags_input' => 'rad', + ]); + $term = Timber::get_term($term_id); + + $this->assertCount(3, $term->get_posts()); + } + + public function testPostsWithPostCount() + { + $term_id = $this->factory->term->create(); + // Assign some pages to our post_tag Term. + $page_ids = $this->factory->post->create_many(3, [ + 'post_type' => 'page', + 'post_date' => '2020-01-01', + ]); + // Create some posts too. + $post_ids = $this->factory->post->create_many(3, [ + 'post_date' => '2019-01-01', + ]); + // Tag all posts. + foreach (array_merge($page_ids, $post_ids) as $post_id) { + wp_set_object_terms($post_id, $term_id, 'post_tag', true); } - public function testPostsWithPostCount() - { - $term_id = $this->factory->term->create(); - // Assign some pages to our post_tag Term. - $page_ids = $this->factory->post->create_many(3, [ - 'post_type' => 'page', + $this->register_post_classmap_temporarily([ + 'page' => TermTestPage::class, + ]); + + // Get the first four posts from this term. + $term_posts = Timber::get_term($term_id)->posts(4); + + $this->assertCount(4, $term_posts); + + // Pages should come first due to later publish dates. + $this->assertInstanceOf(TermTestPage::class, $term_posts[0]); + $this->assertInstanceOf(TermTestPage::class, $term_posts[1]); + $this->assertInstanceOf(TermTestPage::class, $term_posts[2]); + $this->assertInstanceOf(Post::class, $term_posts[3]); + } + + public function testPostsWithExtraQueryArgs() + { + $term_id = $this->factory->term->create([ + 'name' => 'Rad', + ]); + + $posts = [ + $this->factory->post->create([ + 'post_title' => 'Earlier', 'post_date' => '2020-01-01', - ]); - // Create some posts too. - $post_ids = $this->factory->post->create_many(3, [ - 'post_date' => '2019-01-01', - ]); - // Tag all posts. - foreach (array_merge($page_ids, $post_ids) as $post_id) { - wp_set_object_terms($post_id, $term_id, 'post_tag', true); - } - - $this->register_post_classmap_temporarily([ - 'page' => TermTestPage::class, - ]); - - // Get the first four posts from this term. - $term_posts = Timber::get_term($term_id)->posts(4); - - $this->assertCount(4, $term_posts); - - // Pages should come first due to later publish dates. - $this->assertInstanceOf(TermTestPage::class, $term_posts[0]); - $this->assertInstanceOf(TermTestPage::class, $term_posts[1]); - $this->assertInstanceOf(TermTestPage::class, $term_posts[2]); - $this->assertInstanceOf(Post::class, $term_posts[3]); - } + 'tags_input' => 'rad', + ]), + $this->factory->post->create([ + 'post_title' => 'Later', + 'post_date' => '2020-03-01', + 'tags_input' => 'rad', + ]), + $this->factory->post->create([ + 'post_title' => 'Much Later', + 'post_date' => '2020-08-01', + 'tags_input' => 'rad', + ]), + ]; - public function testPostsWithExtraQueryArgs() - { - $term_id = $this->factory->term->create([ - 'name' => 'Rad', - ]); - - $posts = [ - $this->factory->post->create([ - 'post_title' => 'Earlier', - 'post_date' => '2020-01-01', - 'tags_input' => 'rad', - ]), - $this->factory->post->create([ - 'post_title' => 'Later', - 'post_date' => '2020-03-01', - 'tags_input' => 'rad', - ]), - $this->factory->post->create([ - 'post_title' => 'Much Later', - 'post_date' => '2020-08-01', - 'tags_input' => 'rad', - ]), - ]; - - $term = Timber::get_term($term_id); - - $term_posts = $term->posts([ - 'posts_per_page' => 2, - 'orderby' => 'post_date', - 'order' => 'ASC', - ]); - - $this->assertCount(2, $term_posts); - $this->assertEquals('Earlier', $term_posts[0]->title()); - $this->assertEquals('Later', $term_posts[1]->title()); - } + $term = Timber::get_term($term_id); - public function testTermChildren() - { - $parent_id = $this->factory->term->create([ - 'name' => 'News', - 'taxonomy' => 'category', - ]); - $local = $this->factory->term->create([ - 'name' => 'Local', - 'parent' => $parent_id, - 'taxonomy' => 'category', - ]); - $int = $this->factory->term->create([ - 'name' => 'International', - 'parent' => $parent_id, - 'taxonomy' => 'category', - ]); - - // @todo #2087 get this to work w/o $taxonomy param - $term = Timber::get_term($parent_id, ''); - $children = $term->children(); - $this->assertEquals(2, count($children)); - $this->assertEquals('Local', $children[0]->name); - } + $term_posts = $term->posts([ + 'posts_per_page' => 2, + 'orderby' => 'post_date', + 'order' => 'ASC', + ]); - /** - * @ticket #824 - */ - public function testTermWithNativeMeta() - { - $tid = $this->factory->term->create([ - 'name' => 'News', - 'taxonomy' => 'category', - ]); - add_term_meta($tid, 'foo', 'bar'); - // @todo #2087 get this to work w/o $taxonomy param - $term = Timber::get_term($tid, ''); - $template = '{{term.foo}}'; - $compiled = Timber::compile_string($template, [ - 'term' => $term, - ]); - $this->assertEquals('bar', $compiled); - } + $this->assertCount(2, $term_posts); + $this->assertEquals('Earlier', $term_posts[0]->title()); + $this->assertEquals('Later', $term_posts[1]->title()); + } - /** - * @ticket #824 - */ - public function testTermWithNativeMetaFalse() - { - $tid = $this->factory->term->create([ - 'name' => 'News', - 'taxonomy' => 'category', - ]); - add_term_meta($tid, 'foo', false); - // @todo #2087 get this to work w/o $taxonomy param - $term = Timber::get_term($tid, ''); - $this->assertEquals('', $term->meta('foo')); - } + public function testTermChildren() + { + $parent_id = $this->factory->term->create([ + 'name' => 'News', + 'taxonomy' => 'category', + ]); + $local = $this->factory->term->create([ + 'name' => 'Local', + 'parent' => $parent_id, + 'taxonomy' => 'category', + ]); + $int = $this->factory->term->create([ + 'name' => 'International', + 'parent' => $parent_id, + 'taxonomy' => 'category', + ]); + + // @todo #2087 get this to work w/o $taxonomy param + $term = Timber::get_term($parent_id, ''); + $children = $term->children(); + $this->assertEquals(2, count($children)); + $this->assertEquals('Local', $children[0]->name); + } - /** - * @ticket #824 - */ - public function testTermWithNativeMetaNotExisting() - { - $tid = $this->factory->term->create([ - 'name' => 'News', - 'taxonomy' => 'category', - ]); - - add_term_meta($tid, 'bar', 'qux'); - ; - $wp_native_value = get_term_meta($tid, 'foo', true); - $acf_native_value = get_field('foo', 'category_' . $tid); - - $valid_wp_native_value = get_term_meta($tid, 'bar', true); - $valid_acf_native_value = get_field('bar', 'category_' . $tid); - - // @todo #2087 get this to work w/o $taxonomy param - $term = Timber::get_term($tid, ''); - - //test baseline "bar" data - $this->assertEquals('qux', $valid_wp_native_value); - $this->assertEquals('qux', $valid_acf_native_value); - $this->assertEquals('qux', $term->bar); - - //test the one that doesn't exist - $this->assertEquals('string', gettype($wp_native_value)); - $this->assertEmpty($wp_native_value); - $this->assertNull($acf_native_value); - $this->assertNotTrue($term->meta('foo')); - } + /** + * @ticket #824 + */ + public function testTermWithNativeMeta() + { + $tid = $this->factory->term->create([ + 'name' => 'News', + 'taxonomy' => 'category', + ]); + add_term_meta($tid, 'foo', 'bar'); + // @todo #2087 get this to work w/o $taxonomy param + $term = Timber::get_term($tid, ''); + $template = '{{term.foo}}'; + $compiled = Timber::compile_string($template, [ + 'term' => $term, + ]); + $this->assertEquals('bar', $compiled); + } - public function testTermEditLink() - { - wp_set_current_user(1); - $tid = $this->factory->term->create([ - 'name' => 'News', - 'taxonomy' => 'category', - ]); - // @todo #2087 get this to work w/o $taxonomy param - $term = Timber::get_term($tid, ''); - $links = []; - - $links[] = 'http://example.org/wp-admin/term.php?taxonomy=category&tag_ID=' . $tid . '&post_type=post'; - $links[] = 'http://example.org/wp-admin/edit-tags.php?action=edit&taxonomy=category&tag_ID=' . $tid . '&post_type=post'; - $links[] = 'http://example.org/wp-admin/edit-tags.php?action=edit&taxonomy=category&tag_ID=' . $tid; - $links[] = 'http://example.org/wp-admin/term.php?taxonomy=category&term_id=' . $tid . '&post_type=post'; - $this->assertContains($term->edit_link(), $links); - } + /** + * @ticket #824 + */ + public function testTermWithNativeMetaFalse() + { + $tid = $this->factory->term->create([ + 'name' => 'News', + 'taxonomy' => 'category', + ]); + add_term_meta($tid, 'foo', false); + // @todo #2087 get this to work w/o $taxonomy param + $term = Timber::get_term($tid, ''); + $this->assertEquals('', $term->meta('foo')); } - class Arts extends Timber\Term + /** + * @ticket #824 + */ + public function testTermWithNativeMetaNotExisting() { - public function foobar() - { - return 'Zebra'; - } + $tid = $this->factory->term->create([ + 'name' => 'News', + 'taxonomy' => 'category', + ]); + + add_term_meta($tid, 'bar', 'qux'); + ; + $wp_native_value = get_term_meta($tid, 'foo', true); + $acf_native_value = get_field('foo', 'category_' . $tid); + + $valid_wp_native_value = get_term_meta($tid, 'bar', true); + $valid_acf_native_value = get_field('bar', 'category_' . $tid); + + // @todo #2087 get this to work w/o $taxonomy param + $term = Timber::get_term($tid, ''); + + //test baseline "bar" data + $this->assertEquals('qux', $valid_wp_native_value); + $this->assertEquals('qux', $valid_acf_native_value); + $this->assertEquals('qux', $term->bar); + + //test the one that doesn't exist + $this->assertEquals('string', gettype($wp_native_value)); + $this->assertEmpty($wp_native_value); + $this->assertNull($acf_native_value); + $this->assertNotTrue($term->meta('foo')); + } + + public function testTermEditLink() + { + wp_set_current_user(1); + $tid = $this->factory->term->create([ + 'name' => 'News', + 'taxonomy' => 'category', + ]); + // @todo #2087 get this to work w/o $taxonomy param + $term = Timber::get_term($tid, ''); + $links = []; + + $links[] = 'http://example.org/wp-admin/term.php?taxonomy=category&tag_ID=' . $tid . '&post_type=post'; + $links[] = 'http://example.org/wp-admin/edit-tags.php?action=edit&taxonomy=category&tag_ID=' . $tid . '&post_type=post'; + $links[] = 'http://example.org/wp-admin/edit-tags.php?action=edit&taxonomy=category&tag_ID=' . $tid; + $links[] = 'http://example.org/wp-admin/term.php?taxonomy=category&term_id=' . $tid . '&post_type=post'; + $this->assertContains($term->edit_link(), $links); } +} + +class Arts extends Timber\Term +{ + public function foobar() + { + return 'Zebra'; + } +} diff --git a/tests/test-timber-text-helper.php b/tests/test-timber-text-helper.php index 34c2d1233..e50dad27c 100644 --- a/tests/test-timber-text-helper.php +++ b/tests/test-timber-text-helper.php @@ -1,34 +1,34 @@ gettysburg, 'Four score'); - $this->assertTrue($maybe_starts_with); - } + public function testStartsWith() + { + $maybe_starts_with = Timber\TextHelper::starts_with($this->gettysburg, 'Four score'); + $this->assertTrue($maybe_starts_with); + } - public function testDontStartWith() - { - $maybe_starts_with = Timber\TextHelper::starts_with($this->gettysburg, "Can't get enough of that SugarCrisp"); - $this->assertFalse($maybe_starts_with); - } + public function testDontStartWith() + { + $maybe_starts_with = Timber\TextHelper::starts_with($this->gettysburg, "Can't get enough of that SugarCrisp"); + $this->assertFalse($maybe_starts_with); + } - public function testTruncateEastAsian() - { - $chars = "寒くなってきましたね。14日には北海道でも記録的に遅い初雪が降ったそ"; - $str = '{{ "' . $chars . '"|truncate( 5, true ) }}'; - $result = Timber::compile_string($str); - $this->assertEquals(wp_trim_words($chars, 5), $result); - } + public function testTruncateEastAsian() + { + $chars = "寒くなってきましたね。14日には北海道でも記録的に遅い初雪が降ったそ"; + $str = '{{ "' . $chars . '"|truncate( 5, true ) }}'; + $result = Timber::compile_string($str); + $this->assertEquals(wp_trim_words($chars, 5), $result); + } - public function testTruncaseEnglish() - { - $chars = $this->gettysburg; - $str = '{{ "' . $chars . '"|truncate( 5, true ) }}'; - $result = Timber::compile_string($str); - $this->assertEquals(wp_trim_words($this->gettysburg, 5), $result); - } + public function testTruncaseEnglish() + { + $chars = $this->gettysburg; + $str = '{{ "' . $chars . '"|truncate( 5, true ) }}'; + $result = Timber::compile_string($str); + $this->assertEquals(wp_trim_words($this->gettysburg, 5), $result); } +} diff --git a/tests/test-timber-theme.php b/tests/test-timber-theme.php index f44804ec7..f182b6b70 100644 --- a/tests/test-timber-theme.php +++ b/tests/test-timber-theme.php @@ -1,138 +1,138 @@ theme_slug); + $theme = new Timber\Theme(); + $this->assertGreaterThan(1.2, $theme->version); + switch_theme('default'); + } - public $theme_slug = 'twentythirty'; + public function testThemeParentWithNoParent() + { + switch_theme('twentynineteen'); + $context = Timber::context(); + $theme = $context['site']->theme; + $output = Timber::compile_string('{{ site.theme.parent.slug }}', $context); + $this->assertEquals('twentynineteen', $output); + } - public function testThemeVersion() - { - switch_theme($this->theme_slug); - $theme = new Timber\Theme(); - $this->assertGreaterThan(1.2, $theme->version); - switch_theme('default'); - } + public function testThemeMods() + { + set_theme_mod('foo', 'bar'); + $theme = new Timber\Theme(); + $mods = $theme->theme_mods(); + $this->assertEquals('bar', $mods['foo']); + $bar = $theme->theme_mod('foo'); + $this->assertEquals('bar', $bar); + } - public function testThemeParentWithNoParent() - { - switch_theme('twentynineteen'); - $context = Timber::context(); - $theme = $context['site']->theme; - $output = Timber::compile_string('{{ site.theme.parent.slug }}', $context); - $this->assertEquals('twentynineteen', $output); - } + public function testPath() + { + $context = Timber::context(); + $theme = $context['site']->theme; + $output = Timber::compile_string('{{site.theme.path}}', $context); + $this->assertEquals('/wp-content/themes/' . $theme->slug, $output); + } - public function testThemeMods() - { - set_theme_mod('foo', 'bar'); - $theme = new Timber\Theme(); - $mods = $theme->theme_mods(); - $this->assertEquals('bar', $mods['foo']); - $bar = $theme->theme_mod('foo'); - $this->assertEquals('bar', $bar); + public function testPathWithPort() + { + /* setUp */ + update_option('siteurl', 'http://example.org:3000', true); + update_option('home', 'http://example.org:3000', true); + self::setPermalinkStructure(); + $old_port = $_SERVER['SERVER_PORT']; + $_SERVER['SERVER_PORT'] = 3000; + if (!isset($_SERVER['SERVER_NAME'])) { + $_SERVER['SERVER_NAME'] = 'example.org'; } - public function testPath() - { - $context = Timber::context(); - $theme = $context['site']->theme; - $output = Timber::compile_string('{{site.theme.path}}', $context); - $this->assertEquals('/wp-content/themes/' . $theme->slug, $output); - } + /* test */ + $theme = new Timber\Theme(); + $this->assertEquals('/wp-content/themes/default', $theme->path()); - public function testPathWithPort() - { - /* setUp */ - update_option('siteurl', 'http://example.org:3000', true); - update_option('home', 'http://example.org:3000', true); - self::setPermalinkStructure(); - $old_port = $_SERVER['SERVER_PORT']; - $_SERVER['SERVER_PORT'] = 3000; - if (!isset($_SERVER['SERVER_NAME'])) { - $_SERVER['SERVER_NAME'] = 'example.org'; - } - - /* test */ - $theme = new Timber\Theme(); - $this->assertEquals('/wp-content/themes/default', $theme->path()); - - /* tearDown */ - $_SERVER['SERVER_PORT'] = $old_port; - update_option('siteurl', 'http://example.org', true); - update_option('home', 'http://example.org', true); - } + /* tearDown */ + $_SERVER['SERVER_PORT'] = $old_port; + update_option('siteurl', 'http://example.org', true); + update_option('home', 'http://example.org', true); + } - public function testPathOnSubdirectoryInstall() - { - update_option('siteurl', 'http://example.org/wordpress', true); - $context = Timber::context(); - $theme = $context['site']->theme; - $output = Timber::compile_string('{{site.theme.path}}', $context); - $this->assertEquals('/wp-content/themes/' . $theme->slug, $output); - } + public function testPathOnSubdirectoryInstall() + { + update_option('siteurl', 'http://example.org/wordpress', true); + $context = Timber::context(); + $theme = $context['site']->theme; + $output = Timber::compile_string('{{site.theme.path}}', $context); + $this->assertEquals('/wp-content/themes/' . $theme->slug, $output); + } - public function testLink() - { - $context = Timber::context(); - $theme = $context['site']->theme; - $output = Timber::compile_string('{{site.theme.link}}', $context); - $this->assertEquals('http://example.org/wp-content/themes/' . $theme->slug, $output); - } + public function testLink() + { + $context = Timber::context(); + $theme = $context['site']->theme; + $output = Timber::compile_string('{{site.theme.link}}', $context); + $this->assertEquals('http://example.org/wp-content/themes/' . $theme->slug, $output); + } - public function testLinkOnSubdirectoryInstall() - { - update_option('siteurl', 'http://example.org/wordpress', true); - $context = Timber::context(); - $theme = $context['site']->theme; - $output = Timber::compile_string('{{site.theme.link}}', $context); - $this->assertEquals('http://example.org/wp-content/themes/' . $theme->slug, $output); - } + public function testLinkOnSubdirectoryInstall() + { + update_option('siteurl', 'http://example.org/wordpress', true); + $context = Timber::context(); + $theme = $context['site']->theme; + $output = Timber::compile_string('{{site.theme.link}}', $context); + $this->assertEquals('http://example.org/wp-content/themes/' . $theme->slug, $output); + } - public function testThemeGet() - { - switch_theme($this->theme_slug); - $context = Timber::context(); - $output = Timber::compile_string('{{site.theme.get("Name")}}', $context); - $this->assertEquals('Twenty Nineteen', $output); - switch_theme('default'); - } + public function testThemeGet() + { + switch_theme($this->theme_slug); + $context = Timber::context(); + $output = Timber::compile_string('{{site.theme.get("Name")}}', $context); + $this->assertEquals('Twenty Nineteen', $output); + switch_theme('default'); + } - public function testThemeDisplay() - { - switch_theme($this->theme_slug); - $context = Timber::context(); - $output = Timber::compile_string('{{site.theme.display("Description")}}', $context); - $this->assertEquals("Our 2019 default theme is designed to show off the power of the block editor. It features custom styles for all the default blocks, and is built so that what you see in the editor looks like what you’ll see on your website. Twenty Nineteen is designed to be adaptable to a wide range of websites, whether you’re running a photo blog, launching a new business, or supporting a non-profit. Featuring ample whitespace and modern sans-serif headlines paired with classic serif body text, it’s built to be beautiful on all screen sizes.", $output); - switch_theme('default'); - } + public function testThemeDisplay() + { + switch_theme($this->theme_slug); + $context = Timber::context(); + $output = Timber::compile_string('{{site.theme.display("Description")}}', $context); + $this->assertEquals("Our 2019 default theme is designed to show off the power of the block editor. It features custom styles for all the default blocks, and is built so that what you see in the editor looks like what you’ll see on your website. Twenty Nineteen is designed to be adaptable to a wide range of websites, whether you’re running a photo blog, launching a new business, or supporting a non-profit. Featuring ample whitespace and modern sans-serif headlines paired with classic serif body text, it’s built to be beautiful on all screen sizes.", $output); + switch_theme('default'); + } - public function set_up() - { - global $wp_theme_directories; + public function set_up() + { + global $wp_theme_directories; - parent::set_up(); + parent::set_up(); - $this->backup_wp_theme_directories = $wp_theme_directories; - $wp_theme_directories = [WP_CONTENT_DIR . '/themes']; + $this->backup_wp_theme_directories = $wp_theme_directories; + $wp_theme_directories = [WP_CONTENT_DIR . '/themes']; - wp_clean_themes_cache(); - unset($GLOBALS['wp_themes']); + wp_clean_themes_cache(); + unset($GLOBALS['wp_themes']); - $theme = wp_get_theme($this->theme_slug); - if (!$theme->exists()) { - $this->markTestSkipped('The ' . $this->theme_slug . ' theme is not available'); - } + $theme = wp_get_theme($this->theme_slug); + if (!$theme->exists()) { + $this->markTestSkipped('The ' . $this->theme_slug . ' theme is not available'); } + } - public function tear_down() - { - global $wp_theme_directories; + public function tear_down() + { + global $wp_theme_directories; - $wp_theme_directories = $this->backup_wp_theme_directories; + $wp_theme_directories = $this->backup_wp_theme_directories; - wp_clean_themes_cache(); - unset($GLOBALS['wp_themes']); - parent::tear_down(); - } + wp_clean_themes_cache(); + unset($GLOBALS['wp_themes']); + parent::tear_down(); } +} diff --git a/tests/test-timber-twig-filters.php b/tests/test-timber-twig-filters.php index ced1389dd..bee726d81 100644 --- a/tests/test-timber-twig-filters.php +++ b/tests/test-timber-twig-filters.php @@ -1,51 +1,51 @@ assertEquals('jareds-big-adventure', $str); - } + $data['title'] = "Jared's Big Adventure"; + $str = Timber::compile_string('{{title|sanitize}}', $data); + $this->assertEquals('jareds-big-adventure', $str); + } - public function testTimberPreTags() - { - $data = '

              thing

              '; - $template = '{{foo|pretags}}'; - $str = Timber::compile_string($template, [ - 'foo' => $data, - ]); - $this->assertEquals('
              <h1>thing</h1>
              ', $str); - } + public function testTimberPreTags() + { + $data = '

              thing

              '; + $template = '{{foo|pretags}}'; + $str = Timber::compile_string($template, [ + 'foo' => $data, + ]); + $this->assertEquals('
              <h1>thing</h1>
              ', $str); + } - public function testTimberFilterString() - { - $data['arr'] = ['foo', 'foo']; - $str = Timber::compile_string('{{arr|join(" ")}}', $data); - $this->assertEquals('foo foo', trim($str)); - $data['arr'] = ['bar']; - $str = Timber::compile_string('{{arr|join}}', $data); - $this->assertEquals('bar', trim($str)); - $data['arr'] = ['foo', 'bar']; - $str = Timber::compile_string('{{arr|join(", ")}}', $data); - $this->assertEquals('foo, bar', trim($str)); - $data['arr'] = 6; - $str = Timber::compile_string('{{arr}}', $data); - $this->assertEquals('6', trim($str)); - } + public function testTimberFilterString() + { + $data['arr'] = ['foo', 'foo']; + $str = Timber::compile_string('{{arr|join(" ")}}', $data); + $this->assertEquals('foo foo', trim($str)); + $data['arr'] = ['bar']; + $str = Timber::compile_string('{{arr|join}}', $data); + $this->assertEquals('bar', trim($str)); + $data['arr'] = ['foo', 'bar']; + $str = Timber::compile_string('{{arr|join(", ")}}', $data); + $this->assertEquals('foo, bar', trim($str)); + $data['arr'] = 6; + $str = Timber::compile_string('{{arr}}', $data); + $this->assertEquals('6', trim($str)); + } - public function testTwigFilterList() - { - $data['authors'] = ['Tom', 'Rick', 'Harry', 'Mike']; - $str = Timber::compile_string("{{authors|list}}", $data); - $this->assertEquals('Tom, Rick, Harry and Mike', $str); - } + public function testTwigFilterList() + { + $data['authors'] = ['Tom', 'Rick', 'Harry', 'Mike']; + $str = Timber::compile_string("{{authors|list}}", $data); + $this->assertEquals('Tom, Rick, Harry and Mike', $str); + } - public function testTwigFilterListOxford() - { - $data['authors'] = ['Tom', 'Rick', 'Harry', 'Mike']; - $str = Timber::compile_string("{{authors|list(',', ', and')}}", $data); - $this->assertEquals('Tom, Rick, Harry, and Mike', $str); - } + public function testTwigFilterListOxford() + { + $data['authors'] = ['Tom', 'Rick', 'Harry', 'Mike']; + $str = Timber::compile_string("{{authors|list(',', ', and')}}", $data); + $this->assertEquals('Tom, Rick, Harry, and Mike', $str); } +} diff --git a/tests/test-timber-twig.php b/tests/test-timber-twig.php index f4c3d6d0a..f96ccf4b3 100644 --- a/tests/test-timber-twig.php +++ b/tests/test-timber-twig.php @@ -1,424 +1,403 @@ installTranlsationFiles($lang_dir); - } - - $td = 'timber_test_theme'; - load_theme_textdomain($td, $lang_dir); - - return $td; + $lang_dir = get_stylesheet_directory() . '/languages'; + if (file_exists($lang_dir . '/en_US.po')) { + unlink($lang_dir . '/en_US.po'); } - - public function testFormat() - { - $str = '{{ "I like %s and %s"|format(foo, "bar") }}'; - $return = Timber::compile_string($str, [ - 'foo' => 'foo', - ]); - $this->assertEquals('I like foo and bar', $return); + if (file_exists($lang_dir . '/en_US.mo')) { + unlink($lang_dir . '/en_US.mo'); } + } - public function testTranslate() - { - $td = $this->_setupTranslationFiles(); - $str = "I like {{ __('thingy', '$td') }}"; - $return = Timber::compile_string($str, [ - 'foo' => 'foo', - ]); - $this->assertEquals('I like Cheesy Poofs', $return); - - $str = "I like {{ __('doobie', '$td') }}"; - $return = Timber::compile_string($str, [ - 'foo' => 'foo', - ]); - $this->assertEquals('I like doobie', $return); - } + public function testFormat() + { + $str = '{{ "I like %s and %s"|format(foo, "bar") }}'; + $return = Timber::compile_string($str, [ + 'foo' => 'foo', + ]); + $this->assertEquals('I like foo and bar', $return); + } - public function testTranslateAndFormat() - { - $td = $this->_setupTranslationFiles(); + public function testTranslate() + { + load_textdomain('timber-test', __DIR__ . '/languages/timber-test-en_US.mo'); + + $str = "I like {{ __('thingy', 'timber-test') }}"; + $return = Timber::compile_string($str, [ + 'foo' => 'foo', + ]); + $this->assertEquals('I like Cheesy Poofs', $return); + + $str = "I like {{ __('doobie', 'timber-test') }}"; + $return = Timber::compile_string($str, [ + 'foo' => 'foo', + ]); + $this->assertEquals('I like doobie', $return); + } - $str = "You like {{__('%s', '$td')|format('thingy')}}"; - $return = Timber::compile_string($str); - $this->assertEquals('You like thingy', $return); - $str = "You like {{__('%s'|format('thingy'), '$td')}}"; - $return = Timber::compile_string($str); - $this->assertEquals('You like Cheesy Poofs', $return); - } + public function testTranslateAndFormat() + { + load_textdomain('timber-test', __DIR__ . '/languages/timber-test-en_US.mo'); + + $str = "You like {{__('%s', 'timber-test')|format('thingy')}}"; + $return = Timber::compile_string($str); + $this->assertEquals('You like thingy', $return); + $str = "You like {{__('%s'|format('thingy'), 'timber-test')}}"; + $return = Timber::compile_string($str); + $this->assertEquals('You like Cheesy Poofs', $return); + } - public function testDoAction() - { - global $action_tally; - global $php_unit; - $php_unit = $this; - $action_tally = []; + public function testDoAction() + { + global $action_tally; + global $php_unit; + $php_unit = $this; + $action_tally = []; - $my_action_foo = function () { - global $action_tally, $php_unit; - $php_unit->assertTrue(true); - $action_tally[] = 'my_action_foo'; + $my_action_foo = function () { + global $action_tally, $php_unit; + $php_unit->assertTrue(true); + $action_tally[] = 'my_action_foo'; - return 'foo'; - }; + return 'foo'; + }; - $my_action_args = function ($bar) { - global $action_tally, $php_unit; - $php_unit->assertEquals('bar', $bar); - $action_tally[] = 'my_action_args'; + $my_action_args = function ($bar) { + global $action_tally, $php_unit; + $php_unit->assertEquals('bar', $bar); + $action_tally[] = 'my_action_args'; - return 'foo'; - }; + return 'foo'; + }; - $timber_compile_done = function () { - global $action_tally, $php_unit; + $timber_compile_done = function () { + global $action_tally, $php_unit; - $php_unit->assertContains('my_action_args', $action_tally); - $php_unit->assertContains('my_action_foo', $action_tally); - }; + $php_unit->assertContains('my_action_args', $action_tally); + $php_unit->assertContains('my_action_foo', $action_tally); + }; - $this->add_action_temporarily('my_action_foo', $my_action_foo); - $this->add_action_temporarily('my_action_args', $my_action_args); - $this->add_action_temporarily('timber/compile/done', $timber_compile_done); + $this->add_action_temporarily('my_action_foo', $my_action_foo); + $this->add_action_temporarily('my_action_args', $my_action_args); + $this->add_action_temporarily('timber/compile/done', $timber_compile_done); - $str = Timber::compile('assets/test-do-action.twig'); - $str = trim($str); + $str = Timber::compile('assets/test-do-action.twig'); + $str = trim($str); - $this->assertEquals('Stuff', $str); - } + $this->assertEquals('Stuff', $str); + } - public function testWordPressPasswordFilters() - { - $post_id = $this->factory->post->create([ - 'post_title' => 'My Private Post', - 'post_password' => 'abc123', - ]); - $context = []; - add_filter('protected_title_format', function ($title) { - return 'Protected: ' . $title; - }); - $context['post'] = Timber::get_post($post_id); - if (post_password_required($post_id)) { - $this->assertTrue(true); - $str = Timber::compile('assets/test-wp-filters.twig', $context); - $this->assertEquals('Protected: My Private Post', trim($str)); - } else { - $this->assertTrue(false, 'Something wrong with the post password reqd'); - } + public function testWordPressPasswordFilters() + { + $post_id = $this->factory->post->create([ + 'post_title' => 'My Private Post', + 'post_password' => 'abc123', + ]); + $context = []; + add_filter('protected_title_format', function ($title) { + return 'Protected: ' . $title; + }); + $context['post'] = Timber::get_post($post_id); + if (post_password_required($post_id)) { + $this->assertTrue(true); + $str = Timber::compile('assets/test-wp-filters.twig', $context); + $this->assertEquals('Protected: My Private Post', trim($str)); + } else { + $this->assertTrue(false, 'Something wrong with the post password reqd'); } + } - public function testToArrayWithString() - { - $thing = 'thing'; - $str = '{% for thing in things|array %}{{thing}}{% endfor %}'; - $this->assertEquals('thing', Timber::compile_string($str, [ - 'things' => $thing, - ])); - } + public function testToArrayWithString() + { + $thing = 'thing'; + $str = '{% for thing in things|array %}{{thing}}{% endfor %}'; + $this->assertEquals('thing', Timber::compile_string($str, [ + 'things' => $thing, + ])); + } - public function testToArrayWithArray() - { - $thing = ['thing', 'thang']; - $str = '{% for thing in things|array %}{{thing}}{% endfor %}'; - $this->assertEquals('thingthang', Timber::compile_string($str, [ - 'things' => $thing, - ])); - } + public function testToArrayWithArray() + { + $thing = ['thing', 'thang']; + $str = '{% for thing in things|array %}{{thing}}{% endfor %}'; + $this->assertEquals('thingthang', Timber::compile_string($str, [ + 'things' => $thing, + ])); + } - public function testTwigString() - { - $str = 'Foo'; - $arr = ['Bar', 'Quack']; - $twig = '{{string|join}}x{{array|join("x")}}'; - $this->assertEquals('FooxBarxQuack', trim(Timber::compile_string($twig, [ - 'string' => $str, - 'array' => $arr, - ]))); - } + public function testTwigString() + { + $str = 'Foo'; + $arr = ['Bar', 'Quack']; + $twig = '{{string|join}}x{{array|join("x")}}'; + $this->assertEquals('FooxBarxQuack', trim(Timber::compile_string($twig, [ + 'string' => $str, + 'array' => $arr, + ]))); + } - /** - * @expectedDeprecated {{ my_object | get_class }} - */ - public function testFilterFunction() - { - $pid = $this->factory->post->create([ - 'post_title' => 'Foo', - ]); - $post = Timber::get_post($pid); - $str = 'I am a {{post | get_class }}'; - $this->assertEquals('I am a Timber\Post', Timber::compile_string($str, [ - 'post' => $post, - ])); - } + /** + * @expectedDeprecated {{ my_object | get_class }} + */ + public function testFilterFunction() + { + $pid = $this->factory->post->create([ + 'post_title' => 'Foo', + ]); + $post = Timber::get_post($pid); + $str = 'I am a {{post | get_class }}'; + $this->assertEquals('I am a Timber\Post', Timber::compile_string($str, [ + 'post' => $post, + ])); + } - public function testFilterTruncate() - { - $gettysburg = 'Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.'; - $str = Timber::compile_string("{{address | truncate(6)}}", [ - 'address' => $gettysburg, - ]); - $this->assertEquals('Four score and seven years ago…', $str); - } + public function testFilterTruncate() + { + $gettysburg = 'Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.'; + $str = Timber::compile_string("{{address | truncate(6)}}", [ + 'address' => $gettysburg, + ]); + $this->assertEquals('Four score and seven years ago…', $str); + } - public function testFilterTrimCharacters() - { - $gettysburg = 'Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.'; - $str = Timber::compile_string("{{content | excerpt_chars(100)}}", [ - 'content' => $gettysburg, - ]); - $this->assertEquals('Four score and seven years ago our fathers brought forth on this continent, a new nation, co…', $str); - } + public function testFilterTrimCharacters() + { + $gettysburg = 'Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.'; + $str = Timber::compile_string("{{content | excerpt_chars(100)}}", [ + 'content' => $gettysburg, + ]); + $this->assertEquals('Four score and seven years ago our fathers brought forth on this continent, a new nation, co…', $str); + } - public function testSetSimple() - { - $result = Timber::compile('assets/set-simple.twig', [ - 'foo' => 'bar', - ]); - $this->assertEquals('jiggy', trim($result)); - } + public function testSetSimple() + { + $result = Timber::compile('assets/set-simple.twig', [ + 'foo' => 'bar', + ]); + $this->assertEquals('jiggy', trim($result)); + } - public function testEscUrl() - { - $url = 'http://example.com/Mr WordPress'; - $str = Timber::compile_string("{{the_url | e('esc_url')}}", [ - 'the_url' => $url, - ]); - $this->assertEquals('http://example.com/Mr%20WordPress', $str); - } + public function testEscUrl() + { + $url = 'http://example.com/Mr WordPress'; + $str = Timber::compile_string("{{the_url | e('esc_url')}}", [ + 'the_url' => $url, + ]); + $this->assertEquals('http://example.com/Mr%20WordPress', $str); + } - public function testWpKsesPost() - { - $evil_script = '
              Foo
              '; - $str = Timber::compile_string("{{ evil_script | e('wp_kses_post') }}", [ - 'evil_script' => $evil_script, - ]); - $this->assertEquals('
              Foo
              DoEvilThing();', $str); - } + public function testWpKsesPost() + { + $evil_script = '
              Foo
              '; + $str = Timber::compile_string("{{ evil_script | e('wp_kses_post') }}", [ + 'evil_script' => $evil_script, + ]); + $this->assertEquals('
              Foo
              DoEvilThing();', $str); + } - public function testEscHtml() - { + public function testEscHtml() + { - // Simple string - $html = "The quick brown fox."; + // Simple string + $html = "The quick brown fox."; - $str = Timber::compile_string("{{text | e('esc_html')}}", [ - 'text' => $html, - ]); + $str = Timber::compile_string("{{text | e('esc_html')}}", [ + 'text' => $html, + ]); - $this->assertEquals($html, $str); + $this->assertEquals($html, $str); - $escaped = "http://localhost/trunk/wp-login.php?action=logout&_wpnonce=cd57d75985"; + $escaped = "http://localhost/trunk/wp-login.php?action=logout&_wpnonce=cd57d75985"; - $str = Timber::compile_string("{{text | e('esc_html')}}", [ - 'text' => 'http://localhost/trunk/wp-login.php?action=logout&_wpnonce=cd57d75985', - ]); + $str = Timber::compile_string("{{text | e('esc_html')}}", [ + 'text' => 'http://localhost/trunk/wp-login.php?action=logout&_wpnonce=cd57d75985', + ]); - $this->assertEquals($escaped, $str); + $this->assertEquals($escaped, $str); - // SQL query + // SQL query - $escaped = "SELECT meta_key, meta_value FROM wp_trunk_sitemeta WHERE meta_key IN ('site_name', 'siteurl', 'active_sitewide_plugins', '_site_transient_timeout_theme_roots', '_site_transient_theme_roots', 'site_admins', 'can_compress_scripts', 'global_terms_enabled') AND site_id = 1"; + $escaped = "SELECT meta_key, meta_value FROM wp_trunk_sitemeta WHERE meta_key IN ('site_name', 'siteurl', 'active_sitewide_plugins', '_site_transient_timeout_theme_roots', '_site_transient_theme_roots', 'site_admins', 'can_compress_scripts', 'global_terms_enabled') AND site_id = 1"; - $str = Timber::compile_string("{{text | e('esc_html')}}", [ - 'text' => "SELECT meta_key, meta_value FROM wp_trunk_sitemeta WHERE meta_key IN ('site_name', 'siteurl', 'active_sitewide_plugins', '_site_transient_timeout_theme_roots', '_site_transient_theme_roots', 'site_admins', 'can_compress_scripts', 'global_terms_enabled') AND site_id = 1", - ]); - $this->assertEquals($escaped, $str); - } + $str = Timber::compile_string("{{text | e('esc_html')}}", [ + 'text' => "SELECT meta_key, meta_value FROM wp_trunk_sitemeta WHERE meta_key IN ('site_name', 'siteurl', 'active_sitewide_plugins', '_site_transient_timeout_theme_roots', '_site_transient_theme_roots', 'site_admins', 'can_compress_scripts', 'global_terms_enabled') AND site_id = 1", + ]); + $this->assertEquals($escaped, $str); + } - public function testEscJs() - { - $escaped = 'foo & bar &baz;  '; - $str = Timber::compile_string("{{text | e('esc_js')}}", [ - 'text' => 'foo & bar &baz;  ', - ]); + public function testEscJs() + { + $escaped = 'foo & bar &baz;  '; + $str = Timber::compile_string("{{text | e('esc_js')}}", [ + 'text' => 'foo & bar &baz;  ', + ]); - $this->assertEquals($escaped, $str); + $this->assertEquals($escaped, $str); - $escaped = "foo \\' bar \\' baz &"; - $str = Timber::compile_string("{{text | e('esc_js')}}", [ - 'text' => 'foo ' bar ' baz &', - ]); + $escaped = "foo \\' bar \\' baz &"; + $str = Timber::compile_string("{{text | e('esc_js')}}", [ + 'text' => 'foo ' bar ' baz &', + ]); - $this->assertEquals($escaped, $str); - } + $this->assertEquals($escaped, $str); + } - public function testSetObject() - { - $this->expectException(\Twig\Error\SyntaxError::class); - $pid = $this->factory->post->create([ - 'post_title' => 'Spaceballs', - ]); - $post = Timber::get_post($pid); - $result = Timber::compile('assets/set-object.twig', [ - 'post' => $post, - ]); - $this->assertEquals('Spaceballs: may the schwartz be with you', trim($result)); - } + public function testSetObject() + { + $this->expectException(\Twig\Error\SyntaxError::class); + $pid = $this->factory->post->create([ + 'post_title' => 'Spaceballs', + ]); + $post = Timber::get_post($pid); + $result = Timber::compile('assets/set-object.twig', [ + 'post' => $post, + ]); + $this->assertEquals('Spaceballs: may the schwartz be with you', trim($result)); + } - public function testTwigFunction() - { - $template = '{{bloginfo("name")}}'; - $result = Timber::compile_string($template); - $this->assertEquals('Test Blog', $result); - } + public function testTwigFunction() + { + $template = '{{bloginfo("name")}}'; + $result = Timber::compile_string($template); + $this->assertEquals('Test Blog', $result); + } - public function testAddToTwig() - { - add_filter('timber/twig', function ($twig) { - $twig->addFilter(new \Twig\TwigFilter('foobar', function ($text) { - return $text . 'foobar'; - })); - return $twig; - }); - $str = Timber::compile_string('{{ "jared" | foobar }}'); - $this->assertEquals('jaredfoobar', $str); - } + public function testAddToTwig() + { + add_filter('timber/twig', function ($twig) { + $twig->addFilter(new \Twig\TwigFilter('foobar', function ($text) { + return $text . 'foobar'; + })); + return $twig; + }); + $str = Timber::compile_string('{{ "jared" | foobar }}'); + $this->assertEquals('jaredfoobar', $str); + } - public function testTimberTwigObjectFilter() - { - add_filter('timber/twig', function ($twig) { - $twig->addFilter(new \Twig\TwigFilter('quack', function ($text) { - return $text . ' Quack!'; - })); - return $twig; - }); - $str = Timber::compile_string('{{ "jared" | quack }}'); - $this->assertEquals('jared Quack!', $str); - } + public function testTimberTwigObjectFilter() + { + add_filter('timber/twig', function ($twig) { + $twig->addFilter(new \Twig\TwigFilter('quack', function ($text) { + return $text . ' Quack!'; + })); + return $twig; + }); + $str = Timber::compile_string('{{ "jared" | quack }}'); + $this->assertEquals('jared Quack!', $str); + } - public function testTwigShortcode() - { - add_shortcode('my_shortcode', function ($atts, $content) { - return 'Jaredfoo'; - }); - $str = Timber::compile_string('{{shortcode("[my_shortcode]")}}'); - $this->assertEquals('Jaredfoo', $str); - } + public function testTwigShortcode() + { + add_shortcode('my_shortcode', function ($atts, $content) { + return 'Jaredfoo'; + }); + $str = Timber::compile_string('{{shortcode("[my_shortcode]")}}'); + $this->assertEquals('Jaredfoo', $str); + } - public function testTwigShortcodeWithContent() - { - add_shortcode('duck', function ($atts, $content) { - return $content . ' says quack!'; - }); + public function testTwigShortcodeWithContent() + { + add_shortcode('duck', function ($atts, $content) { + return $content . ' says quack!'; + }); - $str = Timber::compile_string('{{shortcode("[duck]Lauren[/duck]")}}'); - $this->assertEquals('Lauren says quack!', $str); - } + $str = Timber::compile_string('{{shortcode("[duck]Lauren[/duck]")}}'); + $this->assertEquals('Lauren says quack!', $str); + } - /** - * @expectedDeprecated Timber::$autoescape - */ - public function testAutoescapeVariableDeprecated() - { - Timber::$autoescape = true; + /** + * @expectedDeprecated Timber::$autoescape + */ + public function testAutoescapeVariableDeprecated() + { + Timber::$autoescape = true; - $str = Timber\Timber::compile_string('The {{ region }} remembers…', [ - 'region' => 'North', - ]); + $str = Timber\Timber::compile_string('The {{ region }} remembers…', [ + 'region' => 'North', + ]); - $this->assertEquals( - 'The <strong>North</strong> remembers…', - $str - ); + $this->assertEquals( + 'The <strong>North</strong> remembers…', + $str + ); - Timber::$autoescape = false; - } + Timber::$autoescape = false; + } - public function testAutoescapeTrueBackwardsCompatibilityWithFilter() - { - $autoescape_filter = function ($options) { - $options['autoescape'] = true; + public function testAutoescapeTrueBackwardsCompatibilityWithFilter() + { + $autoescape_filter = function ($options) { + $options['autoescape'] = true; - return $options; - }; + return $options; + }; - add_filter('timber/twig/environment/options', $autoescape_filter); + add_filter('timber/twig/environment/options', $autoescape_filter); - $str = Timber\Timber::compile_string('The {{ region }} remembers…', [ - 'region' => 'North', - ]); + $str = Timber\Timber::compile_string('The {{ region }} remembers…', [ + 'region' => 'North', + ]); - remove_filter('timber/twig/environment/options', $autoescape_filter); + remove_filter('timber/twig/environment/options', $autoescape_filter); - $this->assertEquals( - 'The <strong>North</strong> remembers…', - $str - ); - } + $this->assertEquals( + 'The <strong>North</strong> remembers…', + $str + ); + } - public function testAutoescapeStrategyWithFilter() - { - $autoescape_filter = function ($options) { - $options['autoescape'] = 'html'; + public function testAutoescapeStrategyWithFilter() + { + $autoescape_filter = function ($options) { + $options['autoescape'] = 'html'; - return $options; - }; + return $options; + }; - add_filter('timber/twig/environment/options', $autoescape_filter); + add_filter('timber/twig/environment/options', $autoescape_filter); - $str = Timber\Timber::compile_string('The {{ region }} remembers…', [ - 'region' => 'North', - ]); + $str = Timber\Timber::compile_string('The {{ region }} remembers…', [ + 'region' => 'North', + ]); - remove_filter('timber/twig/environment/options', $autoescape_filter); + remove_filter('timber/twig/environment/options', $autoescape_filter); - $this->assertEquals( - 'The <strong>North</strong> remembers…', - $str - ); - } + $this->assertEquals( + 'The <strong>North</strong> remembers…', + $str + ); + } - public function testRemoveADefaultFunction() - { - $this->expectException(\Twig\Error\SyntaxError::class); - add_filter('timber/twig/functions', function ($functions) { - unset($functions['shortcode']); - return $functions; - }); - Timber::compile_string("{{ text|shortcode }}", [ - 'text' => 'A function has been removed', - ]); - } + public function testRemoveADefaultFunction() + { + $this->expectException(\Twig\Error\SyntaxError::class); + add_filter('timber/twig/functions', function ($functions) { + unset($functions['shortcode']); + return $functions; + }); + Timber::compile_string("{{ text|shortcode }}", [ + 'text' => 'A function has been removed', + ]); + } - public function testRemoveADefaultFilter() - { - $this->expectException(\Twig\Error\SyntaxError::class); - add_filter('timber/twig/filters', function ($filters) { - unset($filters['wpautop']); - return $filters; - }); - Timber::compile_string("{{ text|wpautop }}", [ - 'text' => 'A filter has been removed', - ]); - } + public function testRemoveADefaultFilter() + { + $this->expectException(\Twig\Error\SyntaxError::class); + add_filter('timber/twig/filters', function ($filters) { + unset($filters['wpautop']); + return $filters; + }); + Timber::compile_string("{{ text|wpautop }}", [ + 'text' => 'A filter has been removed', + ]); } +} diff --git a/tests/test-timber-user.php b/tests/test-timber-user.php index 32969e4bc..ab92bd165 100644 --- a/tests/test-timber-user.php +++ b/tests/test-timber-user.php @@ -2,164 +2,164 @@ use Timber\User; - /** - * @group integrations - * @group users-api - */ - class TestTimberUser extends Timber_UnitTestCase +/** + * @group integrations + * @group users-api + */ +class TestTimberUser extends Timber_UnitTestCase +{ + public function set_up() { - public function set_up() - { - parent::set_up(); - - // Restore integration-free Class Map for users. - $this->add_filter_temporarily('timber/user/class', function () { - return User::class; - }); - } - - public function testIDDataType() - { - $uid = $this->factory->user->create([ - 'display_name' => 'James Marshall', - ]); - $user = Timber::get_user($uid); - $this->assertEquals('integer', gettype($user->id)); - $this->assertEquals('integer', gettype($user->ID)); - } - - public function testInitWithID() - { - $uid = $this->factory->user->create([ - 'display_name' => 'Baberaham Lincoln', - ]); - $user = Timber::get_user($uid); - $this->assertEquals('Baberaham Lincoln', $user->name); - $this->assertEquals($uid, $user->id); - } - - public function testInitWithSlug() - { - $uid = $this->factory->user->create([ - 'display_name' => 'Tito Bottitta', - 'user_login' => 'mbottitta', - ]); - $user = Timber::get_user_by('login', 'mbottitta'); - $this->assertEquals('Tito Bottitta', $user->name); - $this->assertEquals($uid, $user->id); - } - - public function testPostWithBlankUser() - { - $post_id = wp_insert_post( - [ - 'post_title' => 'Baseball', - 'post_content' => 'is fine, I guess', - 'post_status' => 'publish', - ] - ); - $post = Timber::get_post($post_id); - $template = '{{ post.title }} by {{ post.author }}'; - $str = Timber::compile_string($template, [ - 'post' => $post, - ]); - $this->assertEquals('Baseball by', trim($str)); - } - - public function testUserCapability() - { - $uid = $this->factory->user->create([ - 'display_name' => 'Tito Bottitta', - 'user_login' => 'mbottitta', - 'role' => 'editor', - ]); - $user = Timber::get_user_by('login', 'mbottitta'); - $this->assertTrue($user->can('edit_posts')); - $this->assertFalse($user->can('activate_plugins')); - } - - public function testUserRole() - { - $uid = $this->factory->user->create([ - 'display_name' => 'Tito Bottitta', - 'user_login' => 'mbottitta', - 'role' => 'editor', - ]); - $user = Timber::get_user_by('login', 'mbottitta'); - $this->assertArrayHasKey('editor', $user->roles()); - } - - public function testDescription() - { - $uid = $this->factory->user->create([ - 'display_name' => 'Baberaham Lincoln', - 'user_login' => 'blincoln', - ]); - update_user_meta($uid, 'description', 'Sixteenth President'); - $user = Timber::get_user($uid); - $this->assertEquals('Sixteenth President', $user->meta('description')); - - $pid = $this->factory->post->create([ - 'post_author' => $uid, - ]); - $post = Timber::get_post($pid); - $str = Timber::compile_string("{{post.author.meta('description')}}", [ - 'post' => $post, - ]); - $this->assertEquals('Sixteenth President', $str); - } - - public function testInitShouldUnsetPassword() - { - $uid = $this->factory->user->create([ - 'display_name' => 'Tom Riddle', - ]); - $user = Timber::get_user($uid); - $this->assertFalse(property_exists($user, 'user_pass')); - } - - public function testInitWithObject() - { - $uid = $this->factory->user->create([ - 'display_name' => 'Baberaham Lincoln', - ]); - $wp_user = get_user_by('id', $uid); - $user = Timber::get_user($wp_user); - $this->assertEquals('Baberaham Lincoln', $user->name); - } - - public function testLinks() - { - $this->setPermalinkStructure('/blog/%year%/%monthnum%/%postname%/'); - $uid = $this->factory->user->create([ - 'display_name' => 'Baberaham Lincoln', - 'user_login' => 'lincoln', - ]); - $uid = get_user_by('id', $uid); - $user = Timber::get_user($uid); - $this->assertEquals('http://example.org/blog/author/lincoln/', trailingslashit($user->link())); - $this->assertEquals('/blog/author/lincoln/', trailingslashit($user->path())); - $user->president = '16th'; - $this->assertEquals('16th', $user->president); - } - - public function testAvatar() - { - // Restore integration-free Class Map for users. - // CoAuthorsPlus overrides avatar behavior, so we disable it explicitly. - $this->add_filter_temporarily('timber/user/class', function () { - return User::class; - }); - - $uid = $this->factory->user->create([ - 'display_name' => 'Maciej Palmowski', - 'user_login' => 'palmiak', - 'user_email' => 'm.palmowski@spiders.agency', - ]); - $user = Timber::get_user($uid); - $this->assertEquals('http://2.gravatar.com/avatar/b2965625410b81a2b25ef02b54493ce0?s=96&d=mm&r=g', $user->avatar()); - $this->assertEquals('http://2.gravatar.com/avatar/b2965625410b81a2b25ef02b54493ce0?s=120&d=mm&r=g', $user->avatar([ - 'size' => 120, - ])); - } + parent::set_up(); + + // Restore integration-free Class Map for users. + $this->add_filter_temporarily('timber/user/class', function () { + return User::class; + }); + } + + public function testIDDataType() + { + $uid = $this->factory->user->create([ + 'display_name' => 'James Marshall', + ]); + $user = Timber::get_user($uid); + $this->assertEquals('integer', gettype($user->id)); + $this->assertEquals('integer', gettype($user->ID)); + } + + public function testInitWithID() + { + $uid = $this->factory->user->create([ + 'display_name' => 'Baberaham Lincoln', + ]); + $user = Timber::get_user($uid); + $this->assertEquals('Baberaham Lincoln', $user->name); + $this->assertEquals($uid, $user->id); + } + + public function testInitWithSlug() + { + $uid = $this->factory->user->create([ + 'display_name' => 'Tito Bottitta', + 'user_login' => 'mbottitta', + ]); + $user = Timber::get_user_by('login', 'mbottitta'); + $this->assertEquals('Tito Bottitta', $user->name); + $this->assertEquals($uid, $user->id); + } + + public function testPostWithBlankUser() + { + $post_id = wp_insert_post( + [ + 'post_title' => 'Baseball', + 'post_content' => 'is fine, I guess', + 'post_status' => 'publish', + ] + ); + $post = Timber::get_post($post_id); + $template = '{{ post.title }} by {{ post.author }}'; + $str = Timber::compile_string($template, [ + 'post' => $post, + ]); + $this->assertEquals('Baseball by', trim($str)); + } + + public function testUserCapability() + { + $uid = $this->factory->user->create([ + 'display_name' => 'Tito Bottitta', + 'user_login' => 'mbottitta', + 'role' => 'editor', + ]); + $user = Timber::get_user_by('login', 'mbottitta'); + $this->assertTrue($user->can('edit_posts')); + $this->assertFalse($user->can('activate_plugins')); + } + + public function testUserRole() + { + $uid = $this->factory->user->create([ + 'display_name' => 'Tito Bottitta', + 'user_login' => 'mbottitta', + 'role' => 'editor', + ]); + $user = Timber::get_user_by('login', 'mbottitta'); + $this->assertArrayHasKey('editor', $user->roles()); + } + + public function testDescription() + { + $uid = $this->factory->user->create([ + 'display_name' => 'Baberaham Lincoln', + 'user_login' => 'blincoln', + ]); + update_user_meta($uid, 'description', 'Sixteenth President'); + $user = Timber::get_user($uid); + $this->assertEquals('Sixteenth President', $user->meta('description')); + + $pid = $this->factory->post->create([ + 'post_author' => $uid, + ]); + $post = Timber::get_post($pid); + $str = Timber::compile_string("{{post.author.meta('description')}}", [ + 'post' => $post, + ]); + $this->assertEquals('Sixteenth President', $str); + } + + public function testInitShouldUnsetPassword() + { + $uid = $this->factory->user->create([ + 'display_name' => 'Tom Riddle', + ]); + $user = Timber::get_user($uid); + $this->assertFalse(property_exists($user, 'user_pass')); + } + + public function testInitWithObject() + { + $uid = $this->factory->user->create([ + 'display_name' => 'Baberaham Lincoln', + ]); + $wp_user = get_user_by('id', $uid); + $user = Timber::get_user($wp_user); + $this->assertEquals('Baberaham Lincoln', $user->name); + } + + public function testLinks() + { + $this->setPermalinkStructure('/blog/%year%/%monthnum%/%postname%/'); + $uid = $this->factory->user->create([ + 'display_name' => 'Baberaham Lincoln', + 'user_login' => 'lincoln', + ]); + $uid = get_user_by('id', $uid); + $user = Timber::get_user($uid); + $this->assertEquals('http://example.org/blog/author/lincoln/', trailingslashit($user->link())); + $this->assertEquals('/blog/author/lincoln/', trailingslashit($user->path())); + $user->president = '16th'; + $this->assertEquals('16th', $user->president); + } + + public function testAvatar() + { + // Restore integration-free Class Map for users. + // CoAuthorsPlus overrides avatar behavior, so we disable it explicitly. + $this->add_filter_temporarily('timber/user/class', function () { + return User::class; + }); + + $uid = $this->factory->user->create([ + 'display_name' => 'Maciej Palmowski', + 'user_login' => 'palmiak', + 'user_email' => 'm.palmowski@spiders.agency', + ]); + $user = Timber::get_user($uid); + $this->assertEquals('http://2.gravatar.com/avatar/b2965625410b81a2b25ef02b54493ce0?s=96&d=mm&r=g', $user->avatar()); + $this->assertEquals('http://2.gravatar.com/avatar/b2965625410b81a2b25ef02b54493ce0?s=120&d=mm&r=g', $user->avatar([ + 'size' => 120, + ])); } +} diff --git a/tests/test-timber-wp-functions.php b/tests/test-timber-wp-functions.php index 485b0df7b..b266bc400 100644 --- a/tests/test-timber-wp-functions.php +++ b/tests/test-timber-wp-functions.php @@ -114,17 +114,17 @@ public function testInTwigStringHeadAndFooter() } } - function do_jared_action() - { - do_action('jared_action'); - } +function do_jared_action() +{ + do_action('jared_action'); +} - function echo_junk() - { - echo 'foo'; - } +function echo_junk() +{ + echo 'foo'; +} - function my_test_function() - { - return 'jared sez hi'; - } +function my_test_function() +{ + return 'jared sez hi'; +} diff --git a/tests/wp-overrides.php b/tests/wp-overrides.php index 8fe63b2eb..3ab06ab76 100644 --- a/tests/wp-overrides.php +++ b/tests/wp-overrides.php @@ -79,7 +79,7 @@ public static function media_handle_upload($file_id, $post_id, $post_data = [], $content .= ' ' . sprintf(__('Genre: %s.'), $meta['genre']); } - // use image exif/iptc data for title and caption defaults if possible + // use image exif/iptc data for title and caption defaults if possible } elseif ($image_meta = @wp_read_image_metadata($file)) { if (trim($image_meta['title']) && !is_numeric(sanitize_title($image_meta['title']))) { $title = $image_meta['title'];