@@ -242,4 +242,65 @@ public function test_performance_multiple_calls() {
242242 // Should complete within a reasonable time (5 seconds).
243243 $ this ->assertLessThan ( 5.0 , $ execution_time , 'Method took too long to execute multiple calls ' );
244244 }
245+
246+ /**
247+ * Test that the result is cached in a transient after the first call.
248+ */
249+ public function test_result_is_cached_in_transient () {
250+ $ domain = 'localhost ' ;
251+ $ cache_key = 'edac_loopback_ ' . md5 ( sanitize_text_field ( $ domain ) );
252+
253+ // Clear any existing transient.
254+ delete_transient ( $ cache_key );
255+
256+ // First call performs the DNS lookup and stores the result.
257+ $ result = Helpers::is_domain_loopback ( $ domain );
258+ $ this ->assertTrue ( $ result );
259+
260+ // The transient should now be set with an integer value.
261+ $ cached = get_transient ( $ cache_key );
262+ $ this ->assertNotFalse ( $ cached , 'Transient should be set after first call. ' );
263+ $ this ->assertSame ( 1 , (int ) $ cached );
264+ }
265+
266+ /**
267+ * Test that a non-loopback result is also cached correctly.
268+ */
269+ public function test_non_loopback_result_is_cached () {
270+ $ domain = '8.8.8.8 ' ;
271+ $ cache_key = 'edac_loopback_ ' . md5 ( sanitize_text_field ( $ domain ) );
272+
273+ // Clear any existing transient.
274+ delete_transient ( $ cache_key );
275+
276+ // First call performs the DNS lookup.
277+ $ result = Helpers::is_domain_loopback ( $ domain );
278+ $ this ->assertFalse ( $ result );
279+
280+ // The transient should be set with 0 (not false) so a cache miss can
281+ // be distinguished from a cached false result.
282+ $ cached = get_transient ( $ cache_key );
283+ $ this ->assertNotFalse ( $ cached , 'Transient should be set even for non-loopback domains. ' );
284+ $ this ->assertSame ( 0 , (int ) $ cached );
285+ }
286+
287+ /**
288+ * Test that a cached result is returned without re-doing the DNS lookup.
289+ */
290+ public function test_cached_result_is_returned () {
291+ $ domain = '127.0.0.1 ' ;
292+ $ cache_key = 'edac_loopback_ ' . md5 ( sanitize_text_field ( $ domain ) );
293+
294+ // Pre-seed the transient with a value opposite to the real DNS answer.
295+ // If the cache is respected, this value will be returned as-is.
296+ set_transient ( $ cache_key , 0 , HOUR_IN_SECONDS );
297+
298+ $ result = Helpers::is_domain_loopback ( $ domain );
299+
300+ // The seeded value (0 / false) should be returned from cache.
301+ $ this ->assertFalse ( $ result );
302+
303+ // Clean up.
304+ delete_transient ( $ cache_key );
305+ }
245306}
0 commit comments