File: SymbolTests.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (441 lines) | stat: -rw-r--r-- 15,412 bytes parent folder | download
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
/*
 This source file is part of the Swift.org open source project

 Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
 Licensed under Apache License v2.0 with Runtime Library Exception

 See https://swift.org/LICENSE.txt for license information
 See https://swift.org/CONTRIBUTORS.txt for Swift project authors
*/

import XCTest
@testable import SymbolKit

class SymbolTests: XCTestCase {
    
    func testIsDocCommentFromSameModuleAsSymbol() throws {
        // nil doc comment
        do {
            let jsonData = encodedSymbol(withDocComment: nil).data(using: .utf8)!
            let symbol = try JSONDecoder().decode(SymbolGraph.Symbol.self, from: jsonData)

            XCTAssertNil(symbol._isDocCommentFromSameModule)
            XCTAssertNil(symbol.isDocCommentFromSameModule(symbolModuleName: "Test"))
        }
        
        // without range information
        do {
            let jsonData = encodedSymbol(withDocComment:
                (lines: ["First line", "Second line"], rangeStart: nil, moduleName: nil, fileName: nil)
            ).data(using: .utf8)!
            let symbol = try JSONDecoder().decode(SymbolGraph.Symbol.self, from: jsonData)

            XCTAssertEqual(symbol._isDocCommentFromSameModule, false)
            XCTAssertEqual(symbol.isDocCommentFromSameModule(symbolModuleName: "Test"), false)
        }
        
        // with range information
        do {
            let jsonData = encodedSymbol(withDocComment:
                (lines: ["First line", "Second line"], rangeStart: (line: 2, character: 4), moduleName: nil, fileName: nil)
            ).data(using: .utf8)!
            let symbol = try JSONDecoder().decode(SymbolGraph.Symbol.self, from: jsonData)

            XCTAssertEqual(symbol._isDocCommentFromSameModule, true)
            XCTAssertEqual(symbol.isDocCommentFromSameModule(symbolModuleName: "Test"), true)
        }
        
        // empty doc comment
        do {
            let jsonData = encodedSymbol(withDocComment:
                (lines: [], rangeStart: (line: 2, character: 4), moduleName: nil, fileName: nil)
            ).data(using: .utf8)!
            let symbol = try JSONDecoder().decode(SymbolGraph.Symbol.self, from: jsonData)

            XCTAssertNil(symbol._isDocCommentFromSameModule)
            XCTAssertNil(symbol.isDocCommentFromSameModule(symbolModuleName: "Test"))
        }
    }
    
    func testDocCommentModuleInformation() throws {
        let jsonData = encodedSymbol(withDocComment:
            (lines: ["First line", "Second line"], rangeStart: nil, moduleName: "ModuleName", fileName: "file name")
        ).data(using: .utf8)!
        let symbol = try JSONDecoder().decode(SymbolGraph.Symbol.self, from: jsonData)

        XCTAssertEqual(symbol.docComment?.moduleName, "ModuleName")
        XCTAssertEqual(symbol.docComment?.url?.isFileURL, true)
        XCTAssertEqual(symbol.docComment?.url?.pathComponents.last, "file name")
        
        XCTAssertEqual(symbol.isDocCommentFromSameModule(symbolModuleName: "ModuleName"), true)
        XCTAssertEqual(symbol.isDocCommentFromSameModule(symbolModuleName: "Test"), false)
    }
    
