From d74d152f55bb462a3e36819c24fb8c5b01b1a3ff Mon Sep 17 00:00:00 2001 From: Paul Bearne Date: Mon, 31 Aug 2026 16:33:33 -0400 Subject: [PATCH] Add unit tests for `_get_cron_lock()` function in cron API --- tests/phpunit/tests/cron/getCronLock.php | 103 +++++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 tests/phpunit/tests/cron/getCronLock.php diff --git a/tests/phpunit/tests/cron/getCronLock.php b/tests/phpunit/tests/cron/getCronLock.php new file mode 100644 index 0000000000000..020a3ba95dbd0 --- /dev/null +++ b/tests/phpunit/tests/cron/getCronLock.php @@ -0,0 +1,103 @@ +initial_ext_object_cache = wp_using_ext_object_cache(); + delete_option( '_transient_doing_cron' ); + wp_cache_delete( 'doing_cron', 'transient' ); + + $this->cron_event_timestamp = time() - 1; + wp_schedule_single_event( $this->cron_event_timestamp, __CLASS__ ); + set_transient( 'doing_cron', 'different-lock' ); + $doing_wp_cron = 'test-lock'; + require_once ABSPATH . 'wp-cron.php'; + delete_option( '_transient_doing_cron' ); + wp_cache_delete( 'doing_cron', 'transient' ); + } + + /** + * Restores the cache state and clears the cron lock after the test. + */ + public function tear_down() { + wp_unschedule_event( $this->cron_event_timestamp, __CLASS__ ); + delete_option( '_transient_doing_cron' ); + wp_cache_delete( 'doing_cron', 'transient' ); + wp_using_ext_object_cache( $this->initial_ext_object_cache ); + + parent::tear_down(); + } + + /** + * Tests that `_get_cron_lock()` returns a stored lock from either storage mechanism. + * + * @ticket 65958 + * + * @dataProvider data_get_cron_lock_returns_stored_lock + * + * @param bool $use_external_cache Whether to use the external object cache. + * @param string $expected The expected cron lock. + */ + public function test_get_cron_lock_returns_stored_lock( $use_external_cache, $expected ) { + wp_using_ext_object_cache( $use_external_cache ); + update_option( '_transient_doing_cron', 'database-lock' ); + wp_cache_set( 'doing_cron', $expected, 'transient' ); + + $this->assertSame( $expected, _get_cron_lock() ); + } + + /** + * Data provider for test_get_cron_lock_returns_stored_lock(). + * + * @return array + */ + public function data_get_cron_lock_returns_stored_lock(): array { + return array( + 'database' => array( + 'use_external_cache' => false, + 'expected' => 'database-lock', + ), + 'external cache' => array( + 'use_external_cache' => true, + 'expected' => 'external-cache-lock', + ), + ); + } + + /** + * Tests that `_get_cron_lock()` returns zero when no lock is stored. + * + * @ticket 65958 + */ + public function test_get_cron_lock_returns_zero_when_not_set() { + $this->assertSame( 0, _get_cron_lock() ); + } +}