SPB Git

Repository Public

Support.swift 4.7 KB 80 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Tests/CoreTests/Support.swift3// Description: Test support: access to the real local SP Drive backend started by Scripts/backend-dev.sh, temporary folders, random files.4import CryptoKit5import Foundation6import XCTest7@testable import SPDriveCore8@testable import SPDriveSync910enum Backend {11    static let env: [String: String] = {12        guard let text = try? String(contentsOfFile: "/tmp/spdrive-backend-dev/env", encoding: .utf8) else { return [:] }13        var out: [String: String] = [:]14        for line in text.split(separator: "\n") { let kv = line.dropFirst("export ".count).split(separator: "=", maxSplits: 1); if kv.count == 2 { out[String(kv[0])] = String(kv[1]) } }15        return out16    }()17    /// The integration tests need the real backend: without it they fail (they are never silently skipped).18    static func require(file: StaticString = #filePath, line: UInt = #line) throws -> (url: URL, token: String) {19        guard let u = env["SPDRIVE_TEST_URL"].flatMap(URL.init(string:)), let t = env["SPDRIVE_TEST_TOKEN"] else {20            XCTFail("backend de test absent : lancer Scripts/backend-dev.sh start", file: file, line: line); throw DriveError.local("no backend")21        }22        return (u, t)23    }24    static func api(token: String? = nil) throws -> APIClient {25        let b = try require()26        return try APIClient(baseURL: b.url, tokens: MemoryTokenStore(token ?? b.token), userAgent: "SPDriveTests/1.0")27    }28    /// Runs Scripts/backend-dev.sh with arguments and returns its output.29    @discardableResult static func script(_ args: String...) throws -> String {30        let p = Process(); p.executableURL = URL(fileURLWithPath: "/bin/bash"); p.arguments = [env["SPDRIVE_TEST_SCRIPT"] ?? ""] + args31        let pipe = Pipe(); p.standardOutput = pipe; p.standardError = pipe32        try p.run()33        let data = pipe.fileHandleForReading.readDataToEndOfFile(); p.waitUntilExit()34        let out = String(data: data, encoding: .utf8) ?? ""35        guard p.terminationStatus == 0 else { throw DriveError.local("script \(args): \(out)") }36        return out.trimmingCharacters(in: .whitespacesAndNewlines)37    }38    static func serverDown() throws { try script("web-stop") }39    static func serverUp() throws { try script("web-start") }40}4142class TempCase: XCTestCase {43    var dir: URL!44    override func setUpWithError() throws {45        dir = FileManager.default.temporaryDirectory.appendingPathComponent("spdrive-tests-\(UUID().uuidString)")46        try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)47    }48    override func tearDownWithError() throws { try? FileManager.default.removeItem(at: dir) }49    func store(_ name: String = "meta.sqlite") throws -> MetadataStore { try MetadataStore(url: dir.appendingPathComponent(name)) }50    /// A file of pseudo-random (incompressible) bytes; returns its SHA-256.51    @discardableResult func randomFile(_ name: String, bytes: Int, seed: UInt64 = .random(in: 0 ... .max)) throws -> (url: URL, sha: String) {52        let url = dir.appendingPathComponent(name)53        FileManager.default.createFile(atPath: url.path, contents: nil)54        let h = try FileHandle(forWritingTo: url); defer { try? h.close() }55        var hasher = SHA256(), left = bytes, state = seed | 156        while left > 0 {57            let n = min(left, 1 << 20)58            var block = Data(count: n)59            block.withUnsafeMutableBytes { raw in60                let p = raw.bindMemory(to: UInt64.self)61                for i in 0..<p.count { state ^= state << 13; state ^= state >> 7; state ^= state << 17; p[i] = state }62            }63            try h.write(contentsOf: block); hasher.update(data: block); left -= n64        }65        return (url, Hashing.hex(hasher.finalize()))66    }67    func text(_ name: String, _ content: String) throws -> URL { let u = dir.appendingPathComponent(name); try Data(content.utf8).write(to: u); return u }68}6970/// Thread-safe box for values collected from progress callbacks.71final class Box<T: Sendable>: @unchecked Sendable {72    private let lock = NSLock(); private var v: T73    init(_ v: T) { self.v = v }74    var value: T { get { lock.withLock { v } } set { lock.withLock { v = newValue } } }75    func update(_ f: (inout T) -> Void) { lock.withLock { f(&v) } }76}77func item(_ id: String, _ name: String, parent: String?, kind: ItemKind = .file, rev: Int64, size: Int64 = 0, starred: Bool = false, trashed: Bool = false, updated: Date = Date()) -> DriveItem {78    DriveItem(id: id, kind: kind, name: name, parentID: parent, size: size, sha256: "", versionID: kind == .file ? "v-\(id)-\(rev)" : nil, updatedAt: updated, starred: starred, trashedAt: trashed ? Date() : nil, trashRoot: trashed, rev: rev)79}80
Files main
Menu

Theme