summaryrefslogtreecommitdiff
path: root/SoraTests/SettingsManagerSyncTests.swift
blob: 72cf2ad8cac7880d41c510e3c9eca3ab1a50b502 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
import Foundation
import XCTest

// swiftlint:disable type_body_length
final class SettingsManagerSyncTests: XCTestCase {
  func testBookmarkMutationPathReusesEncodedPayload() throws {
    let source = try loadSource(at: "Sora/Data/Settings/SettingsManager.swift")
    let addBookmarkSection = try extractFunction(
      named: "func addBookmark(provider: BooruProvider, tags: [String], folder: UUID? = nil)",
      from: source
    )
    let updateBookmarksSection = try extractFunction(named: "func updateBookmarks(", from: source)
    let bookmarksSetterSection = try extractFunction(named: "var bookmarks: [SettingsBookmark]", from: source)
    let normalizedAddBookmark = strippingCommentsAndStrings(from: addBookmarkSection)
    let normalizedUpdateBookmarks = strippingCommentsAndStrings(from: updateBookmarksSection)
    let normalizedBookmarksSetter = strippingCommentsAndStrings(from: bookmarksSetterSection)

    let addBookmarkInlineEncodeCount = tokenCount(
      matching: #"Self\s*\.\s*encode\s*\(\s*updatedBookmarks\s*\)"#,
      in: normalizedAddBookmark
    )
    let updateBookmarksPreEncodedForwardCount = tokenCount(
      matching: #"syncableData\s*\([\s\S]*?\bencodedData\s*:"#,
      in: normalizedUpdateBookmarks
    )
    let bookmarksSetterPreEncodedForwardCount = tokenCount(
      matching: #"syncableData\s*\([\s\S]*?\bencodedData\s*:"#,
      in: normalizedBookmarksSetter
    )

    // swiftlint:disable:next prefer_nimble
    XCTAssertEqual(
      addBookmarkInlineEncodeCount,
      0,
      "addBookmark should not pre-encode and then trigger another encode downstream."
    )
    // swiftlint:disable:next prefer_nimble
    XCTAssertGreaterThan(
      updateBookmarksPreEncodedForwardCount,
      0,
      "updateBookmarks should forward a pre-encoded payload to syncableData to avoid duplicate encoding."
    )
    // swiftlint:disable:next prefer_nimble
    XCTAssertGreaterThan(
      bookmarksSetterPreEncodedForwardCount,
      0,
      "bookmarks setter should forward a pre-encoded payload to syncableData."
    )
  }

  func testFavoriteMutationPathReusesEncodedPayload() throws {
    let source = try loadSource(at: "Sora/Data/Settings/SettingsManager.swift")
    let addFavoriteSection = try extractFunction(
      named: "func addFavorite(post: BooruPost, provider: BooruProvider, folder: UUID? = nil)",
      from: source
    )
    let updateFavoritesSection = try extractFunction(named: "func updateFavorites(", from: source)
    let favoritesSetterSection = try extractFunction(named: "var favorites: [SettingsFavoritePost]", from: source)
    let normalizedAddFavorite = strippingCommentsAndStrings(from: addFavoriteSection)
    let normalizedUpdateFavorites = strippingCommentsAndStrings(from: updateFavoritesSection)
    let normalizedFavoritesSetter = strippingCommentsAndStrings(from: favoritesSetterSection)

    let addFavoriteInlineEncodeCount = tokenCount(
      matching: #"Self\s*\.\s*encode\s*\(\s*updatedFavorites\s*\)"#,
      in: normalizedAddFavorite
    )
    let updateFavoritesPreEncodedForwardCount = tokenCount(
      matching: #"syncableData\s*\([\s\S]*?\bencodedData\s*:"#,
      in: normalizedUpdateFavorites
    )
    let favoritesSetterPreEncodedForwardCount = tokenCount(
      matching: #"syncableData\s*\([\s\S]*?\bencodedData\s*:"#,
      in: normalizedFavoritesSetter
    )

    // swiftlint:disable:next prefer_nimble
    XCTAssertEqual(
      addFavoriteInlineEncodeCount,
      0,
      "addFavorite should not pre-encode and then trigger another encode downstream."
    )
    // swiftlint:disable:next prefer_nimble
    XCTAssertGreaterThan(
      updateFavoritesPreEncodedForwardCount,
      0,
      "updateFavorites should forward a pre-encoded payload to syncableData to avoid duplicate encoding."
    )
    // swiftlint:disable:next prefer_nimble
    XCTAssertGreaterThan(
      favoritesSetterPreEncodedForwardCount,
      0,
      "favorites setter should forward a pre-encoded payload to syncableData."
    )
  }

  func testBatchedSyncPathGuardsUnchangedPayloadWrites() throws {
    let source = try loadSource(at: "Sora/Data/Settings/SettingsManager.swift")
    let triggerSyncSection = try extractFunction(
      named: "private func triggerSyncIfNeeded(for key: SettingsSyncKey)",
      from: source
    )
    let normalizedSection = strippingCommentsAndStrings(from: triggerSyncSection)

    let cloudWriteCount = tokenCount(
      matching: #"\bNSUbiquitousKeyValueStore\s*\.\s*default\s*\.\s*set\s*\(\s*encoded\s*,\s*forKey\s*:"#,
      in: normalizedSection
    )
    let unchangedGuardCount = tokenCount(
      matching: #"\!\=\s*encoded\b"#,
      in: normalizedSection
    )

    // swiftlint:disable:next prefer_nimble
    XCTAssertGreaterThan(cloudWriteCount, 0, "Expected batched sync path to contain cloud writes.")
    // swiftlint:disable:next prefer_nimble
    XCTAssertGreaterThanOrEqual(
      unchangedGuardCount,
      cloudWriteCount,
      "Every batched iCloud write should be guarded to avoid unchanged payload rewrites."
    )
  }

