DeterminationStorageTests.swift 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. import CoreData
  2. import Foundation
  3. import Swinject
  4. import Testing
  5. @testable import Trio
  6. @Suite("Determination Storage Tests", .serialized) struct DeterminationStorageTests: Injectable {
  7. @Injected() var storage: DeterminationStorage!
  8. let resolver: Resolver
  9. var coreDataStack: CoreDataStack!
  10. var testContext: NSManagedObjectContext!
  11. init() async throws {
  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. coreDataStack = try await CoreDataStack.createForTests()
  15. testContext = coreDataStack.newTaskContext()
  16. // Create assembler with test assembly
  17. let assembler = Assembler([
  18. StorageAssembly(),
  19. ServiceAssembly(),
  20. APSAssembly(),
  21. NetworkAssembly(),
  22. UIAssembly(),
  23. SecurityAssembly(),
  24. TestAssembly(testContext: testContext) // Add our test assembly last to override Storage
  25. ])
  26. resolver = assembler.resolver
  27. injectServices(resolver)
  28. }
  29. @Test("Storage is correctly initialized") func testStorageInitialization() {
  30. // Verify storage exists
  31. #expect(storage != nil, "DeterminationStorage should be injected")
  32. // Verify it's the correct type
  33. #expect(storage is BaseDeterminationStorage, "Storage should be of type BaseDeterminationStorage")
  34. }
  35. @Test("Test fetchLastDeterminationObjectID with different predicates") func testFetchLastDeterminationWithPredicates() async throws {
  36. // Given
  37. let date = Date()
  38. let id = UUID()
  39. // Create a mock determination
  40. await testContext.perform {
  41. let determination = OrefDetermination(context: testContext)
  42. determination.id = id
  43. determination.deliverAt = date
  44. determination.timestamp = date
  45. determination.enacted = true
  46. determination.isUploadedToNS = true
  47. try? testContext.save()
  48. }
  49. // Tests with predicates that we use the most for this function
  50. // 1. Test within 30 minutes
  51. let results = try await storage
  52. .fetchLastDeterminationObjectID(predicate: NSPredicate.predicateFor30MinAgoForDetermination)
  53. #expect(results.count == 1, "Should find 1 determination within 30 minutes")
  54. // Get NSManagedObjectID from exactDateResults
  55. try await testContext.perform {
  56. do {
  57. guard let results = results.first,
  58. let object = try testContext.existingObject(with: results) as? OrefDetermination
  59. else {
  60. throw TestError("Failed to fetch determination")
  61. }
  62. #expect(object.timestamp == date, "Determination within 30 minutes should have the same timestamp as date")
  63. #expect(object.deliverAt == date, "Determination within 30 minutes should have the same deliverAt as date")
  64. #expect(object.enacted == true, "Determination within 30 minutes should be enacted")
  65. #expect(object.isUploadedToNS == true, "Determination within 30 minutes should be uploaded to NS")
  66. #expect(object.id == id, "Determination within 30 minutes should have the same id")
  67. } catch {
  68. throw TestError("Failed to fetch determination")
  69. }
  70. }
  71. // 2. Test enacted determinations
  72. let enactedPredicate = NSPredicate.enactedDetermination
  73. let enactedResults = try await storage.fetchLastDeterminationObjectID(predicate: enactedPredicate)
  74. #expect(enactedResults.count == 1, "Should find 1 enacted determination")
  75. // Get NSManagedObjectID from enactedResults
  76. try await testContext.perform {
  77. do {
  78. guard let results = enactedResults.first,
  79. let object = try testContext.existingObject(with: results) as? OrefDetermination
  80. else {
  81. throw TestError("Failed to fetch determination")
  82. }
  83. #expect(object.enacted == true, "Enacted determination should be enacted")
  84. #expect(object.isUploadedToNS == true, "Enacted determination should be uploaded to NS")
  85. #expect(object.id == id, "Enacted determination should have the same id")
  86. #expect(object.timestamp == date, "Enacted determination should have the same timestamp")
  87. #expect(object.deliverAt == date, "Enacted determination should have the same deliverAt")
  88. // Delete the determination
  89. testContext.delete(object)
  90. try testContext.save()
  91. } catch {
  92. throw TestError("Failed to fetch determination")
  93. }
  94. }
  95. }
  96. @Test("Test complete forecast hierarchy prefetching") func testForecastHierarchyPrefetching() async throws {
  97. // Given
  98. let date = Date()
  99. let forecastTypes = ["iob", "cob", "zt", "uam"]
  100. let expectedValuesPerForecast = 5
  101. // STEP 1: Create test data
  102. let id = try await createTestData(
  103. date: date,
  104. forecastTypes: forecastTypes,
  105. expectedValuesPerForecast: expectedValuesPerForecast
  106. )
  107. // STEP 2: Test hierarchy fetching
  108. let hierarchy = try await storage.fetchForecastHierarchy(
  109. for: id,
  110. in: testContext
  111. )
  112. // Test hierarchy structure
  113. #expect(hierarchy.count == forecastTypes.count, "Should have correct number of forecasts")
  114. // STEP 3: Test individual forecasts
  115. for data in hierarchy {
  116. let (_, forecast, values) = await storage.fetchForecastObjects(
  117. for: data,
  118. in: testContext
  119. )
  120. // Test basic structure
  121. #expect(forecast != nil, "Forecast should exist")
  122. #expect(values.count == expectedValuesPerForecast, "Should have correct number of values")
  123. // Test forecast type and values
  124. if let forecast = forecast {
  125. #expect(forecastTypes.contains(forecast.type ?? ""), "Should have valid forecast type")
  126. // Test value patterns
  127. let sortedValues = values.sorted { $0.index < $1.index }
  128. switch forecast.type {
  129. case "iob":
  130. #expect(sortedValues.first?.value == 100, "IOB should start at 100")
  131. #expect(sortedValues.last?.value == 140, "IOB should end at 140")
  132. case "cob":
  133. #expect(sortedValues.first?.value == 50, "COB should start at 50")
  134. #expect(sortedValues.last?.value == 70, "COB should end at 70")
  135. case "zt":
  136. #expect(sortedValues.first?.value == 80, "ZT should start at 80")
  137. #expect(sortedValues.last?.value == 112, "ZT should end at 112")
  138. case "uam":
  139. #expect(sortedValues.first?.value == 120, "UAM should start at 120")
  140. #expect(sortedValues.last?.value == 60, "UAM should end at 60")
  141. default:
  142. break
  143. }
  144. }
  145. }
  146. // STEP 4: Test relationship integrity
  147. try await testContext.perform {
  148. do {
  149. let determination = try testContext.existingObject(with: id) as? OrefDetermination
  150. let forecasts = Array(determination?.forecasts ?? [])
  151. #expect(forecasts.count == forecastTypes.count, "Determination should have all forecasts")
  152. #expect(
  153. forecasts.allSatisfy { Array($0.forecastValues ?? []).count == expectedValuesPerForecast },
  154. "Each forecast should have correct number of values"
  155. )
  156. } catch {
  157. throw TestError("Failed to verify relationships: \(error)")
  158. }
  159. }
  160. }
  161. private func createTestData(
  162. date: Date,
  163. forecastTypes: [String],
  164. expectedValuesPerForecast: Int
  165. ) async throws -> NSManagedObjectID {
  166. try await testContext.perform {
  167. let determination = OrefDetermination(context: testContext)
  168. determination.id = UUID()
  169. determination.deliverAt = date
  170. determination.timestamp = date
  171. determination.enacted = true
  172. // Create all forecast types with values
  173. for type in forecastTypes {
  174. let forecast = Forecast(context: testContext)
  175. forecast.id = UUID()
  176. forecast.date = date
  177. forecast.type = type
  178. forecast.orefDetermination = determination
  179. // Add test values with different patterns per type
  180. for i in 0 ..< expectedValuesPerForecast {
  181. let value = ForecastValue(context: testContext)
  182. value.index = Int32(i)
  183. // Different value patterns for each type
  184. switch type {
  185. case "iob": value.value = Int32(100 + i * 10) // 100, 110, 120...
  186. case "cob": value.value = Int32(50 + i * 5) // 50, 55, 60...
  187. case "zt": value.value = Int32(80 + i * 8) // 80, 88, 96...
  188. case "uam": value.value = Int32(120 - i * 15) // 120, 105, 90...
  189. default: value.value = 0
  190. }
  191. value.forecast = forecast
  192. }
  193. }
  194. do {
  195. try testContext.save()
  196. return determination.objectID
  197. } catch {
  198. throw TestError("Failed to create test data: \(error)")
  199. }
  200. }
  201. }
  202. }