DeterminationStorageTests.swift 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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. let expectedValuesPerForecast = 5
  100. // STEP 1: Create test data
  101. let id = try await createTestData(
  102. date: date,
  103. forecastTypes: forecastTypes,
  104. expectedValuesPerForecast: expectedValuesPerForecast
  105. )
  106. // STEP 2: Test hierarchy fetching
  107. let hierarchy = try await storage.fetchForecastHierarchy(
  108. for: id,
  109. in: testContext
  110. )
  111. // Test hierarchy structure
  112. #expect(hierarchy.count == forecastTypes.count, "Should have correct number of forecasts")
  113. // STEP 3: Test individual forecasts
  114. for data in hierarchy {
  115. let (_, forecast, values) = await storage.fetchForecastObjects(
  116. for: data,
  117. in: testContext
  118. )
  119. // Test basic structure
  120. #expect(forecast != nil, "Forecast should exist")
  121. #expect(values.count == expectedValuesPerForecast, "Should have correct number of values")
  122. // Test forecast type and values
  123. if let forecast = forecast {
  124. #expect(forecastTypes.contains(forecast.type ?? ""), "Should have valid forecast type")
  125. // Test value patterns
  126. let sortedValues = values.sorted { $0.index < $1.index }
  127. switch forecast.type {
  128. case "iob":
  129. #expect(sortedValues.first?.value == 100, "IOB should start at 100")
  130. #expect(sortedValues.last?.value == 140, "IOB should end at 140")
  131. case "cob":
  132. #expect(sortedValues.first?.value == 50, "COB should start at 50")
  133. #expect(sortedValues.last?.value == 70, "COB should end at 70")
  134. case "zt":
  135. #expect(sortedValues.first?.value == 80, "ZT should start at 80")
  136. #expect(sortedValues.last?.value == 112, "ZT should end at 112")
  137. case "uam":
  138. #expect(sortedValues.first?.value == 120, "UAM should start at 120")
  139. #expect(sortedValues.last?.value == 60, "UAM should end at 60")
  140. default:
  141. break
  142. }
  143. }
  144. }
  145. // STEP 4: Test relationship integrity
  146. try await testContext.perform {
  147. do {
  148. let determination = try testContext.existingObject(with: id) as? OrefDetermination
  149. let forecasts = Array(determination?.forecasts ?? [])
  150. #expect(forecasts.count == forecastTypes.count, "Determination should have all forecasts")
  151. #expect(
  152. forecasts.allSatisfy { Array($0.forecastValues ?? []).count == expectedValuesPerForecast },
  153. "Each forecast should have correct number of values"
  154. )
  155. } catch {
  156. throw TestError("Failed to verify relationships: \(error)")
  157. }
  158. }
  159. }
  160. private func createTestData(
  161. date: Date,
  162. forecastTypes: [String],
  163. expectedValuesPerForecast: Int
  164. ) async throws -> NSManagedObjectID {
  165. try await testContext.perform {
  166. let determination = OrefDetermination(context: testContext)
  167. determination.id = UUID()
  168. determination.deliverAt = date
  169. determination.timestamp = date
  170. determination.enacted = true
  171. // Create all forecast types with values
  172. for type in forecastTypes {
  173. let forecast = Forecast(context: testContext)
  174. forecast.id = UUID()
  175. forecast.date = date
  176. forecast.type = type
  177. forecast.orefDetermination = determination
  178. // Add test values with different patterns per type
  179. for i in 0 ..< expectedValuesPerForecast {
  180. let value = ForecastValue(context: testContext)
  181. value.index = Int32(i)
  182. // Different value patterns for each type
  183. switch type {
  184. case "iob": value.value = Int32(100 + i * 10) // 100, 110, 120...
  185. case "cob": value.value = Int32(50 + i * 5) // 50, 55, 60...
  186. case "zt": value.value = Int32(80 + i * 8) // 80, 88, 96...
  187. case "uam": value.value = Int32(120 - i * 15) // 120, 105, 90...
  188. default: value.value = 0
  189. }
  190. value.forecast = forecast
  191. }
  192. }
  193. do {
  194. try testContext.save()
  195. return determination.objectID
  196. } catch {
  197. throw TestError("Failed to create test data: \(error)")
  198. }
  199. }
  200. }
  201. }