diff --git a/.github/workflows/cs-lint.yml b/.github/workflows/cs-lint.yml index fbed4369f..71e67087c 100644 --- a/.github/workflows/cs-lint.yml +++ b/.github/workflows/cs-lint.yml @@ -22,7 +22,7 @@ jobs: - name: Setup PHP uses: shivammathur/setup-php@v2 with: - php-version: "7.4" + php-version: "8.3" coverage: none tools: cs2pr @@ -37,7 +37,7 @@ jobs: uses: korelstar/xmllint-problem-matcher@v1 - name: Checkout code - uses: actions/checkout@v3 + uses: actions/checkout@v4 # Validate the composer.json file. # @link https://getcomposer.org/doc/03-cli.md#validate @@ -49,7 +49,7 @@ jobs: - name: Install PHP Dependencies with Composer uses: ramsey/composer-install@2.2.0 # Lint PHP. - + - name: Lint PHP against parse errors run: composer lint-ci | cs2pr diff --git a/.github/workflows/integrations.yml b/.github/workflows/integrations.yml index 8f5577e38..61e45b549 100644 --- a/.github/workflows/integrations.yml +++ b/.github/workflows/integrations.yml @@ -13,33 +13,36 @@ on: jobs: test: name: WP ${{ matrix.wordpress }} on PHP ${{ matrix.php }} - # Ubuntu-20.x includes MySQL 8.0, which causes `caching_sha2_password` issues with PHP < 7.4 - # https://www.php.net/manual/en/mysqli.requirements.php - # TODO: change to ubuntu-latest when we no longer support PHP < 7.4 - runs-on: ubuntu-18.04 + runs-on: ubuntu-latest + continue-on-error: ${{ matrix.allowed_failure }} env: WP_VERSION: ${{ matrix.wordpress }} strategy: matrix: - wordpress: ["5.5", "5.6", "5.7"] - php: ["5.6", "7.0", "7.1", "7.2", "7.3", "7.4"] + wordpress: [ '5.9', '6.4' ] + php: [ '7.4', '8.3' ] + allowed_failure: [ false ] include: - - php: "8.0" - # Ignore platform requirements, so that PHPUnit 7.5 can be installed on PHP 8.0 (and above). - composer-options: "--ignore-platform-reqs" + # Check upcoming WP. + - php: '8.3' + wordpress: 'trunk' + allowed_failure: true + # Check upcoming PHP. +# - php: '8.4' +# wordpress: 'latest' +# allowed_failure: true + - php: '8.2' extensions: pcov ini-values: pcov.directory=., "pcov.exclude=\"~(vendor|tests)~\"" coverage: pcov - exclude: - - php: "8.0" - wordpress: "5.5" + allowed_failure: false fail-fast: false steps: - name: Checkout code - uses: actions/checkout@v2 + uses: actions/checkout@v4 - name: Setup PHP ${{ matrix.php }} uses: shivammathur/setup-php@v2 @@ -52,22 +55,11 @@ jobs: - name: Setup problem matchers for PHP run: echo "::add-matcher::${{ runner.tool_cache }}/php.json" - # Setup PCOV since we're using PHPUnit < 8 which has it integrated. Requires PHP 7.1. - # Ignore platform reqs to make it install on PHP 8. - # https://github.com/krakjoe/pcov-clobber - - name: Setup PCOV - if: ${{ matrix.php == 8.0 }} - run: | - composer require pcov/clobber --ignore-platform-reqs - vendor/bin/pcov clobber - - name: Setup Problem Matchers for PHPUnit run: echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json" - name: Install Composer dependencies - uses: ramsey/composer-install@v1 - with: - composer-options: "${{ matrix.composer-options }}" + uses: ramsey/composer-install@v2 - name: Start MySQL Service run: sudo systemctl start mysql.service @@ -76,10 +68,10 @@ jobs: run: composer prepare-ci - name: Run integration tests (single site) - if: ${{ matrix.php != 8.0 }} + if: ${{ matrix.php != 8.2 }} run: composer test - name: Run integration tests (single site with code coverage) - if: ${{ matrix.php == 8.0 }} + if: ${{ matrix.php == 8.2 }} run: composer coverage-ci - name: Run integration tests (multisite) run: composer test-ms diff --git a/.gitignore b/.gitignore index 5ab6be736..76951223e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ -composer.lock -/vendor +/.phpunit.cache/ +/composer.lock +/vendor/ .vscode diff --git a/.phpcs.xml.dist b/.phpcs.xml.dist index ef092b744..e7b90d454 100644 --- a/.phpcs.xml.dist +++ b/.phpcs.xml.dist @@ -31,7 +31,7 @@ - + @@ -40,7 +40,7 @@ - + diff --git a/composer.json b/composer.json index e1f47f820..41670100c 100644 --- a/composer.json +++ b/composer.json @@ -11,7 +11,7 @@ } ], "require": { - "php": ">=5.6", + "php": ">=7.4", "composer/installers": "~1.0" }, "require-dev": { @@ -22,11 +22,16 @@ "phpunit/phpunit": "^9", "squizlabs/php_codesniffer": "^3.5", "wp-coding-standards/wpcs": "^2.3.0", - "yoast/phpunit-polyfills": "^2.0" + "yoast/wp-test-utils": "^1.2.0" + }, + "autoload-dev": { + "psr-4": { + "Automattic\\MSM_Sitemap\\Tests\\": "tests/" + } }, "scripts": { "coverage": [ - "@php ./vendor/bin/phpunit --coverage-html ./build/coverage-html" + "@php ./vendor/bin/phpunit --coverage-html ./.phpunit.cache/code-coverage-html" ], "coverage-ci": [ "@php ./vendor/bin/phpunit" @@ -47,7 +52,7 @@ "bash bin/install-wp-tests.sh wordpress_test root root localhost" ], "test": [ - "@php ./vendor/bin/phpunit --testsuite WP_Tests" + "@php ./vendor/bin/phpunit --testsuite WP_Tests --no-coverage" ], "test-ms": [ "@putenv WP_MULTISITE=1", diff --git a/msm-sitemap.php b/msm-sitemap.php index 92c527404..3b3536eaf 100644 --- a/msm-sitemap.php +++ b/msm-sitemap.php @@ -6,6 +6,7 @@ Version: 1.4.1 Stable tag: 1.4.1 License: GPLv2 +Requires PHP: 7.4 */ if ( defined( 'WP_CLI' ) && true === WP_CLI ) { @@ -67,7 +68,9 @@ public static function sitemap_15_min_cron_interval( $schedules ) { * Register endpoint for sitemap and other hooks */ public static function sitemap_init() { - define( 'WPCOM_SKIP_DEFAULT_SITEMAP', true ); + if ( ! defined( 'WPCOM_SKIP_DEFAULT_SITEMAP' ) ) { + define( 'WPCOM_SKIP_DEFAULT_SITEMAP', true ); + } self::sitemap_rewrite_init(); diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 7b37cceeb..f08906fa1 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,11 +1,30 @@ - - - - ./tests/ - - + + + + + tests + + + + + + msm-sitemap.php + templates + includes + + diff --git a/tests/test-sitemap-cpt.php b/tests/CPTTest.php similarity index 67% rename from tests/test-sitemap-cpt.php rename to tests/CPTTest.php index 1ea608ac8..d88a748b3 100644 --- a/tests/test-sitemap-cpt.php +++ b/tests/CPTTest.php @@ -5,33 +5,28 @@ * @package Metro_Sitemap/unit_tests */ -require_once( 'msm-sitemap-test.php' ); +namespace Automattic\MSM_Sitemap\Tests; + +use Metro_Sitemap; /** * Unit Tests to confirm Sitemaps are properly handled for Custom Post Types * * @author Matthew Denton (mdbitz) */ -class WP_Test_Sitemap_CPT extends WP_UnitTestCase { - - /** - * Base Test Class Instance - * - * @var MSM_SIteMap_Test - */ - private $test_base; +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( @@ -55,56 +50,54 @@ static function setupBeforeClass(): void { /** * Initialize MSM_SiteMap_Test */ - function setup(): void { - - $this->test_base = new MSM_SiteMap_Test(); - - // 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 $cur_day = date( 'Y', $date ) . '-' . date( 'm', $date ) . '-' . date( 'd', $date ) . ' 00:00:00'; - $this->test_base->create_dummy_post( $cur_day ); - $this->test_base->create_dummy_post( $cur_day ); - $this->test_base->create_dummy_post( $cur_day, 'draft' ); + $this->create_dummy_post( $cur_day ); + $this->create_dummy_post( $cur_day ); + $this->create_dummy_post( $cur_day, 'draft' ); // 1 for each day in last week for CPT for ( $i = 0; $i < 6; $i++ ) { $date = strtotime( '-1 day', $date ); $cur_day = date( 'Y', $date ) . '-' . date( 'm', $date ) . '-' . date( 'd', $date ) . ' 00:00:00'; - $this->test_base->create_dummy_post( $cur_day, 'publish', self::TEST_CPT ); + $this->create_dummy_post( $cur_day, 'publish', self::TEST_CPT ); } // 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->test_base->create_dummy_post( $cur_day, 'draft', self::TEST_CPT ); + $this->create_dummy_post( $cur_day, 'draft', self::TEST_CPT ); - $this->assertCount( 10, $this->test_base->posts ); - $this->test_base->build_sitemaps(); + $this->assertCount( 10, $this->posts ); + $this->build_sitemaps(); } /** * Remove the sample posts and the sitemap posts */ - function teardown(): void { - $this->test_base->posts = array(); + public function teardown(): void { + $this->posts = array(); $sitemaps = get_posts( array( 'post_type' => Metro_Sitemap::SITEMAP_CPT, 'fields' => 'ids', 'posts_per_page' => -1, ) ); update_option( 'msm_sitemap_indexed_url_count' , 0 ); - array_map( 'wp_delete_post', array_merge( $this->test_base->posts_created, $sitemaps ) ); + array_map( 'wp_delete_post', array_merge( $this->posts_created, $sitemaps ) ); } /** * 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->test_base->build_sitemaps(); + $this->build_sitemaps(); $sitemaps = get_posts( array( 'post_type' => Metro_Sitemap::SITEMAP_CPT, 'fields' => 'ids', @@ -119,11 +112,12 @@ 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' ) ); - $this->test_base->build_sitemaps(); + $this->build_sitemaps(); $sitemaps = get_posts( array( 'post_type' => Metro_Sitemap::SITEMAP_CPT, 'fields' => 'ids', @@ -138,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/test-sitemap-creation.php b/tests/CreationTest.php similarity index 80% rename from tests/test-sitemap-creation.php rename to tests/CreationTest.php index 3a04a67b3..192a3617f 100644 --- a/tests/test-sitemap-creation.php +++ b/tests/CreationTest.php @@ -5,7 +5,11 @@ * @package Metro_Sitemap/unit_tests */ -require_once( 'msm-sitemap-test.php' ); +namespace Automattic\MSM_Sitemap\Tests; + +use Metro_Sitemap; +use MSM_Sitemap_Builder_Cron; +use WP_Post; /** * Unit Tests to confirm Sitemaps are generated. @@ -13,29 +17,19 @@ * @author michaelblouin * @author Matthew Denton (mdbitz) */ -class WP_Test_Sitemap_Creation extends WP_UnitTestCase { +class CreationTest extends TestCase { /** * Humber of Posts to Create (1 per day) * * @var Integer */ - private $num_days = 4; - - /** - * Base Test Class Instance - * - * @var MSM_SIteMap_Test - */ - private $test_base; + private int $num_days = 4; /** * Generate posts and build the sitemap */ - function setup(): void { - - $this->test_base = new MSM_SiteMap_Test(); - + public function setup(): void { // Create posts for the last num_days days. $dates = array(); $date = time(); @@ -44,30 +38,31 @@ function setup(): void { $dates[] = date( 'Y', $date ) . '-' . date( 'm', $date ) . '-' . date( 'd', $date ); } - $this->test_base->create_dummy_posts( $dates ); - $this->assertCount( $this->num_days, $this->test_base->posts ); - $this->test_base->build_sitemaps(); + $this->create_dummy_posts( $dates ); + $this->assertCount( $this->num_days, $this->posts ); + $this->build_sitemaps(); } /** * Remove the sample posts and the sitemap posts */ - function teardown(): void { - $this->test_base->posts = array(); + public function teardown(): void { + $this->posts = array(); $sitemaps = get_posts( array( 'post_type' => Metro_Sitemap::SITEMAP_CPT, 'fields' => 'ids', 'posts_per_page' => -1, ) ); update_option( 'msm_sitemap_indexed_url_count' , 0 ); - array_map( 'wp_delete_post', array_merge( $this->test_base->posts_created, $sitemaps ) ); - $this->test_base->fake_cron( false ); + array_map( 'wp_delete_post', array_merge( $this->posts_created, $sitemaps ) ); + $this->fake_cron( false ); } /** * 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( @@ -80,7 +75,7 @@ function test_sitemap_posts_were_created() { foreach ( $sitemaps as $i => $map_id ) { $xml = get_post_meta( $map_id, 'msm_sitemap_xml', true ); - $post_id = $this->test_base->posts[ $i ]['ID']; + $post_id = $this->posts[ $i ]['ID']; $this->assertStringContainsString( 'p=' . $post_id, $xml ); $xml_struct = simplexml_load_string( $xml ); @@ -103,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' ); @@ -115,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 ); } @@ -124,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/test-sitemap--cron.php b/tests/CronTest.php similarity index 67% rename from tests/test-sitemap--cron.php rename to tests/CronTest.php index 357603eba..ca485c8f3 100644 --- a/tests/test-sitemap--cron.php +++ b/tests/CronTest.php @@ -5,40 +5,34 @@ * @package Metro_Sitemap/unit_tests */ -require_once( 'msm-sitemap-test.php' ); +namespace Automattic\MSM_Sitemap\Tests; + +use Metro_Sitemap; +use MSM_Sitemap_Builder_Cron; /** * Unit Tests to confirm Cron is populated as expected * * @author Matthew Denton (mdbitz) */ -class WP_Test_Sitemap_Cron extends WP_UnitTestCase { +class CronTest extends TestCase { /** * Humber of Posts to Create (1 per year) * * @var Integer */ - private $num_years_data = 2; - - /** - * Base Test Class Instance - * - * @var MSM_SIteMap_Test - */ - private $test_base; + 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(); } - $this->test_base = new MSM_SiteMap_Test(); - // Add a post for each day in the last x years. $dates = array(); $date = time(); @@ -48,28 +42,29 @@ function setup(): void { $date = strtotime( '-1 year', $date ); } - $this->test_base->create_dummy_posts( $dates ); - $this->assertCount( $this->num_years_data, $this->test_base->posts ); + $this->create_dummy_posts( $dates ); + $this->assertCount( $this->num_years_data, $this->posts ); } /** * Remove the sample posts and the sitemap posts */ - function teardown(): void { - $this->test_base->posts = array(); + public function teardown(): void { + $this->posts = array(); $sitemaps = get_posts( array( 'post_type' => Metro_Sitemap::SITEMAP_CPT, 'fields' => 'ids', 'posts_per_page' => -1, ) ); update_option( 'msm_sitemap_indexed_url_count' , 0 ); - array_map( 'wp_delete_post', array_merge( $this->test_base->posts_created, $sitemaps ) ); + array_map( 'wp_delete_post', array_merge( $this->posts_created, $sitemaps ) ); } /** * 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(); @@ -77,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. @@ -91,37 +84,32 @@ function test_cron_jobs_scheduling() { $this->assertSame( array_diff( $expected_years, $years_being_processed ), array_diff( $years_being_processed, $expected_years ), "Years Scheduled for Processing don't align with Posts." ); // fake_cron. - $this->test_base->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->test_base->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' ) ); - + // Validate Current Month only processes days that have passed and today. $this->assertSame( array_diff( $expected_days, $days_being_processed ), array_diff( $days_being_processed, $expected_days ), "Current Month shouldn't process days in future." ); $cur_year = date( 'Y' ); while ( in_array( $cur_year, $years_being_processed ) ) { - $this->test_base->fake_cron(); + $this->fake_cron(); $years_being_processed = (array) get_option( 'msm_years_to_process', array() ); } // 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. @@ -133,26 +121,22 @@ function test_cron_jobs_scheduling() { $this->assertSame( array_diff( $expected_years, $years_being_processed ), array_diff( $years_being_processed, $expected_years ), "Years Scheduled for Processing don't align when year finishes processing" ); // fake_cron. - $this->test_base->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; $this->assertContains( $month, $months_being_processed, 'New Year Processing should start in December' ); // fake_cron. - $this->test_base->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() ); $this->assertGreaterThanOrEqual( 27, count( $days_being_processed ), 'New Month Processing should star at end of Month' ); } - + } diff --git a/tests/test-sitemap-filter.php b/tests/FiltersTest.php similarity index 77% rename from tests/test-sitemap-filter.php rename to tests/FiltersTest.php index 0b1e99fbc..d809ebaa6 100644 --- a/tests/test-sitemap-filter.php +++ b/tests/FiltersTest.php @@ -5,50 +5,56 @@ * @package Metro_Sitemap/unit_tests */ -require_once( 'msm-sitemap-test.php' ); +namespace Automattic\MSM_Sitemap\Tests; + +use Metro_Sitemap; +use WP_Query; /** * Unit Tests to validate Filters applied when generating Sitemaps * * @author Matthew Denton (mdbitz) */ -class WP_Test_Sitemap_Filter extends WP_UnitTestCase { +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 ); $this->assertEmpty( $posts ); - + } - + /** * 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); - + $query = new WP_Query( array( 'post_type' => 'post', 'sitemap' => 'true' ) ); $sitemap_posts = apply_filters_ref_array( 'posts_pre_query', array( $exp_result, $query ) ); $this->assertEquals($exp_result, $sitemap_posts, 'Non-Main WP_Query is being modified from sitemap query var'); - + } /** * 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/test-sitemap-functions.php b/tests/FunctionsTest.php similarity index 61% rename from tests/test-sitemap-functions.php rename to tests/FunctionsTest.php index 0a69f67d1..7725ab818 100644 --- a/tests/test-sitemap-functions.php +++ b/tests/FunctionsTest.php @@ -5,47 +5,35 @@ * @package Metro_Sitemap/unit_tests */ -require_once( 'msm-sitemap-test.php' ); +namespace Automattic\MSM_Sitemap\Tests; + +use Metro_Sitemap; /** * Unit Tests to confirm Sitemaps are generated. * * @author Matthew Denton (mdbitz) */ -class WP_Test_Sitemap_Functions extends WP_UnitTestCase { - - /** - * Base Test Class Instance - * - * @var MSM_SIteMap_Test - */ - private $test_base; - - /** - * Initialize MSM_SiteMap_Test - */ - function setup(): void { - $this->test_base = new MSM_SiteMap_Test(); - } - +class FunctionsTest extends TestCase { /** * Remove the sample posts and the sitemap posts */ - function teardown(): void { - $this->test_base->posts = array(); + public function teardown(): void { + $this->posts = array(); $sitemaps = get_posts( array( 'post_type' => Metro_Sitemap::SITEMAP_CPT, 'fields' => 'ids', 'posts_per_page' => -1, ) ); update_option( 'msm_sitemap_indexed_url_count' , 0 ); - array_map( 'wp_delete_post', array_merge( $this->test_base->posts_created, $sitemaps ) ); + array_map( 'wp_delete_post', array_merge( $this->posts_created, $sitemaps ) ); } /** * custom post_status setup */ - public function customPostStatusSetUp() { + public function customPostStatusSetUp(): void + { // register new post status. register_post_status( 'live', array( 'public' => true, @@ -59,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 ), @@ -80,43 +70,42 @@ 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'; - $this->test_base->create_dummy_post( $cur_day ); - $this->test_base->create_dummy_post( $cur_day ); - $this->test_base->create_dummy_post( $cur_day, 'draft' ); + $this->create_dummy_post( $cur_day ); + $this->create_dummy_post( $cur_day ); + $this->create_dummy_post( $cur_day, 'draft' ); // 1 for each day in last week for ( $i = 0; $i < 6; $i++ ) { $date = strtotime( '-1 day', $date ); $cur_day = date( 'Y', $date ) . '-' . date( 'm', $date ) . '-' . date( 'd', $date ) . ' 00:00:00'; - $this->test_base->create_dummy_post( $cur_day ); + $this->create_dummy_post( $cur_day ); } // 1 per week for previous 3 weeks for ( $i = 0; $i < 3; $i++ ) { $date = strtotime( '-7 day', $date ); $cur_day = date( 'Y', $date ) . '-' . date( 'm', $date ) . '-' . date( 'd', $date ) . ' 00:00:00'; - $this->test_base->create_dummy_post( $cur_day ); + $this->create_dummy_post( $cur_day ); } - $this->assertCount( 12, $this->test_base->posts ); - $this->test_base->build_sitemaps(); + $this->assertCount( 12, $this->posts ); + $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 ); } @@ -124,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 ), ); } @@ -139,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->test_base->create_dummy_post( $cur_day ); + $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->test_base->create_dummy_post( $cur_day, 'live' ); + $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(); @@ -183,32 +177,34 @@ 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->test_base->create_dummy_post( $cur_day ); + $this->create_dummy_post( $cur_day ); $date = strtotime( '-4 year', $date ); $cur_day = date( 'Y', $date ) . '-' . date( 'm', $date ) . '-' . date( 'd', $date ) . ' 00:00:00'; $prev5_year = (int) date( 'Y', $date ); - $this->test_base->create_dummy_post( $cur_day ); + $this->create_dummy_post( $cur_day ); // Verify only Years for Posts are returned. $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' ), @@ -221,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 ) ); } @@ -234,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 ), @@ -250,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 ), @@ -263,20 +263,22 @@ 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->test_base->create_dummy_post( '2016-10-12 00:00:00', 'draft' ); + $this->create_dummy_post( '2016-10-12 00:00:00', 'draft' ); // 1 for 2016-01-01. - $this->test_base->create_dummy_post( '2016-01-01 00:00:00' ); + $this->create_dummy_post( '2016-01-01 00:00:00' ); // 1 for 2015-06-02. - $this->test_base->create_dummy_post( '2015-06-02 00:00:00' ); + $this->create_dummy_post( '2015-06-02 00:00:00' ); // Validate Range result. if ( $has_post ) { @@ -291,22 +293,24 @@ 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(); // 1 for 2016-10-12 in "live" status. - $this->test_base->create_dummy_post( '2015-10-12 00:00:00', 'live' ); + $this->create_dummy_post( '2015-10-12 00:00:00', 'live' ); // 1 for 2016-01-01. - $this->test_base->create_dummy_post( '2016-01-01 00:00:00' ); + $this->create_dummy_post( '2016-01-01 00:00:00' ); // // 1 for 2015-06-02. - $this->test_base->create_dummy_post( '2015-06-02 00:00:00' ); + $this->create_dummy_post( '2015-06-02 00:00:00' ); // Validate Range result. if ( $has_post ) { @@ -323,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 ), @@ -338,27 +343,29 @@ 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->test_base->create_dummy_post( '2016-10-01 00:00:00', 'draft' ); + $this->create_dummy_post( '2016-10-01 00:00:00', 'draft' ); $created_post_ids = array(); // 20 for 2016-10-02. for ( $i = 0; $i < 20; $i ++ ) { $hour = $i < 10 ? '0' . $i : $i; if ( '2016-10-02' === $sitemap_date ) { - $created_post_ids[] = $this->test_base->create_dummy_post( '2016-10-02 ' . $hour . ':00:00' ); + $created_post_ids[] = $this->create_dummy_post( '2016-10-02 ' . $hour . ':00:00' ); } } $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 ); } @@ -367,30 +374,32 @@ 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(); // 1 for 2016-10-03 in "draft" status. - $this->test_base->create_dummy_post( '2016-10-01 00:00:00', 'draft' ); + $this->create_dummy_post( '2016-10-01 00:00:00', 'draft' ); $created_post_ids = array(); // 20 for 2016-10-02. for ( $i = 0; $i < 20; $i ++ ) { $hour = $i < 10 ? '0' . $i : $i; if ( '2016-10-02' === $sitemap_date ) { - $created_post_ids[] = $this->test_base->create_dummy_post( '2016-10-02 ' . $hour . ':00:00', 'live' ); + $created_post_ids[] = $this->create_dummy_post( '2016-10-02 ' . $hour . ':00:00', 'live' ); } } $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(); @@ -399,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(); @@ -412,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'; } ); @@ -420,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'; @@ -436,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 ); @@ -456,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/test-sitemap-index.php b/tests/IndexesTest.php similarity index 67% rename from tests/test-sitemap-index.php rename to tests/IndexesTest.php index 979766dbd..a2fcc5633 100644 --- a/tests/test-sitemap-index.php +++ b/tests/IndexesTest.php @@ -5,37 +5,28 @@ * @package Metro_Sitemap/unit_tests */ -require_once( 'msm-sitemap-test.php' ); +namespace Automattic\MSM_Sitemap\Tests; + +use Metro_Sitemap; /** * Unit Tests to validate indexes are properly generated by Metro_Sitemap * * @author bcampeau */ -class WP_Test_Sitemap_Index extends WP_UnitTestCase { +class IndexesTest extends TestCase { /** * Create posts across a number of years * * @var int */ - private $num_years_data = 3; - - /** - * Base Test Class Instance - * - * @var MSM_SIteMap_Test - */ - private $test_base; + private int $num_years_data = 3; /** * Generate posts and build initial sitemaps */ - function setup(): void { - _delete_all_posts(); - - $this->test_base = new MSM_SiteMap_Test(); - + public function setup(): void { // Add a post for each day in the last x years. $dates = array(); $date = time(); @@ -45,30 +36,31 @@ function setup(): void { $date = strtotime( '-1 year', $date ); } - $this->test_base->create_dummy_posts( $dates ); + $this->create_dummy_posts( $dates ); - $this->assertCount( $this->num_years_data, $this->test_base->posts ); - $this->test_base->build_sitemaps(); + $this->assertCount( $this->num_years_data, $this->posts ); + $this->build_sitemaps(); } /** * Remove created posts, sitemaps and options */ - function teardown(): void { - $this->test_base->posts = array(); + public function teardown(): void { + $this->posts = array(); $sitemaps = get_posts( array( 'post_type' => Metro_Sitemap::SITEMAP_CPT, 'fields' => 'ids', 'posts_per_page' => -1, ) ); update_option( 'msm_sitemap_indexed_url_count' , 0 ); - array_map( 'wp_delete_post', array_merge( $this->test_base->posts_created, $sitemaps ) ); + array_map( 'wp_delete_post', array_merge( $this->posts_created, $sitemaps ) ); } /** * 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; @@ -78,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/test-sitemap-stats.php b/tests/StatsTest.php similarity index 56% rename from tests/test-sitemap-stats.php rename to tests/StatsTest.php index cf5d89a77..b505ad668 100644 --- a/tests/test-sitemap-stats.php +++ b/tests/StatsTest.php @@ -5,38 +5,29 @@ * @package Metro_Sitemap/unit_tests */ -require_once( 'msm-sitemap-test.php' ); +namespace Automattic\MSM_Sitemap\Tests; + +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) */ -class WP_Test_Sitemap_Stats extends WP_UnitTestCase { +class StatsTest extends TestCase { /** * Humber of Posts to Create (1 per year) * * @var Integer */ - private $num_years_data = 3; - - /** - * Base Test Class Instance - * - * @var MSM_SIteMap_Test - */ - private $test_base; + private int $num_years_data = 3; /** * Generate posts and build initial sitemaps */ - function setup(): void { - _delete_all_posts(); - - $this->test_base = new MSM_SiteMap_Test(); - + public function setup(): void { // Add a post for each day in the last x years. $dates = array(); $date = time(); @@ -46,72 +37,77 @@ function setup(): void { $date = strtotime( '-1 year', $date ); } - $this->test_base->create_dummy_posts( $dates ); + $this->create_dummy_posts( $dates ); - $this->assertCount( $this->num_years_data, $this->test_base->posts ); - $this->test_base->build_sitemaps(); + $this->assertCount( $this->num_years_data, $this->posts ); + $this->build_sitemaps(); } /** * Remove created posts, Sitemaps and options */ - function teardown(): void { - $this->test_base->posts = array(); + public function teardown(): void { + $this->posts = array(); $sitemaps = get_posts( array( 'post_type' => Metro_Sitemap::SITEMAP_CPT, 'fields' => 'ids', 'posts_per_page' => -1, ) ); update_option( 'msm_sitemap_indexed_url_count' , 0 ); - array_map( 'wp_delete_post', array_merge( $this->test_base->posts_created, $sitemaps ) ); + array_map( 'wp_delete_post', array_merge( $this->posts_created, $sitemaps ) ); } /** * 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() ); // Check specific stats. - $this->assertTrue( $this->test_base->check_stats_for_created_posts() ); + $this->assertTrue( $this->check_stats_for_created_posts() ); } /** * 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. - $this->test_base->create_dummy_posts( array( $today_str . ' 00:00:00' ) ); + $this->create_dummy_posts( array( $today_str . ' 00:00:00' ) ); // Build sitemaps. - $this->test_base->build_sitemaps(); + $this->build_sitemaps(); // Check stats. $this->assertEquals( $this->num_years_data + 1, Metro_Sitemap::get_total_indexed_url_count() ); // Check specific stats. - $this->assertTrue( $this->test_base->check_stats_for_created_posts() ); + $this->assertTrue( $this->check_stats_for_created_posts() ); } /** * 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->test_base->posts ); + $post_count = count( $this->posts ); while ( $post_count ) { - $last_post = array_pop( $this->test_base->posts ); + $last_post = array_pop( $this->posts ); $post = wp_delete_post( $last_post['ID'], true ); - $post_count -= 1; + --$post_count; - $this->test_base->update_sitemap_by_post( $post ); - $this->assertEquals( $post_count, Metro_Sitemap::get_total_indexed_url_count() ); - $this->assertTrue( $this->test_base->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/msm-sitemap-test.php b/tests/TestCase.php similarity index 74% rename from tests/msm-sitemap-test.php rename to tests/TestCase.php index 255ec3976..e6b30531b 100644 --- a/tests/msm-sitemap-test.php +++ b/tests/TestCase.php @@ -5,25 +5,33 @@ * @package Metro_Sitemap/unit_tests */ +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. * * @author michaelblouin * @author Matthew Denton (mdbitz) */ -class MSM_SiteMap_Test { +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(); @@ -32,18 +40,19 @@ class MSM_SiteMap_Test { * * 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, ); @@ -60,16 +69,18 @@ function create_dummy_post( $day, $post_status = 'publish', $post_type = 'post' return $post_data['ID']; } - + /** * Creates a new post for every day in $dates. * * Does not trigger building of sitemaps. * - * @param array(str) $dates The days to create posts on. + * @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 ); @@ -79,7 +90,8 @@ 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. @@ -110,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" ); @@ -118,25 +131,21 @@ 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 ) ); } } - + /** * 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_prepared = array(); @@ -152,7 +161,8 @@ 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 ) ); @@ -160,19 +170,20 @@ function update_sitemap_by_post( $post ) { /** * 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 ); } } diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 4c9d30e08..90a6bfb26 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -1,15 +1,59 @@