1 /* 2 * Copyright (C) 2023 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 com.android.tools.metalava.testing 18 19 import com.android.tools.lint.checks.infrastructure.TestFile 20 import java.io.File 21 import org.junit.Assert.assertNotNull 22 import org.junit.rules.TemporaryFolder 23 24 /** Provides helper functions for a test class that has a [TemporaryFolder] rule. */ 25 interface TemporaryFolderOwner { 26 27 val temporaryFolder: TemporaryFolder 28 29 /** 30 * Given an array of [TestFile] get a folder called "project" (creating it if it is empty), 31 * write the files to the folder and then return the folder. 32 */ createProjectnull33 fun createProject(files: Array<TestFile>): File { 34 val dir = newFolder("project") 35 36 files.map { it.createFile(dir) }.forEach { assertNotNull(it) } 37 38 return dir 39 } 40 newFoldernull41 fun newFolder(children: String = ""): File { 42 val dir = File(temporaryFolder.root.path, children) 43 return if (dir.exists()) { 44 dir 45 } else { 46 temporaryFolder.newFolder(children) 47 } 48 } 49 newFilenull50 fun newFile(children: String = ""): File { 51 val dir = File(temporaryFolder.root.path, children) 52 return if (dir.exists()) { 53 dir 54 } else { 55 temporaryFolder.newFile(children) 56 } 57 } 58 59 /** Hides path prefixes from /tmp folders used by the testing infrastructure */ cleanupStringnull60 fun cleanupString( 61 string: String, 62 project: File? = null, 63 ): String { 64 var s = string 65 66 if (project != null) { 67 s = s.replace(project.path, "TESTROOT") 68 s = s.replace(project.canonicalPath, "TESTROOT") 69 } 70 71 s = s.replace(temporaryFolder.root.path, "TESTROOT") 72 73 s = s.trim() 74 75 return s 76 } 77 } 78