File: AutoCapitalizationTests.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 (200 lines) | stat: -rw-r--r-- 11,743 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
/*
 This source file is part of the Swift.org open source project

 Copyright (c) 2024 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 Foundation
import XCTest
import SymbolKit
@testable import SwiftDocC
import SwiftDocCTestUtilities

class AutoCapitalizationTests: XCTestCase {
    
    // MARK: Test helpers
    
    private let start = SymbolGraph.LineList.SourceRange.Position(line: 7, character: 6) // an arbitrary non-zero start position
    private let symbolURL =  URL(fileURLWithPath: "/path/to/SomeFile.swift")
    
    private func makeSymbolGraph(docComment: String, parameters: [String]) -> SymbolGraph {
        makeSymbolGraph(
            docComment: docComment,
            sourceLanguage: .swift,
            parameters: parameters.map { ($0, nil) },
            returnValue: .init(kind: .typeIdentifier, spelling: "ReturnValue", preciseIdentifier: "return-value-id")
        )
    }
    
    private func makeSymbolGraph(
        docComment: String?,
        sourceLanguage: SourceLanguage,
        parameters: [(name: String, externalName: String?)],
        returnValue: SymbolGraph.Symbol.DeclarationFragments.Fragment
    ) -> SymbolGraph {
        let uri = symbolURL.absoluteString // we want to include the file:// scheme here
        func makeLineList(text: String) -> SymbolGraph.LineList {
            return .init(text.splitByNewlines.enumerated().map { lineOffset, line in
                    .init(text: line, range: .init(start: .init(line: start.line + lineOffset, character: start.character),
                                                   end: .init(line: start.line + lineOffset, character: start.character + line.count)))
            }, uri: uri)
        }
        
        return makeSymbolGraph(
            moduleName: "ModuleName",
            symbols: [
                .init(
                    identifier: .init(precise: "symbol-id", interfaceLanguage: sourceLanguage.id),
                    names: .init(title: "functionName(...)", navigator: nil, subHeading: nil, prose: nil),
                    pathComponents: ["functionName(...)"],
                    docComment: docComment.map { makeLineList(text: $0) },
                    accessLevel: .public, kind: .init(parsedIdentifier: .func, displayName: "Function"),
                    mixins: [
                        SymbolGraph.Symbol.Location.mixinKey: SymbolGraph.Symbol.Location(uri: uri, position: start),
                        
                        SymbolGraph.Symbol.FunctionSignature.mixinKey: SymbolGraph.Symbol.FunctionSignature(
                            parameters: parameters.map {
                                .init(name: $0.name, externalName: $0.externalName, declarationFragments: [], children: [])
                            },
                            returns: [returnValue]
                        )
                    ]
                )
            ]
        )
    }
    
    
    // MARK: End-to-end integration tests
    
    func testParametersCapitalization() throws {
        let symbolGraph = makeSymbolGraph(
            docComment: """
            Some symbol description.

            - Parameters:
                - one: upper-cased first parameter description.
                - two:     the second parameter has extra white spaces
                - three: inValid third parameter will not be capitalized
                - four: `code block` will not be capitalized
                - five: a`nother invalid capitalization
            """,
            parameters: ["one", "two", "three", "four", "five"]
        )
        
        let url = try createTempFolder(content: [
            Folder(name: "unit-test.docc", content: [
                JSONFile(name: "ModuleName.symbols.json", content: symbolGraph)
            ])
        ])
        let (_, bundle, context) = try loadBundle(from: url)
        
        XCTAssertEqual(context.problems.count, 0)
        
        let reference = ResolvedTopicReference(bundleIdentifier: bundle.identifier, path: "/documentation/ModuleName/functionName(...)", sourceLanguage: .swift)
        let node = try context.entity(with: reference)
        let symbol = try XCTUnwrap(node.semantic as? Symbol)
        let parameterSections = symbol.parametersSectionVariants
        XCTAssertEqual(parameterSections[.swift]?.parameters.map(\.name), ["one", "two", "three", "four", "five"])
        
        let parameterSectionTranslator = ParametersSectionTranslator()
        var renderNodeTranslator = RenderNodeTranslator(context: context, bundle: bundle, identifier: reference, source: url)
        var renderNode = renderNodeTranslator.visit(symbol) as! RenderNode
        let translatedParameters = parameterSectionTranslator.translateSection(for: symbol, renderNode: &renderNode, renderNodeTranslator: &renderNodeTranslator)
        let paramsRenderSection = translatedParameters?.defaultValue?.section as! ParametersRenderSection
        
        // Different locales treat capitalization of hyphenated words differently (e.g. Upper-Cased vs Upper-cased).
        let hyphenatedString = "upper-cased"
        let hyphenatedCapitalizedResult = hyphenatedString.localizedCapitalized + " first parameter description."
        
        XCTAssertEqual(paramsRenderSection.parameters.map(\.content), [
            [SwiftDocC.RenderBlockContent.paragraph(SwiftDocC.RenderBlockContent.Paragraph(inlineContent: [SwiftDocC.RenderInlineContent.text(hyphenatedCapitalizedResult)]))],
            [SwiftDocC.RenderBlockContent.paragraph(SwiftDocC.RenderBlockContent.Paragraph(inlineContent: [SwiftDocC.RenderInlineContent.text("The second parameter has extra white spaces")]))],
            [SwiftDocC.RenderBlockContent.paragraph(SwiftDocC.RenderBlockContent.Paragraph(inlineContent: [SwiftDocC.RenderInlineContent.text("inValid third parameter will not be capitalized")]))],
            [SwiftDocC.RenderBlockContent.paragraph(SwiftDocC.RenderBlockContent.Paragraph(inlineContent: [SwiftDocC.RenderInlineContent.text(""), SwiftDocC.RenderInlineContent.codeVoice(code: "code block"), SwiftDocC.RenderInlineContent.text(" will not be capitalized")]))],
            [SwiftDocC.RenderBlockContent.paragraph(SwiftDocC.RenderBlockContent.Paragraph(inlineContent: [SwiftDocC.RenderInlineContent.text("a`nother invalid capitalization")]))]])
    }
    
    func testIndividualParametersCapitalization() throws {
        let symbolGraph = makeSymbolGraph(
            docComment: """
            Some symbol description.

            - parameter one: upper-cased first parameter description.
            - parameter two:     the second parameter has extra white spaces
            - parameter three: inValid third parameter will not be capitalized
            - parameter four: `code block` will not be capitalized
            - parameter five: a`nother invalid capitalization
            """,
            parameters: ["one", "two", "three", "four", "five"]
        )
        
        let url = try createTempFolder(content: [
            Folder(name: "unit-test.docc", content: [
                JSONFile(name: "ModuleName.symbols.json", content: symbolGraph)
            ])
        ])
        let (_, bundle, context) = try loadBundle(from: url)
        
        XCTAssertEqual(context.problems.count, 0)
        
        let reference = ResolvedTopicReference(bundleIdentifier: bundle.identifier, path: "/documentation/ModuleName/functionName(...)", sourceLanguage: .swift)
        let node = try context.entity(with: reference)
        let symbol = try XCTUnwrap(node.semantic as? Symbol)
        let parameterSections = symbol.parametersSectionVariants
        XCTAssertEqual(parameterSections[.swift]?.parameters.map(\.name), ["one", "two", "three", "four", "five"])
        
        let parameterSectionTranslator = ParametersSectionTranslator()
        var renderNodeTranslator = RenderNodeTranslator(context: context, bundle: bundle, identifier: reference, source: url)
        var renderNode = renderNodeTranslator.visit(symbol) as! RenderNode
        let translatedParameters = parameterSectionTranslator.translateSection(for: symbol, renderNode: &renderNode, renderNodeTranslator: &renderNodeTranslator)
        let paramsRenderSection = translatedParameters?.defaultValue?.section as! ParametersRenderSection
        
        // Different locales treat capitalization of hyphenated words differently (e.g. Upper-Cased vs Upper-cased).
        let hyphenatedString = "upper-cased"
        let hyphenatedCapitalizedResult = hyphenatedString.localizedCapitalized + " first parameter description."
        
        XCTAssertEqual(paramsRenderSection.parameters.map(\.content), [
            [SwiftDocC.RenderBlockContent.paragraph(SwiftDocC.RenderBlockContent.Paragraph(inlineContent: [SwiftDocC.RenderInlineContent.text(hyphenatedCapitalizedResult)]))],
            [SwiftDocC.RenderBlockContent.paragraph(SwiftDocC.RenderBlockContent.Paragraph(inlineContent: [SwiftDocC.RenderInlineContent.text("The second parameter has extra white spaces")]))],
            [SwiftDocC.RenderBlockContent.paragraph(SwiftDocC.RenderBlockContent.Paragraph(inlineContent: [SwiftDocC.RenderInlineContent.text("inValid third parameter will not be capitalized")]))],
            [SwiftDocC.RenderBlockContent.paragraph(SwiftDocC.RenderBlockContent.Paragraph(inlineContent: [SwiftDocC.RenderInlineContent.text(""), SwiftDocC.RenderInlineContent.codeVoice(code: "code block"), SwiftDocC.RenderInlineContent.text(" will not be capitalized")]))],
            [SwiftDocC.RenderBlockContent.paragraph(SwiftDocC.RenderBlockContent.Paragraph(inlineContent: [SwiftDocC.RenderInlineContent.text("a`nother invalid capitalization")]))]])
    }
    
    func testReturnsCapitalization() throws {
        let symbolGraph = makeSymbolGraph(
            docComment: """
            Some symbol description.

            - Returns: string, first word should have been capitalized here.
            """,
            parameters: []
        )
        
        let url = try createTempFolder(content: [
            Folder(name: "unit-test.docc", content: [
                JSONFile(name: "ModuleName.symbols.json", content: symbolGraph)
            ])
        ])
        let (_, bundle, context) = try loadBundle(from: url)
        
        XCTAssertEqual(context.problems.count, 0)
        
        let reference = ResolvedTopicReference(bundleIdentifier: bundle.identifier, path: "/documentation/ModuleName/functionName(...)", sourceLanguage: .swift)
        let node = try context.entity(with: reference)
        let symbol = try XCTUnwrap(node.semantic as? Symbol)
        
        let returnsSectionTranslator = ReturnsSectionTranslator()
        var renderNodeTranslator = RenderNodeTranslator(context: context, bundle: bundle, identifier: reference, source: url)
        var renderNode = renderNodeTranslator.visit(symbol) as! RenderNode
        let translatedReturns = returnsSectionTranslator.translateSection(for: symbol, renderNode: &renderNode, renderNodeTranslator: &renderNodeTranslator)
        let returnsRenderSection = translatedReturns?.defaultValue?.section as! ContentRenderSection
        
        XCTAssertEqual(returnsRenderSection.content, [SwiftDocC.RenderBlockContent.heading(SwiftDocC.RenderBlockContent.Heading(level: 2, text: "Return Value", anchor: Optional("return-value"))), SwiftDocC.RenderBlockContent.paragraph(SwiftDocC.RenderBlockContent.Paragraph(inlineContent: [SwiftDocC.RenderInlineContent.text("String, first word should have been capitalized here.")]))])
    }
}