1 /* 2 * Copyright 2022 Google LLC 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package com.google.android.libraries.mobiledatadownload.file.backends; 17 18 import static com.google.common.truth.Truth.assertThat; 19 import static org.junit.Assert.assertThrows; 20 21 import android.net.Uri; 22 import android.os.ParcelFileDescriptor; 23 import android.util.Pair; 24 import com.google.android.libraries.mobiledatadownload.file.common.MalformedUriException; 25 import java.io.Closeable; 26 import java.io.File; 27 import org.junit.Test; 28 import org.junit.runner.RunWith; 29 import org.junit.runners.JUnit4; 30 31 /** Test {@link com.google.android.libraries.mobiledatadownload.file.backends.FileDescriptorUri}. */ 32 @RunWith(JUnit4.class) 33 public class FileDescriptorUriAndroidTest { 34 35 @Test convenienceMethod_shouldGenerateUriFromPFD()36 public void convenienceMethod_shouldGenerateUriFromPFD() throws Exception { 37 ParcelFileDescriptor stdin = ParcelFileDescriptor.adoptFd(0); 38 Pair<Uri, Closeable> result = FileDescriptorUri.fromParcelFileDescriptor(stdin); 39 assertThat(result.first.getScheme()).isEqualTo("fd"); 40 assertThat(result.first.getSchemeSpecificPart()).isEqualTo("0"); 41 assertThat(FileDescriptorUri.getFd(result.first)).isEqualTo(0); 42 assertThat(result.first.toString()).isEqualTo("fd:0"); 43 } 44 45 @Test close_shouldCloseFd()46 public void close_shouldCloseFd() throws Exception { 47 ParcelFileDescriptor cwd = 48 ParcelFileDescriptor.open(new File("."), ParcelFileDescriptor.MODE_READ_ONLY); 49 Pair<Uri, Closeable> result = FileDescriptorUri.fromParcelFileDescriptor(cwd); 50 51 assertThat(result.first.getScheme()).isEqualTo("fd"); 52 assertThat(FileDescriptorUri.getFd(result.first)).isGreaterThan(0); 53 54 File procFd = new File("/proc/self/fd/" + result.first.getSchemeSpecificPart()); 55 assertThat(procFd.exists()).isTrue(); 56 result.second.close(); 57 assertThat(procFd.exists()).isFalse(); 58 } 59 60 @Test getFd_validatesUri()61 public void getFd_validatesUri() throws Exception { 62 assertThrows(MalformedUriException.class, () -> FileDescriptorUri.getFd(Uri.parse("file:5"))); 63 assertThrows(MalformedUriException.class, () -> FileDescriptorUri.getFd(Uri.parse("fd:"))); 64 assertThrows(MalformedUriException.class, () -> FileDescriptorUri.getFd(Uri.parse("fd:abc"))); 65 } 66 } 67