CacheUtilTest.java 11.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * Copyright (C) 2017 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.android.exoplayer2.upstream.cache;

18 19 20 21 22 23 24 25 26
import static android.net.Uri.EMPTY;
import static android.net.Uri.parse;
import static com.google.android.exoplayer2.C.LENGTH_UNSET;
import static com.google.android.exoplayer2.upstream.cache.CacheAsserts.assertCacheEmpty;
import static com.google.android.exoplayer2.upstream.cache.CacheAsserts.assertCachedData;
import static com.google.android.exoplayer2.upstream.cache.CacheUtil.generateKey;
import static com.google.android.exoplayer2.upstream.cache.CacheUtil.getKey;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
27 28 29

import android.net.Uri;
import com.google.android.exoplayer2.C;
T
tonihei 已提交
30
import com.google.android.exoplayer2.testutil.FakeDataSet;
31 32 33 34 35 36 37
import com.google.android.exoplayer2.testutil.FakeDataSource;
import com.google.android.exoplayer2.testutil.TestUtil;
import com.google.android.exoplayer2.upstream.DataSpec;
import com.google.android.exoplayer2.upstream.cache.CacheUtil.CachingCounters;
import com.google.android.exoplayer2.util.Util;
import java.io.EOFException;
import java.io.File;
38 39 40 41
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
42 43
import org.mockito.Answers;
import org.mockito.Mock;
44 45 46 47
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
48 49 50 51

/**
 * Tests {@link CacheUtil}.
 */
52 53 54
@RunWith(RobolectricTestRunner.class)
@Config(sdk = Config.TARGET_SDK, manifest = Config.NONE)
public final class CacheUtilTest {
55 56 57 58 59 60

  /**
   * Abstract fake Cache implementation used by the test. This class must be public so Mockito can
   * create a proxy for it.
   */
  public abstract static class AbstractFakeCache implements Cache {
O
olly 已提交
61

62 63 64 65 66 67 68 69
    // This array is set to alternating length of cached and not cached regions in tests:
    // spansAndGaps = {<length of 1st cached region>, <length of 1st not cached region>,
    //    <length of 2nd cached region>, <length of 2nd not cached region>, ... }
    // Ideally it should end with a cached region but it shouldn't matter for any code.
    private int[] spansAndGaps;
    private long contentLength;

    private void init() {
O
olly 已提交
70
      spansAndGaps = new int[] {};
71 72 73 74
      contentLength = C.LENGTH_UNSET;
    }

    @Override
E
eguven 已提交
75
    public long getCachedLength(String key, long position, long length) {
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
      for (int i = 0; i < spansAndGaps.length; i++) {
        int spanOrGap = spansAndGaps[i];
        if (position < spanOrGap) {
          long left = Math.min(spanOrGap - position, length);
          return (i & 1) == 1 ? -left : left;
        }
        position -= spanOrGap;
      }
      return -length;
    }

    @Override
    public long getContentLength(String key) {
      return contentLength;
    }
  }