    func testURIStringsThatAreNotValidURLs() throws {
        let uris = [
            "filename.swift",
            "relative/path/to/filename.swift",
            "/absolute/path/to/filename.swift",
            "file:///absolute/path/to/filename.swift",
            
            "relative/path with spaces/to/filename.swift",
            "/absolute/path with spaces/to/filename.swift",
            "file:///absolute/path with spaces/to/filename.swift",
            
            "filename with spaces.swift",
            "relative/path/to/filename with spaces.swift",
            "/absolute/path/to/filename with spaces.swift",
            "file:///absolute/path/to/filename with spaces.swift",
            
            "filename%20with%20escaped%20spaces.swift",
            "relative/path/to/filename%20with%20escaped%20spaces.swift",
            "/absolute/path/to/filename%20with%20escaped%20spaces.swift",
            "file:///absolute/path/to/filename%20with%20escaped%20spaces.swift",
        ]
        
        for uri in uris {
            let inputGraph = """
            {
              "accessLevel" : "public",
              "kind" : {
                "displayName" : "Instance Method",
                "identifier" : "swift.method"
              },
              "pathComponents" : [
                "ClassName",
                "something()"
              ],
              "identifier" : {
                "precise" : "precise-identifier",
                "interfaceLanguage" : "swift"
              },
              "names" : {
                "title" : "something()"
              },
              "location" : {
                "position" : {
                  "character" : 4,
                  "line" : 3
                },
                "uri" : "\(uri)"
              },
              "docComment" : {
                "lines" : [
                  {
                    "range" : {
                      "end" : {
                        "character" : 21,
                        "line": 2
                      },
                      "start" : {
                        "character" : 4,
                        "line" : 2
                      }
                    },
                    "text" : "Doc comment text."
                  }
                ],
                "module" : "SourceModuleName",
                "uri" : "\(uri)"
              },
              "declarationFragments" : [
                {
                  "kind" : "keyword",
                  "spelling" : "func"
                },
                {
                  "kind" : "text",
                  "spelling" : " "
                },
                {
                  "kind" : "identifier",
                  "spelling" : "something"
                },
                {
                  "kind" : "text",
                  "spelling" : "() -> "
                },
                {
                  "kind" : "keyword",
                  "spelling" : "Any"
                }
              ]
            }
            """.data(using: .utf8)!
            
            let symbol = try JSONDecoder().decode(SymbolGraph.Symbol.self, from: inputGraph)
            
            // This doesn't do full percent encoding to preserve the "file://" prefix.
            let expectedAbsoluteURLString = uri.replacingOccurrences(of: " ", with: "%20")
            
            let docComment = try XCTUnwrap(symbol.docComment)
            XCTAssertEqual(docComment.uri, uri)
            XCTAssertNotNil(docComment.url)
            XCTAssertEqual(false, docComment.url?.path.contains("%20"))
            XCTAssertEqual(docComment.url?.absoluteString, expectedAbsoluteURLString)
            
            let location = try XCTUnwrap(symbol.mixins[SymbolGraph.Symbol.Location.mixinKey] as? SymbolGraph.Symbol.Location)
            XCTAssertEqual(location.uri, uri)
            XCTAssertNotNil(location.url)
            XCTAssertEqual(false, location.url?.path.contains("%20"))
            XCTAssertEqual(location.url?.absoluteString, expectedAbsoluteURLString)
        }
    }

    /// Check that a Location mixin without position information still decodes a symbol graph without throwing.
    func testMalformedLocationDoesNotThrow() throws {
        let inputGraph = """
        {
          "accessLevel" : "public",
          "kind" : {
            "displayName" : "Instance Method",
            "identifier" : "swift.method"
          },
          "pathComponents" : [
            "ClassName",
            "something()"
          ],
          "identifier" : {
            "precise" : "precise-identifier",
            "interfaceLanguage" : "swift"
          },
          "names" : {
            "title" : "something()"
          },
          "location" : {
            "uri" : "file:///path/to/someSource.swift"
          },
          "declarationFragments" : [
            {
              "kind" : "keyword",
              "spelling" : "func"
            },
            {
              "kind" : "text",
              "spelling" : " "
            },
            {
              "kind" : "identifier",
              "spelling" : "something"
            },
            {
              "kind" : "text",
              "spelling" : "() -> "
            },
            {
              "kind" : "keyword",
              "spelling" : "Any"
            }
          ]
        }
        """.data(using: .utf8)!

        let symbol = try JSONDecoder().decode(SymbolGraph.Symbol.self, from: inputGraph)
        XCTAssertNil(symbol.mixins[SymbolGraph.Symbol.Location.mixinKey])
    }
 
    /// Check that an Extension mixin keeps the `typeKind` information if available and doesn't throw if it is absent.
    func testOptionalExtensionTypeKindCoding() throws {
        let inputGraphWithTypeKindInformation = """
        {
          "extendedModule": "ExtendedModule",
          "typeKind": "class"
        }
        """.data(using: .utf8)!
    
        let mixinWithTypeKind = try JSONDecoder().decode(SymbolGraph.Symbol.Swift.Extension.self, from: inputGraphWithTypeKindInformation)
        XCTAssert(mixinWithTypeKind.typeKind?.identifier == "class")
        
        let roundTripCodedMixinWithTypeKind = try JSONDecoder().decode(SymbolGraph.Symbol.Swift.Extension.self, from: try JSONEncoder().encode(mixinWithTypeKind))
        
        XCTAssert(roundTripCodedMixinWithTypeKind.typeKind?.identifier == "class")
        
        let inputGraphWithoutTypeKindInformation = """
        {
          "extendedModule": "ExtendedModule",
        }
        """.data(using: .utf8)!
    
        let mixinWithoutTypeKind = try JSONDecoder().decode(SymbolGraph.Symbol.Swift.Extension.self, from: inputGraphWithoutTypeKindInformation)
        XCTAssertNil(mixinWithoutTypeKind.typeKind)
    }
    
