Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Drive pour iPhone et iPad9// File : UITests/DriveUITests.swift10// Description : Interface tests on the simulator against the disposable11// backend: sign-in screens, explorer, folder creation,12// preview, rename, favourites, offline pin, trash and13// restore, search, share link, the secondary screens, and14// the Files app location. Data is prepared through the real15// API; nothing is mocked.16// Module : UITests17// Repository : https://git.spboucher.ai/sp-drive-ios18// Created : 2026-11-1919// Last Modified : 2026-11-1920//21// =============================================================================22// AUTHOR & PROFESSIONAL AFFILIATION23// =============================================================================24//25// Author : Simon-Pierre Boucher26// Position : Professor of Finance27// Institution : Université du Québec en Outaouais (UQO)28// Department : Département des sciences administratives29// Organization : SP Boucher30//31// Website : https://spboucher.ai32// Git : https://git.spboucher.ai33//34// =============================================================================35// OFFICIAL CONTACT DIRECTORY36// =============================================================================37//38// General : info@spboucher.ai39// Professional : contact@spboucher.ai40// Direct : simon@spboucher.ai41// Research : research@spboucher.ai42// Development : dev@spboucher.ai43// Support : support@spboucher.ai44// Security/Admin : admin@spboucher.ai45// Notifications : notifications@spboucher.ai46//47// Preferred Contact: support@spboucher.ai48//49// =============================================================================50// COPYRIGHT & INTELLECTUAL PROPERTY51// =============================================================================52//53// Copyright (c) 202654// Simon-Pierre Boucher55//56// All rights reserved where applicable.57//58// This file is governed by the applicable project license,59// copyright notices, institutional agreements and relevant law.60//61// Unless expressly authorized by the applicable license or62// rights holder, copying, redistribution, sublicensing,63// publication and commercial exploitation are not permitted.64//65// Existing third-party rights and notices remain unaffected.66//67// =============================================================================68// CONFIDENTIALITY & SECURITY69// =============================================================================70//71// Classification : Public72// Distribution : Public repository; use is governed by the project license73// Security Contact : admin@spboucher.ai74//75// Access to this source does not independently grant permission76// to redistribute or disclose confidential materials.77//78// Do not embed credentials, private keys, access tokens,79// certificates or confidential personal information.80//81// =============================================================================82// LICENSE & MAINTENANCE83// =============================================================================84//85// License : None specified (no license file in this repository)86// Maintainer : Simon-Pierre Boucher87// Technical Contact: dev@spboucher.ai88//89// =============================================================================90// END OF SP BOUCHER SOURCE HEADER91// =============================================================================9293import XCTest9495/// Shared rig of the UI tests: launch, screenshots, the real API from the test runner.96class DriveUITestCase: XCTestCase {97 var baseURL: String { ProcessInfo.processInfo.environment["SPDRIVE_TEST_URL"] ?? "" }98 var token: String { ProcessInfo.processInfo.environment["SPDRIVE_TEST_TOKEN_B"] ?? "" }99 var isPad: Bool { UIDevice.current.userInterfaceIdiom == .pad }100101 override func setUpWithError() throws {102 continueAfterFailure = false103 try XCTSkipIf(baseURL.isEmpty || token.isEmpty, "disposable backend not configured: Scripts/test-server.sh up")104 // start from an empty Drive: what earlier runs left at the root goes to the trash, then the trash is emptied105 let root = try api("GET", "/api/v1/folders/root")106 let folders = (root["folders"] as? [[String: Any]] ?? []).compactMap { $0["id"] as? String }107 let files = (root["files"] as? [[String: Any]] ?? []).compactMap { $0["id"] as? String }108 if !folders.isEmpty || !files.isEmpty { try api("POST", "/api/v1/trash", json: ["fileIds": files, "folderIds": folders]) }109 try api("POST", "/api/v1/purge", json: ["all": true])110 }111112 // MARK: Helpers113114 func launch(signedIn: Bool, reset: Bool = true, environment: [String: String] = [:], arguments: [String] = [], language: String = "fr") -> XCUIApplication {115 let app = XCUIApplication()116 app.launchEnvironment = ["SPDRIVE_BASE_URL": baseURL, "SPDRIVE_UITEST": "1", "SPDRIVE_RESET": reset ? "1" : "0", "SPDRIVE_TEST_TOKEN": signedIn ? token : ""].merging(environment) { $1 }117 app.launchArguments = ["-AppleLanguages", "(\(language))", "-AppleLocale", language == "fr" ? "fr_CA" : "en_CA"] + arguments118 app.launch()119 return app120 }121122 func shot(_ name: String) {123 let a = XCTAttachment(screenshot: XCUIScreen.main.screenshot())124 a.name = name125 a.lifetime = .keepAlways126 add(a)127 }128129 /// Calls the real API from the test runner (prepares data, checks what reached the server).130 @discardableResult131 func api(_ method: String, _ path: String, json: [String: Any]? = nil, raw: Data? = nil, headers: [String: String] = [:]) throws -> [String: Any] {132 var r = URLRequest(url: URL(string: baseURL + path)!)133 r.httpMethod = method134 r.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")135 if let json { r.httpBody = try JSONSerialization.data(withJSONObject: json); r.setValue("application/json", forHTTPHeaderField: "Content-Type") }136 else if let raw { r.httpBody = raw; r.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type") }137 else if method != "GET" { r.httpBody = Data("{}".utf8); r.setValue("application/json", forHTTPHeaderField: "Content-Type") }138 for (k, v) in headers { r.setValue(v, forHTTPHeaderField: k) }139 let done = expectation(description: path)140 nonisolated(unsafe) var out: [String: Any] = [:]141 nonisolated(unsafe) var status = 0142 URLSession.shared.dataTask(with: r) { data, response, _ in143 status = (response as? HTTPURLResponse)?.statusCode ?? 0144 out = (data.flatMap { try? JSONSerialization.jsonObject(with: $0) } as? [String: Any]) ?? [:]145 done.fulfill()146 }.resume()147 wait(for: [done], timeout: 30)148 XCTAssertTrue((200..<300).contains(status), "\(method) \(path) → \(status) \(out)")149 return out150 }151152 func seedFolder(_ name: String) throws -> String {153 try XCTUnwrap(api("POST", "/api/v1/folders", json: ["parentId": "root", "name": name, "onConflict": "rename"])["id"] as? String)154 }155156 func seedFile(_ name: String, _ text: String, in folder: String) throws -> String {157 let data = Data(text.utf8)158 let up = try XCTUnwrap(api("POST", "/api/v1/uploads", json: ["folderId": folder, "name": name, "size": data.count])["id"] as? String)159 try api("PATCH", "/api/v1/uploads/\(up)?offset=0", raw: data)160 let file = try XCTUnwrap(api("POST", "/api/v1/uploads/\(up)/complete")["file"] as? [String: Any])161 return try XCTUnwrap(file["id"] as? String)162 }163164 func openSection(_ app: XCUIApplication, _ section: String, tab: String? = nil) {165 if isPad {166 let row = app.descendants(matching: .any)["sidebar.\(section)"].firstMatch167 if !row.waitForExistence(timeout: 3) { app.navigationBars.buttons.firstMatch.tap() } // sidebar collapsed in portrait168 XCTAssertTrue(row.waitForExistence(timeout: 5), "sidebar row \(section)")169 row.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).tap()170 } else if let tab {171 app.tabBars.buttons[tab].tap()172 } else {173 app.tabBars.buttons["Plus"].tap()174 let row = app.descendants(matching: .any)["more.\(section)"].firstMatch175 if !row.waitForExistence(timeout: 2) { app.navigationBars.buttons.firstMatch.tap() } // a previous section is still pushed176 XCTAssertTrue(row.waitForExistence(timeout: 5), "row \(section)")177 row.tap()178 }179 }180181 func item(_ app: XCUIApplication, _ name: String) -> XCUIElement { app.descendants(matching: .any)["item.\(name)"].firstMatch }182183 func apiSync(_ path: String) throws -> [String: Any] {184 var r = URLRequest(url: URL(string: baseURL + path)!)185 r.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")186 let sem = DispatchSemaphore(value: 0)187 nonisolated(unsafe) var out: [String: Any] = [:]188 URLSession.shared.dataTask(with: r) { data, _, _ in out = (data.flatMap { try? JSONSerialization.jsonObject(with: $0) } as? [String: Any]) ?? [:]; sem.signal() }.resume()189 sem.wait()190 return out191 }192}193194final class DriveUITests: DriveUITestCase {195 // MARK: Tests196197 func testSignedOutShowsPasskeyAndDeviceLink() throws {198 let app = launch(signedIn: false)199 XCTAssertTrue(app.buttons["signInPasskey"].waitForExistence(timeout: 15))200 shot("01-connexion")201 app.buttons["signInLink"].tap()202 // the code comes from the real server203 let code = app.staticTexts["linkCode"]204 XCTAssertTrue(code.waitForExistence(timeout: 15))205 XCTAssertNotNil(code.label.range(of: #"^[A-Z0-9]{4}-[A-Z0-9]{4}$"#, options: .regularExpression), code.label)206 shot("02-liaison-appareil")207 }208209 func testExplorerEndToEnd() throws {210 let folderName = "UI \(UUID().uuidString.prefix(6))"211 let folderID = try seedFolder(folderName)212 _ = try seedFile("lisez-moi.txt", "Bonjour depuis le serveur de test.", in: folderID)213 _ = try seedFile("rapport.md", "# Rapport\n\nContenu.", in: folderID)214215 let app = launch(signedIn: true)216 // first sync brings the seeded folder217 let folder = item(app, folderName)218 XCTAssertTrue(folder.waitForExistence(timeout: 30), "seeded folder visible in Mon Drive")219 shot("10-mon-drive")220 folder.tap()221 let file = item(app, "lisez-moi.txt")222 XCTAssertTrue(file.waitForExistence(timeout: 10))223224 // create a folder from the app; it must reach the server225 app.buttons["add"].tap()226 app.buttons["Nouveau dossier"].tap()227 let field = app.alerts.textFields.firstMatch228 XCTAssertTrue(field.waitForExistence(timeout: 5))229 field.typeText("Créé sur iPhone")230 app.alerts.buttons["Créer"].tap()231 XCTAssertTrue(item(app, "Créé sur iPhone").waitForExistence(timeout: 10))232 let created = expectation(description: "folder on server")233 DispatchQueue.global().async {234 for _ in 0..<40 {235 if let r = try? self.apiSync("/api/v1/folders/\(folderID)"), (r["folders"] as? [[String: Any]])?.contains(where: { $0["name"] as? String == "Créé sur iPhone" }) == true { created.fulfill(); return }236 Thread.sleep(forTimeInterval: 0.5)237 }238 }239 wait(for: [created], timeout: 30)240 shot("11-dossier")241242 // open a file: downloaded, verified, shown by QuickLook243 file.tap()244 XCTAssertTrue(app.buttons["Done"].waitForExistence(timeout: 20) || app.buttons["OK"].waitForExistence(timeout: 2) || app.buttons["Terminé"].waitForExistence(timeout: 2), "viewer opened")245 shot("12-apercu")246 for label in ["Done", "OK", "Terminé"] where app.buttons[label].exists { app.buttons[label].tap(); break }247 XCTAssertTrue(file.waitForExistence(timeout: 10))248249 // rename through the context menu250 file.press(forDuration: 1.0)251 shot("13-menu-contextuel")252 app.buttons["Renommer"].tap()253 let rename = app.alerts.textFields.firstMatch254 XCTAssertTrue(rename.waitForExistence(timeout: 5))255 rename.tap()256 if let current = rename.value as? String { rename.typeText(String(repeating: XCUIKeyboardKey.delete.rawValue, count: current.count)) }257 rename.typeText("renomme.txt")258 app.alerts.buttons["Renommer"].tap()259 let renamed = item(app, "renomme.txt")260 XCTAssertTrue(renamed.waitForExistence(timeout: 10))261262 // favourite + keep offline263 renamed.press(forDuration: 1.0)264 app.buttons["Ajouter aux favoris"].tap()265 renamed.press(forDuration: 1.0)266 app.buttons["Garder hors ligne"].tap()267268 // grid layout269 app.buttons["options"].tap()270 app.buttons["Grille"].tap()271 XCTAssertTrue(item(app, "rapport.md").waitForExistence(timeout: 5))272 shot("14-grille")273 app.buttons["options"].tap()274 app.buttons["Liste"].tap()275276 // share link: created on the server, URL shown once277 item(app, "rapport.md").press(forDuration: 1.0)278 app.buttons["Partager par lien…"].tap()279 let create = app.descendants(matching: .any)["share.create"].firstMatch280 if !create.waitForExistence(timeout: 8) { app.swipeUp() } // the form is lazy: on a short sheet the button is below the fold281 XCTAssertTrue(create.waitForExistence(timeout: 10))282 if !create.isHittable { app.swipeUp() }283 create.tap()284 let url = app.descendants(matching: .any)["share.url"].firstMatch285 XCTAssertTrue(url.waitForExistence(timeout: 15), "share URL shown")286 shot("15-lien-de-partage")287 let shares = try api("GET", "/api/v1/auth/state") // session still valid; the list itself is an array, checked below288 XCTAssertEqual(shares["authenticated"] as? Bool, true)289290 // the secondary screens291 app.terminate()292 let again = launch(signedIn: true, reset: false) // relaunch: the local store and the pin survive293 XCTAssertTrue(item(again, folderName).waitForExistence(timeout: 20))294 openSection(again, "offline", tab: "Hors ligne")295 XCTAssertTrue(item(again, "renomme.txt").waitForExistence(timeout: 20) || again.staticTexts["renomme.txt"].waitForExistence(timeout: 5), "pinned file listed offline")296 shot("16-hors-ligne")297 openSection(again, "favorites")298 XCTAssertTrue(item(again, "renomme.txt").waitForExistence(timeout: 10))299 shot("17-favoris")300 openSection(again, "shared")301 XCTAssertTrue(again.staticTexts["rapport.md"].waitForExistence(timeout: 15), "share link listed")302 shot("18-partages")303 openSection(again, "transfers")304 shot("19-transferts")305 openSection(again, "settings")306 XCTAssertTrue(again.descendants(matching: .any)["settings.signOut"].firstMatch.waitForExistence(timeout: 10) || again.staticTexts["Stockage"].waitForExistence(timeout: 5))307 shot("20-parametres")308 }309310 func testTrashRestoreAndSearch() throws {311 let folderName = "Corbeille \(UUID().uuidString.prefix(6))"312 let folderID = try seedFolder(folderName)313 let fileID = try seedFile("a-supprimer.txt", "bientôt à la corbeille", in: folderID)314 _ = try seedFile("Été budget.csv", "a,b\n1,2\n", in: folderID)315316 let app = launch(signedIn: true)317 XCTAssertTrue(item(app, folderName).waitForExistence(timeout: 30))318 item(app, folderName).tap()319 let file = item(app, "a-supprimer.txt")320 XCTAssertTrue(file.waitForExistence(timeout: 10))321 file.press(forDuration: 1.0)322 app.buttons["Supprimer du Drive"].tap()323 let confirm = app.alerts.buttons["Supprimer du Drive"].firstMatch324 XCTAssertTrue(confirm.waitForExistence(timeout: 5))325 shot("30-confirmation-suppression")326 confirm.tap()327 XCTAssertTrue(file.waitForNonExistence(timeout: 10))328329 // on the server the file is in the trash, not destroyed330 let trashed = expectation(description: "trashed on server")331 DispatchQueue.global().async {332 for _ in 0..<40 {333 if let r = try? self.apiSync("/api/v1/files/\(fileID)"), let f = r["file"] as? [String: Any], !(f["trashedAt"] is NSNull), f["trashedAt"] != nil { trashed.fulfill(); return }334 Thread.sleep(forTimeInterval: 0.5)335 }336 }337 wait(for: [trashed], timeout: 30)338339 openSection(app, "trash")340 let inTrash = app.staticTexts["a-supprimer.txt"].firstMatch341 XCTAssertTrue(inTrash.waitForExistence(timeout: 10))342 shot("31-corbeille")343 inTrash.press(forDuration: 1.0)344 // the context menu's entry (a toolbar button of the same name exists while selecting)345 XCTAssertTrue(app.buttons["Restaurer"].firstMatch.waitForExistence(timeout: 5))346 let restore = app.buttons.matching(identifier: "Restaurer").allElementsBoundByIndex.first(where: { $0.isHittable }) ?? app.buttons["Restaurer"].firstMatch347 restore.tap()348 XCTAssertTrue(inTrash.waitForNonExistence(timeout: 15))349350 // search: accent-insensitive, local index351 if isPad { app.buttons["Rechercher"].firstMatch.tap() } else { app.tabBars.buttons["Recherche"].tap() }352 let search = app.searchFields.firstMatch353 XCTAssertTrue(search.waitForExistence(timeout: 10))354 search.tap()355 search.typeText("ete budget")356 XCTAssertTrue(item(app, "Été budget.csv").waitForExistence(timeout: 10))357 shot("32-recherche")358 }359360 /// SP Drive must be a location of the Files app, listing the Drive through the File Provider extension.361 func testFilesAppShowsSPDriveLocation() throws {362 let folderName = "Fichiers \(UUID().uuidString.prefix(6))"363 let folderID = try seedFolder(folderName)364 _ = try seedFile("depuis-fichiers.txt", "visible dans l'app Fichiers", in: folderID)365 let app = launch(signedIn: true)366 XCTAssertTrue(item(app, folderName).waitForExistence(timeout: 30)) // signed in: the domain is registered367368 let files = XCUIApplication(bundleIdentifier: "com.apple.DocumentsApp")369 files.launchArguments = ["-AppleLanguages", "(fr)", "-AppleLocale", "fr_CA"]370 files.launch()371 // go to the root of the browse tab (its name changed across iOS versions)372 for name in ["Explorer", "Parcourir", "Browse"] {373 // a tab bar at the bottom on iPhone, a segmented bar at the top on iPad374 let tab = files.tabBars.buttons[name].exists ? files.tabBars.buttons[name] : files.buttons[name].firstMatch375 guard tab.waitForExistence(timeout: name == "Explorer" ? 10 : 1) else { continue }376 tab.tap()377 if tab.exists && tab.isHittable { tab.tap() } // a second tap returns to the root of the tab (iPhone); on iPad the bar collapses378 break379 }380 let location = files.descendants(matching: .any).matching(NSPredicate(format: "label == %@", "SP Drive")).firstMatch381 if !location.waitForExistence(timeout: 8) {382 // iOS lists a new provider's location switched off: turn it on, as a user does once383 let d = XCTAttachment(string: files.debugDescription); d.name = "files-hierarchy"; d.lifetime = .keepAlways; add(d)384 shot("39-fichiers-avant-activation")385 }386 XCTAssertTrue(location.waitForExistence(timeout: 20), "SP Drive listed among the locations of Files")387 shot("40-fichiers-emplacements")388 location.tap()389 // first use: iOS asks the owner's consent before a new provider's location can be browsed390 let enable = files.buttons["Activer"].exists ? files.buttons["Activer"] : files.buttons["Turn On"]391 if enable.waitForExistence(timeout: 4) { shot("40b-fichiers-activer"); enable.tap() }392 let seeded = files.descendants(matching: .any).matching(NSPredicate(format: "label BEGINSWITH %@", folderName)).firstMatch393 XCTAssertTrue(seeded.waitForExistence(timeout: 40), "the Drive's folder is listed by the File Provider extension")394 shot("41-fichiers-contenu")395 seeded.tap()396 let file = files.descendants(matching: .any).matching(NSPredicate(format: "label BEGINSWITH %@", "depuis-fichiers")).firstMatch397 XCTAssertTrue(file.waitForExistence(timeout: 30))398 shot("42-fichiers-dossier")399 }400}401