  @Mock(answer = Answers.CALLS_REAL_METHODS) private AbstractFakeCache mockCache;
  private File tempFolder;
  private SimpleCache cache;

97
  @Before
98
  public void setUp() throws Exception {
99
    MockitoAnnotations.initMocks(this);
100
    mockCache.init();
101
    tempFolder = Util.createTempDirectory(RuntimeEnvironment.application, "ExoPlayerTest");
102 103 104
    cache = new SimpleCache(tempFolder, new NoOpCacheEvictor());
  }

105
  @After
106 107 108 109
  public void tearDown() throws Exception {
    Util.recursiveDelete(tempFolder);
  }

110
  @Test
111
  public void testGenerateKey() throws Exception {
112
    assertThat(generateKey(EMPTY)).isNotNull();
113 114 115

    Uri testUri = Uri.parse("test");
    String key = CacheUtil.generateKey(testUri);
116
    assertThat(key).isNotNull();
117 118

    // Should generate the same key for the same input
119
    assertThat(generateKey(testUri)).isEqualTo(key);
120 121

    // Should generate different key for different input
122
    assertThat(key.equals(generateKey(parse("test2")))).isFalse();
123 124
  }

125
  @Test
126 127 128 129
  public void testGetKey() throws Exception {
    Uri testUri = Uri.parse("test");
    String key = "key";
    // If DataSpec.key is present, returns it
130
    assertThat(getKey(new DataSpec(testUri, 0, LENGTH_UNSET, key))).isEqualTo(key);
131
    // If not generates a new one using DataSpec.uri
132 133
    assertThat(getKey(new DataSpec(testUri, 0, LENGTH_UNSET, null)))
        .isEqualTo(generateKey(testUri));
134 135
  }

136
  @Test
137
  public void testGetCachedNoData() throws Exception {
O
olly 已提交
138 139
    CachingCounters counters = new CachingCounters();
    CacheUtil.getCached(new DataSpec(Uri.parse("test")), mockCache, counters);
140 141 142 143

    assertCounters(counters, 0, 0, C.LENGTH_UNSET);
  }

144
  @Test
145 146
  public void testGetCachedDataUnknownLength() throws Exception {
    // Mock there is 100 bytes cached at the beginning
O
olly 已提交
147 148 149
    mockCache.spansAndGaps = new int[] {100};
    CachingCounters counters = new CachingCounters();
    CacheUtil.getCached(new DataSpec(Uri.parse("test")), mockCache, counters);
150 151 152 153

    assertCounters(counters, 100, 0, C.LENGTH_UNSET);
  }

154
  @Test
155 156
  public void testGetCachedNoDataKnownLength() throws Exception {
    mockCache.contentLength = 1000;
O
olly 已提交
157 158
    CachingCounters counters = new CachingCounters();
    CacheUtil.getCached(new DataSpec(Uri.parse("test")), mockCache, counters);
159 160 161 162

    assertCounters(counters, 0, 0, 1000);
  }

163
  @Test
164 165
  public void testGetCached() throws Exception {
    mockCache.contentLength = 1000;
O
olly 已提交
166 167 168
    mockCache.spansAndGaps = new int[] {100, 100, 200};
    CachingCounters counters = new CachingCounters();
    CacheUtil.getCached(new DataSpec(Uri.parse("test")), mockCache, counters);
169 170 171 172

    assertCounters(counters, 300, 0, 1000);
  }

173
  @Test
174 175 176 177
  public void testCache() throws Exception {
    FakeDataSet fakeDataSet = new FakeDataSet().setRandomData("test_data", 100);
    FakeDataSource dataSource = new FakeDataSource(fakeDataSet);

O
olly 已提交
178 179
    CachingCounters counters = new CachingCounters();
    CacheUtil.cache(new DataSpec(Uri.parse("test_data")), cache, dataSource, counters);
180 181 182 183 184

    assertCounters(counters, 0, 100, 100);
    assertCachedData(cache, fakeDataSet);
  }

185
  @Test
186 187 188 189 190 191
  public void testCacheSetOffsetAndLength() throws Exception {
    FakeDataSet fakeDataSet = new FakeDataSet().setRandomData("test_data", 100);
    FakeDataSource dataSource = new FakeDataSource(fakeDataSet);

    Uri testUri = Uri.parse("test_data");
    DataSpec dataSpec = new DataSpec(testUri, 10, 20, null);
O
olly 已提交
192 193
    CachingCounters counters = new CachingCounters();
    CacheUtil.cache(dataSpec, cache, dataSource, counters);
194 195 196 197 198 199 200 201 202

    assertCounters(counters, 0, 20, 20);

    CacheUtil.cache(new DataSpec(testUri), cache, dataSource, counters);

    assertCounters(counters, 20, 80, 100);
    assertCachedData(cache, fakeDataSet);
  }

203
  @Test
204 205 206 207 208 209 210
  public void testCacheUnknownLength() throws Exception {
    FakeDataSet fakeDataSet = new FakeDataSet().newData("test_data")
        .setSimulateUnknownLength(true)
        .appendReadData(TestUtil.buildTestData(100)).endData();
    FakeDataSource dataSource = new FakeDataSource(fakeDataSet);

    DataSpec dataSpec = new DataSpec(Uri.parse("test_data"));
O
olly 已提交
211 212
    CachingCounters counters = new CachingCounters();
    CacheUtil.cache(dataSpec, cache, dataSource, counters);
213 214 215 216 217

    assertCounters(counters, 0, 100, 100);
    assertCachedData(cache, fakeDataSet);
  }

218
  @Test
219 220 221 222 223 224 225 226
  public void testCacheUnknownLengthPartialCaching() throws Exception {
    FakeDataSet fakeDataSet = new FakeDataSet().newData("test_data")
        .setSimulateUnknownLength(true)
        .appendReadData(TestUtil.buildTestData(100)).endData();
    FakeDataSource dataSource = new FakeDataSource(fakeDataSet);

    Uri testUri = Uri.parse("test_data");
    DataSpec dataSpec = new DataSpec(testUri, 10, 20, null);
O
olly 已提交
227 228
    CachingCounters counters = new CachingCounters();
    CacheUtil.cache(dataSpec, cache, dataSource, counters);
229 230 231 232 233 234 235 236 237

    assertCounters(counters, 0, 20, 20);

    CacheUtil.cache(new DataSpec(testUri), cache, dataSource, counters);

    assertCounters(counters, 20, 80, 100);
    assertCachedData(cache, fakeDataSet);
  }

238
  @Test
239 240 241 242 243 244
  public void testCacheLengthExceedsActualDataLength() throws Exception {
    FakeDataSet fakeDataSet = new FakeDataSet().setRandomData("test_data", 100);
    FakeDataSource dataSource = new FakeDataSource(fakeDataSet);

    Uri testUri = Uri.parse("test_data");
    DataSpec dataSpec = new DataSpec(testUri, 0, 1000, null);
O
olly 已提交
245 246
    CachingCounters counters = new CachingCounters();
    CacheUtil.cache(dataSpec, cache, dataSource, counters);
247 248 249 250 251

    assertCounters(counters, 0, 100, 1000);
    assertCachedData(cache, fakeDataSet);
  }

252
  @Test
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
  public void testCacheThrowEOFException() throws Exception {
    FakeDataSet fakeDataSet = new FakeDataSet().setRandomData("test_data", 100);
    FakeDataSource dataSource = new FakeDataSource(fakeDataSet);

    Uri testUri = Uri.parse("test_data");
    DataSpec dataSpec = new DataSpec(testUri, 0, 1000, null);

    try {
      CacheUtil.cache(dataSpec, cache, new CacheDataSource(cache, dataSource),
          new byte[CacheUtil.DEFAULT_BUFFER_SIZE_BYTES], null, 0, null,
          /*enableEOFException*/ true);
      fail();
    } catch (EOFException e) {
      // Do nothing.
    }
  }

270
  @Test
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
  public void testCachePolling() throws Exception {
    final CachingCounters counters = new CachingCounters();
    FakeDataSet fakeDataSet = new FakeDataSet().newData("test_data")
        .appendReadData(TestUtil.buildTestData(100))
        .appendReadAction(new Runnable() {
          @Override
          public void run() {
            assertCounters(counters, 0, 100, 300);
          }
        })
        .appendReadData(TestUtil.buildTestData(100))
        .appendReadAction(new Runnable() {
          @Override
          public void run() {
            assertCounters(counters, 0, 200, 300);
          }
        })
        .appendReadData(TestUtil.buildTestData(100)).endData();
    FakeDataSource dataSource = new FakeDataSource(fakeDataSet);

    CacheUtil.cache(new DataSpec(Uri.parse("test_data")), cache, dataSource, counters);

    assertCounters(counters, 0, 300, 300);
    assertCachedData(cache, fakeDataSet);
  }

297
  @Test
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
  public void testRemove() throws Exception {
    FakeDataSet fakeDataSet = new FakeDataSet().setRandomData("test_data", 100);
    FakeDataSource dataSource = new FakeDataSource(fakeDataSet);

    Uri uri = Uri.parse("test_data");
    CacheUtil.cache(new DataSpec(uri), cache,
        // set maxCacheFileSize to 10 to make sure there are multiple spans
        new CacheDataSource(cache, dataSource, 0, 10),
        new byte[CacheUtil.DEFAULT_BUFFER_SIZE_BYTES], null, 0, null, true);
    CacheUtil.remove(cache, CacheUtil.generateKey(uri));

    assertCacheEmpty(cache);
  }

  private static void assertCounters(CachingCounters counters, int alreadyCachedBytes,
O
olly 已提交
313
      int newlyCachedBytes, int contentLength) {
314 315 316
    assertThat(counters.alreadyCachedBytes).isEqualTo(alreadyCachedBytes);
    assertThat(counters.newlyCachedBytes).isEqualTo(newlyCachedBytes);
    assertThat(counters.contentLength).isEqualTo(contentLength);
317 318 319
  }

}