|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +/** |
| 6 | + * This file is part of CodeIgniter 4 framework. |
| 7 | + * |
| 8 | + * (c) CodeIgniter Foundation <admin@codeigniter.com> |
| 9 | + * |
| 10 | + * For the full copyright and license information, please view |
| 11 | + * the LICENSE file that was distributed with this source code. |
| 12 | + */ |
| 13 | + |
| 14 | +namespace Tests\Support\Cache; |
| 15 | + |
| 16 | +use CodeIgniter\Cache\FactoriesCache\FileVarExportHandler; |
| 17 | + |
| 18 | +/** |
| 19 | + * Gives the test class its own directory for the files created |
| 20 | + * by the FileVarExportHandler. |
| 21 | + * |
| 22 | + * The handler stores its files in the shared "writable/cache" directory by |
| 23 | + * default. Since the random test execution runs the components in parallel, |
| 24 | + * one component may delete the cache file that another component is |
| 25 | + * asserting on. A dedicated directory per test class avoids that. |
| 26 | + */ |
| 27 | +trait IsolatedCacheTrait |
| 28 | +{ |
| 29 | + /** |
| 30 | + * The directory used to store the cache files of the test class. |
| 31 | + */ |
| 32 | + private static string $isolatedCachePath; |
| 33 | + |
| 34 | + public static function setUpBeforeClassIsolatedCache(): void |
| 35 | + { |
| 36 | + helper('filesystem'); |
| 37 | + |
| 38 | + self::$isolatedCachePath = WRITEPATH . 'cache_test_' . str_replace('\\', '_', static::class); |
| 39 | + |
| 40 | + // Remove the files left over by a previous run. |
| 41 | + if (is_dir(self::$isolatedCachePath)) { |
| 42 | + delete_files(self::$isolatedCachePath, true); |
| 43 | + @rmdir(self::$isolatedCachePath); |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + public static function tearDownAfterClassIsolatedCache(): void |
| 48 | + { |
| 49 | + if (! isset(self::$isolatedCachePath) || ! is_dir(self::$isolatedCachePath)) { |
| 50 | + return; |
| 51 | + } |
| 52 | + |
| 53 | + delete_files(self::$isolatedCachePath, true); |
| 54 | + @rmdir(self::$isolatedCachePath); |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * Returns a handler that stores its files in the isolated directory. |
| 59 | + */ |
| 60 | + protected function getIsolatedCacheHandler(): FileVarExportHandler |
| 61 | + { |
| 62 | + return new FileVarExportHandler(self::$isolatedCachePath); |
| 63 | + } |
| 64 | + |
| 65 | + /** |
| 66 | + * Returns the path of the isolated cache directory. |
| 67 | + */ |
| 68 | + protected static function getIsolatedCachePath(): string |
| 69 | + { |
| 70 | + return self::$isolatedCachePath; |
| 71 | + } |
| 72 | +} |
0 commit comments