From 3d156c99bc28b5301e4f61fce2881cee3c1b1442 Mon Sep 17 00:00:00 2001 From: Gary Jones Date: Wed, 7 Feb 2024 23:27:19 +0000 Subject: [PATCH] Tests: Code QOL improvements - Replace nested dirname() calls - Remove unnecessary local variables - Replace qualifiers with an import - Unwrap unnecessary typecast - Use strpos() instead of substr() - Use instanceof instead of is_a() - Update DocBlocks - Use decrement operator - Replace misused foreach() with array_sum() - Declare closure static - Declare access modifiers - Declare return types where possible - Add parameter and property types - Use more appropriate assertions - Improve regular expression - Remove unnecessary time() argument from strotime() calls - Add more entropy to uniqid() calls - Remove unused code --- tests/CPTTest.php | 26 ++++--- tests/CreationTest.php | 18 +++-- tests/CronTest.php | 24 ++---- tests/FiltersTest.php | 11 ++- tests/FunctionsTest.php | 161 +++++++++++++++++++++++----------------- tests/IndexesTest.php | 20 ++--- tests/StatsTest.php | 29 ++++---- tests/TestCase.php | 79 +++++++++++--------- 8 files changed, 203 insertions(+), 165 deletions(-) diff --git a/tests/CPTTest.php b/tests/CPTTest.php index 61c76859..d88a748b 100644 --- a/tests/CPTTest.php +++ b/tests/CPTTest.php @@ -19,14 +19,14 @@ class CPTTest extends TestCase { /** * Custom Post Type * - * @var str + * @var string */ - const TEST_CPT = 'msm_stest'; + public const TEST_CPT = 'msm_stest'; /** * Initialize Test CPT */ - static function setupBeforeClass(): void { + public static function setupBeforeClass(): void { register_post_type( self::TEST_CPT, array( @@ -50,8 +50,8 @@ static function setupBeforeClass(): void { /** * Initialize MSM_SiteMap_Test */ - function setup(): void { - // Create Multiple Posts acorss various Dates. + public function setup(): void { + // Create Multiple Posts across various Dates. $date = time(); // 3 for Today, 1 in "draft" status @@ -68,7 +68,7 @@ function setup(): void { } // 1 CPT draft for a month ago - $date = strtotime( '-1 month', time() ); + $date = strtotime( '-1 month' ); $cur_day = date( 'Y', $date ) . '-' . date( 'm', $date ) . '-' . date( 'd', $date ) . ' 00:00:00'; $this->create_dummy_post( $cur_day, 'draft', self::TEST_CPT ); @@ -80,7 +80,7 @@ function setup(): void { /** * Remove the sample posts and the sitemap posts */ - function teardown(): void { + public function teardown(): void { $this->posts = array(); $sitemaps = get_posts( array( 'post_type' => Metro_Sitemap::SITEMAP_CPT, @@ -94,7 +94,8 @@ function teardown(): void { /** * Verify Custom Post Types don't have Sitemaps generated by default */ - function test_cpt_ignored_by_default() { + public function test_cpt_ignored_by_default(): void + { $this->build_sitemaps(); $sitemaps = get_posts( array( @@ -111,7 +112,8 @@ function test_cpt_ignored_by_default() { * Verify Custom Post Types included when "msm_sitemap_entry_post_type" * filter applied */ - function test_cpt_included_by_filter() { + public function test_cpt_included_by_filter(): void + { add_filter( 'msm_sitemap_entry_post_type', array( $this, 'add_cpt_to_msm_sitemap' ) ); @@ -130,9 +132,11 @@ function test_cpt_included_by_filter() { * Filter hook to add TEST_CPT to Metro_Sitemap supported post types * * @param array $cpts Array of Post Types. - * @return array(str) Array of Post Types. + * + * @return array Array of Post Types. */ - public function add_cpt_to_msm_sitemap( $cpts ) { + public function add_cpt_to_msm_sitemap( array $cpts ): array + { $cpts[] = self::TEST_CPT; return $cpts; } diff --git a/tests/CreationTest.php b/tests/CreationTest.php index 7416ad4e..192a3617 100644 --- a/tests/CreationTest.php +++ b/tests/CreationTest.php @@ -9,6 +9,7 @@ use Metro_Sitemap; use MSM_Sitemap_Builder_Cron; +use WP_Post; /** * Unit Tests to confirm Sitemaps are generated. @@ -23,12 +24,12 @@ class CreationTest extends TestCase { * * @var Integer */ - private $num_days = 4; + private int $num_days = 4; /** * Generate posts and build the sitemap */ - function setup(): void { + public function setup(): void { // Create posts for the last num_days days. $dates = array(); $date = time(); @@ -45,7 +46,7 @@ function setup(): void { /** * Remove the sample posts and the sitemap posts */ - function teardown(): void { + public function teardown(): void { $this->posts = array(); $sitemaps = get_posts( array( 'post_type' => Metro_Sitemap::SITEMAP_CPT, @@ -60,7 +61,8 @@ function teardown(): void { /** * Validate the XML stored in the database after sitemap generation */ - function test_sitemap_posts_were_created() { + public function test_sitemap_posts_were_created(): void + { global $post; $sitemaps = get_posts( array( @@ -96,7 +98,8 @@ function test_sitemap_posts_were_created() { /** * Validate that get_sitemap_post_id function returns the expected Sitemap */ - function test_get_sitemap_post_id() { + public function test_get_sitemap_post_id(): void + { // Get yesterday's sitemap post. $date = strtotime( '-1 day' ); @@ -108,7 +111,7 @@ function test_get_sitemap_post_id() { $sitemap_post_id = Metro_Sitemap::get_sitemap_post_id( $sitemap_year, $sitemap_month, $sitemap_day ); $sitemap_post = get_post( $sitemap_post_id ); - $this->assertTrue( is_a( $sitemap_post, 'WP_Post' ), 'get_sitemap_post_id returned non-WP_Post value' ); + $this->assertInstanceOf( WP_Post::class, $sitemap_post, 'get_sitemap_post_id returned non-WP_Post value' ); $this->assertEquals( $sitemap_ymd, $sitemap_post->post_title ); } @@ -117,7 +120,8 @@ function test_get_sitemap_post_id() { * Validate that Metro Sitemap CPTs are deleted when all posts are removed * for a date */ - function test_delete_empty_sitemap() { + public function test_delete_empty_sitemap(): void + { global $wpdb; list( $sitemap ) = get_posts( array( diff --git a/tests/CronTest.php b/tests/CronTest.php index 5e74711f..ca485c8f 100644 --- a/tests/CronTest.php +++ b/tests/CronTest.php @@ -22,14 +22,14 @@ class CronTest extends TestCase { * * @var Integer */ - private $num_years_data = 2; + private int $num_years_data = 2; /** * Generate posts and build the sitemap */ - function setup(): void { + public function setup(): void { if ( ! class_exists( 'MSM_Sitemap_Builder_Cron' ) ) { - require dirname( dirname( __FILE__ ) ) . '/includes/msm-sitemap-builder-cron.php'; + require dirname( __FILE__, 2 ) . '/includes/msm-sitemap-builder-cron.php'; MSM_Sitemap_Builder_Cron::setup(); } @@ -49,7 +49,7 @@ function setup(): void { /** * Remove the sample posts and the sitemap posts */ - function teardown(): void { + public function teardown(): void { $this->posts = array(); $sitemaps = get_posts( array( 'post_type' => Metro_Sitemap::SITEMAP_CPT, @@ -63,7 +63,8 @@ function teardown(): void { /** * Validate that Cron Jobs are scheduled as expected. */ - function test_cron_jobs_scheduling() { + public function test_cron_jobs_scheduling(): void + { // Reset Cron SitemapBuilder. MSM_Sitemap_Builder_Cron::reset_sitemap_data(); @@ -71,8 +72,6 @@ function test_cron_jobs_scheduling() { MSM_Sitemap_Builder_Cron::generate_full_sitemap(); update_option( 'msm_sitemap_create_in_progress', true ); - $days_being_processed = (array) get_option( 'msm_days_to_process', array() ); - $months_being_processed = (array) get_option( 'msm_months_to_process', array() ); $years_being_processed = (array) get_option( 'msm_years_to_process', array() ); // Validate initial Options is set to years for Posts. @@ -87,19 +86,16 @@ function test_cron_jobs_scheduling() { // fake_cron. $this->fake_cron(); - $days_being_processed = (array) get_option( 'msm_days_to_process', array() ); $months_being_processed = (array) get_option( 'msm_months_to_process', array() ); - $years_being_processed = (array) get_option( 'msm_years_to_process', array() ); // Validate Current Month is added to months_to_process. - $month = (int) date( 'n', time() ); + $month = (int) date( 'n' ); $this->assertContains( $month, $months_being_processed, 'Initial Year Processing should use Current Month if same year' ); // fake_cron. $this->fake_cron(); $days_being_processed = (array) get_option( 'msm_days_to_process', array() ); - $months_being_processed = (array) get_option( 'msm_months_to_process', array() ); $years_being_processed = (array) get_option( 'msm_years_to_process', array() ); $expected_days = range( 1, date( 'j' ) ); @@ -114,8 +110,6 @@ function test_cron_jobs_scheduling() { } // Check New Year. - $days_being_processed = (array) get_option( 'msm_days_to_process', array() ); - $months_being_processed = (array) get_option( 'msm_months_to_process', array() ); $years_being_processed = (array) get_option( 'msm_years_to_process', array() ); // Validate initial Options is set to years for Posts. @@ -129,9 +123,7 @@ function test_cron_jobs_scheduling() { // fake_cron. $this->fake_cron(); - $days_being_processed = (array) get_option( 'msm_days_to_process', array() ); $months_being_processed = (array) get_option( 'msm_months_to_process', array() ); - $years_being_processed = (array) get_option( 'msm_years_to_process', array() ); // Validate Current Month is added to months_to_process. $month = 12; @@ -141,8 +133,6 @@ function test_cron_jobs_scheduling() { $this->fake_cron(); $days_being_processed = (array) get_option( 'msm_days_to_process', array() ); - $months_being_processed = (array) get_option( 'msm_months_to_process', array() ); - $years_being_processed = (array) get_option( 'msm_years_to_process', array() ); $this->assertGreaterThanOrEqual( 27, count( $days_being_processed ), 'New Month Processing should star at end of Month' ); diff --git a/tests/FiltersTest.php b/tests/FiltersTest.php index fa3adc4e..d809ebaa 100644 --- a/tests/FiltersTest.php +++ b/tests/FiltersTest.php @@ -20,10 +20,11 @@ class FiltersTest extends TestCase { /** * Verify that request for sitemap url doesn't cause Main Query to hit db. */ - function test_bypass_main_query() { + public function test_bypass_main_query(): void + { global $wp_query; - // Verify post_pre_query on sitemap queryvar returns empty array + // Verify post_pre_query on sitemap query_var returns empty array set_query_var( 'sitemap', 'true' ); $posts = apply_filters_ref_array( 'posts_pre_query', array( null, $wp_query ) ); $this->assertIsArray( $posts ); @@ -34,7 +35,8 @@ function test_bypass_main_query() { /** * Verify that secondary query is not get modified if sitemap var is set. */ - function test_secondary_query_not_bypassed() { + public function test_secondary_query_not_bypassed(): void + { // Verify post_pre_query filter returns null by default $exp_result = array(1); @@ -51,7 +53,8 @@ function test_secondary_query_not_bypassed() { /** * Verify that msm_sitemap_index filter runs when build_root_sitemap_xml is called. */ - function test_msm_sitemap_index_filter_ran() { + public function test_msm_sitemap_index_filter_ran(): void + { $ran = false; add_filter( 'msm_sitemap_index', function() use ( &$ran ) { $ran = true; return []; } ); diff --git a/tests/FunctionsTest.php b/tests/FunctionsTest.php index 7b9b7514..7725ab81 100644 --- a/tests/FunctionsTest.php +++ b/tests/FunctionsTest.php @@ -18,7 +18,7 @@ class FunctionsTest extends TestCase { /** * Remove the sample posts and the sitemap posts */ - function teardown(): void { + public function teardown(): void { $this->posts = array(); $sitemaps = get_posts( array( 'post_type' => Metro_Sitemap::SITEMAP_CPT, @@ -32,7 +32,8 @@ function teardown(): void { /** * custom post_status setup */ - public function customPostStatusSetUp() { + public function customPostStatusSetUp(): void + { // register new post status. register_post_status( 'live', array( 'public' => true, @@ -46,16 +47,18 @@ public function customPostStatusSetUp() { /** * custom post_status teardown */ - public function customPostStatusTearDown() { + public function customPostStatusTearDown(): void + { remove_filter( 'msm_sitemap_post_status', array( $this, 'add_post_status_to_msm_sitemap' ) ); } /** - * Data Provider prividing map of recent variable and expected url count. + * Data provider providing map of recent variable and expected URL count. * - * @return array(int,int) Array of Test parameters. + * @return array> Array of Test parameters. */ - public function recentSitemapURLCountDataProvider() { + public function recentSitemapURLCountDataProvider(): array + { return array( array( 1,2 ), array( 7,8 ), @@ -67,12 +70,14 @@ public function recentSitemapURLCountDataProvider() { * Verify get_recent_sitemap_url_counts returns correct count * * @dataProvider recentSitemapURLCountDataProvider + * * @param int $n Days. - * @param in $expected_count Expected Urls to be counted. + * @param int $expected_count Expected Urls to be counted. */ - function test_get_recent_sitemap_url_counts( $n, $expected_count ) { + public function test_get_recent_sitemap_url_counts( int $n, int $expected_count ): void + { - // Create Multiple Posts acorss various Dates. + // Create Multiple Posts across various Dates. $date = time(); // 3 for Today, 1 in "draft" status $cur_day = date( 'Y', $date ) . '-' . date( 'm', $date ) . '-' . date( 'd', $date ) . ' 00:00:00'; @@ -97,13 +102,10 @@ function test_get_recent_sitemap_url_counts( $n, $expected_count ) { $this->build_sitemaps(); $stats = Metro_Sitemap::get_recent_sitemap_url_counts( $n ); - $tot_count = 0; - // Check counts for each date. - foreach ( $stats as $date => $count ) { - $tot_count += $count; - } + $tot_count = array_sum( $stats ); + // Verify Stat returned for each day in n. - $this->assertEquals( $n, count( $stats ) ); + $this->assertCount($n, $stats); // Verify total Stats are per post count. $this->assertEquals( $expected_count, $tot_count ); } @@ -111,14 +113,15 @@ function test_get_recent_sitemap_url_counts( $n, $expected_count ) { /** * Data Provider for post year ranges * - * @return array(int,int) Array of Test parameters. + * @return array> Array of Test parameters. */ - public function postYearRangeDataProvider() { + public function postYearRangeDataProvider(): array + { return array( - array( 'none',0 ), - array( 0,1 ), - array( 1,2 ), - array( 10,11 ), + array( 'none', 0 ), + array( 0, 1 ), + array( 1, 2 ), + array( 10, 11 ), ); } @@ -126,42 +129,46 @@ public function postYearRangeDataProvider() { * Verify get_post_year_range returns proper year ranges * * @dataProvider postYearRangeDataProvider - * @param int @years # of Years. - * @param int @range_values # of years in range. + * + * @param mixed $years Number of Years or "none". + * @param int $range_values # of years in range. */ - function test_get_post_year_range( $years, $range_values ) { + public function test_get_post_year_range( $years, int $range_values ): void + { // Add a post for each day in the last x years. if ( 'none' !== $years ) { - $date = strtotime( "-$years year", time() ); + $date = strtotime("-$years year"); $cur_day = date( 'Y', $date ) . '-' . date( 'm', $date ) . '-' . date( 'd', $date ) . ' 00:00:00'; $this->create_dummy_post( $cur_day ); } $year_range = Metro_Sitemap::get_post_year_range(); - $this->assertEquals( $range_values, count( $year_range ) ); + $this->assertCount($range_values, $year_range); } /** * Verify get_post_year_range returns proper year ranges with custom status hook * * @dataProvider postYearRangeDataProvider - * @param int $years Number of years. + * + * @param mixed $years Number of years of "none". * @param int $range_values Number of years in range. */ - function test_get_post_year_range_custom_status_posts( $years, $range_values ) { + public function test_get_post_year_range_custom_status_posts( $years, int $range_values ): void + { // set msm_sitemap_post_status filter to custom_status. $this->customPostStatusSetUp(); // Add a post for each day in the last x years. if ( 'none' !== $years ) { - $date = strtotime( "-$years year", time() ); + $date = strtotime("-$years year"); $cur_day = date( 'Y', $date ) . '-' . date( 'm', $date ) . '-' . date( 'd', $date ) . ' 00:00:00'; $this->create_dummy_post( $cur_day, 'live' ); } $year_range = Metro_Sitemap::get_post_year_range(); - $this->assertEquals( $range_values, count( $year_range ) ); + $this->assertCount($range_values, $year_range); // remove filter. $this->customPostStatusTearDown(); @@ -170,9 +177,10 @@ function test_get_post_year_range_custom_status_posts( $years, $range_values ) { /** * Verify check_year_has_posts returns only years with posts */ - function test_check_year_has_posts() { + public function test_check_year_has_posts(): void + { // Add a post for last year and 5 years ago. - $date = strtotime( '-1 year', time() ); + $date = strtotime('-1 year'); $cur_day = date( 'Y', $date ) . '-' . date( 'm', $date ) . '-' . date( 'd', $date ) . ' 00:00:00'; $prev_year = (int) date( 'Y', $date ); $this->create_dummy_post( $cur_day ); @@ -186,16 +194,17 @@ function test_check_year_has_posts() { $range_with_posts = Metro_Sitemap::check_year_has_posts(); $this->assertContains( $prev_year, $range_with_posts ); $this->assertContains( $prev5_year, $range_with_posts ); - $this->assertEquals( 2, count( $range_with_posts ) ); + $this->assertCount(2, $range_with_posts); } /** * Data Provider for get_date_stamp * - * @return array(int,int, int, string) Array of Test parameters. + * @return array> Array of Test parameters. */ - public function dateStampDataProvider() { + public function dateStampDataProvider(): array + { return array( array( 2016, 1, 7, '2016-01-07' ), array( 2010, 8, 22, '2010-08-22' ), @@ -208,12 +217,14 @@ public function dateStampDataProvider() { * Verify get_date_stamp returns proper formatted date string * * @dataProvider dateStampDataProvider + * * @param int $year Year. * @param int $month Month. * @param int $day Day. - * @param str $expected_string Expected DateStamp. + * @param string $expected_string Expected DateStamp. */ - function test_get_date_stamp( $year, $month, $day, $expected_string ) { + public function test_get_date_stamp( int $year, int $month, int $day, string $expected_string ): void + { $this->assertEquals( $expected_string, Metro_Sitemap::get_date_stamp( $year, $month, $day ) ); } @@ -221,9 +232,10 @@ function test_get_date_stamp( $year, $month, $day, $expected_string ) { /** * Data Provider for date_range_has_posts * - * @return array( str, str, boolean ) Array of Test parameters. + * @return array> Array of Test parameters. */ - public function dateRangeHasPostsDataProvider() { + public function dateRangeHasPostsDataProvider(): array + { return array( array( '2016-11-01', '2016-12-15', false ), array( '2016-10-01', '2016-10-15', false ), @@ -237,9 +249,10 @@ public function dateRangeHasPostsDataProvider() { /** * Data Provider for date_range_has_posts * - * @return array( str, str, boolean ) Array of Test parameters. + * @return array> Array of Test parameters. */ - public function dateRangeHasPostsCustomStatusDataProvider() { + public function dateRangeHasPostsCustomStatusDataProvider(): array + { return array( array( '2016-11-01', '2016-12-15', false ), array( '2014-12-28', '2016-05-04', true ), @@ -250,11 +263,13 @@ public function dateRangeHasPostsCustomStatusDataProvider() { * Verify date_range_has_posts returns expected value * * @dataProvider dateRangeHasPostsDataProvider - * @param Str $start_date Start Date of Range in Y-M-D format. - * @param Str $end_date End Date of Range in Y-M-D format. + * + * @param string $start_date Start Date of Range in Y-M-D format. + * @param string $end_date End Date of Range in Y-M-D format. * @param boolean $has_post Does Range have Post. */ - function test_date_range_has_posts( $start_date, $end_date, $has_post ) { + public function test_date_range_has_posts( string $start_date, string $end_date, bool $has_post ): void + { // 1 for 2016-10-12 in "draft" status. $this->create_dummy_post( '2016-10-12 00:00:00', 'draft' ); @@ -278,11 +293,13 @@ function test_date_range_has_posts( $start_date, $end_date, $has_post ) { * Verify date_range_has_posts returns expected value with custom status hook * * @dataProvider dateRangeHasPostsCustomStatusDataProvider - * @param string $start_date Start Date of Range in Y-M-D format. - * @param string $end_date End Date of Range in Y-M-D format. + * + * @param string $start_date Start Date of Range in Y-M-D format. + * @param string $end_date End Date of Range in Y-M-D format. * @param boolean $has_post Does Range have Post. */ - function test_date_range_has_posts_custom_status( $start_date, $end_date, $has_post ) { + public function test_date_range_has_posts_custom_status( string $start_date, string $end_date, bool $has_post ): void + { // set msm_sitemap_post_status filter to custom_status. $this->customPostStatusSetUp(); @@ -310,9 +327,10 @@ function test_date_range_has_posts_custom_status( $start_date, $end_date, $has_p /** * Data Provider for get_post_ids_for_date * - * @return array( str, int, int ) Array of Test parameters. + * @return array> Array of Test parameters. */ - public function postIdsForDateDataProvider() { + public function postIdsForDateDataProvider(): array + { return array( array( '2016-10-01', 500, 0 ), array( '2016-10-02', 500, 20 ), @@ -325,11 +343,13 @@ public function postIdsForDateDataProvider() { * Verify get_post_ids_for_date returns expected value * * @dataProvider postIdsForDateDataProvider - * @param str $sitemap_date Date in Y-M-D format. - * @param str $limit max number of posts to return. + * + * @param string $sitemap_date Date in Y-M-D format. + * @param int $limit max number of posts to return. * @param int $expected_count Number of posts expected to be returned. */ - function test_get_post_ids_for_date( $sitemap_date, $limit, $expected_count ) { + public function test_get_post_ids_for_date( string $sitemap_date, int $limit, int $expected_count ): void + { // 1 for 2016-10-03 in "draft" status. $this->create_dummy_post( '2016-10-01 00:00:00', 'draft' ); @@ -345,7 +365,7 @@ function test_get_post_ids_for_date( $sitemap_date, $limit, $expected_count ) { $post_ids = Metro_Sitemap::get_post_ids_for_date( $sitemap_date, $limit ); - $this->assertEquals( $expected_count, count( $post_ids ) ); + $this->assertCount($expected_count, $post_ids); $this->assertEquals( array_slice( $created_post_ids, 0, $limit ), $post_ids ); } @@ -354,11 +374,13 @@ function test_get_post_ids_for_date( $sitemap_date, $limit, $expected_count ) { * Verify get_post_ids_for_date returns expected value with custom status hook * * @dataProvider postIdsForDateDataProvider - * @param string $sitemap_date Date in Y-M-D format. - * @param string $limit Max number of posts to return. - * @param int $expected_count Number of posts expected to be returned. + * + * @param string $sitemap_date Date in Y-M-D format. + * @param int $limit Max number of posts to return. + * @param int $expected_count Number of posts expected to be returned. */ - function test_get_post_ids_for_date_custom_status( $sitemap_date, $limit, $expected_count ) { + public function test_get_post_ids_for_date_custom_status( string $sitemap_date, int $limit, int $expected_count ): void + { // set msm_sitemap_post_status filter to custom_status. $this->customPostStatusSetUp(); @@ -377,7 +399,7 @@ function test_get_post_ids_for_date_custom_status( $sitemap_date, $limit, $expec $post_ids = Metro_Sitemap::get_post_ids_for_date( $sitemap_date, $limit ); - $this->assertEquals( $expected_count, count( $post_ids ) ); + $this->assertCount($expected_count, $post_ids); $this->assertEquals( array_slice( $created_post_ids, 0, $limit ), $post_ids ); $this->customPostStatusTearDown(); @@ -386,7 +408,8 @@ function test_get_post_ids_for_date_custom_status( $sitemap_date, $limit, $expec /** * Verify msm_sitemap_post_status filter returns expected value */ - function test_get_post_status() { + public function test_get_post_status(): void + { // set msm_sitemap_post_status filter to custom_status. $this->customPostStatusSetUp(); @@ -399,7 +422,7 @@ function test_get_post_status() { $this->assertEquals( 'publish', Metro_Sitemap::get_post_status() ); // remove filter. - remove_filter( 'msm_sitemap_post_status', function() { + remove_filter( 'msm_sitemap_post_status', static function() { return 'bad_status'; } ); @@ -407,11 +430,13 @@ function test_get_post_status() { } - function add_post_status_to_msm_sitemap( $post_status ) { + public function add_post_status_to_msm_sitemap(): string + { return 'live'; } - function test_get_last_modified_posts_filter_no_change() { + public function test_get_last_modified_posts_filter_no_change(): void + { $posts_before = Metro_Sitemap::get_last_modified_posts(); $tag = 'msm_pre_get_last_modified_posts'; @@ -423,18 +448,18 @@ function test_get_last_modified_posts_filter_no_change() { $posts_after = Metro_Sitemap::get_last_modified_posts(); remove_filter( $tag, $function ); - $this->assertEquals( count( $posts_before ), count( $posts_after ) ); + $this->assertCount(count($posts_before), $posts_after); } - function test_get_last_modified_posts_filter_change_query() { + public function test_get_last_modified_posts_filter_change_query(): void + { $posts_before = Metro_Sitemap::get_last_modified_posts(); $tag = 'msm_pre_get_last_modified_posts'; // Modify query to fetch posts created in the last 3 months. - $function = function ( $query, $post_types_in, $date ) { + $function = static function ($query, $post_types_in, $date ) { global $wpdb; - $query = $wpdb->prepare( "SELECT ID, post_date FROM $wpdb->posts WHERE post_type IN ( {$post_types_in} ) AND post_date >= DATE_SUB(NOW(), INTERVAL 3 MONTH) AND post_modified_gmt >= %s LIMIT 1000", $date ); - return $query; + return $wpdb->prepare( "SELECT ID, post_date FROM $wpdb->posts WHERE post_type IN ( {$post_types_in} ) AND post_date >= DATE_SUB(NOW(), INTERVAL 3 MONTH) AND post_modified_gmt >= %s LIMIT 1000", $date ); }; add_filter( $tag, $function, 10, 3 ); @@ -443,7 +468,7 @@ function test_get_last_modified_posts_filter_change_query() { // Modify query as string to fetch only 10 posts. $limit = 10; - $function = function ( $query ) use ( $limit ) { + $function = static function ($query ) use ( $limit ) { return str_replace( 'LIMIT 1000', "LIMIT $limit", $query ); }; diff --git a/tests/IndexesTest.php b/tests/IndexesTest.php index 75d5a396..a2fcc563 100644 --- a/tests/IndexesTest.php +++ b/tests/IndexesTest.php @@ -21,14 +21,12 @@ class IndexesTest extends TestCase { * * @var int */ - private $num_years_data = 3; + private int $num_years_data = 3; /** * Generate posts and build initial sitemaps */ - function setup(): void { - _delete_all_posts(); - + public function setup(): void { // Add a post for each day in the last x years. $dates = array(); $date = time(); @@ -47,7 +45,7 @@ function setup(): void { /** * Remove created posts, sitemaps and options */ - function teardown(): void { + public function teardown(): void { $this->posts = array(); $sitemaps = get_posts( array( 'post_type' => Metro_Sitemap::SITEMAP_CPT, @@ -61,7 +59,8 @@ function teardown(): void { /** * Test that robots.txt has a single sitemap index when sitemaps by year are disabled */ - function test_single_sitemap_index() { + public function test_single_sitemap_index(): void + { // Turn on indexing by year Metro_Sitemap::$index_by_year = false; @@ -71,23 +70,24 @@ function test_single_sitemap_index() { preg_match_all( '|sitemap\.xml|', apply_filters( 'robots_txt', '', true ), $matches ); // Check that we've indexed the proper total number of URLs. - $this->assertEquals( 1, count( $matches[0] ) ); + $this->assertCount(1, $matches[0]); } /** * Test that robots.txt has sitemap indexes for all years when sitemaps by year are enabled */ - function test_sitemap_index_by_year() { + public function test_sitemap_index_by_year(): void + { // Turn on indexing by year Metro_Sitemap::$index_by_year = true; // Check that we have a single instance of sitemap.xml in robots.txt // We can't actually use the core function since it outputs headers, // but we only care about our stuff output to a public blog. - preg_match_all( '|sitemap-([0-9]{4})\.xml|', apply_filters( 'robots_txt', '', true ), $matches ); + preg_match_all( '|sitemap-(\d{4})\.xml|', apply_filters( 'robots_txt', '', true ), $matches ); // Check that we've indexed the proper total number of URLs. - $this->assertEquals( 3, count( $matches[0] ) ); + $this->assertCount(3, $matches[0]); } } diff --git a/tests/StatsTest.php b/tests/StatsTest.php index eda7ae3e..b505ad66 100644 --- a/tests/StatsTest.php +++ b/tests/StatsTest.php @@ -10,7 +10,7 @@ use Metro_Sitemap; /** - * Unit Tests to validate stats are propelry generated by Metro_Sitemap + * Unit Tests to validate stats are properly generated by Metro_Sitemap * * @author michaelblouin * @author Matthew Denton (mdbitz) @@ -22,14 +22,12 @@ class StatsTest extends TestCase { * * @var Integer */ - private $num_years_data = 3; + private int $num_years_data = 3; /** * Generate posts and build initial sitemaps */ - function setup(): void { - _delete_all_posts(); - + public function setup(): void { // Add a post for each day in the last x years. $dates = array(); $date = time(); @@ -48,7 +46,7 @@ function setup(): void { /** * Remove created posts, Sitemaps and options */ - function teardown(): void { + public function teardown(): void { $this->posts = array(); $sitemaps = get_posts( array( 'post_type' => Metro_Sitemap::SITEMAP_CPT, @@ -62,7 +60,8 @@ function teardown(): void { /** * Verify that indexed URL count is calculated correctly */ - function test_site_stats_creation() { + public function test_site_stats_creation(): void + { // Check that we've indexed the proper total number of URLs. $this->assertEquals( $this->num_years_data, Metro_Sitemap::get_total_indexed_url_count() ); @@ -74,7 +73,8 @@ function test_site_stats_creation() { * Checks that site stats are correct after inserting a new post on a day * that already has a sitemap. */ - function test_site_stats_for_new_post() { + public function test_site_stats_for_new_post(): void + { $today_str = date( 'Y-m-d' ); // Insert a new post for today. @@ -93,18 +93,21 @@ function test_site_stats_for_new_post() { /** * Validate that Indexed URL Count is updated properly as posts are removed */ - function test_site_stats_for_deleted_post() { + public function test_site_stats_for_deleted_post(): void + { // Delete all posts (going backwards in time). $post_count = count( $this->posts ); while ( $post_count ) { $last_post = array_pop( $this->posts ); $post = wp_delete_post( $last_post['ID'], true ); - $post_count -= 1; + --$post_count; - $this->update_sitemap_by_post( $post ); - $this->assertEquals( $post_count, Metro_Sitemap::get_total_indexed_url_count() ); - $this->assertTrue( $this->check_stats_for_created_posts() ); + if ( $post instanceof \WP_Post ) { + $this->update_sitemap_by_post( $post ); + $this->assertEquals( $post_count, Metro_Sitemap::get_total_indexed_url_count() ); + $this->assertTrue( $this->check_stats_for_created_posts() ); + } } $this->assertEquals( 0, Metro_Sitemap::count_sitemaps() ); diff --git a/tests/TestCase.php b/tests/TestCase.php index 5721a23e..e6b30531 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -7,6 +7,12 @@ namespace Automattic\MSM_Sitemap\Tests; +use DateTime; +use Exception; +use Metro_Sitemap; +use MSM_Sitemap_Builder_Cron; +use WP_Post; + /** * A base class for MSM SiteMap Tests that exposes a few handy functions for test cases. * @@ -18,14 +24,14 @@ class TestCase extends \Yoast\WPTestUtils\WPIntegration\TestCase { /** * Array of Posts Created for Test * - * @var type array + * @var array $posts */ public $posts = array(); /** * Array of Created Post IDs * - * @var type array + * @var array $posts_created */ public $posts_created = array(); @@ -34,27 +40,28 @@ class TestCase extends \Yoast\WPTestUtils\WPIntegration\TestCase { * * Does not trigger building of sitemaps. * - * @param str $day The day to create posts on. - * @param str $post_type The Post Type Slug. - * @param str @post_status The status of the created post. - * @throws Exception Unable to insert posts. + * @param string $day The day to create posts on. + * @param string $post_status + * @param string $post_type The Post Type Slug. * * @return int ID of created post. + * @throws Exception Unable to insert posts. */ - function create_dummy_post( $day, $post_status = 'publish', $post_type = 'post' ) { + public function create_dummy_post( string $day, string $post_status = 'publish', string $post_type = 'post' ): int + { $post_data = array( - 'post_title' => (string) uniqid(), + 'post_title' => uniqid( '', true ), 'post_type' => $post_type, - 'post_content' => (string) uniqid(), + 'post_content' => uniqid( '', true ), 'post_status' => $post_status, 'post_author' => 1, ); - $post_data['post_date'] = $post_data['post_modified'] = date_format( new \DateTime( $day ), 'Y-m-d H:i:s' ); + $post_data['post_date'] = $post_data['post_modified'] = date_format( new DateTime( $day ), 'Y-m-d H:i:s' ); $post_data['ID'] = wp_insert_post( $post_data, true ); if ( is_wp_error( $post_data['ID'] ) || 0 === $post_data['ID'] ) { - throw new \Exception( "Error: WP Error encountered inserting post. {$post_data['ID']->errors}, {$post_data['ID']->error_data}" ); + throw new Exception( "Error: WP Error encountered inserting post. {$post_data['ID']->errors}, {$post_data['ID']->error_data}" ); } $this->posts_created[] = $post_data['ID']; @@ -68,10 +75,12 @@ function create_dummy_post( $day, $post_status = 'publish', $post_type = 'post' * * Does not trigger building of sitemaps. * - * @param array(str) $dates The days to create posts on. - * @throws \Exception Unable to insert posts. + * @param array $dates The days to create posts on. + * + * @throws Exception Unable to insert posts. */ - function create_dummy_posts( $dates ) { + public function create_dummy_posts( array $dates ): void + { foreach ( $dates as $day ) { $this->create_dummy_post( $day ); @@ -81,12 +90,13 @@ function create_dummy_posts( $dates ) { /** * Checks that the stats are correct for each individual created post */ - function check_stats_for_created_posts() { + public function check_stats_for_created_posts(): bool + { $dates = array(); // Count the number of posts for each date. foreach ( $this->posts as $post ) { - $date = date_format( new \DateTime( $post['post_date'] ), 'Y-m-d' ); + $date = date_format( new DateTime( $post['post_date'] ), 'Y-m-d' ); if ( isset( $dates[ $date ] ) ) { $dates[ $date ] ++; @@ -99,7 +109,7 @@ function check_stats_for_created_posts() { foreach ( $dates as $date => $count ) { list( $year, $month, $day ) = explode( '-', $date, 3 ); - $indexed_url_count = \Metro_Sitemap::get_indexed_url_count( $year, $month, $day ); + $indexed_url_count = Metro_Sitemap::get_indexed_url_count( $year, $month, $day ); if ( $indexed_url_count !== $count ) { echo "\nExpected url count of $indexed_url_count but had count of $count on $year-$month-$day\n"; return false; @@ -112,7 +122,8 @@ function check_stats_for_created_posts() { /** * Generate sitemaps for all Posts */ - function build_sitemaps() { + public function build_sitemaps(): void + { global $wpdb; $post_types_in = $this->get_supported_post_types_in(); $posts = $wpdb->get_results( "SELECT ID, post_date FROM $wpdb->posts WHERE post_type IN ( {$post_types_in} ) ORDER BY post_date LIMIT 1000" ); @@ -120,26 +131,22 @@ function build_sitemaps() { foreach ( $posts as $post ) { $dates[] = date( 'Y-m-d', strtotime( $post->post_date ) ); } - $udates = array_unique( $dates ); - - foreach ( $udates as $date ) { + foreach (array_unique( $dates ) as $date ) { list( $year, $month, $day ) = explode( '-', $date ); - \MSM_Sitemap_Builder_Cron::generate_sitemap_for_year_month_day( array( 'year' => $year, 'month' => $month, 'day' => $day ) ); + MSM_Sitemap_Builder_Cron::generate_sitemap_for_year_month_day( array( 'year' => $year, 'month' => $month, 'day' => $day ) ); } } /** * Duplicate of Metro_Sitemap get_supported_post_types_in * - * @global type $wpdb - * @return type + * @return string */ - function get_supported_post_types_in() { + public function get_supported_post_types_in(): string { global $wpdb; - $post_types_in = ''; - $post_types = \Metro_Sitemap::get_supported_post_types(); + $post_types = Metro_Sitemap::get_supported_post_types(); $post_types_prepared = array(); foreach ( $post_types as $post_type ) { @@ -154,27 +161,29 @@ function get_supported_post_types_in() { * * @param WP_Post $post Post. */ - function update_sitemap_by_post( $post ) { + public function update_sitemap_by_post( WP_Post $post ): void + { $date = date( 'Y-m-d', strtotime( $post->post_date ) ); list( $year, $month, $day ) = explode( '-', $date ); - \MSM_Sitemap_Builder_Cron::generate_sitemap_for_year_month_day( array( 'year' => $year, 'month' => $month, 'day' => $day ) ); + MSM_Sitemap_Builder_Cron::generate_sitemap_for_year_month_day( array( 'year' => $year, 'month' => $month, 'day' => $day ) ); } /** * Fakes a cron job * - * @param str #execute Execute the hook. + * @param string $execute Execute the hook. */ - function fake_cron($execute = 'run') { - $schedule = _get_cron_array(); - foreach ( $schedule as $timestamp => $cron ) { + public function fake_cron( string $execute = 'run' ): void + { + foreach (_get_cron_array() as $timestamp => $cron ) { foreach ( $cron as $hook => $arg_wrapper ) { - if ( substr( $hook, 0, 3 ) !== 'msm' ) { continue; // only run our own jobs. + if ( strpos( $hook, 'msm' ) !== 0 ) { + continue; // only run our own jobs. } $arg_struct = array_pop( $arg_wrapper ); $args = $arg_struct['args'][0]; wp_unschedule_event( $timestamp, $hook, $arg_struct['args'] ); - if( 'run' === $execute ) { + if ( 'run' === $execute ) { do_action( $hook, $args ); } }