1 /* 2 * Copyright (C) 2009 The Android Open Source Project 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 17 package android.os.cts; 18 19 import static org.junit.Assert.fail; 20 21 import android.os.ParcelFileDescriptor; 22 import android.os.ParcelFileDescriptor.AutoCloseOutputStream; 23 import android.platform.test.annotations.AppModeSdkSandbox; 24 25 import androidx.test.runner.AndroidJUnit4; 26 27 import org.junit.Test; 28 import org.junit.runner.RunWith; 29 30 import java.io.FileOutputStream; 31 import java.io.IOException; 32 import java.lang.ref.Reference; 33 import java.nio.channels.FileLock; 34 35 @AppModeSdkSandbox(reason = "Allow test in the SDK sandbox (does not prevent other modes).") 36 @RunWith(AndroidJUnit4.class) 37 public class ParcelFileDescriptor_AutoCloseOutputStreamTest { 38 @Test testAutoCloseOutputStream()39 public void testAutoCloseOutputStream() throws Exception { 40 ParcelFileDescriptor pf = ParcelFileDescriptorTest.makeParcelFileDescriptor(); 41 42 AutoCloseOutputStream out = new AutoCloseOutputStream(pf); 43 44 out.write(2); 45 46 out.close(); 47 48 try { 49 out.write(2); 50 fail("Failed to throw exception."); 51 } catch (IOException e) { 52 // expected 53 } 54 } 55 56 @Test testCloseOrdering()57 public void testCloseOrdering() throws Exception { 58 // b/118316956: Make sure that we close the OutputStream before we close the PFD. 59 ParcelFileDescriptor pfd = ParcelFileDescriptorTest.makeParcelFileDescriptor(); 60 FileLock l = null; 61 try (FileOutputStream out = new AutoCloseOutputStream(pfd)) { 62 l = out.getChannel().lock(); 63 } finally { 64 Reference.reachabilityFence(l); 65 } 66 } 67 } 68