Run.swift 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. /*
  2. * Copyright 2025 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. import ArgumentParser
  17. import Foundation
  18. import Logging
  19. import Util
  20. extension Tests {
  21. /// Command for running the integration tests of a given SDK.
  22. struct Run: ParsableCommand {
  23. nonisolated(unsafe) static var configuration = CommandConfiguration(
  24. abstract: "Run the integration tests for a given SDK.",
  25. usage: """
  26. tests run [--overwrite] [--secrets <file_path>] [--xcode <version_or_path>] [--platforms <platforms> ...] [<sdk>]
  27. tests run --xcode Xcode_16.4.0 --platforms iOS --platforms macOS AI
  28. tests run --xcode "/Applications/Xcode_15.0.0.app" --platforms tvOS Storage
  29. tests run --overwrite --secrets ./scripts/secrets/AI.json AI
  30. """,
  31. discussion: """
  32. If multiple Xcode versions are installed, you must specify an Xcode version manually via the
  33. 'xcode' option. If you run the script without doing so, the script will log an error message
  34. that contains all the Xcode versions installed, telling you to manually specify the 'xcode' option.
  35. Note that Xcode versions can be specified as either the application name, or a full path. For
  36. example, the following are both valid:
  37. "Xcode_16.4.0" and "/Applications/Xcode_16.4.0.app".
  38. If your tests have encrypted secret files, you can pass a json file to the script via the
  39. 'secrets' option. The script will automatically decrypt them before running the tests, and
  40. delete them after running the tests. You'll also need to provide the password that the secret
  41. files were encrypted with via the 'secrets_passphrase' environment variable. The json file
  42. should be an array of json elements in the format of:
  43. { encrypted: <path-to-encrypted-file>, destination: <where-to-output-decrypted-file> }
  44. If you pass a secret file, but decrypted files already exist at the destination, the script
  45. will NOT overwrite them. The script will also not delete these files either. If you want
  46. the script to overwrite and delete secret files, regardless if they existed before the script
  47. ran, you can pass the 'overwrite' flag.
  48. """,
  49. )
  50. @Option(
  51. help:
  52. """
  53. Xcode version to run tests against. \
  54. Can be either the application name, or a full path (eg; "Xcode_16.4.0" or "/Applications/Xcode_16.4.0.app").
  55. By default, the script will look for your local Xcode installation.
  56. """
  57. )
  58. var xcode: String = ""
  59. @Option(help: "Platforms to run rests on.")
  60. var platforms: [Platform] = [.iOS]
  61. @Option(help: "Path to a json file containing an array of secret files to use, if any.")
  62. var secrets: String? = nil
  63. @Flag(help: "Overwrite existing decrypted secret files.")
  64. var overwrite: Bool = false
  65. @Argument(
  66. help: """
  67. The SDK to run integration tests for.
  68. There should be a build target for the SDK that follows the format "Firebase{SDK}Integration"
  69. """
  70. )
  71. var sdk: String
  72. static let log: Logger = .init(label: "Tests::Run")
  73. private var log: Logger { Self.log }
  74. /// A path to the Xcode to use.
  75. ///
  76. /// Only populated after `validate()` runs.
  77. private var xcodePath: String = ""
  78. mutating func validate() throws {
  79. if xcode.isEmpty {
  80. try findAndValidateXcodeOnDisk()
  81. } else {
  82. try validateProvidedXcode()
  83. }
  84. }
  85. /// When the `xcode` option isn't provided, try to find an installation on disk.
  86. private mutating func findAndValidateXcodeOnDisk() throws {
  87. let xcodes = try findXcodeVersions()
  88. guard xcodes.count == 1 else {
  89. let formattedXcodes = xcodes.map { $0.path(percentEncoded: false) }
  90. log.error(
  91. "Multiple Xcode versions found.",
  92. metadata: ["versions": "\(formattedXcodes)"]
  93. )
  94. throw ValidationError(
  95. "Multiple Xcode installations found. Explicitly pass the 'xcode' option to specify which to use."
  96. )
  97. }
  98. xcodePath = xcodes[0].path()
  99. log.debug("Found Xcode installation", metadata: ["path": "\(xcodePath)"])
  100. }
  101. /// When the `xcode` option is provided, ensure it exists.
  102. ///
  103. /// The `xcode` argument can be either a full path to the application, or just the application
  104. /// name.
  105. private mutating func validateProvidedXcode() throws {
  106. if xcode.hasSuffix(".app") {
  107. // it's a full path to the Xcode, just ensure it exists
  108. guard FileManager.default.fileExists(atPath: xcode) else {
  109. throw ValidationError("Xcode application not found at path: \(xcode)")
  110. }
  111. xcodePath = URL(filePath: xcode).path()
  112. } else {
  113. // it's the application name, find an Xcode installation that matches
  114. let xcodes = try findXcodeVersions()
  115. guard
  116. let match = xcodes.first(where: {
  117. $0.path(percentEncoded: false).contains("\(xcode).app")
  118. })
  119. else {
  120. let formattedXcodes = xcodes.map { $0.path(percentEncoded: false) }
  121. log.error("Invalid Xcode specified.",
  122. metadata: ["versions": "\(formattedXcodes)"])
  123. throw ValidationError(
  124. "Failed to find an Xcode installation that matches: \(xcode)"
  125. )
  126. }
  127. xcodePath = match.path()
  128. log.debug("Found matching Xcode", metadata: ["path": "\(xcodePath)"])
  129. }
  130. }
  131. private func findXcodeVersions() throws -> [URL] {
  132. let applicationDirs = FileManager.default.urls(
  133. for: .applicationDirectory, in: .allDomainsMask
  134. ).filter { url in
  135. // file manager lists application dirs that CAN exist, so we should check if they actually
  136. // do exist before trying to get their contents
  137. let exists = FileManager.default.fileExists(atPath: url.path())
  138. if !exists {
  139. log.debug(
  140. "Application directory doesn't exists, so we're skipping it.",
  141. metadata: ["directory": "\(url.path())"]
  142. )
  143. }
  144. return exists
  145. }
  146. log.debug(
  147. "Searching application directories for Xcode installations.",
  148. metadata: ["directories": "\(applicationDirs)"]
  149. )
  150. let allApplications = try applicationDirs.flatMap { URL in
  151. try FileManager.default.contentsOfDirectory(
  152. at: URL, includingPropertiesForKeys: nil
  153. )
  154. }
  155. let xcodes = allApplications.filter { file in
  156. let isXcode = file.lastPathComponent.contains(/Xcode.*\.app/)
  157. if !isXcode {
  158. log.debug(
  159. "Application isn't an Xcode installation, so we're skipping it.",
  160. metadata: ["application": "\(file.lastPathComponent)"]
  161. )
  162. }
  163. return isXcode
  164. }
  165. guard !xcodes.isEmpty else {
  166. throw ValidationError(
  167. "Failed to find any Xcode versions installed. Please install Xcode."
  168. )
  169. }
  170. log.debug("Found Xcode installations.", metadata: ["installations": "\(xcodes)"])
  171. return xcodes
  172. }
  173. mutating func run() throws {
  174. var secretFiles: [SecretFile] = []
  175. defer {
  176. // ensure secret files are deleted, regardless of test result
  177. for file in secretFiles {
  178. do {
  179. log.debug("Deleting secret file", metadata: ["file": "\(file.destination)"])
  180. try FileManager.default.removeItem(atPath: file.destination)
  181. } catch {
  182. log.error(
  183. "Failed to delete secret file.",
  184. metadata: [
  185. "file": "\(file.destination)",
  186. "error": "\(error.localizedDescription)",
  187. ]
  188. )
  189. }
  190. }
  191. }
  192. // decrypt secrets if we need to
  193. if let secrets {
  194. var args = ["--json"]
  195. if overwrite {
  196. args.append("--overwrite")
  197. }
  198. args.append(secrets)
  199. var decrypt = try Decrypt.parse(args)
  200. try decrypt.validate()
  201. // save the secret files to delete later
  202. secretFiles = decrypt.files
  203. try decrypt.run()
  204. }
  205. let buildScript = URL(filePath: "scripts/build.sh", relativeTo: URL.currentDirectory())
  206. for platform in platforms {
  207. log.info(
  208. "Running integration tests",
  209. metadata: ["sdk": "\(sdk)", "platform": "\(platform)"]
  210. )
  211. // instead of using xcode-select (which requires sudo), we can use the env variable
  212. // `DEVELOPER_DIR` to point to our target xcode
  213. let build = Process(
  214. buildScript.path(percentEncoded: false),
  215. env: ["DEVELOPER_DIR": "\(xcodePath)/Contents/Developer"],
  216. inheritEnvironment: true
  217. )
  218. let exitCode = try build.runWithSignals([
  219. "Firebase\(sdk)Integration", "\(platform)",
  220. ])
  221. guard exitCode == 0 else {
  222. log.error(
  223. "Failed to run integration tests.",
  224. metadata: ["sdk": "\(sdk)", "platform": "\(platform)"]
  225. )
  226. throw ExitCode(exitCode)
  227. }
  228. }
  229. }
  230. }
  231. }
  232. /// Apple platforms that tests can be ran under.
  233. enum Platform: String, Codable, ExpressibleByArgument, CaseIterable {
  234. case iOS
  235. case iPad
  236. case macOS
  237. case tvOS
  238. case watchOS
  239. case visionOS
  240. }