DeterminationStorageTests.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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 = await storage.fetchLastDeterminationObjectID(predicate: NSPredicate.predicateFor30MinAgoForDetermination)
  51. #expect(results.count == 1, "Should find 1 determination within 30 minutes")
  52. // Get NSManagedObjectID from exactDateResults
  53. try await testContext.perform {
  54. do {
  55. guard let results = results.first,
  56. let object = try testContext.existingObject(with: results) as? OrefDetermination
  57. else {
  58. throw TestError("Failed to fetch determination")
  59. }
  60. #expect(object.timestamp == date, "Determination within 30 minutes should have the same timestamp as date")
  61. #expect(object.deliverAt == date, "Determination within 30 minutes should have the same deliverAt as date")
  62. #expect(object.enacted == true, "Determination within 30 minutes should be enacted")
  63. #expect(object.isUploadedToNS == true, "Determination within 30 minutes should be uploaded to NS")
  64. #expect(object.id == id, "Determination within 30 minutes should have the same id")
  65. } catch {
  66. throw TestError("Failed to fetch determination")
  67. }
  68. }
  69. // 2. Test enacted determinations
  70. let enactedPredicate = NSPredicate.enactedDetermination
  71. let enactedResults = await storage.fetchLastDeterminationObjectID(predicate: enactedPredicate)
  72. #expect(enactedResults.count == 1, "Should find 1 enacted determination")
  73. // Get NSManagedObjectID from enactedResults
  74. try await testContext.perform {
  75. do {
  76. guard let results = enactedResults.first,
  77. let object = try testContext.existingObject(with: results) as? OrefDetermination
  78. else {
  79. throw TestError("Failed to fetch determination")
  80. }
  81. #expect(object.enacted == true, "Enacted determination should be enacted")
  82. #expect(object.isUploadedToNS == true, "Enacted determination should be uploaded to NS")
  83. #expect(object.id == id, "Enacted determination should have the same id")
  84. #expect(object.timestamp == date, "Enacted determination should have the same timestamp")
  85. #expect(object.deliverAt == date, "Enacted determination should have the same deliverAt")
  86. // Delete the determination
  87. testContext.delete(object)
  88. try testContext.save()
  89. } catch {
  90. throw TestError("Failed to fetch determination")
  91. }
  92. }
  93. }
  94. @Test("Test complete forecast hierarchy prefetching") func testForecastHierarchyPrefetching() async throws {
  95. // Given
  96. let date = Date()
  97. let forecastTypes = ["iob", "cob", "zt", "uam"]
  98. var determinationId: NSManagedObjectID?
  99. let expectedValuesPerForecast = 5
  100. // STEP 1: Create test data
  101. await testContext.perform {
  102. let determination = OrefDetermination(context: testContext)
  103. determination.id = UUID()
  104. determination.deliverAt = date
  105. determination.timestamp = date
  106. determination.enacted = true
  107. // Create all forecast types with values
  108. for type in forecastTypes {
  109. let forecast = Forecast(context: testContext)
  110. forecast.id = UUID()
  111. forecast.date = date
  112. forecast.type = type
  113. forecast.orefDetermination = determination
  114. // Add test values with different patterns per type
  115. for i in 0 ..< expectedValuesPerForecast {
  116. let value = ForecastValue(context: testContext)
  117. value.index = Int32(i)
  118. // Different value patterns for each type
  119. switch type {
  120. case "iob": value.value = Int32(100 + i * 10) // 100, 110, 120...
  121. case "cob": value.value = Int32(50 + i * 5) // 50, 55, 60...
  122. case "zt": value.value = Int32(80 + i * 8) // 80, 88, 96...
  123. case "uam": value.value = Int32(120 - i * 15) // 120, 105, 90...
  124. default: value.value = 0
  125. }
  126. value.forecast = forecast
  127. }
  128. }
  129. try? testContext.save()
  130. determinationId = determination.objectID
  131. }
  132. guard let determinationId = determinationId else {
  133. throw TestError("Failed to create test data")
  134. }
  135. // STEP 2: Test hierarchy fetching
  136. let hierarchy = await storage.fetchForecastHierarchy(
  137. for: determinationId,
  138. in: testContext
  139. )
  140. // Test hierarchy structure
  141. #expect(hierarchy.count == forecastTypes.count, "Should have correct number of forecasts")
  142. // STEP 3: Test individual forecasts
  143. for data in hierarchy {
  144. let (id, forecast, values) = await storage.fetchForecastObjects(
  145. for: data,
  146. in: testContext
  147. )
  148. // Test basic structure
  149. #expect(id != UUID(), "Should have valid UUID")
  150. #expect(forecast != nil, "Forecast should exist")
  151. #expect(values.count == expectedValuesPerForecast, "Should have correct number of values")
  152. // Test forecast type and values
  153. if let forecast = forecast {
  154. #expect(forecastTypes.contains(forecast.type ?? ""), "Should have valid forecast type")
  155. // Test value patterns
  156. let sortedValues = values.sorted { $0.index < $1.index }
  157. switch forecast.type {
  158. case "iob":
  159. #expect(sortedValues.first?.value == 100, "IOB should start at 100")
  160. #expect(sortedValues.last?.value == 140, "IOB should end at 140")
  161. case "cob":
  162. #expect(sortedValues.first?.value == 50, "COB should start at 50")
  163. #expect(sortedValues.last?.value == 70, "COB should end at 70")
  164. case "zt":
  165. #expect(sortedValues.first?.value == 80, "ZT should start at 80")
  166. #expect(sortedValues.last?.value == 112, "ZT should end at 112")
  167. case "uam":
  168. #expect(sortedValues.first?.value == 120, "UAM should start at 120")
  169. #expect(sortedValues.last?.value == 60, "UAM should end at 60")
  170. default:
  171. break
  172. }
  173. }
  174. }
  175. // STEP 4: Test relationship integrity
  176. try await testContext.perform {
  177. do {
  178. let determination = try testContext.existingObject(with: determinationId) as? OrefDetermination
  179. let forecasts = Array(determination?.forecasts ?? [])
  180. #expect(forecasts.count == forecastTypes.count, "Determination should have all forecasts")
  181. #expect(
  182. forecasts.allSatisfy { Array($0.forecastValues ?? []).count == expectedValuesPerForecast },
  183. "Each forecast should have correct number of values"
  184. )
  185. } catch {
  186. throw TestError("Failed to verify relationships: \(error)")
  187. }
  188. }
  189. }
  190. @Test("Measure performance of Core Data fetch operations") func testCoreDataPerformance() async throws {
  191. // STEP 1: Setup test data
  192. let date = Date()
  193. var determinationId: NSManagedObjectID?
  194. // Create test data
  195. await testContext.perform {
  196. let determination = OrefDetermination(context: self.testContext)
  197. determination.id = UUID()
  198. determination.deliverAt = date
  199. determination.timestamp = date
  200. determination.enacted = true
  201. // Add forecasts
  202. for type in ["iob", "cob", "zt", "uam"] {
  203. let forecast = Forecast(context: self.testContext)
  204. forecast.id = UUID()
  205. forecast.type = type
  206. forecast.date = date
  207. forecast.orefDetermination = determination
  208. // Add 48 values (typical forecast length)
  209. for i in 0 ..< 48 {
  210. let value = ForecastValue(context: self.testContext)
  211. value.index = Int32(i)
  212. value.value = Int32(100 + i)
  213. forecast.addToForecastValues(value)
  214. }
  215. }
  216. try? self.testContext.save()
  217. determinationId = determination.objectID
  218. }
  219. guard let determinationId = determinationId else {
  220. throw TestError("Failed to create test data")
  221. }
  222. // STEP 2: Test fetchLastDeterminationObjectID
  223. let lastDeterminationStartTime = CFAbsoluteTimeGetCurrent()
  224. let lastDetermination = await storage.fetchLastDeterminationObjectID(
  225. predicate: NSPredicate(format: "deliverAt == %@", date as NSDate)
  226. )
  227. let lastDeterminationTime = CFAbsoluteTimeGetCurrent() - lastDeterminationStartTime
  228. debug(.default, "fetchLastDeterminationObjectID time: \(String(format: "%.4f", lastDeterminationTime)) seconds")
  229. // STEP 3: Test fetchForecastHierarchy
  230. let hierarchyStartTime = CFAbsoluteTimeGetCurrent()
  231. let hierarchy = await storage.fetchForecastHierarchy(
  232. for: determinationId,
  233. in: testContext
  234. )
  235. let hierarchyTime = CFAbsoluteTimeGetCurrent() - hierarchyStartTime
  236. debug(.default, "fetchForecastHierarchy time: \(String(format: "%.4f", hierarchyTime)) seconds")
  237. // STEP 4: Test fetchForecastObjects
  238. let objectsStartTime = CFAbsoluteTimeGetCurrent()
  239. var individualFetchTimes: [Double] = []
  240. for data in hierarchy {
  241. let singleFetchStart = CFAbsoluteTimeGetCurrent()
  242. _ = await storage.fetchForecastObjects(
  243. for: data,
  244. in: testContext
  245. )
  246. individualFetchTimes.append(CFAbsoluteTimeGetCurrent() - singleFetchStart)
  247. }
  248. let objectsTime = CFAbsoluteTimeGetCurrent() - objectsStartTime
  249. let avgObjectTime = individualFetchTimes.reduce(0, +) / Double(individualFetchTimes.count)
  250. debug(.default, "Total fetchForecastObjects time: \(String(format: "%.4f", objectsTime)) seconds")
  251. debug(.default, "Average time per forecast object: \(String(format: "%.4f", avgObjectTime)) seconds")
  252. // Performance expectations
  253. #expect(lastDeterminationTime < 0.1, "fetchLastDeterminationObjectID should take less than 0.1 seconds")
  254. #expect(hierarchyTime < 0.1, "fetchForecastHierarchy should take less than 0.1 seconds")
  255. #expect(objectsTime < 0.2, "fetchForecastObjects should take less than 0.2 seconds")
  256. #expect(avgObjectTime < 0.05, "Individual forecast fetches should take less than 0.05 seconds")
  257. }
  258. }