DeterminationStorageTests.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. import CoreData
  2. import Foundation
  3. import Swinject
  4. import Testing
  5. @testable import Trio
  6. @Suite("Determination Storage Tests") struct DeterminationStorageTests: Injectable {
  7. @Injected() var storage: DeterminationStorage!
  8. let resolver: Resolver
  9. let coreDataStack = CoreDataStack.createForTests()
  10. let testContext: NSManagedObjectContext
  11. init() {
  12. // Create test context
  13. // As we are only using this single test context to initialize our in-memory DeterminationStorage we need to perform the Unit Tests serialized
  14. testContext = coreDataStack.newTaskContext()
  15. // Create assembler with test assembly
  16. let assembler = Assembler([
  17. StorageAssembly(),
  18. ServiceAssembly(),
  19. APSAssembly(),
  20. NetworkAssembly(),
  21. UIAssembly(),
  22. SecurityAssembly(),
  23. TestAssembly(testContext: testContext) // Add our test assembly last to override Storage
  24. ])
  25. resolver = assembler.resolver
  26. injectServices(resolver)
  27. }
  28. @Test("Storage is correctly initialized") func testStorageInitialization() {
  29. // Verify storage exists
  30. #expect(storage != nil, "DeterminationStorage should be injected")
  31. // Verify it's the correct type
  32. #expect(storage is BaseDeterminationStorage, "Storage should be of type BaseDeterminationStorage")
  33. }
  34. @Test("Test fetchLastDeterminationObjectID with different predicates") func testFetchLastDeterminationWithPredicates() async throws {
  35. // Given
  36. let date = Date()
  37. let id = UUID()
  38. // Create a mock determination
  39. await testContext.perform {
  40. let determination = OrefDetermination(context: testContext)
  41. determination.id = id
  42. determination.deliverAt = date
  43. determination.timestamp = date
  44. determination.enacted = true
  45. determination.isUploadedToNS = true
  46. try? testContext.save()
  47. }
  48. // Tests with predicates that we use the most for this function
  49. // 1. Test within 30 minutes
  50. let results = try await storage
  51. .fetchLastDeterminationObjectID(predicate: NSPredicate.predicateFor30MinAgoForDetermination)
  52. #expect(results.count == 1, "Should find 1 determination within 30 minutes")
  53. // Get NSManagedObjectID from exactDateResults
  54. try await testContext.perform {
  55. do {
  56. guard let results = results.first,
  57. let object = try testContext.existingObject(with: results) as? OrefDetermination
  58. else {
  59. throw TestError("Failed to fetch determination")
  60. }
  61. #expect(object.timestamp == date, "Determination within 30 minutes should have the same timestamp as date")
  62. #expect(object.deliverAt == date, "Determination within 30 minutes should have the same deliverAt as date")
  63. #expect(object.enacted == true, "Determination within 30 minutes should be enacted")
  64. #expect(object.isUploadedToNS == true, "Determination within 30 minutes should be uploaded to NS")
  65. #expect(object.id == id, "Determination within 30 minutes should have the same id")
  66. } catch {
  67. throw TestError("Failed to fetch determination")
  68. }
  69. }
  70. // 2. Test enacted determinations
  71. let enactedPredicate = NSPredicate.enactedDetermination
  72. let enactedResults = try await storage.fetchLastDeterminationObjectID(predicate: enactedPredicate)
  73. #expect(enactedResults.count == 1, "Should find 1 enacted determination")
  74. // Get NSManagedObjectID from enactedResults
  75. try await testContext.perform {
  76. do {
  77. guard let results = enactedResults.first,
  78. let object = try testContext.existingObject(with: results) as? OrefDetermination
  79. else {
  80. throw TestError("Failed to fetch determination")
  81. }
  82. #expect(object.enacted == true, "Enacted determination should be enacted")
  83. #expect(object.isUploadedToNS == true, "Enacted determination should be uploaded to NS")
  84. #expect(object.id == id, "Enacted determination should have the same id")
  85. #expect(object.timestamp == date, "Enacted determination should have the same timestamp")
  86. #expect(object.deliverAt == date, "Enacted determination should have the same deliverAt")
  87. // Delete the determination
  88. testContext.delete(object)
  89. try testContext.save()
  90. } catch {
  91. throw TestError("Failed to fetch determination")
  92. }
  93. }
  94. }
  95. @Test("Test complete forecast hierarchy prefetching") func testForecastHierarchyPrefetching() async throws {
  96. // Given
  97. let date = Date()
  98. let forecastTypes = ["iob", "cob", "zt", "uam"]
  99. var determinationId: NSManagedObjectID?
  100. let expectedValuesPerForecast = 5
  101. // STEP 1: Create test data
  102. await testContext.perform {
  103. let determination = OrefDetermination(context: testContext)
  104. determination.id = UUID()
  105. determination.deliverAt = date
  106. determination.timestamp = date
  107. determination.enacted = true
  108. // Create all forecast types with values
  109. for type in forecastTypes {
  110. let forecast = Forecast(context: testContext)
  111. forecast.id = UUID()
  112. forecast.date = date
  113. forecast.type = type
  114. forecast.orefDetermination = determination
  115. // Add test values with different patterns per type
  116. for i in 0 ..< expectedValuesPerForecast {
  117. let value = ForecastValue(context: testContext)
  118. value.index = Int32(i)
  119. // Different value patterns for each type
  120. switch type {
  121. case "iob": value.value = Int32(100 + i * 10) // 100, 110, 120...
  122. case "cob": value.value = Int32(50 + i * 5) // 50, 55, 60...
  123. case "zt": value.value = Int32(80 + i * 8) // 80, 88, 96...
  124. case "uam": value.value = Int32(120 - i * 15) // 120, 105, 90...
  125. default: value.value = 0
  126. }
  127. value.forecast = forecast
  128. }
  129. }
  130. try? testContext.save()
  131. determinationId = determination.objectID
  132. }
  133. guard let determinationId = determinationId else {
  134. throw TestError("Failed to create test data")
  135. }
  136. // STEP 2: Test hierarchy fetching
  137. let hierarchy = try await storage.fetchForecastHierarchy(
  138. for: determinationId,
  139. in: testContext
  140. )
  141. // Test hierarchy structure
  142. #expect(hierarchy.count == forecastTypes.count, "Should have correct number of forecasts")
  143. // STEP 3: Test individual forecasts
  144. for data in hierarchy {
  145. let (id, forecast, values) = await storage.fetchForecastObjects(
  146. for: data,
  147. in: testContext
  148. )
  149. // Test basic structure
  150. #expect(id != UUID(), "Should have valid UUID")
  151. #expect(forecast != nil, "Forecast should exist")
  152. #expect(values.count == expectedValuesPerForecast, "Should have correct number of values")
  153. // Test forecast type and values
  154. if let forecast = forecast {
  155. #expect(forecastTypes.contains(forecast.type ?? ""), "Should have valid forecast type")
  156. // Test value patterns
  157. let sortedValues = values.sorted { $0.index < $1.index }
  158. switch forecast.type {
  159. case "iob":
  160. #expect(sortedValues.first?.value == 100, "IOB should start at 100")
  161. #expect(sortedValues.last?.value == 140, "IOB should end at 140")
  162. case "cob":
  163. #expect(sortedValues.first?.value == 50, "COB should start at 50")
  164. #expect(sortedValues.last?.value == 70, "COB should end at 70")
  165. case "zt":
  166. #expect(sortedValues.first?.value == 80, "ZT should start at 80")
  167. #expect(sortedValues.last?.value == 112, "ZT should end at 112")
  168. case "uam":
  169. #expect(sortedValues.first?.value == 120, "UAM should start at 120")
  170. #expect(sortedValues.last?.value == 60, "UAM should end at 60")
  171. default:
  172. break
  173. }
  174. }
  175. }
  176. // STEP 4: Test relationship integrity
  177. try await testContext.perform {
  178. do {
  179. let determination = try testContext.existingObject(with: determinationId) as? OrefDetermination
  180. let forecasts = Array(determination?.forecasts ?? [])
  181. #expect(forecasts.count == forecastTypes.count, "Determination should have all forecasts")
  182. #expect(
  183. forecasts.allSatisfy { Array($0.forecastValues ?? []).count == expectedValuesPerForecast },
  184. "Each forecast should have correct number of values"
  185. )
  186. } catch {
  187. throw TestError("Failed to verify relationships: \(error)")
  188. }
  189. }
  190. }
  191. @Test("Measure performance of Core Data fetch operations") func testCoreDataPerformance() async throws {
  192. // STEP 1: Setup test data
  193. let date = Date()
  194. var determinationId: NSManagedObjectID?
  195. // Create test data
  196. await testContext.perform {
  197. let determination = OrefDetermination(context: self.testContext)
  198. determination.id = UUID()
  199. determination.deliverAt = date
  200. determination.timestamp = date
  201. determination.enacted = true
  202. // Add forecasts
  203. for type in ["iob", "cob", "zt", "uam"] {
  204. let forecast = Forecast(context: self.testContext)
  205. forecast.id = UUID()
  206. forecast.type = type
  207. forecast.date = date
  208. forecast.orefDetermination = determination
  209. // Add 48 values (typical forecast length)
  210. for i in 0 ..< 48 {
  211. let value = ForecastValue(context: self.testContext)
  212. value.index = Int32(i)
  213. value.value = Int32(100 + i)
  214. forecast.addToForecastValues(value)
  215. }
  216. }
  217. try? self.testContext.save()
  218. determinationId = determination.objectID
  219. }
  220. guard let determinationId = determinationId else {
  221. throw TestError("Failed to create test data")
  222. }
  223. // STEP 2: Test fetchLastDeterminationObjectID
  224. let lastDeterminationStartTime = CFAbsoluteTimeGetCurrent()
  225. let lastDetermination = try await storage.fetchLastDeterminationObjectID(
  226. predicate: NSPredicate(format: "deliverAt == %@", date as NSDate)
  227. )
  228. let lastDeterminationTime = CFAbsoluteTimeGetCurrent() - lastDeterminationStartTime
  229. debug(.default, "fetchLastDeterminationObjectID time: \(String(format: "%.4f", lastDeterminationTime)) seconds")
  230. // STEP 3: Test fetchForecastHierarchy
  231. let hierarchyStartTime = CFAbsoluteTimeGetCurrent()
  232. let hierarchy = try await storage.fetchForecastHierarchy(
  233. for: determinationId,
  234. in: testContext
  235. )
  236. let hierarchyTime = CFAbsoluteTimeGetCurrent() - hierarchyStartTime
  237. debug(.default, "fetchForecastHierarchy time: \(String(format: "%.4f", hierarchyTime)) seconds")
  238. // STEP 4: Test fetchForecastObjects
  239. let objectsStartTime = CFAbsoluteTimeGetCurrent()
  240. var individualFetchTimes: [Double] = []
  241. for data in hierarchy {
  242. let singleFetchStart = CFAbsoluteTimeGetCurrent()
  243. _ = await storage.fetchForecastObjects(
  244. for: data,
  245. in: testContext
  246. )
  247. individualFetchTimes.append(CFAbsoluteTimeGetCurrent() - singleFetchStart)
  248. }
  249. let objectsTime = CFAbsoluteTimeGetCurrent() - objectsStartTime
  250. let avgObjectTime = individualFetchTimes.reduce(0, +) / Double(individualFetchTimes.count)
  251. debug(.default, "Total fetchForecastObjects time: \(String(format: "%.4f", objectsTime)) seconds")
  252. debug(.default, "Average time per forecast object: \(String(format: "%.4f", avgObjectTime)) seconds")
  253. // Performance expectations
  254. #expect(lastDeterminationTime < 0.1, "fetchLastDeterminationObjectID should take less than 0.1 seconds")
  255. #expect(hierarchyTime < 0.1, "fetchForecastHierarchy should take less than 0.1 seconds")
  256. #expect(objectsTime < 0.2, "fetchForecastObjects should take less than 0.2 seconds")
  257. #expect(avgObjectTime < 0.05, "Individual forecast fetches should take less than 0.05 seconds")
  258. }
  259. }