OpenAPSFixed.swift 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import Combine
  2. import Foundation
  3. import JavaScriptCore
  4. @testable import Trio
  5. /// This class provides us with an implementation of trio-oref with a number of iob bugs that are fixed.
  6. /// We can use this during testing to confirm that for an input that generated an error that a corrected
  7. /// Javascript implementation would have produced the same results
  8. final class OpenAPSFixed {
  9. private let jsWorker = JavaScriptWorker()
  10. func sortPumpHistory(pumpHistory: JSON) throws -> JSON {
  11. let pumpHistorySwift = try JSONBridge.pumpHistory(from: pumpHistory)
  12. return try JSONBridge.to(pumpHistorySwift.sorted(by: { $0.timestamp > $1.timestamp }))
  13. }
  14. func iobJavascript(pumphistory: JSON, profile: JSON, clock: JSON, autosens: JSON) async -> OrefFunctionResult {
  15. do {
  16. let testBundle = Bundle(for: OpenAPSFixed.self)
  17. let pumphistory: JSON = try! sortPumpHistory(pumpHistory: pumphistory)
  18. let result = try await withCheckedThrowingContinuation { continuation in
  19. jsWorker.inCommonContext { worker in
  20. worker.evaluateBatch(scripts: [
  21. Script(name: "prepare/log.js"),
  22. Script.fromTestingBundle(name: "iob.js", bundle: testBundle),
  23. Script(name: "prepare/iob.js")
  24. ])
  25. let result = worker.call(function: "generate", with: [
  26. pumphistory,
  27. profile,
  28. clock,
  29. autosens
  30. ])
  31. continuation.resume(returning: result)
  32. }
  33. }
  34. return .success(result)
  35. } catch {
  36. return .failure(error)
  37. }
  38. }
  39. }
  40. extension Script {
  41. static func fromTestingBundle(name: String, bundle: Bundle) -> Script {
  42. let body: String
  43. if let url = bundle.url(forResource: "\(name)", withExtension: "") {
  44. do {
  45. body = try String(contentsOf: url)
  46. } catch {
  47. print("Error loading script: \(error.localizedDescription)")
  48. body = "Error loading script"
  49. }
  50. } else {
  51. print("Resource not found: javascript/\(name)")
  52. body = "Resource not found"
  53. }
  54. return Script(name: name, body: body)
  55. }
  56. }