    /// Check that custom mixins can be decoded, manipulated, and encoded.
    func testCustomMixinRoundTrip() throws {
        let inputGraph = """
{
  "metadata" : {
    "generator" : "manual",
    "formatVersion" : {
      "major" : 0,
      "minor" : 5,
      "patch" : 3
    }
  },
  "module" : {
    "name" : "ModuleName",
    "platform" : {

    }
  },
  "symbols": [
    {
      "accessLevel" : "public",
      "kind" : {
        "displayName" : "Instance Method",
        "identifier" : "swift.method"
      },
      "pathComponents" : [
        "ClassName",
        "something()"
      ],
      "identifier" : {
        "precise" : "precise-identifier",
        "interfaceLanguage" : "swift"
      },
      "names" : {
        "title" : "something()"
      },
      "declarationFragments" : [
        {
          "kind" : "keyword",
          "spelling" : "func"
        },
        {
          "kind" : "text",
          "spelling" : " "
        },
        {
          "kind" : "identifier",
          "spelling" : "something"
        },
        {
          "kind" : "text",
          "spelling" : "() -> "
        },
        {
          "kind" : "keyword",
          "spelling" : "Any"
        }
      ],
      "custom-Int": {
        "value" : 1
      }
    }],
  "relationships": [
    {
      "kind" : "memberOf",
      "source" : "precise-source",
      "target" : "precise-target",
      "targetFallback" : "Swift.Int",
      "custom-String": {
        "value" : "relationship"
      }
    }]
}
""".data(using: .utf8)!
        
        // prepare encoder and decoder to deal with unknown mixins
        let decoder = JSONDecoder()
        decoder.register(symbolMixins: CustomMixin<Int>.self)
        decoder.register(relationshipMixins: CustomMixin<String>.self)
        
        let encoder = JSONEncoder()
        encoder.register(symbolMixins: CustomMixin<Int>.self, CustomMixin<String>.self)
        encoder.register(relationshipMixins: CustomMixin<String>.self)

        var graph = try decoder.decode(SymbolGraph.self, from: inputGraph)
        
        // check custom mixins are present
        XCTAssertEqual("relationship", graph.relationships[0][mixin: CustomMixin<String>.self]?.value)
        XCTAssertEqual(1, graph.symbols["precise-identifier"]![mixin: CustomMixin<Int>.self]?.value)
        
        // edit values + add new mixin of different type to symbol
        graph.relationships[0][mixin: CustomMixin<String>.self]?.value = "first-relationship"
        graph.symbols["precise-identifier"]![mixin: CustomMixin<Int>.self]?.value = 10
        graph.symbols["precise-identifier"]![mixin: CustomMixin<String>.self] = CustomMixin<String>(value: "second-relationship")
        
        // check edited/new data is found in encoded string
        let outputGraph = String(data: try encoder.encode(graph), encoding: .utf8)!
        XCTAssertTrue(outputGraph.contains("first-relationship"))
        XCTAssertTrue(outputGraph.contains("second-relationship"))
        XCTAssertTrue(outputGraph.contains("10"))
        
        // assert encoding and decoding with unprepared coders does not throw
        _ = try JSONDecoder().decode(SymbolGraph.self, from: inputGraph)
        _ = try JSONEncoder().encode(graph)
    }
}

// MARK: Test Data

private func encodedSymbol(withDocComment: (lines: [String], rangeStart: (line: Int, character: Int)?, moduleName: String?, fileName: String?)?) -> String {
    let docCommentJSON: String
    if let withDocComment = withDocComment {
        let lineList = SymbolGraph.LineList(withDocComment.lines.enumerated().map { index, text in
            let range = withDocComment.rangeStart.map { line, character in
                SymbolGraph.LineList.SourceRange(
                    start: SymbolGraph.LineList.SourceRange.Position(line: line + index, character: character),
                    end:   SymbolGraph.LineList.SourceRange.Position(line: line + index, character: character + text.count)
                )
            }
            return SymbolGraph.LineList.Line(text: text, range: range)
        }, uri: withDocComment.fileName.map({ "file:///path/to/" + $0 }), moduleName: withDocComment.moduleName)
        let encoder = JSONEncoder()
        encoder.outputFormatting = .prettyPrinted
        let data = try! encoder.encode(lineList)
        docCommentJSON = String(data: data, encoding: .utf8)!
    } else {
        docCommentJSON = "null"
    }
    
    return """
    {
      "accessLevel" : "public",
      "kind" : {
        "displayName" : "Instance Method",
        "identifier" : "swift.method"
      },
      "pathComponents" : [
        "ClassName",
        "something()"
      ],
      "identifier" : {
        "precise" : "precise-identifier",
        "interfaceLanguage" : "swift"
      },
      "names" : {
        "title" : "something()"
      },
      "docComment" : \(docCommentJSON),
      "declarationFragments" : [
        {
          "kind" : "keyword",
          "spelling" : "func"
        },
        {
          "kind" : "text",
          "spelling" : " "
        },
        {
          "kind" : "identifier",
          "spelling" : "something"
        },
        {
          "kind" : "text",
          "spelling" : "() -> "
        },
        {
          "kind" : "keyword",
          "spelling" : "Any"
        }
      ]
    }
    """
}

private struct CustomMixin<T>: Mixin where T: Codable {
    static var mixinKey: String { "custom-\(T.self)" }
    
    var value: T
}