Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Miscellaneous test changes to avoid making assumptions about what's a valid URL #586

Merged
merged 13 commits into from
Jul 26, 2023
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions Sources/SwiftDocCUtilities/Action/Actions/PreviewAction.swift
Original file line number Diff line number Diff line change
Expand Up @@ -163,9 +163,11 @@ public final class PreviewAction: Action, RecreatingContext {
// Preview the output and monitor the source bundle for changes.
do {
print(String(repeating: "=", count: 40), to: &logHandle)
print("Starting Local Preview Server", to: &logHandle)
printPreviewAddresses(base: URL(string: "http://localhost:\(port)")!)
print(String(repeating: "=", count: 40), to: &logHandle)
if let previewURL = URL(string: "http://localhost:\(port)") {
print("Starting Local Preview Server", to: &logHandle)
printPreviewAddresses(base: previewURL)
print(String(repeating: "=", count: 40), to: &logHandle)
}

let to: PreviewServer.Bind = bindServerToSocketPath.map { .socket(path: $0) } ?? .localhost(port: port)
servers[serverIdentifier] = try PreviewServer(contentURL: convertAction.targetDirectory, bindTo: to, logHandle: &logHandle)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ extension SourceRepository {
"""
)
case let (sourceService?, sourceServiceBaseURL?, checkoutPath?):
guard let sourceServiceBaseURL = URL(string: sourceServiceBaseURL) else {
guard let sourceServiceBaseURL = URL(string: sourceServiceBaseURL), sourceServiceBaseURL.scheme != nil, sourceServiceBaseURL.host != nil else {
throw ValidationError("Invalid URL '\(sourceServiceBaseURL)' for '--source-service-base-url' argument.")
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,15 +45,30 @@ class WebKitCommunicationBridgeTests: XCTestCase {

func assertMessageIsSent(message: Message) throws {
#if canImport(WebKit)
let encodedMessage = try! JSONEncoder().encode(message)
let messageJSON = String(data: encodedMessage, encoding: .utf8)!
let encodedMessage = try JSONEncoder().encode(message)
let json = try XCTUnwrap(JSONSerialization.jsonObject(with: encodedMessage) as? NSDictionary)

let didEvaluateJavaScript = expectation(description: "Did evaluate JavaScript")
let evaluateJavaScript: (String, ((Any?, Error?) -> ())?) -> () = { string, _ in
XCTAssertEqual(string, "window.bridge.receive(\(messageJSON))")
defer { didEvaluateJavaScript.fulfill() }

XCTAssert(string.hasPrefix("window.bridge.receive("))
XCTAssert(string.hasSuffix(")"))

let jsonString = String(string.dropFirst("window.bridge.receive(".count).dropLast())
guard let jsonData = jsonString.data(using: .utf8),
let decodedMessage = try? JSONSerialization.jsonObject(with: jsonData) as? NSDictionary
else {
XCTFail("Unable to decode \(jsonString) as communication bridge Message")
return
}

XCTAssertEqual(json, decodedMessage)
}

let bridge = WebKitCommunicationBridge()
XCTAssertNoThrow(try bridge.send(message, using: evaluateJavaScript))
waitForExpectations(timeout: 1.0)
#endif
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1718,10 +1718,10 @@ let expected = """

## Topics

Only curate the pages. Headings don't support curation.

- ``MyClass/myFunc🙂()``
- <doc:article-with-emoji-in-heading#Hello-🌍>
- <doc:article-with-😃-in-filename>
- <doc:article-with-😃-in-filename#Hello-world>
"""),
])
let bundleURL = try testBundle.write(inside: createTemporaryDirectory())
Expand All @@ -1739,9 +1739,7 @@ let expected = """
// Verify that all the links in the topic section resolved
XCTAssertEqual(topicSection.links.map(\.destination), [
"doc://special-characters/documentation/MyKit/MyClass/myFunc_()",
"doc://special-characters/documentation/special-characters/article-with-emoji-in-heading#Hello-%F0%9F%8C%8D",
"doc://special-characters/documentation/special-characters/article-with---in-filename",
"doc://special-characters/documentation/special-characters/article-with---in-filename#Hello-world",
])

// Verify that all resolved link exist in the context.
Expand All @@ -1756,12 +1754,10 @@ let expected = """
let renderNode = translator.visit(moduleSymbol) as! RenderNode

// Verify that the resolved links rendered as links
XCTAssertEqual(renderNode.topicSections.first?.identifiers.count, 4)
XCTAssertEqual(renderNode.topicSections.first?.identifiers.count, 2)
XCTAssertEqual(renderNode.topicSections.first?.identifiers, [
"doc://special-characters/documentation/MyKit/MyClass/myFunc_()",
"doc://special-characters/documentation/special-characters/article-with-emoji-in-heading#Hello-%F0%9F%8C%8D",
"doc://special-characters/documentation/special-characters/article-with---in-filename",
"doc://special-characters/documentation/special-characters/article-with---in-filename#Hello-world",
])


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ class ResolvedTopicReferenceTests: XCTestCase {
do {
let resolvedOriginal = ResolvedTopicReference(bundleIdentifier: "bundleID", path: "/path/sub-path", fragment: "fragment", sourceLanguage: .swift)

let unresolved = UnresolvedTopicReference(topicURL: ValidatedURL(parsingExact: "doc://host.name/;;;")!)
let unresolved = UnresolvedTopicReference(topicURL: ValidatedURL(parsingExact: "doc://host.name/ ")!)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Test Suite 'Selected tests' started at 2023-07-25 18:53:24.131
Test Suite 'SwiftDocCPackageTests.xctest' started at 2023-07-25 18:53:24.132
Test Suite 'ResolvedTopicReferenceTests' started at 2023-07-25 18:53:24.132
Test Case '-[SwiftDocCTests.ResolvedTopicReferenceTests testAppendingReferenceWithEmptyPath]' started.
SwiftDocCTests/ResolvedTopicReferenceTests.swift:57: Fatal error: Unexpectedly found nil while unwrapping an Optional value

Looks like this change made this URL initializer fail in CI.

XCTAssertFalse(unresolved.path.isEmpty)

let appended = resolvedOriginal.appendingPathOfReference(unresolved)
Expand Down
23 changes: 0 additions & 23 deletions Tests/SwiftDocCTests/Semantics/RedirectedTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -41,29 +41,6 @@ class RedirectedTests: XCTestCase {
XCTAssertEqual(redirected?.oldPath.path, oldPath)
}

func testInvalidURL() throws {
let someCharactersThatAreNotAllowedInPaths = "⊂⧺∀ℝ∀⊂⊤∃∫"
for character in someCharactersThatAreNotAllowedInPaths {
XCTAssertFalse(CharacterSet.urlPathAllowed.contains(character.unicodeScalars.first!), "Verify that \(character) is invalid")

let pathWithInvalidCharacter = "/path/with/invalid\(character)for/paths"
let source = "@Redirected(from: \(pathWithInvalidCharacter))"
let document = Document(parsing: source, options: .parseBlockDirectives)
let directive = document.child(at: 0)! as! BlockDirective
let (bundle, context) = try testBundleAndContext(named: "TestBundle")
var problems = [Problem]()
let redirected = Redirect(from: directive, source: nil, for: bundle, in: context, problems: &problems)
XCTAssertNil(redirected?.oldPath.absoluteString, "\(character)")
XCTAssertFalse(problems.containsErrors)
XCTAssertEqual(1, problems.count)
XCTAssertEqual(problems.first?.diagnostic.identifier, "org.swift.docc.HasArgument.from.ConversionFailed")
XCTAssertEqual(
problems.first?.diagnostic.summary,
"Cannot convert '\(pathWithInvalidCharacter)' to type 'URL'"
)
}
}

func testExtraArguments() throws {
let oldPath = "/old/path/to/this/page"
let source = "@Redirected(from: \(oldPath), argument: value)"
Expand Down
14 changes: 2 additions & 12 deletions Tests/SwiftDocCTests/Utility/ValidatedURLTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,19 +36,9 @@ class ValidatedURLTests: XCTestCase {
}

func testInvalidURLs() {
let invalidURLs = [
URL(string: "http://:domain")!,
]

// Test ValidatedURL.init(String)
invalidURLs.forEach { url in
XCTAssertNil(ValidatedURL(parsingExact: url.absoluteString))
}
XCTAssertNil(ValidatedURL(parsingExact: "http://:domain"))

// Test ValidatedURL.init(URL)
invalidURLs.forEach { url in
XCTAssertNil(ValidatedURL(url))
}
XCTAssertNil(URL(string: "http://:domain").flatMap { ValidatedURL($0) })
}

func testRequiringScheme() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,10 @@ class ConvertSubcommandSourceRepositoryTests: XCTestCase {
try assertSourceRepositoryArguments(
checkoutPath: "checkout path",
sourceService: sourceService,
sourceServiceBaseURL: "example.com/path/to/base"
sourceServiceBaseURL: "https://example.com/path/to/base"
) { action in
XCTAssertEqual(action.sourceRepository?.checkoutPath, "checkout path")
XCTAssertEqual(action.sourceRepository?.sourceServiceBaseURL, URL(string: "example.com/path/to/base")!)
XCTAssertEqual(action.sourceRepository?.sourceServiceBaseURL.absoluteString, "https://example.com/path/to/base")
}
}
}
Expand All @@ -55,7 +55,7 @@ class ConvertSubcommandSourceRepositoryTests: XCTestCase {
try assertSourceRepositoryArguments(
checkoutPath: nil,
sourceService: nil,
sourceServiceBaseURL: "example.com/path/to/base"
sourceServiceBaseURL: "https://example.com/path/to/base"
)
) { error in
XCTAssertEqual(
Expand Down Expand Up @@ -124,7 +124,7 @@ class ConvertSubcommandSourceRepositoryTests: XCTestCase {
try assertSourceRepositoryArguments(
checkoutPath: "checkout path",
sourceService: "not a supported source service",
sourceServiceBaseURL: "example.com/foo"
sourceServiceBaseURL: "https://example.com/foo"
)
) { error in
XCTAssertEqual(
Expand Down