Repository Public
1import Foundation2import Testing3import SheetCore4import SheetUI5import SheetPython6@testable import FeaturePython78/// Recognises date formats like the real format engine would.9struct TestDisplay: CellDisplayProvider {10 func display(_ value: Value, format: String, maxChars: Int?, date1904: Bool) -> CellDisplay { CellDisplay(text: value.description) }11 func isDateTime(_ format: String) -> Bool { let f = format.lowercased(); return f.contains("yy") || f.contains("hh:") || f.contains("[h]") }12}1314@MainActor func makeSession() -> WorkbookSession {15 PythonPaths.supportDirectory = TestEnv.support16 Workspace.shared.displayProvider = TestDisplay()17 let wb = Workbook(sheetNames: ["Sales", "Other"])18 wb.properties.title = "Test book"19 let s = WorkbookSession(workbook: wb, locale: Locale(identifier: "en_US"))20 s.perform("Setup") { e in21 for (c, h) in ["Category", "Region", "Date", "Units", "Revenue"].enumerated() { e.set(sheet: 0, row: 0, col: c, .value(.text(h))) }22 for i in 0..<40 {23 e.set(sheet: 0, row: i + 1, col: 0, .value(.text(["Hardware", "Software", "Services", "Training"][i % 4])))24 e.set(sheet: 0, row: i + 1, col: 1, .value(.text(["East", "West", "North"][i % 3])))25 e.set(sheet: 0, row: i + 1, col: 2, .value(.number(46023 + Double(i))))26 e.set(sheet: 0, row: i + 1, col: 3, .value(.number(Double(3 + (i * 7) % 23))))27 e.set(sheet: 0, row: i + 1, col: 4, .value(.number(Double(100 + i * 10))))28 }29 e.setStyle(sheet: 0, range: RangeRef(a1: "C2:C41")!) { $0.numberFormat = "yyyy-mm-dd" }30 e.setFormula(sheet: 0, row: 42, col: 4, "=SUM(E2:E41)")31 e.setFormula(sheet: 0, row: 43, col: 4, "=1/0")32 e.set(sheet: 0, row: 44, col: 4, .value(.bool(true)))33 e.set(sheet: 1, row: 0, col: 0, .value(.text("other sheet")))34 }35 s.select(RangeRef(a1: "A1:E41")!, active: CellRef(a1: "A1")!)36 return s37}3839enum TestEnv {40 static let support: URL = {41 let url = FileManager.default.temporaryDirectory.appendingPathComponent("orix-feature-tests-\(UUID().uuidString)", isDirectory: true)42 try? FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)43 atexit { try? FileManager.default.removeItem(at: PythonPaths.supportDirectory) }44 return url45 }()46 static let interpreters = Task { await PythonDiscovery.discover() }47 static var scientific: PythonInterpreter? { get async { await interpreters.value.first { $0.has("pandas") && $0.has("matplotlib") && !$0.isVirtualEnv } } }48 static var any: PythonInterpreter? { get async { let a = await interpreters.value; return a.first { $0.has("pandas") } ?? a.first } }49 static let noPython: Comment = "No Python ≥ 3.9 interpreter found: integration test skipped."50 static let noPandas: Comment = "No interpreter with pandas + matplotlib found: integration test skipped."51}5253@MainActor func cell(_ s: WorkbookSession, _ a1: String, sheet: Int = 0) -> Value {54 let r = CellRef(a1: a1)!55 return s.workbook.sheets[sheet].value(r.row, r.col)56}5758func revenueSum(every step: Int) -> Double {59 var total = 0.060 for i in stride(from: 0, to: 40, by: step) { total += 100 + Double(i) * 10 }61 return total62}6364@MainActor func succeeded(_ m: PythonStudioModel) -> Bool { if case .succeeded = m.status { return true }; return false }65@MainActor func stoppedReason(_ m: PythonStudioModel) -> String? { if case .stopped(let why) = m.status { return why }; return nil }6667/// Runs the selected script through the model's real Run path and waits for it to finish.68@MainActor func runModel(_ model: PythonStudioModel, answer: PythonConsent.Choice? = nil) async {69 await withCheckedContinuation { (c: CheckedContinuation<Void, Never>) in70 model.onRunFinished = { model.onRunFinished = nil; c.resume() }71 model.run()72 if model.consent != nil {73 if let answer, answer != .cancel { model.answerConsent(answer) } else { if let answer { model.answerConsent(answer) }; model.onRunFinished = nil; c.resume() }74 } else if !model.isRunning { model.onRunFinished = nil; c.resume() }75 }76}7778@MainActor @Suite(.serialized) struct HostTests {79 @Test func readsValuesErrorsBlanksAndFlagsDateColumns() async throws {80 let s = makeSession()81 let host = SessionPythonHost(session: s)82 #expect(await host.activeSheetName() == "Sales")83 #expect(await host.sheetNames() == ["Sales", "Other"])84 #expect(await host.selectionA1() == "A1:E41")85 #expect(try await host.usedRange(sheet: nil) == "A1:E45")86 #expect(try await host.usedRange(sheet: "Other") == "A1")87 let d = try await host.readRange(sheet: nil, a1: "A1:E3")88 #expect(d.sheet == "Sales" && d.a1 == "A1:E3" && d.rows.count == 3 && d.rows[0].count == 5)89 #expect(d.rows[0] == [.string("Category"), .string("Region"), .string("Date"), .string("Units"), .string("Revenue")])90 #expect(d.rows[1] == [.string("Hardware"), .string("East"), .number(46023), .number(3), .number(100)])91 #expect(d.dateColumns == [2], "only the column whose numbers all carry a date format")92 let tail = try await host.readRange(sheet: "Sales", a1: "D42:F45")93 let total = revenueSum(every: 1)94 let expected: [[PythonCell]] = [[.null, .null, .null], [.null, .number(total), .null], [.null, .error("#DIV/0!"), .null], [.null, .bool(true), .null]]95 #expect(tail.rows == expected)96 #expect(tail.dateColumns.isEmpty)97 let whole = try await host.readRange(sheet: nil, a1: "A:B")98 #expect(whole.a1 == "A1:B45" && whole.rows.count == 45, "whole columns are clipped to the used range")99 #expect(try await host.readRange(sheet: "Other", a1: "Other!A1").rows == [[.string("other sheet")]])100 await #expect(throws: PythonHostError.self) { try await host.readRange(sheet: "Nope", a1: "A1") }101 await #expect(throws: PythonHostError.self) { try await host.readRange(sheet: nil, a1: "not a range") }102 #expect(try await host.readRange(sheet: nil, a1: "A1:XFD1048576").a1 == "A1:E45", "the whole sheet is clipped to the used range")103 }104105 @Test func mixedColumnIsNotADateColumn() async throws {106 let s = makeSession()107 s.perform("x") { e in e.set(sheet: 0, row: 5, col: 2, .value(.number(7))); e.setStyle(sheet: 0, range: RangeRef(a1: "C6")!) { $0.numberFormat = "0.00" } }108 #expect(try await SessionPythonHost(session: s).readRange(sheet: nil, a1: "A1:E41").dateColumns.isEmpty)109 }110}111112@MainActor @Suite(.serialized) struct WriteApplierTests {113 @Test func appliesValuesFormulasAndDateFormatsAsOneUndoStep() throws {114 let s = makeSession()115 let undoBefore = s.engine.undoLabel116 let writes = [117 PythonWrite(sheet: "Sales", anchorA1: "G1", rows: [[.string("k"), .string("v"), .string("when")], [.string("a"), .number(1.5), .number(46100)], [.null, .bool(false), .number(46101.5)],118 [.error("#N/A"), .string("=not a formula"), .null]],119 formats: [PythonFormatHint(r0: 1, c0: 2, r1: 2, c1: 2, format: "yyyy-mm-dd hh:mm:ss")]),120 PythonWrite(sheet: nil, anchorA1: "G6", rows: [[.string("=SUM(H2:H2)*2"), .string("=G6+1")]], formulas: true),121 PythonWrite(sheet: "Other", anchorA1: "$B$2", rows: [[.number(7)]]),122 PythonWrite(sheet: "Sales", anchorA1: "C2", rows: [[.number(46000)]], formats: [PythonFormatHint(r0: 0, c0: 0, r1: 0, c1: 0, format: "yyyy-mm-dd hh:mm:ss")]),123 ]124 let targets = try PythonWriteApplier.apply(writes, to: s)125 #expect(targets.map(\.range.a1) == ["G1:I4", "G6:H6", "B2", "C2"] && targets.map(\.sheetName) == ["Sales", "Sales", "Other", "Sales"])126 #expect(cell(s, "G1") == .text("k") && cell(s, "H2") == .number(1.5) && cell(s, "G3") == .blank && cell(s, "H3") == .bool(false))127 #expect(cell(s, "G4") == .error(.na) && cell(s, "H4") == .text("=not a formula"), "text stays text in a value write: no formula is created")128 #expect(s.workbook.sheets[0].cell(3, 7)?.formula == nil)129 #expect(cell(s, "G6") == .number(3) && cell(s, "H6") == .number(4) && s.workbook.sheets[0].cell(5, 6)?.formula != nil)130 #expect(cell(s, "B2", sheet: 1) == .number(7))131 func format(_ a1: String) -> String { let r = CellRef(a1: a1)!; return s.workbook.styles[s.workbook.sheets[0].styleID(r.row, r.col)].numberFormat }132 #expect(format("I2") == "yyyy-mm-dd hh:mm:ss" && format("I3") == "yyyy-mm-dd hh:mm:ss" && format("I4") == "General" && format("H2") == "General")133 #expect(format("C2") == "yyyy-mm-dd", "a cell that already shows dates keeps the user's format")134 #expect(s.engine.undoLabel == "Run Python Script")135 #expect(s.selection.primary.a1 == "C1:I6" && s.sheetIndex == 0, "the written area of the last sheet written is selected")136 s.undo()137 #expect(cell(s, "G1") == .blank && cell(s, "G6") == .blank && cell(s, "B2", sheet: 1) == .blank && cell(s, "C2") == .number(46023) && format("I2") == "General")138 #expect(s.engine.undoLabel == undoBefore, "exactly one undo step was added")139 s.redo()140 #expect(cell(s, "H6") == .number(4))141 }142143 @Test func anInvalidBatchWritesNothing() {144 let s = makeSession()145 let before = s.engine.changeCount146 let good = PythonWrite(sheet: "Sales", anchorA1: "G1", rows: [[.number(1)]])147 func fails(_ w: PythonWrite, _ fragment: String) {148 do { try PythonWriteApplier.apply([good, w], to: s); Issue.record("should have thrown") }149 catch { #expect(error.localizedDescription.contains(fragment), "\(error.localizedDescription)") }150 #expect(cell(s, "G1") == .blank && s.engine.changeCount == before, "the valid write of the batch was not applied either")151 }152 fails(PythonWrite(sheet: "Sales", anchorA1: "H1", rows: [[.string("=SUM(")]], formulas: true), "not valid")153 fails(PythonWrite(sheet: "Deleted sheet", anchorA1: "A1", rows: [[.number(1)]]), "no longer exists")154 fails(PythonWrite(sheet: "Sales", anchorA1: "XFD1", rows: [[.number(1), .number(2)]]), "do not fit")155 fails(PythonWrite(sheet: "Sales", anchorA1: "A1048576", rows: [[.number(1)], [.number(2)]]), "do not fit")156 fails(PythonWrite(sheet: "Sales", anchorA1: "nonsense", rows: [[.number(1)]]), "not a valid cell")157 #expect((try? PythonWriteApplier.apply([], to: s))?.isEmpty == true && s.engine.changeCount == before)158 }159160 @Test func largeWriteIsApplied() throws {161 let s = makeSession()162 let rows = (0..<50_000).map { i in [PythonCell.number(Double(i)), .string("r\(i)"), .number(Double(i) * 0.5), .null] }163 let t0 = Date()164 try PythonWriteApplier.apply([PythonWrite(sheet: "Other", anchorA1: "A1", rows: rows)], to: s)165 print(String(format: "APPLY 50 000 × 4 cells as one undo step: %.3f s", Date().timeIntervalSince(t0)))166 #expect(cell(s, "C50000", sheet: 1) == .number(24999.5) && cell(s, "D10", sheet: 1) == .blank)167 s.undo()168 #expect(cell(s, "C50000", sheet: 1) == .blank && cell(s, "A1", sheet: 1) == .text("other sheet"))169 }170}171172@MainActor @Suite(.serialized) struct StudioModelTests {173 func model(_ s: WorkbookSession, interpreter: PythonInterpreter) -> PythonStudioModel {174 let m = PythonStudioStore.model(for: s)175 m.setInterpreters([interpreter])176 return m177 }178179 @Test func registersPaneAndToolsAction() {180 PythonFeature.register()181 #expect(Workspace.shared.panes(.studio).contains { $0.id == "python" && $0.systemImage == "terminal" })182 let action = Workspace.shared.actions(.tools).first { $0.id == "python.studio" }183 let s = makeSession()184 action?.perform(s)185 #expect(s.studioPane == "python")186 #expect(PythonStudioStore.model(for: s) === PythonStudioStore.model(for: s), "one model per session")187 }188189 @Test func modelDoesNotKeepTheSessionAlive() {190 weak var weakSession: WorkbookSession?191 weak var weakModel: PythonStudioModel?192 do { let s = makeSession(); weakSession = s; weakModel = PythonStudioStore.model(for: s); #expect(weakModel != nil) }193 #expect(weakSession == nil && weakModel == nil)194 }195196 @Test func scriptsAreSavedInTheWorkbook() {197 let s = makeSession()198 let m = PythonStudioStore.model(for: s)199 #expect(m.scripts.isEmpty && m.selected == nil)200 let a = m.newScript()201 #expect(a.name == "Script" && m.selectedID == a.id && m.code == PythonSnippets.starter)202 let b = m.newScript()203 #expect(b.name == "Script 2")204 m.userEdited("print('edited')")205 m.rename(b.id, to: " Analysis ")206 m.rename(b.id, to: " ")207 m.duplicate(b.id)208 #expect(m.scripts.map(\.name) == ["Script", "Analysis", "Analysis copy"])209 let stored = PythonScripts.load(from: s.workbook)210 #expect(Set(stored.map(\.name)) == ["Script", "Analysis", "Analysis copy"] && stored.first { $0.name == "Analysis" }?.code == "print('edited')")211 m.delete(a.id)212 #expect(PythonScripts.load(from: s.workbook).count == 2 && m.scripts.count == 2 && m.selected != nil)213 // a second model on the same workbook (as after reopening the file) sees them as untrusted workbook scripts214 let reopened = PythonStudioModel(session: s)215 #expect(reopened.scripts.count == 2 && reopened.scriptStates.values.allSatisfy { $0 == PythonConsent.ScriptState(origin: .workbook) })216 }217218 @Test(.enabled(TestEnv.noPandas) { await TestEnv.scientific != nil })219 func successfulRunAppliesWritesOnceAndCollectsResults() async throws {220 let s = makeSession()221 let m = model(s, interpreter: try #require(await TestEnv.scientific))222 m.newScript(code: """223 import orix224 import matplotlib.pyplot as plt225 df = orix.selection().to_dataframe()226 assert str(df["Date"].dtype).startswith("datetime64"), df.dtypes227 summary = df.groupby("Category")["Revenue"].sum()228 print("rows", len(df))229 orix.show(summary, name="By category")230 plt.plot(df["Units"]); plt.title("Units")231 s = orix.active_sheet()232 s.range("G1").write(summary)233 s.range("J1").write(df["Date"].head(2))234 s.range("G7").write_formula("=SUM(H2:H5)")235 """, name: "Summary")236 let undoBefore = s.engine.undoLabel237 await runModel(m)238 #expect(succeeded(m) && m.changes.count == 3, "\(m.status) \(m.consoleText)")239 #expect(m.consoleText.contains("rows 40") && m.consoleText.contains("Summary"))240 #expect(m.tables.map(\.name) == ["By category"] && m.figures.count == 1 && m.figures[0].title == "Units" && m.figures[0].png.count > 1_000)241 #expect(m.changes.count == 3 && m.changes.allSatisfy(\.applied) && m.changes.map(\.target.range.a1) == ["G1:H5", "J1:K3", "G7"])242 let hardware = revenueSum(every: 4)243 let total = revenueSum(every: 1)244 #expect(cell(s, "G1") == .text("Category") && cell(s, "G2") == .text("Hardware"))245 #expect(cell(s, "H2") == .number(hardware))246 #expect(cell(s, "G7") == .number(total), "the formula was parsed and calculated")247 #expect(cell(s, "K2") == .number(46023) && s.workbook.styles[s.workbook.sheets[0].styleID(1, 10)].numberFormat == "yyyy-mm-dd", "dates come back as serials with a date format")248 #expect(s.engine.undoLabel == "Run Python Script" && m.tab == .plots && m.errorLine == nil)249 #expect(s.selection.primary.a1 == "G1:K7")250 s.undo()251 #expect(cell(s, "G1") == .blank && cell(s, "G7") == .blank && cell(s, "K2") == .blank && s.engine.undoLabel == undoBefore, "one undo reverts the whole run")252 #expect(PythonRunner.existingRunDirectories().isEmpty || !m.figures.isEmpty, "figures are held in memory; the run directory is gone")253 m.refreshHistory()254 #expect(m.history.first?.script == "Summary.py" && m.history.first?.workbook == "Test book" && m.history.first?.outcome == .ok)255 }256257 @Test(.enabled(TestEnv.noPython) { await TestEnv.any != nil })258 func failedRunWritesNothingAndMarksTheLine() async throws {259 let s = makeSession()260 let m = model(s, interpreter: try #require(await TestEnv.any))261 m.newScript(code: "import orix\norix.active_sheet().range('G1').write('never')\nprint('before')\nraise ValueError('boom')\n", name: "Bad")262 let changes = s.engine.changeCount263 await runModel(m)264 #expect(m.status == .failed("ValueError on line 4: boom"), "\(m.status)")265 #expect(m.errorLine == 4 && m.consoleText.contains("before") && m.consoleText.contains("ValueError: boom"))266 #expect(cell(s, "G1") == .blank && s.engine.changeCount == changes, "on failure nothing is written")267 #expect(m.changes.count == 1 && m.changes[0].applied == false && m.changesNote?.contains("nothing was written") == true)268 m.userEdited("print('fixed')")269 #expect(m.errorLine == nil, "the error mark is cleared when the code is edited")270 await runModel(m)271 #expect(succeeded(m))272 }273274 @Test(.enabled(TestEnv.noPython) { await TestEnv.any != nil })275 func stopAndTimeout() async throws {276 let s = makeSession()277 let m = model(s, interpreter: try #require(await TestEnv.any))278 m.newScript(code: "import orix, time\norix.active_sheet().range('G1').write(1)\nprint('started', flush=True)\nwhile True: time.sleep(0.05)", name: "Loop")279 m.timeout = 1280 await runModel(m)281 #expect(stoppedReason(m)?.contains("1 s limit") == true, "\(m.status)")282 #expect(cell(s, "G1") == .blank && m.changes.first?.applied == false)283 m.timeout = 60284 let finished = Task { await runModel(m) }285 let deadline = Date().addingTimeInterval(15)286 while !m.consoleText.contains("started\n▶") && !(m.isRunning && m.consoleText.hasSuffix("started\n")) && Date() < deadline { try await Task.sleep(nanoseconds: 30_000_000) }287 #expect(m.isRunning)288 // the grid stays usable while the script runs289 s.perform("Edit during run") { $0.set(sheet: 0, row: 0, col: 8, .value(.number(5))) }290 #expect(cell(s, "I1") == .number(5))291 let t0 = Date()292 m.stop()293 await finished.value294 #expect(Date().timeIntervalSince(t0) < 3 && !m.isRunning)295 #expect(stoppedReason(m) != nil)296 #expect(cell(s, "G1") == .blank)297 }298299 @Test(.enabled(TestEnv.noPython) { await TestEnv.any != nil })300 func scriptsFromAWorkbookNeverRunWithoutConsent() async throws {301 let s = makeSession()302 // a workbook that arrives with a script inside303 let marker = FileManager.default.temporaryDirectory.appendingPathComponent("orix-consent-marker-\(UUID().uuidString)")304 let code = "import orix\norix.active_sheet().range('G1').write('ran')\nprint('executed')"305 PythonScripts.save(PythonScript(name: "Embedded", code: code), to: s.workbook)306 let m = model(s, interpreter: try #require(await TestEnv.any))307 m.reloadScripts()308 try await Task.sleep(nanoseconds: 300_000_000)309 #expect(m.status == .idle && m.console.isEmpty && cell(s, "G1") == .blank, "opening the workbook and showing the studio executes nothing")310 #expect(PythonAuditLog.recent(limit: 50).allSatisfy { $0.codeHash != PythonHash.sha256(code) })311312 await runModel(m, answer: .cancel)313 #expect(m.status == .idle && cell(s, "G1") == .blank && m.consent == nil, "Cancel runs nothing")314 m.run()315 let request = try #require(m.consent)316 #expect(request.reason == .arrivedWithWorkbook && request.code == code && request.restricted && !m.isRunning)317 // the answer is only valid for the text that was shown318 m.userEdited(code + "\nopen(\(String(reflecting: marker.path)), 'w').close()")319 m.answerConsent(.runOnce)320 #expect(!m.isRunning && m.alert != nil && !FileManager.default.fileExists(atPath: marker.path))321 m.alert = nil322 m.userEdited(code)323324 await runModel(m, answer: .runOnce)325 #expect(succeeded(m) && cell(s, "G1") == .text("ran"))326 #expect(!PythonTrust.isTrusted(codeHash: PythonHash.sha256(code), workbookID: PythonScripts.workbookID(s.workbook)), "Run once records nothing")327 m.run()328 #expect(m.consent == nil, "reviewed in this session: no second prompt")329 while m.isRunning { try await Task.sleep(nanoseconds: 30_000_000) }330331 // a new session on the same workbook asks again…332 let later = PythonStudioModel(session: s)333 later.setInterpreters(m.interpreters)334 later.run()335 #expect(later.consent != nil && !later.isRunning)336 // …unless that exact text was trusted for good337 await runModel(later, answer: .alwaysTrust)338 #expect(PythonTrust.isTrusted(codeHash: PythonHash.sha256(code), workbookID: PythonScripts.workbookID(s.workbook)))339 let third = PythonStudioModel(session: s)340 third.setInterpreters(m.interpreters)341 await runModel(third)342 #expect(third.consent == nil && succeeded(third))343 // modified outside the app: same script id, different text → untrusted again344 var tampered = try #require(PythonScripts.load(from: s.workbook).first)345 tampered.code += "\nimport os"346 PythonScripts.save(tampered, to: s.workbook)347 let fourth = PythonStudioModel(session: s)348 fourth.setInterpreters(m.interpreters)349 fourth.run()350 #expect(fourth.consent?.reason == .arrivedWithWorkbook && !fourth.isRunning)351 fourth.answerConsent(.cancel)352 PythonTrust.revokeAll()353 }354355 @Test(.enabled(TestEnv.noPython) { await TestEnv.any != nil })356 func unrestrictedModeNeedsItsOwnConfirmations() async throws {357 let s = makeSession()358 let m = model(s, interpreter: try #require(await TestEnv.any))359 PythonStudioModel.unrestrictedConfirmedThisSession = false360 #expect(m.restricted, "restricted mode is on by default")361 m.requestRestricted(false)362 #expect(m.restricted && m.showUnrestrictedConfirmation, "turning it off only asks")363 m.showUnrestrictedConfirmation = false364 #expect(m.restricted, "dismissing the alert changes nothing")365 m.requestRestricted(false); m.confirmUnrestricted()366 #expect(!m.restricted)367 m.newScript(code: "import orix\nprint('restricted' if orix.RESTRICTED else 'unrestricted')", name: "Mode")368 m.run()369 #expect(m.consent?.reason == .unrestricted && m.consent?.restricted == false && !m.isRunning, "even a script written here needs consent to run unrestricted")370 m.answerConsent(.cancel)371 await runModel(m, answer: .runOnce)372 #expect(m.consoleText.contains("\nunrestricted\n"))373 m.requestRestricted(true)374 await runModel(m)375 #expect(m.consoleText.contains("\nrestricted\n"))376 #expect(PythonAuditLog.recent(limit: 2).map(\.restricted) == [true, false])377 PythonStudioModel.unrestrictedConfirmedThisSession = false378 }379380 @Test(.enabled(TestEnv.noPandas) { await TestEnv.scientific != nil })381 func everySnippetRunsOnASelectionWithHeaders() async throws {382 let py = try #require(await TestEnv.scientific)383 for snippet in PythonSnippets.all where snippet.id != "regression" || py.has("statsmodels") {384 let s = makeSession()385 let m = model(s, interpreter: py)386 m.newScript(code: snippet.code, name: snippet.title)387 await runModel(m)388 #expect(succeeded(m), "snippet \(snippet.id): \(m.status)\n\(m.consoleText)")389 switch snippet.id {390 case "histogram": #expect(m.figures.count == 1)391 case "write": #expect(cell(s, "H1") == .text("Month") && cell(s, "I4") == .number(990.25))392 case "regression": #expect(m.consoleText.contains("OLS Regression Results") && m.tables.count == 1)393 default: #expect(m.tables.count == 1)394 }395 }396 #expect(PythonSnippets.all.map(\.title) == ["Read selection as DataFrame", "Group and summarise", "Describe statistics", "Linear regression with statsmodels", "Plot a histogram", "Write a DataFrame"])397 }398399 @Test(.enabled(TestEnv.noPandas) { await TestEnv.scientific != nil })400 func insertTablePreviewAtSelection() async throws {401 let s = makeSession()402 let m = model(s, interpreter: try #require(await TestEnv.scientific))403 m.newScript(code: "import orix, pandas as pd\norix.show(pd.DataFrame({'name': ['a', 'b'], 'value': [1.5, None]}))", name: "T")404 await runModel(m)405 let table = try #require(m.tables.first)406 s.select(RangeRef(a1: "M3")!, active: CellRef(a1: "M3")!)407 m.insertTable(table)408 #expect(cell(s, "M3") == .text("name") && cell(s, "N3") == .text("value") && cell(s, "M4") == .text("a") && cell(s, "N4") == .number(1.5) && cell(s, "N5") == .blank)409 #expect(s.engine.undoLabel == "Insert Table Preview")410 }411412 @Test func noPythonStateAndNoInterpreterRun() {413 let s = makeSession()414 let m = PythonStudioStore.model(for: s)415 m.setInterpreters([])416 #expect(m.hasDiscovered && m.interpreters.isEmpty && m.interpreter == nil)417 m.newScript()418 m.run()419 #expect(!m.isRunning && m.alert?.contains("No Python interpreter") == true, "the core app keeps working; the studio explains")420 s.perform("still works") { $0.set(sheet: 0, row: 0, col: 9, .value(.number(1))) }421 #expect(cell(s, "J1") == .number(1))422 }423424 @Test func consoleIsBounded() {425 let m = PythonStudioStore.model(for: makeSession())426 for i in 0..<10_000 { m.appendConsole(i % 2 == 0 ? .stdout : .stderr, "line \(i)\n") }427 #expect(m.console.count <= 4_000 && m.consoleText.hasSuffix("line 9999\n"))428 m.clearConsole()429 #expect(m.console.isEmpty)430 }431}432