Improve performance of link fetcher unit tests

This commit is contained in:
Max Radermacher 2023-03-23 16:49:14 -07:00
parent 0a105cf732
commit a254819cc7
3 changed files with 14 additions and 12 deletions

View File

@ -27,8 +27,8 @@ public enum LinkValidator {
}
public static func firstLinkPreviewURL(in entireMessage: String) -> URL? {
guard let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) else {
owsFailDebug("Could not create NSDataDetector")
// Don't include link previews for oversize text messages.
guard entireMessage.utf8.dropFirst(Int(kOversizeTextMessageSizeThreshold) - 1).isEmpty else {
return nil
}
@ -36,6 +36,11 @@ public enum LinkValidator {
return nil
}
guard let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) else {
owsFailDebug("Could not create NSDataDetector")
return nil
}
var result: URL?
detector.enumerateMatches(in: entireMessage, range: entireMessage.entireRange) { match, _, stop in
guard let match = match else { return }

View File

@ -77,8 +77,11 @@ class LinkValidatorTest: XCTestCase {
("alice bob https://www.youtube.com/watch?v=tP-Ipsat90c jim", "https://www.youtube.com/watch?v=tP-Ipsat90c"),
// If there are more than one, take the first.
("alice bob https://signal.org/url_1 jim https://signal.org/url_2 carol", "https://signal.org/url_1")
// If there is more than one, take the first.
("alice bob https://signal.org/url_1 jim https://signal.org/url_2 carol", "https://signal.org/url_1"),
// If there's too much text, we can't parse any URLs.
("https://signal.org " + String(repeating: "A", count: 4096), nil)
]
for (entireMessage, expectedValue) in testCases {
let actualValue = LinkValidator.firstLinkPreviewURL(in: entireMessage)
@ -86,12 +89,11 @@ class LinkValidatorTest: XCTestCase {
}
}
func testFindFirstValidUrlPerformance() throws {
func testFirstLinkPreviewURLPerformance() throws {
let entireMessage = String(repeating: "https://example.com ", count: 1_000_000)
let expectedValue = try XCTUnwrap(URL(string: "https://example.com"))
measure {
let actualValue = LinkValidator.firstLinkPreviewURL(in: entireMessage)
XCTAssertEqual(actualValue, expectedValue)
XCTAssertNil(actualValue)
}
}
}

View File

@ -149,11 +149,6 @@ public class LinkPreviewFetcher {
self.prependSchemeIfNeeded(to: &filteredText)
}
// Don't include link previews for oversize text messages.
guard filteredText.lengthOfBytes(using: .utf8) < kOversizeTextMessageSizeThreshold else {
return nil
}
return LinkValidator.firstLinkPreviewURL(in: filteredText)
}