/*
 * Copyright 2022 Google LLC
 *
 * 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.libraries.mobiledatadownload.file.openers;

import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import android.net.Uri;
import com.google.android.libraries.mobiledatadownload.file.SynchronousFileStorage;
import com.google.android.libraries.mobiledatadownload.file.common.testing.TemporaryUri;
import com.google.android.libraries.mobiledatadownload.file.spi.Backend;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;

@RunWith(RobolectricTestRunner.class)
public final class ReadStreamOpenerTest {

  private final InputStream backendStream = new ByteArrayInputStream(new byte[1]);
  private SynchronousFileStorage storage;

  @Rule public TemporaryUri tmpUri = new TemporaryUri();

  @Before
  public void setUpStorage() throws Exception {
    Backend mockBackend = mock(Backend.class);
    when(mockBackend.name()).thenReturn("file");
    when(mockBackend.openForRead(any())).thenReturn(backendStream);

    storage = new SynchronousFileStorage(Arrays.asList(mockBackend));
  }

  @Test
  public void open_withoutTransforms_returnsRawBackendStream() throws Exception {
    Uri uri = tmpUri.newUri();

    try (InputStream result = storage.open(uri, ReadStreamOpener.create())) {
      assertThat(result).isEqualTo(backendStream);
    }
  }

  @Test
  public void open_withBufferedIo_returnsBufferedInputStream() throws Exception {
    Uri uri = tmpUri.newUri();

    try (InputStream result = storage.open(uri, ReadStreamOpener.create().withBufferedIo())) {
      assertThat(result).isInstanceOf(BufferedInputStream.class);
    }
  }
}