  private func loadSource(at relativePath: String) throws -> String {
    let currentFile = URL(fileURLWithPath: #filePath)
    let repositoryRoot = currentFile.deletingLastPathComponent().deletingLastPathComponent()
    let fileURL = repositoryRoot.appendingPathComponent(relativePath)

    return try String(contentsOf: fileURL, encoding: .utf8)
  }

  // swiftlint:disable:next cyclomatic_complexity
  private func extractFunction(named signature: String, from source: String) throws -> String {
    guard let signatureRange = source.range(of: signature) else {
      throw NSError(domain: "SettingsManagerSyncTests", code: 1)
    }
    guard let openingBrace = source[signatureRange.upperBound...].firstIndex(of: "{") else {
      throw NSError(domain: "SettingsManagerSyncTests", code: 2)
    }

    let characters = Array(source)
    let startOffset = source.distance(from: source.startIndex, to: signatureRange.lowerBound)
    var currentOffset = source.distance(from: source.startIndex, to: openingBrace)

    var braceDepth = 0
    var inLineComment = false
    var blockCommentDepth = 0
    var inString = false
    var isEscaped = false

    while currentOffset < characters.count {
      let current = characters[currentOffset]
      let next: Character? = currentOffset + 1 < characters.count ? characters[currentOffset + 1] : nil

      if inLineComment {
        if current == "\n" {
          inLineComment = false
        }
        currentOffset += 1
        continue
      }

      if blockCommentDepth > 0 {
        if current == "/", next == "*" {
          blockCommentDepth += 1
          currentOffset += 2
          continue
        }

        if current == "*", next == "/" {
          blockCommentDepth -= 1
          currentOffset += 2
          continue
        }

        currentOffset += 1
        continue
      }

      if inString {
        if isEscaped {
          isEscaped = false
        } else if current == "\\" {
          isEscaped = true
        } else if current == "\"" {
          inString = false
        }

        currentOffset += 1
        continue
      }

      if current == "/", next == "/" {
        inLineComment = true
        currentOffset += 2
        continue
      }

      if current == "/", next == "*" {
        blockCommentDepth = 1
        currentOffset += 2
        continue
      }

      if current == "\"" {
        inString = true
        currentOffset += 1
        continue
      }

      if current == "{" {
        braceDepth += 1
      } else if current == "}" {
        braceDepth -= 1

        if braceDepth == 0 {
          let endIndex = source.index(source.startIndex, offsetBy: currentOffset + 1)
          let startIndex = source.index(source.startIndex, offsetBy: startOffset)

          return String(source[startIndex..<endIndex])
        }
      }

      currentOffset += 1
    }

    throw NSError(domain: "SettingsManagerSyncTests", code: 3)
  }

  // swiftlint:disable:next cyclomatic_complexity
  private func strippingCommentsAndStrings(from source: String) -> String {
    let characters = Array(source)
    var result: [Character] = []
    result.reserveCapacity(characters.count)

    var currentOffset = 0
    var inLineComment = false
    var blockCommentDepth = 0
    var inString = false
    var isEscaped = false

    while currentOffset < characters.count {
      let current = characters[currentOffset]
      let next: Character? = currentOffset + 1 < characters.count ? characters[currentOffset + 1] : nil

      if inLineComment {
        if current == "\n" {
          inLineComment = false
          result.append("\n")
        } else {
          result.append(" ")
        }
        currentOffset += 1
        continue
      }

      if blockCommentDepth > 0 {
        if current == "/", next == "*" {
          blockCommentDepth += 1
          result.append(" ")
          result.append(" ")
          currentOffset += 2
          continue
        }

        if current == "*", next == "/" {
          blockCommentDepth -= 1
          result.append(" ")
          result.append(" ")
          currentOffset += 2
          continue
        }

        result.append(current == "\n" ? "\n" : " ")
        currentOffset += 1
        continue
      }

      if inString {
        if isEscaped {
          isEscaped = false
        } else if current == "\\" {
          isEscaped = true
        } else if current == "\"" {
          inString = false
        }

        result.append(current == "\n" ? "\n" : " ")
        currentOffset += 1
        continue
      }

      if current == "/", next == "/" {
        inLineComment = true
        result.append(" ")
        result.append(" ")
        currentOffset += 2
        continue
      }

      if current == "/", next == "*" {
        blockCommentDepth = 1
        result.append(" ")
        result.append(" ")
        currentOffset += 2
        continue
      }

      if current == "\"" {
        inString = true
        result.append(" ")
        currentOffset += 1
        continue
      }

      result.append(current)
      currentOffset += 1
    }

    return String(result)
  }

  private func tokenCount(matching pattern: String, in source: String) -> Int {
    guard let regex = try? NSRegularExpression(pattern: pattern) else { return 0 }
    let range = NSRange(source.startIndex..<source.endIndex, in: source)

    return regex.numberOfMatches(in: source, range: range)
  }
}
// swiftlint:enable type_body_length