Passed
Push — main ( 1a2591...d5d45e )
by Sílvio
12:51 queued 10:10
created

FileCacheStoreTest::setUp()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 2
nop 0
dl 0
loc 12
rs 10
c 0
b 0
f 0
1
<?php
2
3
use PHPUnit\Framework\TestCase;
4
use Silviooosilva\CacheerPhp\Cacheer;
5
6
class FileCacheStoreTest extends TestCase
7
{
8
    private $cache;
9
    private $cacheDir;
10
11
    protected function setUp(): void
12
    {
13
        $this->cacheDir = __DIR__ . '/cache';
14
        if (!file_exists($this->cacheDir) || !is_dir($this->cacheDir)) {
15
            mkdir($this->cacheDir, 0755, true);
16
        }
17
18
        $options = [
19
            'cacheDir' => $this->cacheDir,
20
        ];
21
22
        $this->cache = new Cacheer($options);
23
    }
24
25
    protected function tearDown(): void
26
    {
27
        $this->cache->flushCache();
28
    }
29
30
    public function testPutCache()
31
    {
32
        $cacheKey = 'test_key';
33
        $data = 'test_data';
34
35
        $this->cache->putCache($cacheKey, $data);
36
        $this->assertTrue($this->cache->isSuccess());
37
        $this->assertEquals('Cache file created successfully', $this->cache->getMessage());
38
39
        $cacheFile = $this->cacheDir . '/' . md5($cacheKey) . '.cache';
40
        $this->assertFileExists($cacheFile);
41
        $this->assertEquals($data, $this->cache->getCache($cacheKey));
42
    }
43
44
    public function testGetCache()
45
    {
46
        $cacheKey = 'test_key';
47
        $data = 'test_data';
48
49
        $this->cache->putCache($cacheKey, $data);
50
51
        $cachedData = $this->cache->getCache($cacheKey);
52
        $this->assertTrue($this->cache->isSuccess());
53
        $this->assertEquals($data, $cachedData);
54
55
        // Recuperar cache fora do período de expiração
56
        sleep(2);
57
        $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...
58
        $this->assertFalse($this->cache->isSuccess());
59
        $this->assertEquals('cacheFile not found, does not exists or expired', $this->cache->getMessage());
60
    }
61
62
    public function testClearCache()
63
    {
64
        $cacheKey = 'test_key';
65
        $data = 'test_data';
66
67
        $this->cache->putCache($cacheKey, $data);
68
        $this->cache->clearCache($cacheKey);
69
70
        $this->assertTrue($this->cache->isSuccess());
71
        $this->assertEquals('Cache file deleted successfully!', $this->cache->getMessage());
72
73
        $cacheFile = $this->cacheDir . '/' . md5($cacheKey) . '.cache';
74
        $this->assertFileDoesNotExist($cacheFile);
75
    }
76
77
    public function testFlushCache()
78
    {
79
        $key1 = 'test_key1';
80
        $data1 = 'test_data1';
81
82
        $key2 = 'test_key2';
83
        $data2 = 'test_data2';
84
85
        $this->cache->putCache($key1, $data1);
86
        $this->cache->putCache($key2, $data2);
87
        $this->cache->flushCache();
88
89
        $cacheFile1 = $this->cacheDir . '/' . md5($key1) . '.cache';
90
        $cacheFile2 = $this->cacheDir . '/' . md5($key2) . '.cache';
91
92
        $this->assertFileDoesNotExist($cacheFile1);
93
        $this->assertFileDoesNotExist($cacheFile2);
94
    }
95
96
    public function testAutoFlush()
97
    {
98
        $options = [
99
            'cacheDir' => $this->cacheDir,
100
            'flushAfter' => '10 seconds'
101
        ];
102
103
        $this->cache = new Cacheer($options);
104
        $this->cache->putCache('test_key', 'test_data');
105
106
        // Verifica se o cache foi criado com sucesso
107
        $this->assertEquals('test_data', $this->cache->getCache('test_key'));
108
        $this->assertTrue($this->cache->isSuccess());
109
110
        // Espera 11 segundos para o cache ser limpo automaticamente
111
        sleep(11);
112
113
        $this->cache = new Cacheer($options);
114
115
        // Verifica se o cache foi limpo automaticamente
116
        $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...
117
        $this->assertFalse($this->cache->isSuccess());
118
        $this->assertEquals('cacheFile not found, does not exists or expired', $this->cache->getMessage());
119
    }
120
121
    public function testAppendCache()
122
    {
123
        $cacheKey = 'test_append_key';
124
        $initialData = ['initial' => 'data'];
125
        $additionalData = ['new' => 'data'];
126
        $expectedData = array_merge($initialData, $additionalData);
127
128
        // Armazena os dados iniciais no cache
129
        $this->cache->putCache($cacheKey, $initialData);
130
        $this->assertTrue($this->cache->isSuccess());
131
132
        // Adiciona novos dados ao cache existente
133
        $this->cache->appendCache($cacheKey, $additionalData);
134
        $this->assertTrue($this->cache->isSuccess());
135
136
        // Verifica se os dados no cache são os esperados
137
        $cachedData = $this->cache->getCache($cacheKey);
138
        $this->assertEquals($expectedData, $cachedData);
139
140
        // Testa adicionar dados como string
141
        $additionalData = ['string_data' => 'string data'];
142
        $expectedData = array_merge($expectedData, $additionalData);
143
        $this->cache->appendCache($cacheKey, $additionalData);
144
        $cachedData = $this->cache->getCache($cacheKey);
145
        $this->assertEquals($expectedData, $cachedData);
146
    }
147
148
    public function testAppendCacheFileNotExists()
149
    {
150
        $cacheKey = 'non_existing_key';
151
        $data = ['data'];
152
153
        // Tenta adicionar dados a um arquivo de cache que não existe
154
        $this->cache->appendCache($cacheKey, $data);
155
        $this->assertFalse($this->cache->isSuccess());
156
        $this->assertEquals('cacheFile not found, does not exists or expired', $this->cache->getMessage());
157
    }
158
159
    public function testAppendCacheWithNamespace()
160
    {
161
        $cacheKey = 'test_append_key_ns';
162
        $namespace = 'test_namespace';
163
164
        $initialData = ['initial' => 'data'];
165
        $additionalData = ['new' => 'data'];
166
167
        $expectedData = array_merge($initialData, $additionalData);
168
169
        // Armazena os dados iniciais no cache com namespace
170
        $this->cache->putCache($cacheKey, $initialData, $namespace);
171
        $this->assertTrue($this->cache->isSuccess());
172
173
        // Adiciona novos dados ao cache existente com namespace
174
        $this->cache->appendCache($cacheKey, $additionalData, $namespace);
175
        $this->assertTrue($this->cache->isSuccess());
176
177
        // Verifica se os dados no cache são os esperados
178
        $cachedData = $this->cache->getCache($cacheKey, $namespace);
179
        $this->assertEquals($expectedData, $cachedData);
180
    }
181
182
    public function testDataOutputShouldBeOfTypeJson()
183
    {
184
        $options = [
185
            'cacheDir' => $this->cacheDir
186
        ];
187
        $this->cache = new Cacheer($options, true);
188
189
        $cacheKey = "key_json";
190
        $cacheData = "data_json";
191
192
        $this->cache->putCache($cacheKey, $cacheData);
193
        $this->assertTrue($this->cache->isSuccess());
194
195
        $cacheOutput = $this->cache->getCache($cacheKey)->toJson();
196
        $this->assertTrue($this->cache->isSuccess());
197
        $this->assertJson($cacheOutput);
198
    }
199
200
    public function testDataOutputShouldBeOfTypeArray()
201
    {
202
        $options = [
203
            'cacheDir' => $this->cacheDir
204
        ];
205
        $this->cache = new Cacheer($options, true);
206
207
        $cacheKey = "key_array";
208
        $cacheData = "data_array";
209
210
        $this->cache->putCache($cacheKey, $cacheData);
211
        $this->assertTrue($this->cache->isSuccess());
212
213
        $cacheOutput = $this->cache->getCache($cacheKey)->toArray();
214
        $this->assertTrue($this->cache->isSuccess());
215
        $this->assertIsArray($cacheOutput);
216
    }
217
218
    public function testDataOutputShouldBeOfTypeObject()
219
    {
220
        $options = [
221
            'cacheDir' => $this->cacheDir
222
        ];
223
        $this->cache = new Cacheer($options, true);
224
225
        $cacheKey = "key_object";
226
        $cacheData = ["id" => 123];
227
228
        $this->cache->putCache($cacheKey, $cacheData);
229
        $this->assertTrue($this->cache->isSuccess());
230
231
        $cacheOutput = $this->cache->getCache($cacheKey)->toObject();
232
        $this->assertTrue($this->cache->isSuccess());
233
        $this->assertIsObject($cacheOutput);
234
    }
235
236
    public function testPutMany()
237
    {
238
        $cacheer = new Cacheer(['cacheDir' => __DIR__ . '/cache']);
239
        $items = [
240
            [
241
                'cacheKey' => 'user_1_profile',
242
                'cacheData' => ['name' => 'John Doe', 'email' => '[email protected]']
243
            ],
244
            [
245
                'cacheKey' => 'user_2_profile',
246
                'cacheData' => ['name' => 'Jane Doe', 'email' => '[email protected]']
247
            ],
248
        ];
249
250
        $cacheer->putMany($items);
251
252
        foreach ($items as $item) {
253
            $this->assertEquals($item['cacheData'], $cacheer->getCache($item['cacheKey']));
254
        }
255
    }
256
257
    public function test_remember_saves_and_recover_values() 
258
    {
259
        $this->cache->flushCache();
260
261
        $value = $this->cache->remember('remember_test_key', 60, function () {
262
            return 'valor_teste';
263
        });
264
265
        $this->assertEquals('valor_teste', $value);
266
267
        $cachedValue = $this->cache->remember('remember_test_key', 60, function (){
268
            return 'novo_valor';
269
        });
270
271
272
        $this->assertEquals('valor_teste', $cachedValue);
273
    }
274
275
    public function test_remember_forever_saves_value_indefinitely()
276
    {
277
        $this->cache->flushCache();
278
279
        $value = $this->cache->rememberForever('remember_forever_key', function () {
280
            return 'valor_eterno';
281
        });
282
        $this->assertEquals('valor_eterno', $value);
283
284
        $cachedValue = $this->cache->rememberForever('remember_forever_key', function () {
285
            return 'novo_valor';
286
        });
287
288
        $this->assertEquals('valor_eterno', $cachedValue);
289
    }
290
291
    public function test_get_and_forget()
292
    {
293
        $cacheKey = 'cache_key_test';
294
        $this->cache->putCache($cacheKey, 10);
295
296
        $this->assertTrue($this->cache->isSuccess());
297
298
        $cacheData = $this->cache->getAndForget($cacheKey);
299
300
        $this->assertTrue($this->cache->isSuccess());
301
        $this->assertEquals(10, $cacheData);
302
303
        $oldCacheData = $this->cache->getAndForget($cacheKey);
304
305
        $this->assertNull($oldCacheData);
306
        $this->assertFalse($this->cache->isSuccess());
307
308
        $noCacheData = $this->cache->getAndForget('non_existent_cache_key');
309
        $this->assertNull($noCacheData);
310
    }
311
312
    public function test_store_if_not_present_with_add_function()
313
    {
314
        $existentKey = 'cache_key_test';
315
316
        $nonExistentKey = 'non_existent_key';
317
318
        $this->cache->putCache($existentKey, 'existent_data');
319
320
        $this->assertTrue($this->cache->isSuccess());
321
        $this->assertEquals('existent_data', $this->cache->getCache($existentKey));
322
323
        $addCache = $this->cache->add($existentKey, 100);
324
        
325
        $this->assertTrue($addCache);
326
        $this->assertNotEquals(100, 'existent_data');
327
    
328
        $addNonExistentKey = $this->cache->add($nonExistentKey, 'non_existent_data');
329
330
        $this->assertFalse($addNonExistentKey);
331
        $this->assertEquals('non_existent_data', $this->cache->getCache($nonExistentKey));
332
        $this->assertTrue($this->cache->isSuccess());
333
334
    }
335
336
    public function test_increment_function() {
337
338
        $cacheKey = 'test_increment';
339
        $cacheData = 2025;
340
341
        $this->cache->putCache($cacheKey, $cacheData);
342
343
        $this->assertTrue($this->cache->isSuccess());
344
        $this->assertEquals($cacheData, $this->cache->getCache($cacheKey));
345
        $this->assertIsNumeric($this->cache->getCache($cacheKey));
346
347
        $increment = $this->cache->increment($cacheKey, 2);
348
        $this->assertTrue($increment);
349
350
        $this->assertEquals(2027, $this->cache->getCache($cacheKey));
351
352
    }
353
354
        public function test_decrement_function() {
355
356
        $cacheKey = 'test_decrement';
357
        $cacheData = 2027;
358
359
        $this->cache->putCache($cacheKey, $cacheData);
360
361
        $this->assertTrue($this->cache->isSuccess());
362
        $this->assertEquals($cacheData, $this->cache->getCache($cacheKey));
363
        $this->assertIsNumeric($this->cache->getCache($cacheKey));
364
365
        $increment = $this->cache->decrement($cacheKey, 2);
366
        $this->assertTrue($increment);
367
368
        $this->assertEquals(2025, $this->cache->getCache($cacheKey));
369
370
    }
371
372
}
373