forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackend_unittest.cc
5315 lines (4392 loc) · 169 KB
/
backend_unittest.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stdint.h>
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/files/file.h"
#include "base/files/file_util.h"
#include "base/memory/memory_pressure_listener.h"
#include "base/metrics/field_trial.h"
#include "base/run_loop.h"
#include "base/sequenced_task_runner.h"
#include "base/stl_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/task/post_task.h"
#include "base/task/thread_pool.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/third_party/dynamic_annotations/dynamic_annotations.h"
#include "base/threading/platform_thread.h"
#include "base/threading/thread_restrictions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/trace_event/memory_allocator_dump.h"
#include "base/trace_event/process_memory_dump.h"
#include "base/trace_event/traced_value.h"
#include "build/build_config.h"
#include "net/base/cache_type.h"
#include "net/base/completion_once_callback.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "net/base/request_priority.h"
#include "net/base/test_completion_callback.h"
#include "net/disk_cache/backend_cleanup_tracker.h"
#include "net/disk_cache/blockfile/backend_impl.h"
#include "net/disk_cache/blockfile/entry_impl.h"
#include "net/disk_cache/blockfile/experiments.h"
#include "net/disk_cache/blockfile/histogram_macros.h"
#include "net/disk_cache/blockfile/mapped_file.h"
#include "net/disk_cache/cache_util.h"
#include "net/disk_cache/disk_cache_test_base.h"
#include "net/disk_cache/disk_cache_test_util.h"
#include "net/disk_cache/memory/mem_backend_impl.h"
#include "net/disk_cache/simple/simple_backend_impl.h"
#include "net/disk_cache/simple/simple_entry_format.h"
#include "net/disk_cache/simple/simple_histogram_enums.h"
#include "net/disk_cache/simple/simple_index.h"
#include "net/disk_cache/simple/simple_synchronous_entry.h"
#include "net/disk_cache/simple/simple_test_util.h"
#include "net/disk_cache/simple/simple_util.h"
#include "net/test/gtest_util.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using disk_cache::EntryResult;
using net::test::IsError;
using net::test::IsOk;
using testing::ByRef;
using testing::Contains;
using testing::Eq;
using testing::Field;
#if defined(OS_WIN)
#include "base/win/scoped_handle.h"
#endif
// Provide a BackendImpl object to macros from histogram_macros.h.
#define CACHE_UMA_BACKEND_IMPL_OBJ backend_
// TODO(crbug.com/949811): Fix memory leaks in tests and re-enable on LSAN.
#ifdef LEAK_SANITIZER
#define MAYBE_BlockFileOpenOrCreateEntry DISABLED_BlockFileOpenOrCreateEntry
#define MAYBE_NonEmptyCorruptSimpleCacheDoesNotRecover \
DISABLED_NonEmptyCorruptSimpleCacheDoesNotRecover
#define MAYBE_SimpleOpenOrCreateEntry DISABLED_SimpleOpenOrCreateEntry
#else
#define MAYBE_BlockFileOpenOrCreateEntry BlockFileOpenOrCreateEntry
#define MAYBE_NonEmptyCorruptSimpleCacheDoesNotRecover \
NonEmptyCorruptSimpleCacheDoesNotRecover
#define MAYBE_SimpleOpenOrCreateEntry SimpleOpenOrCreateEntry
#endif
using base::Time;
namespace {
const char kExistingEntryKey[] = "existing entry key";
std::unique_ptr<disk_cache::BackendImpl> CreateExistingEntryCache(
const base::FilePath& cache_path) {
net::TestCompletionCallback cb;
std::unique_ptr<disk_cache::BackendImpl> cache(
std::make_unique<disk_cache::BackendImpl>(cache_path,
/* cleanup_tracker = */ nullptr,
/* cache_thread = */ nullptr,
net::DISK_CACHE,
/* net_log = */ nullptr));
int rv = cache->Init(cb.callback());
if (cb.GetResult(rv) != net::OK)
return std::unique_ptr<disk_cache::BackendImpl>();
TestEntryResultCompletionCallback cb2;
EntryResult result =
cache->CreateEntry(kExistingEntryKey, net::HIGHEST, cb2.callback());
result = cb2.GetResult(std::move(result));
if (result.net_error() != net::OK)
return std::unique_ptr<disk_cache::BackendImpl>();
return cache;
}
#if defined(OS_FUCHSIA)
// Load tests with large numbers of file descriptors perform poorly on
// virtualized test execution environments.
// TODO(807882): Remove this workaround when virtualized test performance
// improves.
const int kLargeNumEntries = 100;
#else
const int kLargeNumEntries = 512;
#endif
} // namespace
// Tests that can run with different types of caches.
class DiskCacheBackendTest : public DiskCacheTestWithCache {
protected:
// Some utility methods:
// Perform IO operations on the cache until there is pending IO.
int GeneratePendingIO(net::TestCompletionCallback* cb);
// Adds 5 sparse entries. |doomed_start| and |doomed_end| if not NULL,
// will be filled with times, used by DoomEntriesSince and DoomEntriesBetween.
// There are 4 entries after doomed_start and 2 after doomed_end.
void InitSparseCache(base::Time* doomed_start, base::Time* doomed_end);
bool CreateSetOfRandomEntries(std::set<std::string>* key_pool);
bool EnumerateAndMatchKeys(int max_to_open,
TestIterator* iter,
std::set<std::string>* keys_to_match,
size_t* count);
// Computes the expected size of entry metadata, i.e. the total size without
// the actual data stored. This depends only on the entry's |key| size.
int GetEntryMetadataSize(std::string key);
// The Simple Backend only tracks the approximate sizes of entries. This
// rounds the exact size appropriately.
int GetRoundedSize(int exact_size);
// Create a default key with the name provided, populate it with
// CacheTestFillBuffer, and ensure this was done correctly.
void CreateKeyAndCheck(disk_cache::Backend* cache, std::string key);
// For the simple cache, wait until indexing has occurred and make sure
// completes successfully.
void WaitForSimpleCacheIndexAndCheck(disk_cache::Backend* cache);
// Run all of the task runners untile idle, covers cache worker pools.
void RunUntilIdle();
// Actual tests:
void BackendBasics();
void BackendKeying();
void BackendShutdownWithPendingFileIO(bool fast);
void BackendShutdownWithPendingIO(bool fast);
void BackendShutdownWithPendingCreate(bool fast);
void BackendShutdownWithPendingDoom();
void BackendSetSize();
void BackendLoad();
void BackendChain();
void BackendValidEntry();
void BackendInvalidEntry();
void BackendInvalidEntryRead();
void BackendInvalidEntryWithLoad();
void BackendTrimInvalidEntry();
void BackendTrimInvalidEntry2();
void BackendEnumerations();
void BackendEnumerations2();
void BackendDoomMidEnumeration();
void BackendInvalidEntryEnumeration();
void BackendFixEnumerators();
void BackendDoomRecent();
void BackendDoomBetween();
void BackendCalculateSizeOfAllEntries();
void BackendCalculateSizeOfEntriesBetween(
bool expect_access_time_range_comparisons);
void BackendTransaction(const std::string& name, int num_entries, bool load);
void BackendRecoverInsert();
void BackendRecoverRemove();
void BackendRecoverWithEviction();
void BackendInvalidEntry2();
void BackendInvalidEntry3();
void BackendInvalidEntry7();
void BackendInvalidEntry8();
void BackendInvalidEntry9(bool eviction);
void BackendInvalidEntry10(bool eviction);
void BackendInvalidEntry11(bool eviction);
void BackendTrimInvalidEntry12();
void BackendDoomAll();
void BackendDoomAll2();
void BackendInvalidRankings();
void BackendInvalidRankings2();
void BackendDisable();
void BackendDisable2();
void BackendDisable3();
void BackendDisable4();
void BackendDisabledAPI();
void BackendEviction();
void BackendOpenOrCreateEntry();
void BackendDeadOpenNextEntry();
void BackendIteratorConcurrentDoom();
};
void DiskCacheBackendTest::CreateKeyAndCheck(disk_cache::Backend* cache,
std::string key) {
const int kBufSize = 4 * 1024;
scoped_refptr<net::IOBuffer> buffer =
base::MakeRefCounted<net::IOBuffer>(kBufSize);
CacheTestFillBuffer(buffer->data(), kBufSize, true);
TestEntryResultCompletionCallback cb_entry;
disk_cache::EntryResult result =
cache->CreateEntry(key, net::HIGHEST, cb_entry.callback());
result = cb_entry.GetResult(std::move(result));
ASSERT_EQ(net::OK, result.net_error());
disk_cache::Entry* entry = result.ReleaseEntry();
EXPECT_EQ(kBufSize, WriteData(entry, 0, 0, buffer.get(), kBufSize, false));
entry->Close();
RunUntilIdle();
}
void DiskCacheBackendTest::WaitForSimpleCacheIndexAndCheck(
disk_cache::Backend* cache) {
net::TestCompletionCallback wait_for_index_cb;
static_cast<disk_cache::SimpleBackendImpl*>(cache)->index()->ExecuteWhenReady(
wait_for_index_cb.callback());
int rv = wait_for_index_cb.WaitForResult();
ASSERT_THAT(rv, IsOk());
RunUntilIdle();
}
void DiskCacheBackendTest::RunUntilIdle() {
DiskCacheTestWithCache::RunUntilIdle();
base::RunLoop().RunUntilIdle();
disk_cache::SimpleBackendImpl::FlushWorkerPoolForTesting();
}
int DiskCacheBackendTest::GeneratePendingIO(net::TestCompletionCallback* cb) {
if (!use_current_thread_ && !simple_cache_mode_) {
ADD_FAILURE();
return net::ERR_FAILED;
}
TestEntryResultCompletionCallback create_cb;
EntryResult entry_result;
entry_result =
cache_->CreateEntry("some key", net::HIGHEST, create_cb.callback());
entry_result = create_cb.GetResult(std::move(entry_result));
if (entry_result.net_error() != net::OK)
return net::ERR_CACHE_CREATE_FAILURE;
disk_cache::Entry* entry = entry_result.ReleaseEntry();
const int kSize = 25000;
scoped_refptr<net::IOBuffer> buffer =
base::MakeRefCounted<net::IOBuffer>(kSize);
CacheTestFillBuffer(buffer->data(), kSize, false);
int rv = net::OK;
for (int i = 0; i < 10 * 1024 * 1024; i += 64 * 1024) {
// We are using the current thread as the cache thread because we want to
// be able to call directly this method to make sure that the OS (instead
// of us switching thread) is returning IO pending.
if (!simple_cache_mode_) {
rv = static_cast<disk_cache::EntryImpl*>(entry)->WriteDataImpl(
0, i, buffer.get(), kSize, cb->callback(), false);
} else {
rv = entry->WriteData(0, i, buffer.get(), kSize, cb->callback(), false);
}
if (rv == net::ERR_IO_PENDING)
break;
if (rv != kSize)
rv = net::ERR_FAILED;
}
// Don't call Close() to avoid going through the queue or we'll deadlock
// waiting for the operation to finish.
if (!simple_cache_mode_)
static_cast<disk_cache::EntryImpl*>(entry)->Release();
else
entry->Close();
return rv;
}
void DiskCacheBackendTest::InitSparseCache(base::Time* doomed_start,
base::Time* doomed_end) {
InitCache();
const int kSize = 50;
// This must be greater than MemEntryImpl::kMaxSparseEntrySize.
const int kOffset = 10 + 1024 * 1024;
disk_cache::Entry* entry0 = nullptr;
disk_cache::Entry* entry1 = nullptr;
disk_cache::Entry* entry2 = nullptr;
scoped_refptr<net::IOBuffer> buffer =
base::MakeRefCounted<net::IOBuffer>(kSize);
CacheTestFillBuffer(buffer->data(), kSize, false);
ASSERT_THAT(CreateEntry("zeroth", &entry0), IsOk());
ASSERT_EQ(kSize, WriteSparseData(entry0, 0, buffer.get(), kSize));
ASSERT_EQ(kSize,
WriteSparseData(entry0, kOffset + kSize, buffer.get(), kSize));
entry0->Close();
FlushQueueForTest();
AddDelay();
if (doomed_start)
*doomed_start = base::Time::Now();
// Order in rankings list:
// first_part1, first_part2, second_part1, second_part2
ASSERT_THAT(CreateEntry("first", &entry1), IsOk());
ASSERT_EQ(kSize, WriteSparseData(entry1, 0, buffer.get(), kSize));
ASSERT_EQ(kSize,
WriteSparseData(entry1, kOffset + kSize, buffer.get(), kSize));
entry1->Close();
ASSERT_THAT(CreateEntry("second", &entry2), IsOk());
ASSERT_EQ(kSize, WriteSparseData(entry2, 0, buffer.get(), kSize));
ASSERT_EQ(kSize,
WriteSparseData(entry2, kOffset + kSize, buffer.get(), kSize));
entry2->Close();
FlushQueueForTest();
AddDelay();
if (doomed_end)
*doomed_end = base::Time::Now();
// Order in rankings list:
// third_part1, fourth_part1, third_part2, fourth_part2
disk_cache::Entry* entry3 = nullptr;
disk_cache::Entry* entry4 = nullptr;
ASSERT_THAT(CreateEntry("third", &entry3), IsOk());
ASSERT_EQ(kSize, WriteSparseData(entry3, 0, buffer.get(), kSize));
ASSERT_THAT(CreateEntry("fourth", &entry4), IsOk());
ASSERT_EQ(kSize, WriteSparseData(entry4, 0, buffer.get(), kSize));
ASSERT_EQ(kSize,
WriteSparseData(entry3, kOffset + kSize, buffer.get(), kSize));
ASSERT_EQ(kSize,
WriteSparseData(entry4, kOffset + kSize, buffer.get(), kSize));
entry3->Close();
entry4->Close();
FlushQueueForTest();
AddDelay();
}
// Creates entries based on random keys. Stores these keys in |key_pool|.
bool DiskCacheBackendTest::CreateSetOfRandomEntries(
std::set<std::string>* key_pool) {
const int kNumEntries = 10;
const int initial_entry_count = cache_->GetEntryCount();
for (int i = 0; i < kNumEntries; ++i) {
std::string key = GenerateKey(true);
disk_cache::Entry* entry;
if (CreateEntry(key, &entry) != net::OK) {
return false;
}
key_pool->insert(key);
entry->Close();
}
return key_pool->size() ==
static_cast<size_t>(cache_->GetEntryCount() - initial_entry_count);
}
// Performs iteration over the backend and checks that the keys of entries
// opened are in |keys_to_match|, then erases them. Up to |max_to_open| entries
// will be opened, if it is positive. Otherwise, iteration will continue until
// OpenNextEntry stops returning net::OK.
bool DiskCacheBackendTest::EnumerateAndMatchKeys(
int max_to_open,
TestIterator* iter,
std::set<std::string>* keys_to_match,
size_t* count) {
disk_cache::Entry* entry;
if (!iter)
return false;
while (iter->OpenNextEntry(&entry) == net::OK) {
if (!entry)
return false;
EXPECT_EQ(1U, keys_to_match->erase(entry->GetKey()));
entry->Close();
++(*count);
if (max_to_open >= 0 && static_cast<int>(*count) >= max_to_open)
break;
};
return true;
}
int DiskCacheBackendTest::GetEntryMetadataSize(std::string key) {
// For blockfile and memory backends, it is just the key size.
if (!simple_cache_mode_)
return key.size();
// For the simple cache, we must add the file header and EOF, and that for
// every stream.
return disk_cache::kSimpleEntryStreamCount *
(sizeof(disk_cache::SimpleFileHeader) +
sizeof(disk_cache::SimpleFileEOF) + key.size());
}
int DiskCacheBackendTest::GetRoundedSize(int exact_size) {
if (!simple_cache_mode_)
return exact_size;
return (exact_size + 255) & 0xFFFFFF00;
}
void DiskCacheBackendTest::BackendBasics() {
InitCache();
disk_cache::Entry *entry1 = nullptr, *entry2 = nullptr;
EXPECT_NE(net::OK, OpenEntry("the first key", &entry1));
ASSERT_THAT(CreateEntry("the first key", &entry1), IsOk());
ASSERT_TRUE(nullptr != entry1);
entry1->Close();
entry1 = nullptr;
ASSERT_THAT(OpenEntry("the first key", &entry1), IsOk());
ASSERT_TRUE(nullptr != entry1);
entry1->Close();
entry1 = nullptr;
EXPECT_NE(net::OK, CreateEntry("the first key", &entry1));
ASSERT_THAT(OpenEntry("the first key", &entry1), IsOk());
EXPECT_NE(net::OK, OpenEntry("some other key", &entry2));
ASSERT_THAT(CreateEntry("some other key", &entry2), IsOk());
ASSERT_TRUE(nullptr != entry1);
ASSERT_TRUE(nullptr != entry2);
EXPECT_EQ(2, cache_->GetEntryCount());
disk_cache::Entry* entry3 = nullptr;
ASSERT_THAT(OpenEntry("some other key", &entry3), IsOk());
ASSERT_TRUE(nullptr != entry3);
EXPECT_TRUE(entry2 == entry3);
EXPECT_THAT(DoomEntry("some other key"), IsOk());
EXPECT_EQ(1, cache_->GetEntryCount());
entry1->Close();
entry2->Close();
entry3->Close();
EXPECT_THAT(DoomEntry("the first key"), IsOk());
EXPECT_EQ(0, cache_->GetEntryCount());
ASSERT_THAT(CreateEntry("the first key", &entry1), IsOk());
ASSERT_THAT(CreateEntry("some other key", &entry2), IsOk());
entry1->Doom();
entry1->Close();
EXPECT_THAT(DoomEntry("some other key"), IsOk());
EXPECT_EQ(0, cache_->GetEntryCount());
entry2->Close();
}
TEST_F(DiskCacheBackendTest, Basics) {
BackendBasics();
}
TEST_F(DiskCacheBackendTest, NewEvictionBasics) {
SetNewEviction();
BackendBasics();
}
TEST_F(DiskCacheBackendTest, MemoryOnlyBasics) {
SetMemoryOnlyMode();
BackendBasics();
}
TEST_F(DiskCacheBackendTest, AppCacheBasics) {
SetCacheType(net::APP_CACHE);
BackendBasics();
}
TEST_F(DiskCacheBackendTest, ShaderCacheBasics) {
SetCacheType(net::SHADER_CACHE);
BackendBasics();
}
void DiskCacheBackendTest::BackendKeying() {
InitCache();
const char kName1[] = "the first key";
const char kName2[] = "the first Key";
disk_cache::Entry *entry1, *entry2;
ASSERT_THAT(CreateEntry(kName1, &entry1), IsOk());
ASSERT_THAT(CreateEntry(kName2, &entry2), IsOk());
EXPECT_TRUE(entry1 != entry2) << "Case sensitive";
entry2->Close();
char buffer[30];
base::strlcpy(buffer, kName1, base::size(buffer));
ASSERT_THAT(OpenEntry(buffer, &entry2), IsOk());
EXPECT_TRUE(entry1 == entry2);
entry2->Close();
base::strlcpy(buffer + 1, kName1, base::size(buffer) - 1);
ASSERT_THAT(OpenEntry(buffer + 1, &entry2), IsOk());
EXPECT_TRUE(entry1 == entry2);
entry2->Close();
base::strlcpy(buffer + 3, kName1, base::size(buffer) - 3);
ASSERT_THAT(OpenEntry(buffer + 3, &entry2), IsOk());
EXPECT_TRUE(entry1 == entry2);
entry2->Close();
// Now verify long keys.
char buffer2[20000];
memset(buffer2, 's', sizeof(buffer2));
buffer2[1023] = '\0';
ASSERT_EQ(net::OK, CreateEntry(buffer2, &entry2)) << "key on block file";
entry2->Close();
buffer2[1023] = 'g';
buffer2[19999] = '\0';
ASSERT_EQ(net::OK, CreateEntry(buffer2, &entry2)) << "key on external file";
entry2->Close();
entry1->Close();
}
TEST_F(DiskCacheBackendTest, Keying) {
BackendKeying();
}
TEST_F(DiskCacheBackendTest, NewEvictionKeying) {
SetNewEviction();
BackendKeying();
}
TEST_F(DiskCacheBackendTest, MemoryOnlyKeying) {
SetMemoryOnlyMode();
BackendKeying();
}
TEST_F(DiskCacheBackendTest, AppCacheKeying) {
SetCacheType(net::APP_CACHE);
BackendKeying();
}
TEST_F(DiskCacheBackendTest, ShaderCacheKeying) {
SetCacheType(net::SHADER_CACHE);
BackendKeying();
}
TEST_F(DiskCacheTest, CreateBackend) {
net::TestCompletionCallback cb;
{
ASSERT_TRUE(CleanupCacheDir());
// Test the private factory method(s).
std::unique_ptr<disk_cache::Backend> cache;
cache = disk_cache::MemBackendImpl::CreateBackend(0, nullptr);
ASSERT_TRUE(cache.get());
cache.reset();
// Now test the public API.
int rv = disk_cache::CreateCacheBackend(
net::DISK_CACHE, net::CACHE_BACKEND_DEFAULT, cache_path_, 0,
disk_cache::ResetHandling::kNeverReset, nullptr, &cache, cb.callback());
ASSERT_THAT(cb.GetResult(rv), IsOk());
ASSERT_TRUE(cache.get());
cache.reset();
rv = disk_cache::CreateCacheBackend(
net::MEMORY_CACHE, net::CACHE_BACKEND_DEFAULT, base::FilePath(), 0,
disk_cache::ResetHandling::kNeverReset, nullptr, &cache, cb.callback());
ASSERT_THAT(cb.GetResult(rv), IsOk());
ASSERT_TRUE(cache.get());
cache.reset();
}
base::RunLoop().RunUntilIdle();
}
TEST_F(DiskCacheTest, MemBackendPostCleanupCallback) {
net::TestCompletionCallback cb;
net::TestClosure on_cleanup;
std::unique_ptr<disk_cache::Backend> cache;
int rv = disk_cache::CreateCacheBackend(
net::MEMORY_CACHE, net::CACHE_BACKEND_DEFAULT, base::FilePath(), 0,
disk_cache::ResetHandling::kNeverReset, nullptr, &cache,
on_cleanup.closure(), cb.callback());
ASSERT_THAT(cb.GetResult(rv), IsOk());
ASSERT_TRUE(cache.get());
// The callback should be posted after backend is destroyed.
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(on_cleanup.have_result());
cache.reset();
EXPECT_FALSE(on_cleanup.have_result());
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(on_cleanup.have_result());
}
TEST_F(DiskCacheTest, CreateBackendDouble) {
// Make sure that creation for the second backend for same path happens
// after the first one completes.
net::TestCompletionCallback cb, cb2;
std::unique_ptr<disk_cache::Backend> cache, cache2;
int rv = disk_cache::CreateCacheBackend(
net::APP_CACHE, net::CACHE_BACKEND_DEFAULT, cache_path_, 0,
disk_cache::ResetHandling::kNeverReset, nullptr, &cache, cb.callback());
int rv2 = disk_cache::CreateCacheBackend(
net::APP_CACHE, net::CACHE_BACKEND_DEFAULT, cache_path_, 0,
disk_cache::ResetHandling::kNeverReset, nullptr, &cache2, cb2.callback());
EXPECT_THAT(cb.GetResult(rv), IsOk());
EXPECT_TRUE(cache.get());
disk_cache::FlushCacheThreadForTesting();
// No cache 2 yet.
EXPECT_EQ(net::ERR_IO_PENDING, rv2);
EXPECT_FALSE(cb2.have_result());
cache.reset();
// Now cache2 should exist.
EXPECT_THAT(cb2.GetResult(rv2), IsOk());
EXPECT_TRUE(cache2.get());
}
TEST_F(DiskCacheBackendTest, CreateBackendDoubleOpenEntry) {
// Demonstrate the creation sequencing with an open entry. This is done
// with SimpleCache since the block-file cache cancels most of I/O on
// destruction and blocks for what it can't cancel.
// Don't try to sanity-check things as a blockfile cache
SetSimpleCacheMode();
// Make sure that creation for the second backend for same path happens
// after the first one completes, and all of its ops complete.
net::TestCompletionCallback cb, cb2;
std::unique_ptr<disk_cache::Backend> cache, cache2;
int rv = disk_cache::CreateCacheBackend(
net::APP_CACHE, net::CACHE_BACKEND_SIMPLE, cache_path_, 0,
disk_cache::ResetHandling::kNeverReset, nullptr, &cache, cb.callback());
int rv2 = disk_cache::CreateCacheBackend(
net::APP_CACHE, net::CACHE_BACKEND_SIMPLE, cache_path_, 0,
disk_cache::ResetHandling::kNeverReset, nullptr, &cache2, cb2.callback());
EXPECT_THAT(cb.GetResult(rv), IsOk());
ASSERT_TRUE(cache.get());
disk_cache::FlushCacheThreadForTesting();
// No cache 2 yet.
EXPECT_EQ(net::ERR_IO_PENDING, rv2);
EXPECT_FALSE(cb2.have_result());
TestEntryResultCompletionCallback cb3;
EntryResult entry_result =
cache->CreateEntry("key", net::HIGHEST, cb3.callback());
entry_result = cb3.GetResult(std::move(entry_result));
ASSERT_EQ(net::OK, entry_result.net_error());
cache.reset();
// Still doesn't exist.
EXPECT_FALSE(cb2.have_result());
entry_result.ReleaseEntry()->Close();
// Now should exist.
EXPECT_THAT(cb2.GetResult(rv2), IsOk());
EXPECT_TRUE(cache2.get());
}
TEST_F(DiskCacheBackendTest, CreateBackendPostCleanup) {
// Test for the explicit PostCleanupCallback parameter to CreateCacheBackend.
// Extravagant size payload to make reproducing races easier.
const int kBufSize = 256 * 1024;
scoped_refptr<net::IOBuffer> buffer =
base::MakeRefCounted<net::IOBuffer>(kBufSize);
CacheTestFillBuffer(buffer->data(), kBufSize, true);
SetSimpleCacheMode();
CleanupCacheDir();
base::RunLoop run_loop;
net::TestCompletionCallback cb;
std::unique_ptr<disk_cache::Backend> cache;
int rv = disk_cache::CreateCacheBackend(
net::APP_CACHE, net::CACHE_BACKEND_SIMPLE, cache_path_, 0,
disk_cache::ResetHandling::kNeverReset, nullptr, &cache,
run_loop.QuitClosure(), cb.callback());
EXPECT_THAT(cb.GetResult(rv), IsOk());
ASSERT_TRUE(cache.get());
TestEntryResultCompletionCallback cb2;
EntryResult result = cache->CreateEntry("key", net::HIGHEST, cb2.callback());
result = cb2.GetResult(std::move(result));
ASSERT_EQ(net::OK, result.net_error());
disk_cache::Entry* entry = result.ReleaseEntry();
EXPECT_EQ(kBufSize, WriteData(entry, 0, 0, buffer.get(), kBufSize, false));
entry->Close();
cache.reset();
// Wait till the post-cleanup callback.
run_loop.Run();
// All of the payload should be on disk, despite stream 0 being written
// back in the async Close()
base::FilePath entry_path = cache_path_.AppendASCII(
disk_cache::simple_util::GetFilenameFromKeyAndFileIndex("key", 0));
int64_t size = 0;
EXPECT_TRUE(base::GetFileSize(entry_path, &size));
EXPECT_GT(size, kBufSize);
}
TEST_F(DiskCacheBackendTest, SimpleCreateBackendRecoveryAppCache) {
// Tests index recovery in APP_CACHE mode. (This is harder to test for
// DISK_CACHE since post-cleanup callbacks aren't permitted there).
const int kBufSize = 4 * 1024;
scoped_refptr<net::IOBuffer> buffer =
base::MakeRefCounted<net::IOBuffer>(kBufSize);
CacheTestFillBuffer(buffer->data(), kBufSize, true);
SetSimpleCacheMode();
SetCacheType(net::APP_CACHE);
DisableFirstCleanup();
CleanupCacheDir();
base::RunLoop run_loop;
net::TestCompletionCallback cb;
std::unique_ptr<disk_cache::Backend> cache;
// Create a backend with post-cleanup callback specified, in order to know
// when the index has been written back (so it can be deleted race-free).
int rv = disk_cache::CreateCacheBackend(
net::APP_CACHE, net::CACHE_BACKEND_SIMPLE, cache_path_, 0,
disk_cache::ResetHandling::kNeverReset, nullptr, &cache,
run_loop.QuitClosure(), cb.callback());
EXPECT_THAT(cb.GetResult(rv), IsOk());
ASSERT_TRUE(cache.get());
// Create an entry.
TestEntryResultCompletionCallback cb2;
disk_cache::EntryResult result =
cache->CreateEntry("key", net::HIGHEST, cb2.callback());
result = cb2.GetResult(std::move(result));
ASSERT_EQ(net::OK, result.net_error());
disk_cache::Entry* entry = result.ReleaseEntry();
EXPECT_EQ(kBufSize, WriteData(entry, 0, 0, buffer.get(), kBufSize, false));
entry->Close();
cache.reset();
// Wait till the post-cleanup callback.
run_loop.Run();
// Delete the index.
base::DeleteFile(
cache_path_.AppendASCII("index-dir").AppendASCII("the-real-index"));
// Open the cache again. The fixture will also waits for index init.
InitCache();
// Entry should not have a trailer size, since can't tell what it should be
// when doing recovery (and definitely shouldn't interpret last use time as
// such).
EXPECT_EQ(0, simple_cache_impl_->index()->GetTrailerPrefetchSize(
disk_cache::simple_util::GetEntryHashKey("key")));
}
// Tests that |BackendImpl| fails to initialize with a missing file.
TEST_F(DiskCacheBackendTest, CreateBackend_MissingFile) {
ASSERT_TRUE(CopyTestCache("bad_entry"));
base::FilePath filename = cache_path_.AppendASCII("data_1");
base::DeleteFile(filename);
net::TestCompletionCallback cb;
bool prev = base::ThreadRestrictions::SetIOAllowed(false);
std::unique_ptr<disk_cache::BackendImpl> cache(
std::make_unique<disk_cache::BackendImpl>(cache_path_, nullptr, nullptr,
net::DISK_CACHE, nullptr));
int rv = cache->Init(cb.callback());
EXPECT_THAT(cb.GetResult(rv), IsError(net::ERR_FAILED));
base::ThreadRestrictions::SetIOAllowed(prev);
cache.reset();
DisableIntegrityCheck();
}
TEST_F(DiskCacheBackendTest, MemCacheMemoryDump) {
SetMemoryOnlyMode();
BackendBasics();
base::trace_event::MemoryDumpArgs args = {
base::trace_event::MemoryDumpLevelOfDetail::BACKGROUND};
base::trace_event::ProcessMemoryDump pmd(args);
base::trace_event::MemoryAllocatorDump* parent =
pmd.CreateAllocatorDump("net/url_request_context/main/0x123/http_cache");
ASSERT_LT(0u, cache_->DumpMemoryStats(&pmd, parent->absolute_name()));
EXPECT_EQ(2u, pmd.allocator_dumps().size());
const base::trace_event::MemoryAllocatorDump* sub_dump =
pmd.GetAllocatorDump(parent->absolute_name() + "/memory_backend");
ASSERT_NE(nullptr, sub_dump);
using MADEntry = base::trace_event::MemoryAllocatorDump::Entry;
const std::vector<MADEntry>& entries = sub_dump->entries();
ASSERT_THAT(
entries,
Contains(Field(&MADEntry::name,
Eq(base::trace_event::MemoryAllocatorDump::kNameSize))));
ASSERT_THAT(entries,
Contains(Field(&MADEntry::name, Eq("mem_backend_max_size"))));
ASSERT_THAT(entries,
Contains(Field(&MADEntry::name, Eq("mem_backend_size"))));
}
TEST_F(DiskCacheBackendTest, SimpleCacheMemoryDump) {
simple_cache_mode_ = true;
BackendBasics();
base::trace_event::MemoryDumpArgs args = {
base::trace_event::MemoryDumpLevelOfDetail::BACKGROUND};
base::trace_event::ProcessMemoryDump pmd(args);
base::trace_event::MemoryAllocatorDump* parent =
pmd.CreateAllocatorDump("net/url_request_context/main/0x123/http_cache");
ASSERT_LT(0u, cache_->DumpMemoryStats(&pmd, parent->absolute_name()));
EXPECT_EQ(2u, pmd.allocator_dumps().size());
const base::trace_event::MemoryAllocatorDump* sub_dump =
pmd.GetAllocatorDump(parent->absolute_name() + "/simple_backend");
ASSERT_NE(nullptr, sub_dump);
using MADEntry = base::trace_event::MemoryAllocatorDump::Entry;
const std::vector<MADEntry>& entries = sub_dump->entries();
ASSERT_THAT(entries,
ElementsAre(Field(
&MADEntry::name,
Eq(base::trace_event::MemoryAllocatorDump::kNameSize))));
}
TEST_F(DiskCacheBackendTest, BlockFileCacheMemoryDump) {
// TODO(jkarlin): If the blockfile cache gets memory dump support, update
// this test.
BackendBasics();
base::trace_event::MemoryDumpArgs args = {
base::trace_event::MemoryDumpLevelOfDetail::BACKGROUND};
base::trace_event::ProcessMemoryDump pmd(args);
base::trace_event::MemoryAllocatorDump* parent =
pmd.CreateAllocatorDump("net/url_request_context/main/0x123/http_cache");
ASSERT_EQ(0u, cache_->DumpMemoryStats(&pmd, parent->absolute_name()));
EXPECT_EQ(1u, pmd.allocator_dumps().size());
}
TEST_F(DiskCacheBackendTest, MemoryListensToMemoryPressure) {
const int kLimit = 16 * 1024;
const int kEntrySize = 256;
SetMaxSize(kLimit);
SetMemoryOnlyMode();
InitCache();
// Fill in to about 80-90% full.
scoped_refptr<net::IOBuffer> buffer =
base::MakeRefCounted<net::IOBuffer>(kEntrySize);
CacheTestFillBuffer(buffer->data(), kEntrySize, false);
for (int i = 0; i < 0.9 * (kLimit / kEntrySize); ++i) {
disk_cache::Entry* entry = nullptr;
ASSERT_EQ(net::OK, CreateEntry(base::NumberToString(i), &entry));
EXPECT_EQ(kEntrySize,
WriteData(entry, 0, 0, buffer.get(), kEntrySize, true));
entry->Close();
}
EXPECT_GT(CalculateSizeOfAllEntries(), 0.8 * kLimit);
// Signal low-memory of various sorts, and see how small it gets.
base::MemoryPressureListener::NotifyMemoryPressure(
base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE);
base::RunLoop().RunUntilIdle();
EXPECT_LT(CalculateSizeOfAllEntries(), 0.5 * kLimit);
base::MemoryPressureListener::NotifyMemoryPressure(
base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL);
base::RunLoop().RunUntilIdle();
EXPECT_LT(CalculateSizeOfAllEntries(), 0.1 * kLimit);
}
TEST_F(DiskCacheBackendTest, ExternalFiles) {
InitCache();
// First, let's create a file on the folder.
base::FilePath filename = cache_path_.AppendASCII("f_000001");
const int kSize = 50;
scoped_refptr<net::IOBuffer> buffer1 =
base::MakeRefCounted<net::IOBuffer>(kSize);
CacheTestFillBuffer(buffer1->data(), kSize, false);
ASSERT_EQ(kSize, base::WriteFile(filename, buffer1->data(), kSize));
// Now let's create a file with the cache.
disk_cache::Entry* entry;
ASSERT_THAT(CreateEntry("key", &entry), IsOk());
ASSERT_EQ(0, WriteData(entry, 0, 20000, buffer1.get(), 0, false));
entry->Close();
// And verify that the first file is still there.
scoped_refptr<net::IOBuffer> buffer2(
base::MakeRefCounted<net::IOBuffer>(kSize));
ASSERT_EQ(kSize, base::ReadFile(filename, buffer2->data(), kSize));
EXPECT_EQ(0, memcmp(buffer1->data(), buffer2->data(), kSize));
}
// Tests that we deal with file-level pending operations at destruction time.
void DiskCacheBackendTest::BackendShutdownWithPendingFileIO(bool fast) {
ASSERT_TRUE(CleanupCacheDir());
uint32_t flags = disk_cache::kNoBuffering;
if (!fast)
flags |= disk_cache::kNoRandom;
if (!simple_cache_mode_)
UseCurrentThread();
CreateBackend(flags);
net::TestCompletionCallback cb;
int rv = GeneratePendingIO(&cb);
// The cache destructor will see one pending operation here.
cache_.reset();
if (rv == net::ERR_IO_PENDING) {
if (fast || simple_cache_mode_)
EXPECT_FALSE(cb.have_result());
else
EXPECT_TRUE(cb.have_result());
}
base::RunLoop().RunUntilIdle();
#if !defined(OS_IOS)
// Wait for the actual operation to complete, or we'll keep a file handle that
// may cause issues later. Note that on iOS systems even though this test
// uses a single thread, the actual IO is posted to a worker thread and the
// cache destructor breaks the link to reach cb when the operation completes.
rv = cb.GetResult(rv);
#endif
}
TEST_F(DiskCacheBackendTest, ShutdownWithPendingFileIO) {
BackendShutdownWithPendingFileIO(false);
}
// Here and below, tests that simulate crashes are not compiled in LeakSanitizer
// builds because they contain a lot of intentional memory leaks.
#if !defined(LEAK_SANITIZER)
// We'll be leaking from this test.
TEST_F(DiskCacheBackendTest, ShutdownWithPendingFileIO_Fast) {
// The integrity test sets kNoRandom so there's a version mismatch if we don't
// force new eviction.
SetNewEviction();
BackendShutdownWithPendingFileIO(true);
}
#endif
// See crbug.com/330074
#if !defined(OS_IOS)
// Tests that one cache instance is not affected by another one going away.
TEST_F(DiskCacheBackendTest, MultipleInstancesWithPendingFileIO) {
base::ScopedTempDir store;
ASSERT_TRUE(store.CreateUniqueTempDir());
net::TestCompletionCallback cb;
std::unique_ptr<disk_cache::Backend> extra_cache;
int rv = disk_cache::CreateCacheBackend(
net::DISK_CACHE, net::CACHE_BACKEND_DEFAULT, store.GetPath(), 0,
disk_cache::ResetHandling::kNeverReset,
/* net_log = */ nullptr, &extra_cache, cb.callback());