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.common.testing; 17 18 import android.net.Uri; 19 import com.google.android.libraries.mobiledatadownload.file.backends.FileUri; 20 import java.io.IOException; 21 import org.junit.rules.ExternalResource; 22 import org.junit.rules.TemporaryFolder; 23 24 /** 25 * The TemporaryUri Rule allows creation of file: scheme Uris that should be deleted when the test 26 * method finishes (whether it passes or fails). This is intended to be the Uri equivalent of the 27 * built-in TemporaryFolder rule. Example of usage: 28 * 29 * <pre>{@code 30 * public final class TestClass { 31 * @Rule public TemporaryUri tmpUri = new TemporaryUri(); 32 * 33 * @Test 34 * public void test() throws IOException { 35 * Uri uri = tmpUri.newUri(); 36 * } 37 * } 38 * }</pre> 39 */ 40 public final class TemporaryUri extends ExternalResource { 41 42 private final TemporaryFolder tmpFolder = new TemporaryFolder(); 43 44 @Override before()45 protected void before() throws Throwable { 46 tmpFolder.create(); 47 } 48 49 @Override after()50 protected void after() { 51 tmpFolder.delete(); 52 } 53 54 /** Returns a file: Uri to a new temporary file. */ newUri()55 public Uri newUri() throws IOException { 56 return FileUri.fromFile(tmpFolder.newFile()); 57 } 58 59 /** Returns a file: Uri builder to a new temporary file. */ newUriBuilder()60 public FileUri.Builder newUriBuilder() throws IOException { 61 return FileUri.builder().fromFile(tmpFolder.newFile()); 62 } 63 64 /** Returns a file: Uri to a new temporary folder. */ newDirectoryUri()65 public Uri newDirectoryUri() throws IOException { 66 return FileUri.fromFile(tmpFolder.newFolder()); 67 } 68 69 /** Returns the file: Uri of the directory under which other Uris are created. */ getRootUri()70 public Uri getRootUri() { 71 return FileUri.fromFile(tmpFolder.getRoot()); 72 } 73 74 /** Returns a file: Uri builder of the directory under which other Uris are created. */ getRootUriBuilder()75 public FileUri.Builder getRootUriBuilder() { 76 return FileUri.builder().fromFile(tmpFolder.getRoot()); 77 } 78 } 79