66 lines
1.8 KiB
Dart
66 lines
1.8 KiB
Dart
|
|
import 'package:flutter_test/flutter_test.dart';
|
||
|
|
import 'package:social_app/data/cache/cache_policy.dart';
|
||
|
|
import 'package:social_app/data/cache/cached_repository.dart';
|
||
|
|
import 'package:social_app/data/cache/hybrid_cache_store.dart';
|
||
|
|
import 'package:social_app/data/cache/memory_cache_store.dart';
|
||
|
|
import 'package:social_app/data/cache/persistent_cache_store.dart';
|
||
|
|
|
||
|
|
class _IntCachedRepository extends CachedRepository<int> {
|
||
|
|
int loadCount = 0;
|
||
|
|
|
||
|
|
_IntCachedRepository({required super.store})
|
||
|
|
: super(
|
||
|
|
policy: const CachePolicy(
|
||
|
|
softTtl: Duration(hours: 1),
|
||
|
|
hardTtl: Duration(hours: 2),
|
||
|
|
minRefreshInterval: Duration(minutes: 10),
|
||
|
|
),
|
||
|
|
);
|
||
|
|
|
||
|
|
Future<int> fetch({bool forceRefresh = false}) {
|
||
|
|
return getOrLoad(
|
||
|
|
key: 'test:number',
|
||
|
|
forceRefresh: forceRefresh,
|
||
|
|
loadFromRemote: () async {
|
||
|
|
loadCount += 1;
|
||
|
|
return loadCount;
|
||
|
|
},
|
||
|
|
);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
void main() {
|
||
|
|
group('CachedRepository', () {
|
||
|
|
test('reads from cache after first load', () async {
|
||
|
|
final repo = _IntCachedRepository(
|
||
|
|
store: HybridCacheStore(
|
||
|
|
memory: MemoryCacheStore(),
|
||
|
|
persistent: PersistentCacheStore(),
|
||
|
|
),
|
||
|
|
);
|
||
|
|
|
||
|
|
final first = await repo.fetch();
|
||
|
|
final second = await repo.fetch();
|
||
|
|
|
||
|
|
expect(first, 1);
|
||
|
|
expect(second, 1);
|
||
|
|
expect(repo.loadCount, 1);
|
||
|
|
});
|
||
|
|
|
||
|
|
test('force refresh bypasses cached value', () async {
|
||
|
|
final repo = _IntCachedRepository(
|
||
|
|
store: HybridCacheStore(
|
||
|
|
memory: MemoryCacheStore(),
|
||
|
|
persistent: PersistentCacheStore(),
|
||
|
|
),
|
||
|
|
);
|
||
|
|
|
||
|
|
await repo.fetch();
|
||
|
|
final refreshed = await repo.fetch(forceRefresh: true);
|
||
|
|
|
||
|
|
expect(refreshed, 2);
|
||
|
|
expect(repo.loadCount, 2);
|
||
|
|
});
|
||
|
|
});
|
||
|
|
}
|