Repository Public License
1import Foundation2import Testing3@testable import DownloadEngine45@Suite struct ContentDispositionTests {6 @Test(arguments: [7 (#"attachment; filename="report.pdf""#, "report.pdf"),8 ("attachment; filename=report.pdf", "report.pdf"),9 ("attachment;filename=report.pdf;", "report.pdf"),10 (#"ATTACHMENT; FILENAME="Upper.TXT""#, "Upper.TXT"),11 (#"attachment; filename="a \"quoted\" name.txt""#, #"a "quoted" name.txt"#),12 (#"attachment; filename="semi;colon.txt""#, "semi;colon.txt"),13 (#"attachment; size=42; filename="after-other.bin"; x=y"#, "after-other.bin"),14 ("attachment; filename*=UTF-8''%e2%82%ac%20rates.pdf", "€ rates.pdf"),15 (#"attachment; filename="EURO rates.pdf"; filename*=utf-8''%e2%82%ac%20rates.pdf"#, "€ rates.pdf"),16 (#"attachment; filename*=UTF-8''%E2%82%AC%20rates.pdf; filename="EURO rates.pdf""#, "€ rates.pdf"),17 ("attachment; filename*=iso-8859-1'en'%A3%20rates", "£ rates"),18 ("attachment; filename*=UTF-8'fr-CA'r%C3%A9sum%C3%A9.pdf", "résumé.pdf"),19 (#"inline; filename="shown.png""#, "shown.png"),20 // Undecodable extended values fall back to the plain parameter.21 (#"attachment; filename="fallback.txt"; filename*=UTF-8''%ZZbad"#, "fallback.txt"),22 (#"attachment; filename="fallback.txt"; filename*=UTF-8''%ff%fe"#, "fallback.txt"),23 (#"attachment; filename="fallback.txt"; filename*=KOI8-R''%C1%C2"#, "fallback.txt"),24 (#"attachment; filename="fallback.txt"; filename*=missing-quotes"#, "fallback.txt"),25 (#"attachment; filename="first.txt"; filename="second.txt""#, "first.txt"),26 ])27 func preferredFilename(header: String, expected: String) {28 #expect(ContentDisposition.parse(header)?.preferredFilename == expected)29 }3031 @Test(arguments: ["attachment", "inline", "attachment; filename=", #"attachment; filename="""#, "attachment; filename*=UTF-8''",32 "attachment; name=field", "form-data; name=\"x\"", ";;;", "attachment; filename*=UTF-8''%e2%82"])33 func headersWithoutAUsableName(header: String) {34 #expect(ContentDisposition.parse(header)?.preferredFilename == nil)35 }3637 @Test func kindsAndEmptyInput() {38 #expect(ContentDisposition.parse("attachment")?.kind == .attachment)39 #expect(ContentDisposition.parse("INLINE; filename=x")?.kind == .inline)40 #expect(ContentDisposition.parse("form-data; name=x")?.kind == .other)41 #expect(ContentDisposition.parse("") == nil)42 #expect(ContentDisposition.parse(" ") == nil)43 #expect(ContentDisposition.parse(#"attachment; filename="unterminated"#)?.filename == "unterminated")44 }45}4647@Suite struct FilenameSanitizerTests {48 /// Adversarial and ordinary names: input → the single safe path component it becomes.49 @Test(arguments: [50 ("report.pdf", "report.pdf"),51 ("Rapport final (v2).pdf", "Rapport final (v2).pdf"),52 ("📄 notes d’été.txt", "📄 notes d’été.txt"),53 // Path traversal, absolute paths, both separators.54 ("../../etc/passwd", "passwd"),55 ("..\\..\\windows\\system32\\cmd.exe", "cmd.exe"),56 ("/absolute/path/file.txt", "file.txt"),57 ("C:\\Users\\me\\doc.txt", "doc.txt"),58 ("a/b/c/", "c"),59 ("....//....//secret.txt", "secret.txt"),60 ("..%2f..%2fliteral.txt", "%2f..%2fliteral.txt"), // not decoded here: a literal, harmless name61 // NUL and other control characters.62 ("safe.txt\u{0}.exe", "safe.txt.exe"),63 ("a/b\u{0}c.txt", "bc.txt"),64 ("tab\there\nnew\rline.txt", "tabherenewline.txt"),65 ("bell\u{7}escape\u{1B}[31m.txt", "bellescape[31m.txt"),66 ("del\u{7F}c1\u{85}.txt", "delc1.txt"),67 // Bidirectional overrides and invisible characters (the "exe.fdp" trick).68 ("evil\u{202E}fdp.exe", "evilfdp.exe"),69 ("photo\u{202E}gnp.scr", "photognp.scr"),70 ("iso\u{2066}late\u{2069}.txt", "isolate.txt"),71 ("zero\u{200B}width\u{FEFF}\u{200D}.txt", "zerowidth.txt"),72 ("soft\u{AD}hyphen.txt", "softhyphen.txt"),73 ("line\u{2028}para\u{2029}.txt", "linepara.txt"),74 ("tag\u{E0041}chars.txt", "tagchars.txt"),75 // Hidden files, dots and spaces at the edges.76 (".hidden", "hidden"),77 (".htaccess", "htaccess"),78 ("...dots.txt...", "dots.txt"),79 (" leading.txt", "leading.txt"),80 ("trailing space.txt ", "trailing space.txt"),81 ("name.", "name"),82 ("file.exe .", "file.exe"),83 ("file.exe...", "file.exe"),84 ("invoice.pdf .exe", "invoice.pdf.exe"),85 ("spaced out \u{A0}\u{2003} name.txt", "spaced out name.txt"),86 // Characters other systems reject.87 ("a:b*c?d\"e<f>g|h.txt", "a_b_c_d_e_f_g_h.txt"),88 ("12:30 meeting.ics", "12_30 meeting.ics"),89 // Windows reserved device names.90 ("CON", "_CON"), ("con.txt", "_con.txt"), ("LPT1.pdf", "_LPT1.pdf"), ("nul.tar.gz", "_nul.tar.gz"), ("Aux.h", "_Aux.h"),91 ("COM0", "COM0"), ("console.txt", "console.txt"), ("lpt10.txt", "lpt10.txt"),92 // Double extensions are kept: they are what the file really is.93 ("archive.tar.gz", "archive.tar.gz"),94 ("invoice.pdf.exe", "invoice.pdf.exe"),95 ("-rf", "-rf"),96 ("~", "~"),97 ])98 func sanitize(input: String, expected: String) {99 let result = DownloadFilename.sanitize(input)100 #expect(result == expected, "\(input.debugDescription)")101 if let result {102 #expect(!result.contains("/") && !result.contains("\\") && !result.hasPrefix(".") && !result.hasSuffix(".") && !result.hasSuffix(" "))103 #expect(DownloadFilename.sanitize(result) == result) // idempotent104 }105 }106107 @Test(arguments: ["", " ", ".", "..", "...", "/", "//", "\\", "foo/..", "a/.", "\u{0}", "\u{202E}", "\u{200B}\u{FEFF}", " . . ", "../..", "\t\n"])108 func emptyNamesGiveNothing(input: String) {109 #expect(DownloadFilename.sanitize(input) == nil, "\(input.debugDescription)")110 }111112 @Test func unicodeIsNormalisedToNFC() {113 let decomposed = "re\u{301}sume\u{301}.pdf"114 #expect(DownloadFilename.sanitize(decomposed) == "résumé.pdf")115 #expect(DownloadFilename.sanitize(decomposed)?.unicodeScalars.count == 10)116 }117118 @Test func veryLongNamesAreCappedAndKeepTheirExtension() throws {119 let long = try #require(DownloadFilename.sanitize(String(repeating: "a", count: 5_000) + ".pdf"))120 #expect(long.utf8.count == DownloadFilename.maximumBytes && long.hasSuffix(".pdf"))121 let accented = try #require(DownloadFilename.sanitize(String(repeating: "é", count: 500) + ".txt"))122 #expect(accented.utf8.count <= DownloadFilename.maximumBytes && accented.hasSuffix(".txt") && accented.count == 98 + 4)123 let compound = try #require(DownloadFilename.sanitize(String(repeating: "b", count: 400) + ".tar.gz"))124 #expect(compound.hasSuffix(".tar.gz") && compound.utf8.count == DownloadFilename.maximumBytes)125 // Never cut inside a character: the result is still valid text made of whole emoji.126 let emoji = try #require(DownloadFilename.sanitize(String(repeating: "🧑🏽🚀", count: 80) + ".png"))127 #expect(emoji.utf8.count <= DownloadFilename.maximumBytes && emoji.hasSuffix(".png"))128 #expect(emoji.dropLast(4).allSatisfy { !$0.isASCII })129 // An absurdly long "extension" is not treated as one.130 let fakeExtension = try #require(DownloadFilename.sanitize("a." + String(repeating: "x", count: 600)))131 #expect(fakeExtension.utf8.count == DownloadFilename.maximumBytes)132 let noExtension = try #require(DownloadFilename.sanitize(String(repeating: "n", count: 300)))133 #expect(noExtension.utf8.count == DownloadFilename.maximumBytes)134 }135136 @Test func splitUnderstandsCompoundExtensions() {137 #expect(DownloadFilename.split("a.pdf") == ("a", "pdf"))138 #expect(DownloadFilename.split("archive.tar.gz") == ("archive", "tar.gz"))139 #expect(DownloadFilename.split("archive.TAR.BZ2") == ("archive", "TAR.BZ2"))140 #expect(DownloadFilename.split("photo.jpg.gz") == ("photo.jpg", "gz"))141 #expect(DownloadFilename.split("README") == ("README", ""))142 #expect(DownloadFilename.split("v1.2 notes") == ("v1.2 notes", ""))143 #expect(DownloadFilename.split(".tar.gz") == (".tar", "gz"))144 #expect(DownloadFilename.split("a.b c") == ("a.b c", ""))145 }146}147148@Suite struct FilenameDerivationTests {149 private func derive(_ url: String, header: String? = nil, suggested: String? = nil, mime: String? = nil) -> DerivedFilename {150 DownloadFilename.derive(contentDisposition: header, suggested: suggested, url: URL(string: url), mimeType: mime)151 }152153 @Test func sourcesInOrderOfTrust() {154 let header = #"attachment; filename="from-header.pdf""#155 #expect(derive("https://e.com/from-url.pdf", header: header, suggested: "from-webkit.pdf") == DerivedFilename(name: "from-header.pdf", source: .contentDisposition))156 #expect(derive("https://e.com/from-url.pdf", suggested: "from-webkit.pdf") == DerivedFilename(name: "from-webkit.pdf", source: .suggested))157 #expect(derive("https://e.com/dir/from-url.pdf?x=1#f") == DerivedFilename(name: "from-url.pdf", source: .url))158 #expect(derive("https://e.com/") == DerivedFilename(name: "download", source: .fallback))159 #expect(derive("https://e.com") == DerivedFilename(name: "download", source: .fallback))160 // An unusable header or suggestion falls through to the next source.161 #expect(derive("https://e.com/real.pdf", header: #"attachment; filename="..""#, suggested: "\u{202E}").name == "real.pdf")162 #expect(DownloadFilename.derive(url: nil, fallback: "../x").name == "x")163 }164165 @Test func hostileNamesFromEverySource() {166 #expect(derive("https://e.com/x", header: #"attachment; filename="../../../etc/passwd""#).name == "passwd")167 #expect(derive("https://e.com/x", header: "attachment; filename*=UTF-8''..%2F..%2F.ssh%2Fauthorized_keys").name == "authorized_keys")168 #expect(derive("https://e.com/x", header: #"attachment; filename="C:\temp\x.txt""#).name == "C_tempx.txt")169 #expect(derive("https://e.com/files/%2e%2e%2f%2e%2e%2fetc%2fpasswd").name == "passwd")170 #expect(derive("https://e.com/a%00b.txt").name == "ab.txt")171 #expect(derive("https://e.com/x", suggested: "invoice\u{202E}fdp.exe").name == "invoicefdp.exe")172 #expect(derive("https://e.com/r%C3%A9sum%C3%A9.pdf").name == "résumé.pdf")173 #expect(derive("https://e.com/bad%ZZencoding.txt").name == "bad%ZZencoding.txt")174 }175176 @Test(arguments: [177 // (suggested, MIME type, expected)178 ("report", "application/pdf", "report.pdf"),179 ("notes", "text/plain", "notes.txt"),180 ("x", "Application/PDF; charset=binary", "x.pdf"),181 ("report.final", "application/pdf", "report.final.pdf"), // unknown extension: the real type is appended182 ("data", "application/octet-stream", "data"), // generic type says nothing183 ("data", "application/x-no-such-type-anywhere", "data"),184 ("data", "", "data"),185 ("photo.jpg", "application/x-msdownload", "photo.jpg"), // never renamed silently: see DownloadRisk186 ("setup.exe", "text/plain", "setup.exe"),187 ("archive.tar.gz", "application/gzip", "archive.tar.gz"),188 ("page.html", "text/html", "page.html"),189 ("image.JPG", "image/jpeg", "image.JPG"),190 ])191 func extensionsAreReconciledWithTheMIMEType(suggested: String, mime: String, expected: String) {192 #expect(derive("https://e.com/x", suggested: suggested, mime: mime).name == expected)193 }194195 @Test func serverSideExtensionsInAURLGiveWayToTheRealType() {196 #expect(derive("https://e.com/download.php?id=3", mime: "application/pdf").name == "download.pdf")197 #expect(derive("https://e.com/view.aspx", mime: "image/png").name == "view.png")198 #expect(derive("https://e.com/index.php", mime: "text/html").name == "index.html")199 #expect(derive("https://e.com/page.html", mime: "text/html").name == "page.html")200 #expect(derive("https://e.com/", mime: "application/pdf").name == "download.pdf")201 // Stated by the server: kept.202 #expect(derive("https://e.com/x", header: #"attachment; filename="export.php""#, mime: "application/pdf").name == "export.php")203 // Not a server-side extension: kept even when it comes from the URL.204 #expect(derive("https://e.com/setup.exe", mime: "text/plain").name == "setup.exe")205 }206}207208@Suite struct DestinationTests {209 @Test func numberedNames() {210 #expect(DownloadFilename.numbered("file.pdf", attempt: 1) == "file.pdf")211 #expect(DownloadFilename.numbered("file.pdf", attempt: 2) == "file (2).pdf")212 #expect(DownloadFilename.numbered("archive.tar.gz", attempt: 3) == "archive (3).tar.gz")213 #expect(DownloadFilename.numbered("README", attempt: 12) == "README (12)")214 let long = DownloadFilename.sanitize(String(repeating: "a", count: 400) + ".pdf")!215 let numbered = DownloadFilename.numbered(long, attempt: 9_999)216 #expect(numbered.utf8.count <= DownloadFilename.maximumBytes && numbered.hasSuffix(" (9999).pdf"))217 }218219 @Test func uniqueNamesNeverOverwrite() throws {220 let directory = FileManager.default.temporaryDirectory.appending(path: "orix-dl-\(UUID().uuidString)", directoryHint: .isDirectory)221 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)222 defer { try? FileManager.default.removeItem(at: directory) }223 let exists: (URL) -> Bool = { FileManager.default.fileExists(atPath: $0.path(percentEncoded: false)) }224 #expect(DownloadFilename.uniqueURL(in: directory, filename: "file.pdf", isTaken: exists).lastPathComponent == "file.pdf")225 for name in ["file.pdf", "file (2).pdf", "file (3).pdf"] { try Data().write(to: directory.appending(path: name)) }226 #expect(DownloadFilename.uniqueURL(in: directory, filename: "file.pdf", isTaken: exists).lastPathComponent == "file (4).pdf")227 // In-flight names count too.228 let reserved: Set<String> = ["new.zip", "new (2).zip"]229 #expect(DownloadFilename.uniqueURL(in: directory, filename: "new.zip") { reserved.contains($0.lastPathComponent) }.lastPathComponent == "new (3).zip")230 // Everything taken: a neutral unique name, same extension, still inside the directory.231 let fallback = DownloadFilename.uniqueURL(in: directory, filename: "always.txt") { _ in true }232 #expect(fallback.lastPathComponent.hasPrefix("download-") && fallback.pathExtension == "txt")233 #expect(DownloadFilename.isDirectChild(fallback, of: directory))234 }235236 @Test(arguments: ["../../escape.txt", "/etc/passwd", "..", "a/../../b.txt", "sub/dir/file.txt", "..\\..\\x.bat", "\u{0}/../x", ".", ""])237 func theDestinationNeverLeavesItsDirectory(hostile: String) {238 let directory = URL(fileURLWithPath: "/tmp/orix-downloads", isDirectory: true)239 let url = DownloadFilename.uniqueURL(in: directory, filename: hostile) { _ in false }240 #expect(DownloadFilename.isDirectChild(url, of: directory), "\(url.path)")241 #expect(url.deletingLastPathComponent().standardizedFileURL.path == directory.standardizedFileURL.path)242 }243244 @Test func directChildCheck() {245 let directory = URL(fileURLWithPath: "/tmp/dl", isDirectory: true)246 #expect(DownloadFilename.isDirectChild(URL(fileURLWithPath: "/tmp/dl/a.txt"), of: directory))247 #expect(!DownloadFilename.isDirectChild(URL(fileURLWithPath: "/tmp/dl/sub/a.txt"), of: directory))248 #expect(!DownloadFilename.isDirectChild(URL(fileURLWithPath: "/tmp/dl/../a.txt"), of: directory))249 #expect(!DownloadFilename.isDirectChild(URL(fileURLWithPath: "/tmp/dl-other/a.txt"), of: directory))250 #expect(!DownloadFilename.isDirectChild(URL(fileURLWithPath: "/tmp/dl"), of: directory))251 #expect(!DownloadFilename.isDirectChild(URL(fileURLWithPath: "/etc/passwd"), of: directory))252 }253}254255@Suite struct DownloadRiskTests {256 @Test(arguments: [257 ("setup.exe", [DownloadRiskReason.executable]), ("Tool.APP", [.executable]), ("lib.dylib", [.executable]), ("applet.jar", [.executable]),258 ("Install.pkg", [.installer]), ("disk.dmg", [.installer]), ("app.APK", [.installer]), ("setup.msi", [.installer]), ("ext.crx", [.installer]),259 ("run.sh", [.script]), ("tool.command", [.script]), ("script.py", [.script]), ("macro.vbs", [.script]), ("evil.ps1", [.script]),260 ("x.bat", [.script]), ("automation.scpt", [.script]), ("code.js", [.script]),261 ("profile.mobileconfig", [.configuration]), ("tweak.reg", [.configuration]), ("settings.terminal", [.configuration]),262 ("link.webloc", [.shortcut]), ("shortcut.lnk", [.shortcut]), ("site.url", [.shortcut]),263 ("invoice.pdf.exe", [.executable, .disguisedExtension]), ("photo.jpg.scr", [.executable, .disguisedExtension]),264 ("report.docx.js", [.script, .disguisedExtension]), ("holiday.png.command", [.script, .disguisedExtension]),265 ])266 func dangerousFilesNeedConfirmation(filename: String, reasons: [DownloadRiskReason]) {267 let risk = DownloadRiskClassifier.classify(filename: filename)268 #expect(risk.level == .dangerous && risk.requiresOpenConfirmation, "\(filename)")269 #expect(risk.reasons == reasons, "\(filename): \(risk.reasons)")270 }271272 @Test(arguments: [273 ("archive.zip", [DownloadRiskReason.archive]), ("backup.tar.gz", [.archive]), ("stuff.7z", [.archive]),274 ("budget.xlsm", [.macroDocument]), ("old.doc", [.macroDocument]), ("page.html", [.activeContent]), ("drawing.svg", [.activeContent]),275 ("setup.exe.zip", [.archive, .executable]), ("run.sh.gz", [.archive, .script]),276 ])277 func cautionFilesOpenWithoutConfirmationButAreFlagged(filename: String, reasons: [DownloadRiskReason]) {278 let risk = DownloadRiskClassifier.classify(filename: filename)279 #expect(risk.level == .caution && !risk.requiresOpenConfirmation, "\(filename)")280 #expect(risk.reasons == reasons, "\(filename): \(risk.reasons)")281 }282283 @Test(arguments: ["report.pdf", "photo.JPG", "song.mp3", "movie.mp4", "notes.txt", "data.csv", "data.json", "book.epub", "slides.pptx",284 "README", "Makefile", "photo.jpg.png", "v1.2.3-notes.md", "font.woff2"])285 func ordinaryFilesAreSafe(filename: String) {286 #expect(DownloadRiskClassifier.classify(filename: filename) == .safe, "\(filename)")287 }288289 @Test func theMIMETypeMattersWhenTheNameSaysNothing() {290 #expect(DownloadRiskClassifier.classify(filename: "download", mimeType: "application/x-msdownload") == DownloadRisk(level: .dangerous, reasons: [.executable]))291 #expect(DownloadRiskClassifier.classify(filename: "download", mimeType: "text/x-shellscript; charset=utf-8").reasons == [.script])292 #expect(DownloadRiskClassifier.classify(filename: "download", mimeType: "application/x-apple-diskimage").level == .dangerous)293 #expect(DownloadRiskClassifier.classify(filename: "download", mimeType: "application/pdf") == .safe)294 // A program type on a harmless name: the system opens it as what the name says, so only a caution.295 #expect(DownloadRiskClassifier.classify(filename: "photo.jpg", mimeType: "application/x-msdownload") == DownloadRisk(level: .caution, reasons: [.typeMismatch]))296 #expect(DownloadRiskClassifier.classify(filename: "setup.exe", mimeType: "application/x-msdownload").reasons == [.executable])297 #expect(DownloadRiskClassifier.classify(filename: "setup.exe", mimeType: "image/png").level == .dangerous) // a reassuring type does not help298 #expect(DownloadRisk.Level.caution < .dangerous)299 }300}301302@Suite struct ProgressTests {303 let start = Date(timeIntervalSince1970: 1_000)304305 @Test func speedAndRemainingTimeOverASteadyTransfer() {306 var meter = DownloadSpeedMeter(window: 5)307 #expect(meter.bytesPerSecond(at: start) == nil)308 meter.record(bytes: 0, at: start)309 #expect(meter.bytesPerSecond(at: start) == nil) // one sample is not a speed310 meter.record(bytes: 200, at: start.addingTimeInterval(0.2))311 #expect(meter.bytesPerSecond(at: start.addingTimeInterval(0.2)) == nil) // too short a span312 meter.record(bytes: 1_000, at: start.addingTimeInterval(1))313 meter.record(bytes: 2_000, at: start.addingTimeInterval(2))314 #expect(meter.bytesPerSecond(at: start.addingTimeInterval(2)) == 1_000)315 #expect(meter.estimatedSecondsRemaining(totalBytes: 10_000, at: start.addingTimeInterval(2)) == 8)316 #expect(meter.estimatedSecondsRemaining(totalBytes: nil, at: start.addingTimeInterval(2)) == nil)317 #expect(meter.estimatedSecondsRemaining(totalBytes: 2_000, at: start.addingTimeInterval(2)) == 0)318 #expect(meter.estimatedSecondsRemaining(totalBytes: 1_500, at: start.addingTimeInterval(2)) == 0) // server lied about the size319 }320321 @Test func theWindowSlidesSoTheSpeedFollowsTheTransfer() {322 var meter = DownloadSpeedMeter(window: 5)323 var bytes: Int64 = 0324 for second in 0...10 { meter.record(bytes: bytes, at: start.addingTimeInterval(Double(second))); bytes += 1_000 }325 bytes -= 1_000326 #expect(meter.bytesPerSecond(at: start.addingTimeInterval(10)) == 1_000)327 for second in 11...15 { bytes += 5_000; meter.record(bytes: bytes, at: start.addingTimeInterval(Double(second))) }328 #expect(meter.bytesPerSecond(at: start.addingTimeInterval(15)) == 5_000) // only the last 5 s count329 #expect(meter.estimatedSecondsRemaining(totalBytes: bytes + 10_000, at: start.addingTimeInterval(15)) == 2)330 // Half-way through the change the average mixes both.331 var mixed = DownloadSpeedMeter(window: 4)332 mixed.record(bytes: 0, at: start); mixed.record(bytes: 2_000, at: start.addingTimeInterval(2)); mixed.record(bytes: 12_000, at: start.addingTimeInterval(4))333 #expect(mixed.bytesPerSecond(at: start.addingTimeInterval(4)) == 3_000)334 }335336 @Test func stallsRestartsAndClockJumps() {337 var meter = DownloadSpeedMeter(window: 5)338 meter.record(bytes: 0, at: start); meter.record(bytes: 5_000, at: start.addingTimeInterval(1))339 #expect(meter.bytesPerSecond(at: start.addingTimeInterval(3)) == 5_000)340 #expect(meter.bytesPerSecond(at: start.addingTimeInterval(6)) == 0) // nothing for a whole window: stalled341 #expect(meter.estimatedSecondsRemaining(totalBytes: 9_000, at: start.addingTimeInterval(6)) == nil)342 meter.record(bytes: 100, at: start.addingTimeInterval(7)) // the byte count went backwards: restarted343 #expect(meter.bytesPerSecond(at: start.addingTimeInterval(7)) == nil)344 meter.record(bytes: 1_100, at: start.addingTimeInterval(8))345 #expect(meter.bytesPerSecond(at: start.addingTimeInterval(8)) == 1_000)346 meter.record(bytes: 1_200, at: start.addingTimeInterval(2)) // the clock went backwards347 #expect(meter.bytesPerSecond(at: start.addingTimeInterval(2)) == nil)348 meter.record(bytes: 1_300, at: start.addingTimeInterval(2)) // same instant: replaces the sample349 meter.record(bytes: 2_300, at: start.addingTimeInterval(3))350 #expect(meter.bytesPerSecond(at: start.addingTimeInterval(3)) == 1_000)351 meter.reset()352 #expect(meter.bytesPerSecond(at: start) == nil)353 #expect(DownloadSpeedMeter(window: 0, minimumSpan: 9).window == 0.1)354 }355356 @Test func throttleLetsOneUpdateThroughPerInterval() {357 var throttle = ProgressThrottle(interval: 0.25)358 var emitted = 0359 // 1 000 progress events 10 ms apart: 10 seconds of transfer.360 for tick in 0..<1_000 where throttle.shouldEmit(at: start.addingTimeInterval(Double(tick) * 0.01)) { emitted += 1 }361 #expect(emitted == 40)362 let tooSoon = throttle.shouldEmit(at: start.addingTimeInterval(9.99))363 let forced = throttle.shouldEmit(at: start.addingTimeInterval(9.99), force: true)364 let afterClockWentBack = throttle.shouldEmit(at: start.addingTimeInterval(1)) // never get stuck365 #expect(!tooSoon && forced && afterClockWentBack)366 #expect(ProgressThrottle(interval: -1).interval == 0)367 }368}369