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
|
/*
This source file is part of the Swift.org open source project
Copyright (c) 2021-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
@testable import SwiftDocC
import Markdown
import SwiftDocCTestUtilities
extension XCTestCase {
/// Loads a documentation bundle from the given source URL and creates a documentation context.
func loadBundle(from bundleURL: URL,
codeListings: [String : AttributedCodeListing] = [:],
externalResolvers: [String: ExternalDocumentationSource] = [:],
externalSymbolResolver: GlobalExternalSymbolResolver? = nil,
fallbackResolver: ConvertServiceFallbackResolver? = nil,
diagnosticFilterLevel: DiagnosticSeverity = .hint,
configureContext: ((DocumentationContext) throws -> Void)? = nil
) throws -> (URL, DocumentationBundle, DocumentationContext) {
let workspace = DocumentationWorkspace()
let context = try DocumentationContext(dataProvider: workspace, diagnosticEngine: DiagnosticEngine(filterLevel: diagnosticFilterLevel))
context.externalDocumentationSources = externalResolvers
context.globalExternalSymbolResolver = externalSymbolResolver
context.convertServiceFallbackResolver = fallbackResolver
context.externalMetadata.diagnosticLevel = diagnosticFilterLevel
try configureContext?(context)
// Load the bundle using automatic discovery
let automaticDataProvider = try LocalFileSystemDataProvider(rootURL: bundleURL)
// Mutate the bundle to include the code listings, then apply to the workspace using a manual provider.
var bundle = try XCTUnwrap(automaticDataProvider.bundles().first)
bundle.attributedCodeListings = codeListings
let dataProvider = PrebuiltLocalFileSystemDataProvider(bundles: [bundle])
try workspace.registerProvider(dataProvider)
return (bundleURL, bundle, context)
}
/// Loads a documentation catalog from an in-memory test file system.
///
/// - Parameters:
/// - catalog: The directory structure of the documentation catalog
/// - otherFileSystemDirectories: Any other directories in the test file system.
/// - configureContext: A closure where the caller can configure the context before registering the data provider with the context.
/// - Returns: The loaded documentation bundle and context for the given catalog input.
func loadBundle(
catalog: Folder,
otherFileSystemDirectories: [Folder] = [],
configureContext: (DocumentationContext) throws -> Void = { _ in }
) throws -> (DocumentationBundle, DocumentationContext) {
let workspace = DocumentationWorkspace()
let context = try DocumentationContext(dataProvider: workspace)
try configureContext(context)
let fileSystem = try TestFileSystem(folders: [catalog] + otherFileSystemDirectories)
context.linkResolver.fileManager = fileSystem
try workspace.registerProvider(fileSystem)
let bundle = try XCTUnwrap(context.registeredBundles.first)
return (bundle, context)
}
func testBundleAndContext(copying name: String,
excludingPaths excludedPaths: [String] = [],
codeListings: [String : AttributedCodeListing] = [:],
externalResolvers: [BundleIdentifier : ExternalDocumentationSource] = [:],
externalSymbolResolver: GlobalExternalSymbolResolver? = nil,
fallbackResolver: ConvertServiceFallbackResolver? = nil,
configureBundle: ((URL) throws -> Void)? = nil
) throws -> (URL, DocumentationBundle, DocumentationContext) {
let sourceURL = try XCTUnwrap(Bundle.module.url(
forResource: name, withExtension: "docc", subdirectory: "Test Bundles"))
let sourceExists = FileManager.default.fileExists(atPath: sourceURL.path)
let bundleURL = sourceExists
? try createTemporaryDirectory().appendingPathComponent("\(name).docc")
: try createTemporaryDirectory(named: "\(name).docc")
if sourceExists {
try FileManager.default.copyItem(at: sourceURL, to: bundleURL)
}
for path in excludedPaths {
try FileManager.default.removeItem(at: bundleURL.appendingPathComponent(path))
}
// Do any additional setup to the custom bundle - adding, modifying files, etc
try configureBundle?(bundleURL)
return try loadBundle(
from: bundleURL,
codeListings: codeListings,
externalResolvers: externalResolvers,
externalSymbolResolver: externalSymbolResolver,
fallbackResolver: fallbackResolver
)
}
func testBundleAndContext(named name: String, codeListings: [String : AttributedCodeListing] = [:], externalResolvers: [String: ExternalDocumentationSource] = [:]) throws -> (URL, DocumentationBundle, DocumentationContext) {
let bundleURL = try XCTUnwrap(Bundle.module.url(
forResource: name, withExtension: "docc", subdirectory: "Test Bundles"))
return try loadBundle(from: bundleURL, codeListings: codeListings, externalResolvers: externalResolvers)
}
func testBundleAndContext(named name: String, codeListings: [String : AttributedCodeListing] = [:], externalResolvers: [String: ExternalDocumentationSource] = [:]) throws -> (DocumentationBundle, DocumentationContext) {
let (_, bundle, context) = try testBundleAndContext(named: name, codeListings: codeListings, externalResolvers: externalResolvers)
return (bundle, context)
}
func renderNode(atPath path: String, fromTestBundleNamed testBundleName: String) throws -> RenderNode {
let (bundle, context) = try testBundleAndContext(named: testBundleName)
let node = try context.entity(with: ResolvedTopicReference(bundleIdentifier: bundle.identifier, path: path, sourceLanguage: .swift))
var translator = RenderNodeTranslator(context: context, bundle: bundle, identifier: node.reference, source: nil)
return try XCTUnwrap(translator.visit(node.semantic) as? RenderNode)
}
func testBundle(named name: String) throws -> DocumentationBundle {
let (bundle, _) = try testBundleAndContext(named: name)
return bundle
}
func testBundleFromRootURL(named name: String) throws -> DocumentationBundle {
let bundleURL = try XCTUnwrap(Bundle.module.url(
forResource: name, withExtension: "docc", subdirectory: "Test Bundles"))
let dataProvider = try LocalFileSystemDataProvider(rootURL: bundleURL)
let bundles = try dataProvider.bundles()
return bundles[0]
}
func testBundleAndContext() throws -> (bundle: DocumentationBundle, context: DocumentationContext) {
let bundle = DocumentationBundle(
info: DocumentationBundle.Info(
displayName: "Test",
identifier: "com.example.test",
version: "1.0"
),
baseURL: URL(string: "https://example.com/example")!,
symbolGraphURLs: [],
markupURLs: [],
miscResourceURLs: []
)
let provider = PrebuiltLocalFileSystemDataProvider(bundles: [bundle])
let workspace = DocumentationWorkspace()
try workspace.registerProvider(provider)
let context = try DocumentationContext(dataProvider: workspace)
return (bundle, context)
}
func parseDirective<Directive: DirectiveConvertible>(
_ directive: Directive.Type,
content: () -> String,
file: StaticString = #file,
line: UInt = #line
) throws -> (problemIdentifiers: [String], directive: Directive?) {
let (bundle, context) = try testBundleAndContext()
let source = URL(fileURLWithPath: "/path/to/test-source-\(ProcessInfo.processInfo.globallyUniqueString)")
let document = Document(parsing: content(), source: source, options: .parseBlockDirectives)
let blockDirectiveContainer = try XCTUnwrap(document.child(at: 0) as? BlockDirective, file: file, line: line)
var problems = [Problem]()
let directive = directive.init(
from: blockDirectiveContainer,
source: source,
for: bundle,
in: context,
problems: &problems
)
let problemIDs = problems.map { problem -> String in
XCTAssertNotNil(problem.diagnostic.source, "Problem \(problem.diagnostic.identifier) is missing a source URL.", file: file, line: line)
let line = problem.diagnostic.range?.lowerBound.line.description ?? "unknown-line"
return "\(line): \(problem.diagnostic.severity) – \(problem.diagnostic.identifier)"
}.sorted()
return (problemIDs, directive)
}
func parseDirective<Directive: RenderableDirectiveConvertible>(
_ directive: Directive.Type,
in bundleName: String? = nil,
content: () -> String,
file: StaticString = #file,
line: UInt = #line
) throws -> (renderBlockContent: [RenderBlockContent], problemIdentifiers: [String], directive: Directive?) {
let (renderedContent, problems, directive, _) = try parseDirective(
directive,
in: bundleName,
content: content,
file: file,
line: line
)
return (renderedContent, problems, directive)
}
func parseDirective<Directive: RenderableDirectiveConvertible>(
_ directive: Directive.Type,
in bundleName: String? = nil,
content: () -> String,
file: StaticString = #file,
line: UInt = #line
) throws -> (
renderBlockContent: [RenderBlockContent],
problemIdentifiers: [String],
directive: Directive?,
collectedReferences: [String : RenderReference]
) {
let bundle: DocumentationBundle
let context: DocumentationContext
if let bundleName {
(bundle, context) = try testBundleAndContext(named: bundleName)
} else {
(bundle, context) = try testBundleAndContext()
}
context.diagnosticEngine.clearDiagnostics()
let source = URL(fileURLWithPath: "/path/to/test-source-\(ProcessInfo.processInfo.globallyUniqueString)")
let document = Document(parsing: content(), source: source, options: [.parseBlockDirectives, .parseSymbolLinks])
let blockDirectiveContainer = try XCTUnwrap(document.child(at: 0) as? BlockDirective, file: file, line: line)
var analyzer = SemanticAnalyzer(source: source, context: context, bundle: bundle)
let result = analyzer.visit(blockDirectiveContainer)
context.diagnosticEngine.emit(analyzer.problems)
var referenceResolver = MarkupReferenceResolver(
context: context,
bundle: bundle,
rootReference: bundle.rootReference
)
_ = referenceResolver.visit(blockDirectiveContainer)
context.diagnosticEngine.emit(referenceResolver.problems)
func problemIDs() throws -> [String] {
try context.problems.map { problem -> (line: Int, severity: String, id: String) in
XCTAssertNotNil(problem.diagnostic.source, "Problem \(problem.diagnostic.identifier) is missing a source URL.", file: file, line: line)
let line = try XCTUnwrap(problem.diagnostic.range, file: file, line: line).lowerBound.line
return (line, problem.diagnostic.severity.description, problem.diagnostic.identifier)
}
.sorted { lhs, rhs in
let (lhsLine, _, lhsID) = lhs
let (rhsLine, _, rhsID) = rhs
if lhsLine != rhsLine {
return lhsLine < rhsLine
} else {
return lhsID < rhsID
}
}
.map { (line, severity, id) in
return "\(line): \(severity) – \(id)"
}
}
guard let directive = result as? Directive else {
return ([], try problemIDs(), nil, [:])
}
var contentCompiler = RenderContentCompiler(
context: context,
bundle: bundle,
identifier: ResolvedTopicReference(
bundleIdentifier: bundle.identifier,
path: "/test-path-123",
sourceLanguage: .swift
)
)
let renderedContent = try XCTUnwrap(
directive.render(with: &contentCompiler) as? [RenderBlockContent],
file: file, line: line
)
let collectedReferences = contentCompiler.videoReferences
.mapValues { $0 as RenderReference }
.merging(
contentCompiler.imageReferences,
uniquingKeysWith: { videoReference, _ in
XCTFail("Non-unique references.", file: file, line: line)
return videoReference
}
)
return (renderedContent, try problemIDs(), directive, collectedReferences)
}
func renderNodeApplying(variant: String, to renderNode: RenderNode) throws -> RenderNode {
let variantData = try RenderNodeVariantOverridesApplier().applyVariantOverrides(
in: RenderJSONEncoder.makeEncoder().encode(renderNode),
for: [.interfaceLanguage(variant)]
)
return try RenderJSONDecoder.makeDecoder().decode(
RenderNode.self,
from: variantData
)
}
}
|