Passed
Push — main ( d40bf0...e9466e )
by Sílvio
03:08 queued 16s
created

FileCacheStoreTest::testAppendCacheWithNamespace()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 11
nc 1
nop 0
dl 0
loc 21
rs 9.9
c 0
b 0
f 0
1
<?php
2
3
use PHPUnit\Framework\TestCase;
4
use Silviooosilva\CacheerPhp\Cacheer;
5
use Silviooosilva\CacheerPhp\Utils\CacheDriver;
6
7
class FileCacheStoreTest extends TestCase
8
{
9
    private $cache;
10
    private $cacheDir;
11
12
    protected function setUp(): void
13
    {
14
        $this->cacheDir = __DIR__ . '/cache';
15
        if (!file_exists($this->cacheDir) || !is_dir($this->cacheDir)) {
16
            mkdir($this->cacheDir, 0755, true);
17
        }
18
19
        $options = [
20
            'cacheDir' => $this->cacheDir,
21
        ];
22
23
        $this->cache = new Cacheer($options);
24
    }
25
26
    protected function tearDown(): void
27
    {
28
        $this->cache->flushCache();
29
    }
30
31
    public function testPutCache()
32
    {
33
        $cacheKey = 'test_key';
34
        $data = 'test_data';
35
36
        $this->cache->putCache($cacheKey, $data);
37
        $this->assertTrue($this->cache->isSuccess());
38
        $this->assertEquals('Cache file created successfully', $this->cache->getMessage());
39
40
        $cacheFile = $this->cacheDir . '/' . md5($cacheKey) . '.cache';
41
        $this->assertFileExists($cacheFile);
42
        $this->assertEquals($data, $this->cache->getCache($cacheKey));
43
    }
44
45
    public function testGetCache()
46
    {
47
        $cacheKey = 'test_key';
48
        $data = 'test_data';
49
50
        $this->cache->putCache($cacheKey, $data);
51
52
        $cachedData = $this->cache->getCache($cacheKey);
53
        $this->assertTrue($this->cache->isSuccess());
54
        $this->assertEquals($data, $cachedData);
55
56
        // Recuperar cache fora do período de expiração
57
        sleep(2);
58
        $cachedData = $this->cache->getCache($cacheKey, '', '2 seconds');
0 ignored issues
show
Unused Code introduced by
The assignment to $cachedData is dead and can be removed.
Loading history...
59
        $this->assertFalse($this->cache->isSuccess());
60
        $this->assertEquals('cacheFile not found, does not exists or expired', $this->cache->getMessage());
61
    }
62
63
    public function testClearCache()
64
    {
65
        $cacheKey = 'test_key';
66
        $data = 'test_data';
67
68
        $this->cache->putCache($cacheKey, $data);
69
        $this->cache->clearCache($cacheKey);
70
71
        $this->assertTrue($this->cache->isSuccess());
72
        $this->assertEquals('Cache file deleted successfully!', $this->cache->getMessage());
73
74
        $cacheFile = $this->cacheDir . '/' . md5($cacheKey) . '.cache';
75
        $this->assertFileDoesNotExist($cacheFile);
76
    }
77
78
    public function testFlushCache()
79
    {
80
        $key1 = 'test_key1';
81
        $data1 = 'test_data1';
82
83
        $key2 = 'test_key2';
84
        $data2 = 'test_data2';
85
86
        $this->cache->putCache($key1, $data1);
87
        $this->cache->putCache($key2, $data2);
88
        $this->cache->flushCache();
89
90
        $cacheFile1 = $this->cacheDir . '/' . md5($key1) . '.cache';
91
        $cacheFile2 = $this->cacheDir . '/' . md5($key2) . '.cache';
92
93
        $this->assertFileDoesNotExist($cacheFile1);
94
        $this->assertFileDoesNotExist($cacheFile2);
95
    }
96
97
    public function testAutoFlush()
98
    {
99
        $options = [
100
            'cacheDir' => $this->cacheDir,
101
            'flushAfter' => '10 seconds'
102
        ];
103
104
        $this->cache = new Cacheer($options);
105
        $this->cache->putCache('test_key', 'test_data');
106
107
        // Verifica se o cache foi criado com sucesso
108
        $this->assertEquals('test_data', $this->cache->getCache('test_key'));
109
        $this->assertTrue($this->cache->isSuccess());
110
111
        // Espera 11 segundos para o cache ser limpo automaticamente
112
        sleep(11);
113
114
        $this->cache = new Cacheer($options);
115
116
        // Verifica se o cache foi limpo automaticamente
117
        $cachedData = $this->cache->getCache('test_key');
0 ignored issues
show
Unused Code introduced by
The assignment to $cachedData is dead and can be removed.
Loading history...
118
        $this->assertFalse($this->cache->isSuccess());
119
        $this->assertEquals('cacheFile not found, does not exists or expired', $this->cache->getMessage());
120
    }
121
122
    public function testAppendCache()
123
    {
124
        $cacheKey = 'test_append_key';
125
        $initialData = ['initial' => 'data'];
126
        $additionalData = ['new' => 'data'];
127
        $expectedData = array_merge($initialData, $additionalData);
128
129
        // Armazena os dados iniciais no cache
130
        $this->cache->putCache($cacheKey, $initialData);
131
        $this->assertTrue($this->cache->isSuccess());
132
133
        // Adiciona novos dados ao cache existente
134
        $this->cache->appendCache($cacheKey, $additionalData);
135
        $this->assertTrue($this->cache->isSuccess());
136
137
        // Verifica se os dados no cache são os esperados
138
        $cachedData = $this->cache->getCache($cacheKey);
139
        $this->assertEquals($expectedData, $cachedData);
140
141
        // Testa adicionar dados como string
142
        $additionalData = ['string_data' => 'string data'];
143
        $expectedData = array_merge($expectedData, $additionalData);
144
        $this->cache->appendCache($cacheKey, $additionalData);
145
        $cachedData = $this->cache->getCache($cacheKey);
146
        $this->assertEquals($expectedData, $cachedData);
147
    }
148
149
    public function testAppendCacheFileNotExists()
150
    {
151
        $cacheKey = 'non_existing_key';
152
        $data = ['data'];
153
154
        // Tenta adicionar dados a um arquivo de cache que não existe
155
        $this->cache->appendCache($cacheKey, $data);
156
        $this->assertFalse($this->cache->isSuccess());
157
        $this->assertEquals('cacheFile not found, does not exists or expired', $this->cache->getMessage());
158
    }
159
160
    public function testAppendCacheWithNamespace()
161
    {
162
        $cacheKey = 'test_append_key_ns';
163
        $namespace = 'test_namespace';
164
165
        $initialData = ['initial' => 'data'];
166
        $additionalData = ['new' => 'data'];
167
168
        $expectedData = array_merge($initialData, $additionalData);
169
170
        // Armazena os dados iniciais no cache com namespace
171
        $this->cache->putCache($cacheKey, $initialData, $namespace);
172
        $this->assertTrue($this->cache->isSuccess());
173
174
        // Adiciona novos dados ao cache existente com namespace
175
        $this->cache->appendCache($cacheKey, $additionalData, $namespace);
176
        $this->assertTrue($this->cache->isSuccess());
177
178
        // Verifica se os dados no cache são os esperados
179
        $cachedData = $this->cache->getCache($cacheKey, $namespace);
180
        $this->assertEquals($expectedData, $cachedData);
181
    }
182
183
    public function testDataOutputShouldBeOfTypeJson()
184
    {
185
        $options = [
186
            'cacheDir' => $this->cacheDir
187
        ];
188
        $this->cache = new Cacheer($options, true);
189
190
        $cacheKey = "key_json";
191
        $cacheData = "data_json";
192
193
        $this->cache->putCache($cacheKey, $cacheData);
194
        $this->assertTrue($this->cache->isSuccess());
195
196
        $cacheOutput = $this->cache->getCache($cacheKey)->toJson();
197
        $this->assertTrue($this->cache->isSuccess());
198
        $this->assertJson($cacheOutput);
199
    }
200
201
    public function testDataOutputShouldBeOfTypeArray()
202
    {
203
        $options = [
204
            'cacheDir' => $this->cacheDir
205
        ];
206
        $this->cache = new Cacheer($options, true);
207
208
        $cacheKey = "key_array";
209
        $cacheData = "data_array";
210
211
        $this->cache->putCache($cacheKey, $cacheData);
212
        $this->assertTrue($this->cache->isSuccess());
213
214
        $cacheOutput = $this->cache->getCache($cacheKey)->toArray();
215
        $this->assertTrue($this->cache->isSuccess());
216
        $this->assertIsArray($cacheOutput);
217
    }
218
219
    public function testDataOutputShouldBeOfTypeObject()
220
    {
221
        $options = [
222
            'cacheDir' => $this->cacheDir
223
        ];
224
        $this->cache = new Cacheer($options, true);
225
226
        $cacheKey = "key_object";
227
        $cacheData = ["id" => 123];
228
229
        $this->cache->putCache($cacheKey, $cacheData);
230
        $this->assertTrue($this->cache->isSuccess());
231
232
        $cacheOutput = $this->cache->getCache($cacheKey)->toObject();
233
        $this->assertTrue($this->cache->isSuccess());
234
        $this->assertIsObject($cacheOutput);
235
    }
236
237
    public function testPutMany()
238
    {
239
        $cacheer = new Cacheer(['cacheDir' => __DIR__ . '/cache']);
240
        $items = [
241
            [
242
                'cacheKey' => 'user_1_profile',
243
                'cacheData' => ['name' => 'John Doe', 'email' => '[email protected]']
244
            ],
245
            [
246
                'cacheKey' => 'user_2_profile',
247
                'cacheData' => ['name' => 'Jane Doe', 'email' => '[email protected]']
248
            ],
249
        ];
250
251
        $cacheer->putMany($items);
252
253
        foreach ($items as $item) {
254
            $this->assertEquals($item['cacheData'], $cacheer->getCache($item['cacheKey']));
255
        }
256
    }
257
258
    public function test_remember_saves_and_recover_values() 
259
    {
260
        $this->cache->flushCache();
261
262
        $value = $this->cache->remember('remember_test_key', 60, function () {
263
            return 'valor_teste';
264
        });
265
266
        $this->assertEquals('valor_teste', $value);
267
268
        $cachedValue = $this->cache->remember('remember_test_key', 60, function (){
269
            return 'novo_valor';
270
        });
271
272
273
        $this->assertEquals('valor_teste', $cachedValue);
274
    }
275
276
    public function test_remember_forever_saves_value_indefinitely()
277
    {
278
        $this->cache->flushCache();
279
280
        $value = $this->cache->rememberForever('remember_forever_key', function () {
281
            return 'valor_eterno';
282
        });
283
        $this->assertEquals('valor_eterno', $value);
284
285
        $cachedValue = $this->cache->rememberForever('remember_forever_key', function () {
286
            return 'novo_valor';
287
        });
288
289
        $this->assertEquals('valor_eterno', $cachedValue);
290
    }
291
292
    public function test_get_and_forget()
293
    {
294
        $cacheKey = 'cache_key_test';
295
        $this->cache->putCache($cacheKey, 10);
296
297
        $this->assertTrue($this->cache->isSuccess());
298
299
        $cacheData = $this->cache->getAndForget($cacheKey);
300
301
        $this->assertTrue($this->cache->isSuccess());
302
        $this->assertEquals(10, $cacheData);
303
304
        $oldCacheData = $this->cache->getAndForget($cacheKey);
305
306
        $this->assertNull($oldCacheData);
307
        $this->assertFalse($this->cache->isSuccess());
308
309
        $noCacheData = $this->cache->getAndForget('non_existent_cache_key');
310
        $this->assertNull($noCacheData);
311
    }
312
313
    public function test_store_if_not_present_with_add_function()
314
    {
315
        $existentKey = 'cache_key_test';
316
317
        $nonExistentKey = 'non_existent_key';
318
319
        $this->cache->putCache($existentKey, 'existent_data');
320
321
        $this->assertTrue($this->cache->isSuccess());
322
        $this->assertEquals('existent_data', $this->cache->getCache($existentKey));
323
324
        $addCache = $this->cache->add($existentKey, 100);
325
        
326
        $this->assertTrue($addCache);
327
        $this->assertNotEquals(100, 'existent_data');
328
    
329
        $addNonExistentKey = $this->cache->add($nonExistentKey, 'non_existent_data');
330
331
        $this->assertFalse($addNonExistentKey);
332
        $this->assertEquals('non_existent_data', $this->cache->getCache($nonExistentKey));
333
        $this->assertTrue($this->cache->isSuccess());
334
335
    }
336
337
    public function test_increment_function() {
338
339
        $cacheKey = 'test_increment';
340
        $cacheData = 2025;
341
342
        $this->cache->putCache($cacheKey, $cacheData);
343
344
        $this->assertTrue($this->cache->isSuccess());
345
        $this->assertEquals($cacheData, $this->cache->getCache($cacheKey));
346
        $this->assertIsNumeric($this->cache->getCache($cacheKey));
347
348
        $increment = $this->cache->increment($cacheKey, 2);
349
        $this->assertTrue($increment);
350
351
        $this->assertEquals(2027, $this->cache->getCache($cacheKey));
352
353
    }
354
355
        public function test_decrement_function() {
356
357
        $cacheKey = 'test_decrement';
358
        $cacheData = 2027;
359
360
        $this->cache->putCache($cacheKey, $cacheData);
361
362
        $this->assertTrue($this->cache->isSuccess());
363
        $this->assertEquals($cacheData, $this->cache->getCache($cacheKey));
364
        $this->assertIsNumeric($this->cache->getCache($cacheKey));
365
366
        $increment = $this->cache->decrement($cacheKey, 2);
367
        $this->assertTrue($increment);
368
369
        $this->assertEquals(2025, $this->cache->getCache($cacheKey));
370
371
        }
372
373
        private function removeDirectoryRecursively($dir)
374
        {
375
        if (!is_dir($dir)) {
376
            return;
377
        }
378
        $items = scandir($dir);
379
        foreach ($items as $item) {
380
            if ($item === '.' || $item === '..') {
381
            continue;
382
            }
383
            $path = $dir . DIRECTORY_SEPARATOR . $item;
384
            if (is_dir($path)) {
385
            $this->removeDirectoryRecursively($path);
386
            } else {
387
            unlink($path);
388
            }
389
        }
390
        rmdir($dir);
391
        }
392
393
        public function testUseDefaultDriverCreatesCacheDirInProjectRoot()
394
        {
395
        $cacheer = new Cacheer();
396
        $driver = new CacheDriver($cacheer);
397
398
        $projectRoot = dirname(__DIR__, 2);
399
        $expectedCacheDir = $projectRoot . DIRECTORY_SEPARATOR . "CacheerPHP" . DIRECTORY_SEPARATOR . "Cache";
400
401
        if (is_dir($expectedCacheDir)) {
402
            $this->removeDirectoryRecursively($expectedCacheDir);
403
        }
404
405
        $driver->useDefaultDriver();
406
407
        $this->assertDirectoryExists($expectedCacheDir);
408
409
        if (is_dir($expectedCacheDir)) {
410
            $this->removeDirectoryRecursively($expectedCacheDir);
411
        }
412
        }
413
414
        public function testPutCacheWithNamespace()
415
        {
416
        $cacheKey = 'namespace_key';
417
        $data = 'namespace_data';
418
        $namespace = 'my_namespace';
419
420
        $this->cache->putCache($cacheKey, $data, $namespace);
421
        $this->assertTrue($this->cache->isSuccess());
422
423
        $cachedData = $this->cache->getCache($cacheKey, $namespace);
424
        $this->assertEquals($data, $cachedData);
425
        }
426
427
        public function testClearCacheWithNamespace()
428
        {
429
        $cacheKey = 'namespace_key_clear';
430
        $data = 'namespace_data_clear';
431
        $namespace = 'clear_namespace';
432
433
        $this->cache->putCache($cacheKey, $data, $namespace);
434
        $this->assertTrue($this->cache->isSuccess());
435
436
        $this->cache->clearCache($cacheKey, $namespace);
437
        $this->assertTrue($this->cache->isSuccess());
438
439
        $cachedData = $this->cache->getCache($cacheKey, $namespace);
440
        $this->assertFalse($this->cache->isSuccess());
441
        $this->assertNull($cachedData);
442
        }
443
444
        public function testFlushCacheRemovesNamespacedFiles()
445
        {
446
        $cacheKey = 'ns_flush_key';
447
        $data = 'ns_flush_data';
448
        $namespace = 'flush_namespace';
449
450
        $this->cache->putCache($cacheKey, $data, $namespace);
451
        $this->assertTrue($this->cache->isSuccess());
452
453
        $this->cache->flushCache();
454
455
        $cachedData = $this->cache->getCache($cacheKey, $namespace);
456
        $this->assertFalse($this->cache->isSuccess());
457
        $this->assertNull($cachedData);
458
        }
459
460
        public function testAppendCacheWithDifferentTypes()
461
        {
462
        $cacheKey = 'append_type_key';
463
        $initialData = ['a' => 1];
464
        $additionalData = ['b' => 2];
465
        $expectedData = ['a' => 1, 'b' => 2];
466
467
        $this->cache->putCache($cacheKey, $initialData);
468
        $this->cache->appendCache($cacheKey, $additionalData);
469
        $this->assertEquals($expectedData, $this->cache->getCache($cacheKey));
470
471
        $this->cache->appendCache($cacheKey, ['c' => 'string']);
472
        $expectedData['c'] = 'string';
473
        $this->assertEquals($expectedData, $this->cache->getCache($cacheKey));
474
        }
475
476
    }
477