HttpFiles.swift 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import Foundation
  2. @testable import Trio
  3. /// Helper struct to download files from localhost via HTTP. Must have a HTTP server
  4. /// running on port 8123 that supports listing files and downloading files.
  5. ///
  6. /// You can set two environment variables `HTTP_FILES_OFFSET` and `HTTP_FILES_LENGTH`
  7. /// to implement paging
  8. ///
  9. /// This struct is only useful during testing as it is missing a number of error checks
  10. struct HttpFiles {
  11. static func listFiles() async throws -> [String] {
  12. let url = URL(string: "http://localhost:8123/list")!
  13. let (data, _) = try await URLSession.shared.data(from: url)
  14. let allFiles = try JSONDecoder().decode([String].self, from: data)
  15. let files: [String]
  16. let env = ProcessInfo.processInfo.environment
  17. if let offsetString = env["HTTP_FILES_OFFSET"], let lengthString = env["HTTP_FILES_LENGTH"], let offset = Int(offsetString), let length = Int(lengthString) {
  18. // Both variables exist and are valid integers
  19. let endIndex = min(offset + length, allFiles.count)
  20. let startIndex = min(offset, allFiles.count)
  21. files = Array(allFiles[startIndex..<endIndex])
  22. } else {
  23. files = allFiles
  24. }
  25. return files
  26. }
  27. static func downloadFile(at: String) async throws -> AlgorithmComparison {
  28. let decoder = JSONDecoder()
  29. decoder.dateDecodingStrategy = .secondsSince1970
  30. let dataUrl = URL(string: "http://localhost:8123\(at)")!
  31. let (data, _) = try await URLSession.shared.data(from: dataUrl)
  32. return try decoder.decode(AlgorithmComparison.self, from: data)
  33. }
  34. }