From 2a8242c990f288db8202ddbda7481deccad45033 Mon Sep 17 00:00:00 2001 From: 417-72KI <417.72ki@gmail.com> Date: Fri, 14 Nov 2025 19:57:25 +0900 Subject: [PATCH 01/13] add Package.swift for Swift 6 --- Package@swift-6.0.swift | 92 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 Package@swift-6.0.swift diff --git a/Package@swift-6.0.swift b/Package@swift-6.0.swift new file mode 100644 index 00000000..841819e9 --- /dev/null +++ b/Package@swift-6.0.swift @@ -0,0 +1,92 @@ +// swift-tools-version:6.0 +// The swift-tools-version declares the minimum version of Swift required to build this package. + +import PackageDescription + +let isDevelop = true +let isApplePlatform: Bool = { + #if canImport(Darwin) + true + #else + false + #endif +}() + +let package = Package( + name: "MultipartFormDataParser", + platforms: [ + .macOS(.v13), + .macCatalyst(.v16), + .iOS(.v16), + .tvOS(.v16) + ], + products: [ + .library(name: "MultipartFormDataParser", targets: ["MultipartFormDataParser"]), + ], + dependencies: [], + targets: [ + .target(name: "MultipartFormDataParser"), + .testTarget(name: "MultipartFormDataParserTests", dependencies: ["MultipartFormDataParser"]), + ] +) + +// MARK: - develop +if isDevelop { + if isApplePlatform { + package.dependencies.append(contentsOf: [ + .package(url: "https://github.com/SimplyDanny/SwiftLintPlugins", from: "0.57.0"), + .package(url: "https://github.com/Alamofire/Alamofire.git", from: "5.7.0"), + .package(url: "https://github.com/ishkawa/APIKit.git", from: "5.4.0"), + ]) + package.targets + .filter(\.isTest) + .forEach { + $0.dependencies.append(contentsOf: [ + "Alamofire", + "APIKit", + ]) + } + package.targets.forEach { + if $0.plugins == nil { + $0.plugins = [] + } + $0.plugins?.append(.plugin(name: "SwiftLintBuildToolPlugin", package: "SwiftLintPlugins")) + } + } +} + +// MARK: - Upcoming feature flags for Swift 6 +package.targets.forEach { + $0.swiftSettings = [ + .forwardTrailingClosures, + .existentialAny, + .bareSlashRegexLiterals, + .conciseMagicFile, + .importObjcForwardDeclarations, + .disableOutwardActorInference, + .deprecateApplicationMain, + .isolatedDefaultValues, + .globalConcurrency, + ] +} + +// ref: https://github.com/treastrain/swift-upcomingfeatureflags-cheatsheet +private extension SwiftSetting { + static let forwardTrailingClosures: Self = .enableUpcomingFeature("ForwardTrailingClosures") // SE-0286, Swift 5.3, SwiftPM 5.8+ + static let existentialAny: Self = .enableUpcomingFeature("ExistentialAny") // SE-0335, Swift 5.6, SwiftPM 5.8+ + static let bareSlashRegexLiterals: Self = .enableUpcomingFeature("BareSlashRegexLiterals") // SE-0354, Swift 5.7, SwiftPM 5.8+ + static let conciseMagicFile: Self = .enableUpcomingFeature("ConciseMagicFile") // SE-0274, Swift 5.8, SwiftPM 5.8+ + static let importObjcForwardDeclarations: Self = .enableUpcomingFeature("ImportObjcForwardDeclarations") // SE-0384, Swift 5.9, SwiftPM 5.9+ + static let disableOutwardActorInference: Self = .enableUpcomingFeature("DisableOutwardActorInference") // SE-0401, Swift 5.9, SwiftPM 5.9+ + static let deprecateApplicationMain: Self = .enableUpcomingFeature("DeprecateApplicationMain") // SE-0383, Swift 5.10, SwiftPM 5.10+ + static let isolatedDefaultValues: Self = .enableUpcomingFeature("IsolatedDefaultValues") // SE-0411, Swift 5.10, SwiftPM 5.10+ + static let globalConcurrency: Self = .enableUpcomingFeature("GlobalConcurrency") // SE-0412, Swift 5.10, SwiftPM 5.10+ +} + +// MARK: - Enabling Complete Concurrency Checking for Swift 6 +// ref: https://www.swift.org/documentation/concurrency/ +package.targets.forEach { + var settings = $0.swiftSettings ?? [] + settings.append(.enableExperimentalFeature("StrictConcurrency")) + $0.swiftSettings = settings +} From d43085c7d998c000aa1f672da4d321f2b27aa045 Mon Sep 17 00:00:00 2001 From: 417-72KI <417.72ki@gmail.com> Date: Wed, 14 Oct 2026 00:46:23 +0900 Subject: [PATCH 02/13] replace swift tools version to 6.x --- Package.swift | 47 ++++++++++++++------- Package@swift-6.0.swift | 92 ----------------------------------------- 2 files changed, 33 insertions(+), 106 deletions(-) delete mode 100644 Package@swift-6.0.swift diff --git a/Package.swift b/Package.swift index 71eba91b..c0ddf8c7 100644 --- a/Package.swift +++ b/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:5.10 +// swift-tools-version:6.1 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription @@ -27,7 +27,8 @@ let package = Package( targets: [ .target(name: "MultipartFormDataParser"), .testTarget(name: "MultipartFormDataParserTests", dependencies: ["MultipartFormDataParser"]), - ] + ], + swiftLanguageModes: [.v5] ) // MARK: - develop @@ -58,29 +59,47 @@ if isDevelop { // MARK: - Upcoming feature flags for Swift 6 package.targets.forEach { $0.swiftSettings = [ + .conciseMagicFile, .forwardTrailingClosures, - .existentialAny, + .strictConcurrency, .bareSlashRegexLiterals, - .conciseMagicFile, + .deprecateApplicationMain, .importObjcForwardDeclarations, .disableOutwardActorInference, - .deprecateApplicationMain, .isolatedDefaultValues, .globalConcurrency, + .inferSendableFromCaptures, + .implicitOpenExistentials, + .regionBasedIsolation, + .dynamicActorIsolation, + .nonfrozenEnumExhaustivity, + .globalActorIsolatedTypesUsability, + .existentialAny, + // .internalImportsByDefault, + // .memberImportVisibility, ] } // ref: https://github.com/treastrain/swift-upcomingfeatureflags-cheatsheet private extension SwiftSetting { - static let forwardTrailingClosures: Self = .enableUpcomingFeature("ForwardTrailingClosures") // SE-0286, Swift 5.3, SwiftPM 5.8+ - static let existentialAny: Self = .enableUpcomingFeature("ExistentialAny") // SE-0335, Swift 5.6, SwiftPM 5.8+ - static let bareSlashRegexLiterals: Self = .enableUpcomingFeature("BareSlashRegexLiterals") // SE-0354, Swift 5.7, SwiftPM 5.8+ - static let conciseMagicFile: Self = .enableUpcomingFeature("ConciseMagicFile") // SE-0274, Swift 5.8, SwiftPM 5.8+ - static let importObjcForwardDeclarations: Self = .enableUpcomingFeature("ImportObjcForwardDeclarations") // SE-0384, Swift 5.9, SwiftPM 5.9+ - static let disableOutwardActorInference: Self = .enableUpcomingFeature("DisableOutwardActorInference") // SE-0401, Swift 5.9, SwiftPM 5.9+ - static let deprecateApplicationMain: Self = .enableUpcomingFeature("DeprecateApplicationMain") // SE-0383, Swift 5.10, SwiftPM 5.10+ - static let isolatedDefaultValues: Self = .enableUpcomingFeature("IsolatedDefaultValues") // SE-0411, Swift 5.10, SwiftPM 5.10+ - static let globalConcurrency: Self = .enableUpcomingFeature("GlobalConcurrency") // SE-0412, Swift 5.10, SwiftPM 5.10+ + static let conciseMagicFile: Self = .enableUpcomingFeature("ConciseMagicFile") // SE-0274, Swift 5.8, SwiftPM 5.8+ + static let forwardTrailingClosures: Self = .enableUpcomingFeature("ForwardTrailingClosures") // SE-0286, Swift 5.3, SwiftPM 5.8+ + static let strictConcurrency: Self = .enableUpcomingFeature("StrictConcurrency") // SE-0337, Swift 6.0, SwiftPM 6.0+ + static let bareSlashRegexLiterals: Self = .enableUpcomingFeature("BareSlashRegexLiterals") // SE-0354, Swift 5.7, SwiftPM 5.8+ + static let deprecateApplicationMain: Self = .enableUpcomingFeature("DeprecateApplicationMain") // SE-0383, Swift 5.10, SwiftPM 5.10+ + static let importObjcForwardDeclarations: Self = .enableUpcomingFeature("ImportObjcForwardDeclarations") // SE-0384, Swift 5.9, SwiftPM 5.9+ + static let disableOutwardActorInference: Self = .enableUpcomingFeature("DisableOutwardActorInference") // SE-0401, Swift 5.9, SwiftPM 5.9+ + static let isolatedDefaultValues: Self = .enableUpcomingFeature("IsolatedDefaultValues") // SE-0411, Swift 5.10, SwiftPM 5.10+ + static let globalConcurrency: Self = .enableUpcomingFeature("GlobalConcurrency") // SE-0412, Swift 5.10, SwiftPM 5.10+ + static let inferSendableFromCaptures: Self = .enableUpcomingFeature("InferSendableFromCaptures") // SE-0418, Swift 6.0, SwiftPM 6.0+ + static let implicitOpenExistentials: Self = .enableUpcomingFeature("ImplicitOpenExistentials") // SE-0352, Swift 5.7, SwiftPM 6.0+ + static let regionBasedIsolation: Self = .enableUpcomingFeature("RegionBasedIsolation") // SE-0414, Swift 6.0, SwiftPM 6.0+ + static let dynamicActorIsolation: Self = .enableUpcomingFeature("DynamicActorIsolation") // SE-0423, Swift 6.0, SwiftPM 6.0+ + static let nonfrozenEnumExhaustivity: Self = .enableUpcomingFeature("NonfrozenEnumExhaustivity") // SE-0192, Swift 6.0, SwiftPM 6.0+ + static let globalActorIsolatedTypesUsability: Self = .enableUpcomingFeature("GlobalActorIsolatedTypesUsability") // SE-0434, Swift 6.0, SwiftPM 6.0+ + static let existentialAny: Self = .enableUpcomingFeature("ExistentialAny") // SE-0335, Swift 5.6, SwiftPM 5.8+ + static let internalImportsByDefault: Self = .enableUpcomingFeature("InternalImportsByDefault") // SE-0409, Swift 6.0, SwiftPM 6.0+ + static let memberImportVisibility: Self = .enableUpcomingFeature("MemberImportVisibility") // SE-0444, Swift 6.1, SwiftPM 6.1+ } // MARK: - Enabling Complete Concurrency Checking for Swift 6 diff --git a/Package@swift-6.0.swift b/Package@swift-6.0.swift deleted file mode 100644 index 841819e9..00000000 --- a/Package@swift-6.0.swift +++ /dev/null @@ -1,92 +0,0 @@ -// swift-tools-version:6.0 -// The swift-tools-version declares the minimum version of Swift required to build this package. - -import PackageDescription - -let isDevelop = true -let isApplePlatform: Bool = { - #if canImport(Darwin) - true - #else - false - #endif -}() - -let package = Package( - name: "MultipartFormDataParser", - platforms: [ - .macOS(.v13), - .macCatalyst(.v16), - .iOS(.v16), - .tvOS(.v16) - ], - products: [ - .library(name: "MultipartFormDataParser", targets: ["MultipartFormDataParser"]), - ], - dependencies: [], - targets: [ - .target(name: "MultipartFormDataParser"), - .testTarget(name: "MultipartFormDataParserTests", dependencies: ["MultipartFormDataParser"]), - ] -) - -// MARK: - develop -if isDevelop { - if isApplePlatform { - package.dependencies.append(contentsOf: [ - .package(url: "https://github.com/SimplyDanny/SwiftLintPlugins", from: "0.57.0"), - .package(url: "https://github.com/Alamofire/Alamofire.git", from: "5.7.0"), - .package(url: "https://github.com/ishkawa/APIKit.git", from: "5.4.0"), - ]) - package.targets - .filter(\.isTest) - .forEach { - $0.dependencies.append(contentsOf: [ - "Alamofire", - "APIKit", - ]) - } - package.targets.forEach { - if $0.plugins == nil { - $0.plugins = [] - } - $0.plugins?.append(.plugin(name: "SwiftLintBuildToolPlugin", package: "SwiftLintPlugins")) - } - } -} - -// MARK: - Upcoming feature flags for Swift 6 -package.targets.forEach { - $0.swiftSettings = [ - .forwardTrailingClosures, - .existentialAny, - .bareSlashRegexLiterals, - .conciseMagicFile, - .importObjcForwardDeclarations, - .disableOutwardActorInference, - .deprecateApplicationMain, - .isolatedDefaultValues, - .globalConcurrency, - ] -} - -// ref: https://github.com/treastrain/swift-upcomingfeatureflags-cheatsheet -private extension SwiftSetting { - static let forwardTrailingClosures: Self = .enableUpcomingFeature("ForwardTrailingClosures") // SE-0286, Swift 5.3, SwiftPM 5.8+ - static let existentialAny: Self = .enableUpcomingFeature("ExistentialAny") // SE-0335, Swift 5.6, SwiftPM 5.8+ - static let bareSlashRegexLiterals: Self = .enableUpcomingFeature("BareSlashRegexLiterals") // SE-0354, Swift 5.7, SwiftPM 5.8+ - static let conciseMagicFile: Self = .enableUpcomingFeature("ConciseMagicFile") // SE-0274, Swift 5.8, SwiftPM 5.8+ - static let importObjcForwardDeclarations: Self = .enableUpcomingFeature("ImportObjcForwardDeclarations") // SE-0384, Swift 5.9, SwiftPM 5.9+ - static let disableOutwardActorInference: Self = .enableUpcomingFeature("DisableOutwardActorInference") // SE-0401, Swift 5.9, SwiftPM 5.9+ - static let deprecateApplicationMain: Self = .enableUpcomingFeature("DeprecateApplicationMain") // SE-0383, Swift 5.10, SwiftPM 5.10+ - static let isolatedDefaultValues: Self = .enableUpcomingFeature("IsolatedDefaultValues") // SE-0411, Swift 5.10, SwiftPM 5.10+ - static let globalConcurrency: Self = .enableUpcomingFeature("GlobalConcurrency") // SE-0412, Swift 5.10, SwiftPM 5.10+ -} - -// MARK: - Enabling Complete Concurrency Checking for Swift 6 -// ref: https://www.swift.org/documentation/concurrency/ -package.targets.forEach { - var settings = $0.swiftSettings ?? [] - settings.append(.enableExperimentalFeature("StrictConcurrency")) - $0.swiftSettings = settings -} From a669f29ccc22234c1bcb57bd0d599a1f1910ea82 Mon Sep 17 00:00:00 2001 From: 417-72KI <417.72ki@gmail.com> Date: Wed, 14 Oct 2026 00:52:10 +0900 Subject: [PATCH 03/13] update Dangerfile --- Dangerfile.swift | 17 +++++ DangerfileExtensions/TestResult.swift | 106 ++++++++++++++++++++++++++ 2 files changed, 123 insertions(+) create mode 100644 DangerfileExtensions/TestResult.swift diff --git a/Dangerfile.swift b/Dangerfile.swift index bb4b12db..4f1e08d9 100644 --- a/Dangerfile.swift +++ b/Dangerfile.swift @@ -1,4 +1,7 @@ import Danger +import Foundation + +// fileImport: DangerfileExtensions/TestResult.swift let danger = Danger() @@ -23,3 +26,17 @@ if let github = danger.github { danger.warn("PR is classed as Work in Progress") } } + +let testResultJSON = (ProcessInfo.processInfo.environment["GITHUB_WORKSPACE"] + .flatMap { URL(filePath: $0) } ?? .currentDirectory()) + .appending(path: "test_output/result.json") +if FileManager.default.fileExists(atPath: testResultJSON.path()) { + let testResult = try TestResult.from(jsonFile: testResultJSON) + if testResult.isAllPassed { + danger.message("All tests passed successfully.") + } else { + danger.fail("Some tests failed. Please check the test results.") + } +} else { + danger.warn("Test result file not found at \(testResultJSON.path())") +} diff --git a/DangerfileExtensions/TestResult.swift b/DangerfileExtensions/TestResult.swift new file mode 100644 index 00000000..64e53500 --- /dev/null +++ b/DangerfileExtensions/TestResult.swift @@ -0,0 +1,106 @@ +import Foundation + +struct TestResult: Decodable { + let devices: [Device] + let testNodes: [TestNode] + let testPlanConfigurations: [TestPlanConfiguration] +} + +extension TestResult { + var isAllPassed: Bool { testNodes.allSatisfy(\.isPassed) } +} + +extension TestResult: CustomStringConvertible { + var description: String { + [ + "Devices: \(devices.map(\.description).joined(separator: ", "))", + "Test Nodes: \(testNodes.map(\.description).joined(separator: ", "))", + "Test Plan Configurations: \(testPlanConfigurations.map(\.description).joined(separator: ", "))" + ].joined(separator: "\n") + } +} + +extension TestResult { + struct Device: Decodable { + let architecture: String + let deviceId: String + let deviceName: String + let modelName: String + let osBuildNumber: String + let osVersion: String + let platform: String + } +} + +extension TestResult.Device: CustomStringConvertible { + var description: String { + "\(deviceName) (\(modelName)) - \(osVersion)" + } +} + +extension TestResult.Device: Comparable { + static func < (lhs: TestResult.Device, rhs: TestResult.Device) -> Bool { + if lhs.platform == rhs.platform { + if lhs.osBuildNumber == rhs.osBuildNumber { + lhs.deviceName < rhs.deviceName + } else { + lhs.osBuildNumber < rhs.osBuildNumber + } + } else { + lhs.platform < rhs.platform + } + } +} + +extension TestResult { + struct TestNode: Decodable { + let children: [TestNode]? + let duration: String? + let durationInSeconds: Double? + let name: String + let nodeIdentifier: String? + let nodeIdentifierURL: String? + let nodeType: String + let result: Result? + } +} + +extension TestResult.TestNode { + var isPassed: Bool { result == .passed } +} + +extension TestResult.TestNode: CustomStringConvertible { + var description: String { + "\(name)\(result.map { " - (\($0.rawValue))" } ?? "")" + } +} + +extension TestResult.TestNode { + enum Result: String, Decodable { + case passed = "Passed" + case failed = "Failed" + case skipped = "Skipped" + case expectedFailure = "Expected Failure" + } +} + +extension TestResult { + struct TestPlanConfiguration: Decodable { + let configurationId: String + let configurationName: String + } +} + +extension TestResult.TestPlanConfiguration: CustomStringConvertible { + var description: String { + "\(configurationName) (\(configurationId))" + } +} + +extension TestResult { + static func from(jsonFile: URL) throws -> TestResult { + let data = try Data(contentsOf: jsonFile) + let decoder = JSONDecoder() + return try decoder.decode(TestResult.self, from: data) + } +} From 1d56976602deac1ca2317d9a23d401f30f958ec2 Mon Sep 17 00:00:00 2001 From: 417-72KI <417.72ki@gmail.com> Date: Wed, 14 Oct 2026 00:54:38 +0900 Subject: [PATCH 04/13] update CI releated files --- .github/CODEOWNERS | 1 + .github/create-matrix.sh | 34 ++++++++ .github/matrix.json | 16 ---- .github/matrix.yml | 33 ++++++++ .github/workflows/danger.yml | 20 ----- .github/workflows/pr.yml | 151 +++++++++++++++++++++++++++++++++++ .github/workflows/test.yml | 126 ----------------------------- 7 files changed, 219 insertions(+), 162 deletions(-) create mode 100644 .github/CODEOWNERS create mode 100755 .github/create-matrix.sh delete mode 100644 .github/matrix.json create mode 100644 .github/matrix.yml delete mode 100644 .github/workflows/danger.yml create mode 100644 .github/workflows/pr.yml delete mode 100644 .github/workflows/test.yml diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 00000000..f3e00f8c --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1 @@ +* @417-72KI diff --git a/.github/create-matrix.sh b/.github/create-matrix.sh new file mode 100755 index 00000000..2893579e --- /dev/null +++ b/.github/create-matrix.sh @@ -0,0 +1,34 @@ +#!/bin/bash + +set -euo pipefail + +while getopts "f:" opt; do + case "$opt" in + f) FILE="$OPTARG" ;; + \?) exit 1 ;; + esac +done +shift $((OPTIND - 1)) + +matrix_file="${FILE:-$(git rev-parse --show-toplevel)/.github/matrix.yml}" +mode=$(echo "${1:-macOS}" | tr 'A-Z' 'a-z') + +if [ "$mode" = "macos" ]; then + yq -o=json -I=0 '[ + .macos_runners + | to_entries[] as $runner + | $runner.value.xcode + | to_entries[] as $xcode + | $xcode.value.destination[] + | { + "runner": $runner.key, + "xcode": $xcode.key, + "destination": . + } + ]' "$matrix_file" +elif [ "$mode" = "linux" ]; then + yq -o=json -I=0 '.linux_runner.swift_versions' "$matrix_file" +else + echo "Unsupported mode: $mode" >&2 + exit 1 +fi diff --git a/.github/matrix.json b/.github/matrix.json deleted file mode 100644 index 507e1289..00000000 --- a/.github/matrix.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "xcode_version": [ - "16.4" - ], - "swift_version": [ - "5.10", - "6.0", - "6.1" - ], - "platform": [ - "platform=macOS", - "platform=macOS,variant=Mac Catalyst", - "platform=iOS Simulator,name=iPhone 16 Pro", - "platform=tvOS Simulator,name=Apple TV 4K (3rd generation)" - ] -} diff --git a/.github/matrix.yml b/.github/matrix.yml new file mode 100644 index 00000000..501a6483 --- /dev/null +++ b/.github/matrix.yml @@ -0,0 +1,33 @@ +macos_runners: + xcode-27: # ref: https://github.com/actions/runner-images/blob/main/images/macos/xcode-27-arm64-Readme.md + xcode: + "27.0": # Swift 6.4 + destination: + - platform=macOS + - platform=iOS Simulator,name=iPhone 18 Pro + - platform=tvOS Simulator,name=Apple TV 4K (3rd generation) + macos-26: # ref: https://github.com/actions/runner-images/blob/main/images/macos/macos-26-arm64-Readme.md + xcode: + "26.6": # Swift 6.3 + destination: + - platform=macOS + - platform=iOS Simulator,name=iPhone 17 Pro + - platform=tvOS Simulator,name=Apple TV 4K (3rd generation) + "26.3": # Swift 6.2 + destination: + - platform=macOS + - platform=iOS Simulator,name=iPhone 17 Pro + - platform=tvOS Simulator,name=Apple TV 4K (3rd generation) + macos-15: # ref: https://github.com/actions/runner-images/blob/main/images/macos/macos-15-arm64-Readme.md + xcode: + "16.4": # Swift 6.1 + destination: + - platform=macOS + - platform=iOS Simulator,name=iPhone 16 Pro + - platform=tvOS Simulator,name=Apple TV 4K (3rd generation) +linux_runner: + swift_versions: + - "6.4" + - "6.3" + - "6.2" + - "6.1" diff --git a/.github/workflows/danger.yml b/.github/workflows/danger.yml deleted file mode 100644 index 6fe029fc..00000000 --- a/.github/workflows/danger.yml +++ /dev/null @@ -1,20 +0,0 @@ -name: Danger -on: - pull_request: - types: [opened, synchronize, edited] - branches: - - main - - hotfix -jobs: - danger: - name: Danger - runs-on: ubuntu-latest - concurrency: - group: ${{ github.head_ref }}-${{ github.workflow }} - cancel-in-progress: true - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - - name: Danger - uses: 417-72KI/danger-swiftlint@e0eee1ddb70909a05eb326714b269d7499d28ab8 # v6.4 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml new file mode 100644 index 00000000..e6d6cd42 --- /dev/null +++ b/.github/workflows/pr.yml @@ -0,0 +1,151 @@ +name: Pull Request +on: + pull_request: + types: [opened, synchronize, reopened, edited] + paths: + - .github/workflows/pr.yml + - .github/create-matrix.sh + - .github/matrix.yml + - Package.* + - '**/*.swift' +permissions: + contents: read +concurrency: + group: ${{ github.ref }}-${{ github.workflow }} + cancel-in-progress: true +jobs: + extract-matrix: + name: Create matrix + runs-on: ubuntu-latest + outputs: + macos-versions: ${{ steps.extract-matrix.outputs.macos-versions }} + linux-swift-versions: ${{ steps.extract-matrix.outputs.linux-swift-versions }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - id: extract-matrix + run: | + echo "macos-versions=$(.github/create-matrix.sh macOS)" >> $GITHUB_OUTPUT + echo "linux-swift-versions=$(.github/create-matrix.sh Linux)" >> $GITHUB_OUTPUT + test-macos: + name: Test(macOS) + needs: extract-matrix + strategy: + matrix: + include: ${{ fromJson(needs.extract-matrix.outputs.macos-versions) }} + fail-fast: false + runs-on: ${{ matrix.runner }} + env: + DEVELOPER_DIR: /Applications/Xcode_${{ matrix.xcode }}.app/Contents/Developer + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - id: create-destination-key + name: Create destination key for cache + run: echo "destination-key=$(echo "xcode_${{ matrix.xcode }}-${{ matrix.destination }}" | sed 's/[, ]/_/g')" >> $GITHUB_OUTPUT + - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6 + with: + path: | + .build/SourcePackages + key: ${{ runner.os }}-${{ matrix.xcode }}-${{ steps.create-destination-key.outputs.destination-key }}-${{ hashFiles('Package.swift') }} + restore-keys: | + ${{ runner.os }}-${{ matrix.xcode }}-${{ steps.create-destination-key.outputs.destination-key }}- + ${{ runner.os }}-${{ matrix.xcode }}- + - name: Enable macro and plugin + run: | + defaults write com.apple.dt.Xcode IDESkipPackagePluginFingerprintValidatation -bool YES + defaults write com.apple.dt.Xcode IDESkipMacroFingerprintValidation -bool YES + - name: List available simulators + run: | + xcrun simctl list + - name: Set up test package when repository is a template + if: ${{ github.event.repository.is_template }} + run: swift package init + - name: Preboot iPhone 18 Pro simulator # Ref: https://github.com/actions/runner-images/issues/12777 + if: ${{ startsWith(matrix.xcode, '27') && endsWith(matrix.destination, 'name=iPhone 18 Pro') }} + run: | + xcrun simctl boot "iPhone 18 Pro" || true + xcrun simctl bootstatus "iPhone 18 Pro" + - name: test + run: | + defaults write com.apple.dt.XCBuild EnableSwiftBuildSystemIntegration 1 + set -o pipefail && \ + xcrun xcodebuild \ + -enableCodeCoverage YES \ + -scheme "$(xcodebuild -list -json | jq -rc '.workspace.schemes[0] // .workspace.name')" \ + -destination "${{ matrix.destination }}" \ + -derivedDataPath '.build' \ + -resultBundlePath 'test_output/TestResult.xcresult' \ + clean test | xcbeautify + - name: Upload test result + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + if: success() || failure() + with: + name: ${{ steps.create-destination-key.outputs.destination-key }} + path: test_output + if-no-files-found: error + retention-days: 1 + merge-xcresult: + name: Merge xcresult + needs: test-macos + if: always() && !cancelled() + runs-on: macos-latest + steps: + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + with: + path: test_output + - name: Merge + run: | + xcrun xcresulttool merge --output-path 'TestResult.xcresult' test_output/**/TestResult.xcresult + xcrun xcresulttool get test-results tests --path 'TestResult.xcresult' > 'result.json' + - name: Upload test result + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: merged-test-result + path: | + TestResult.xcresult + result.json + if-no-files-found: error + retention-days: 30 + test-linux: + name: Test(Linux) + needs: extract-matrix + runs-on: ubuntu-latest + container: swift:${{ matrix.swift }} + strategy: + matrix: + swift: ${{ fromJson(needs.extract-matrix.outputs.linux-swift-versions) }} + fail-fast: false + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6 + with: + path: | + .build/artifacts + .build/checkouts + .build/repositories + key: ${{ runner.os }}-${{ matrix.swift }}-${{ hashFiles('Package.swift') }} + restore-keys: | + ${{ runner.os }}-${{ matrix.swift }}- + - name: Set up test package when repository is a template + if: ${{ github.event.repository.is_template }} + run: swift package init + - name: test + run: swift test + danger: + name: Danger + needs: merge-xcresult + runs-on: ubuntu-latest + permissions: + checks: write + pull-requests: write + issues: write + statuses: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + with: + name: merged-test-result + path: test_output + - name: Run Danger + uses: 417-72KI/danger-swiftlint@e0eee1ddb70909a05eb326714b269d7499d28ab8 # v6.4 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml deleted file mode 100644 index 90235c9d..00000000 --- a/.github/workflows/test.yml +++ /dev/null @@ -1,126 +0,0 @@ -name: Test -on: - pull_request: - paths: - - .github/workflows/test.yml - - Package.* - - Sources/**/*.swift - - Tests/**/*.swift - - .github/matrix.json -concurrency: - group: ${{ github.ref }}-${{ github.workflow }} - cancel-in-progress: true -jobs: - extract-matrix: - name: Extract latest Xcode version from matrix - runs-on: ubuntu-latest - outputs: - xcode-versions: ${{ steps.extract-matrix.outputs.xcode-versions }} - latest: ${{ steps.extract-matrix.outputs.latest-xcode-version }} - swift-versions: ${{ steps.extract-matrix.outputs.swift-versions }} - platforms: ${{ steps.extract-matrix.outputs.platforms }} - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - - id: extract-matrix - run: | - echo "xcode-versions=$(cat .github/matrix.json | jq -rc '.xcode_version')" >> $GITHUB_OUTPUT - echo "latest-xcode-version=$(cat .github/matrix.json | jq -r '.xcode_version | max')" >> $GITHUB_OUTPUT - echo "swift-versions=$(cat .github/matrix.json | jq -rc '.swift_version')" >> $GITHUB_OUTPUT - echo "platforms=$(cat .github/matrix.json | jq -rc '.platform')" >> $GITHUB_OUTPUT - - name: dump matrix - run: | - echo 'xcode-versions = ${{ steps.extract-matrix.outputs.xcode-versions }}' - echo 'latest-xcode-version = ${{ steps.extract-matrix.outputs.latest-xcode-version }}' - echo 'swift-versions = ${{ steps.extract-matrix.outputs.swift-versions }}' - echo 'platforms = ${{ steps.extract-matrix.outputs.platforms }}' - test-macos: - name: Test - needs: extract-matrix - runs-on: macOS-15 - concurrency: - group: ${{ github.head_ref }}-${{ github.workflow }}-${{ matrix.xcode }}-${{ matrix.destination }} - cancel-in-progress: true - strategy: - matrix: - xcode: ${{ fromJson(needs.extract-matrix.outputs.xcode-versions) }} - destination: ${{ fromJson(needs.extract-matrix.outputs.platforms) }} - fail-fast: false - env: - DEVELOPER_DIR: /Applications/Xcode_${{ matrix.xcode }}.app/Contents/Developer - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - - id: create-destination-key - name: Create destination key for cache - run: echo "destination-key=$(echo "${{ matrix.destination }}" | sed -r 's/[, ]/_/g')" >> $GITHUB_OUTPUT - - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6 - with: - path: | - .build/SourcePackages/checkouts - key: ${{ runner.os }}-xcode-${{ matrix.xcode }}-${{ steps.create-destination-key.outputs.destination-key }}-${{ hashFiles('Package.swift') }} - restore-keys: | - ${{ runner.os }}-xcode-${{ matrix.xcode }}-${{ steps.create-destination-key.outputs.destination-key }}- - - name: Enable macro and plugin - run: | - defaults write com.apple.dt.Xcode IDESkipPackagePluginFingerprintValidatation -bool YES - defaults write com.apple.dt.Xcode IDESkipMacroFingerprintValidation -bool YES - - name: test - run: | - defaults write com.apple.dt.XCBuild EnableSwiftBuildSystemIntegration 1 - set -o pipefail && \ - rm -rf 'MultipartFormDataParser.xcodeproj' && \ - xcrun xcodebuild \ - -enableCodeCoverage YES \ - -scheme MultipartFormDataParser \ - -destination "${{ matrix.destination }}" \ - -derivedDataPath '.build' \ - -resultBundlePath 'test_output/TestResult.xcresult' \ - clean test | xcpretty - - name: Upload test result - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 - if: ${{ matrix.xcode == needs.extract-matrix.outputs.latest && (success() || failure()) }} - with: - name: ${{ steps.create-destination-key.outputs.destination-key }} - path: test_output - if-no-files-found: error - retention-days: 1 - xcodebuild_result: - name: Export xcodebuild test result - needs: test-macos - runs-on: macOS-15 - steps: - - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 - with: - path: test_output - - name: Merge xcresult files - run: - xcrun xcresulttool merge test_output/**/*.xcresult --output-path test_output/TestResults.xcresult - - uses: slidoapp/xcresulttool@b98987749a0e149b1eecce5387dbb90aa1d58499 # v3.2.0 - if: success() || failure() - with: - path: test_output/TestResults.xcresult - show-passed-tests: false - show-code-coverage: false - upload-bundles: true - test-linux: - name: Test - needs: extract-matrix - runs-on: ubuntu-latest - container: swift:${{ matrix.swift }} - concurrency: - group: ${{ github.head_ref }}-${{ github.workflow }}-${{ matrix.swift }} - cancel-in-progress: true - strategy: - matrix: - swift: ${{ fromJson(needs.extract-matrix.outputs.swift-versions) }} - fail-fast: false - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6 - with: - path: | - .build/SourcePackages/checkouts - key: ${{ runner.os }}-xcode-${{ matrix.swift }}-${{ hashFiles('Package.swift') }} - restore-keys: | - ${{ runner.os }}-xcode-${{ matrix.swift }}- - - name: test - run: swift test From 22852c3aa58762640cb1a2945576841bf82111aa Mon Sep 17 00:00:00 2001 From: 417-72KI <417.72ki@gmail.com> Date: Sat, 24 Oct 2026 01:13:57 +0900 Subject: [PATCH 05/13] fix type-check failure `The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions` --- .../_TestFunctions/TestFunction_URLSession.swift | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/Tests/MultipartFormDataParserTests/_TestFunctions/TestFunction_URLSession.swift b/Tests/MultipartFormDataParserTests/_TestFunctions/TestFunction_URLSession.swift index db4c2b89..dba4e91c 100644 --- a/Tests/MultipartFormDataParserTests/_TestFunctions/TestFunction_URLSession.swift +++ b/Tests/MultipartFormDataParserTests/_TestFunctions/TestFunction_URLSession.swift @@ -112,30 +112,39 @@ private func createBody( pdf: Data, message: Data ) -> Data { - [ + let genbaNekoBlock = [ Data("--\(boundary)\r\n".utf8), Data("Content-Disposition: form-data; name=\"genbaNeko\"; filename=\"genbaNeko\"\r\n".utf8), Data("Content-Type: image/jpeg\r\n".utf8), Data("\r\n".utf8), genbaNeko, Data("\r\n".utf8), + ] + let denwaNekoBlock = [ Data("--\(boundary)\r\n".utf8), Data("Content-Disposition: form-data; name=\"denwaNeko\"; filename=\"denwaNeko\"\r\n".utf8), Data("Content-Type: image/jpeg\r\n".utf8), Data("\r\n".utf8), denwaNeko, Data("\r\n".utf8), + ] + let pdfBlock = [ Data("--\(boundary)\r\n".utf8), Data("Content-Disposition: form-data; name=\"pdf\"; filename=\"example.pdf\"\r\n".utf8), Data("Content-Type: application/pdf\r\n".utf8), Data("\r\n".utf8), pdf, Data("\r\n".utf8), + ] + let messageBlock = [ Data("--\(boundary)\r\n".utf8), Data("Content-Disposition: form-data; name=\"message\"\r\n".utf8), Data("\r\n".utf8), message, Data("\r\n".utf8), + ] + let footer = [ Data("--\(boundary)--\r\n".utf8), - ].reduce(Data(), +) + ] + return (genbaNekoBlock + denwaNekoBlock + pdfBlock + messageBlock + footer).reduce(Data(), +) } From 58f7b0b7cd9ef2a9fbae5755eb0b859342667aa4 Mon Sep 17 00:00:00 2001 From: 417-72KI <417.72ki@gmail.com> Date: Sun, 25 Oct 2026 16:04:34 +0900 Subject: [PATCH 06/13] convert to Swift Testing --- .swiftlint.yml | 2 + Package.swift | 6 +- .../MultipartFormDataParserTests.swift | 223 +++++++++--------- .../_TestFunctions/TestFunction_APIKit.swift | 109 +++------ .../TestFunction_Alamofire.swift | 121 +++------- .../TestFunction_URLSession.swift | 167 +++++++------ .../_Util/StubURLProtocol.swift | 28 ++- .../_Util/TestStub.swift | 73 +++--- 8 files changed, 319 insertions(+), 410 deletions(-) diff --git a/.swiftlint.yml b/.swiftlint.yml index 973bee16..547f9780 100644 --- a/.swiftlint.yml +++ b/.swiftlint.yml @@ -28,11 +28,13 @@ disabled_rules: - no_magic_numbers - non_overridable_class_declaration - object_literal + - one_declaration_per_file - prefer_nimble - prefixed_toplevel_constant - prohibited_interface_builder - required_deinit - sorted_enum_cases + - sorted_imports - static_over_final_class - strict_fileprivate - strong_iboutlet diff --git a/Package.swift b/Package.swift index c0ddf8c7..8b27e5a5 100644 --- a/Package.swift +++ b/Package.swift @@ -18,7 +18,7 @@ let package = Package( .macOS(.v13), .macCatalyst(.v16), .iOS(.v16), - .tvOS(.v16) + .tvOS(.v16), ], products: [ .library(name: "MultipartFormDataParser", targets: ["MultipartFormDataParser"]), @@ -35,8 +35,8 @@ let package = Package( if isDevelop { if isApplePlatform { package.dependencies.append(contentsOf: [ - .package(url: "https://github.com/SimplyDanny/SwiftLintPlugins", from: "0.57.0"), - .package(url: "https://github.com/Alamofire/Alamofire.git", from: "5.7.0"), + .package(url: "https://github.com/SimplyDanny/SwiftLintPlugins", exact: "0.65.1"), + .package(url: "https://github.com/Alamofire/Alamofire.git", from: "5.12.0"), .package(url: "https://github.com/ishkawa/APIKit.git", from: "5.4.0"), ]) package.targets diff --git a/Tests/MultipartFormDataParserTests/MultipartFormDataParserTests.swift b/Tests/MultipartFormDataParserTests/MultipartFormDataParserTests.swift index bbc5e24d..c419f6ec 100644 --- a/Tests/MultipartFormDataParserTests/MultipartFormDataParserTests.swift +++ b/Tests/MultipartFormDataParserTests/MultipartFormDataParserTests.swift @@ -1,8 +1,9 @@ -import XCTest +import Foundation #if canImport(FoundationNetworking) import FoundationNetworking #endif +import Testing import MultipartFormDataParser #if canImport(UIKit) @@ -11,18 +12,19 @@ import UIKit import Cocoa #endif -final class MultipartFormDataParserTests: XCTestCase { - override class func setUp() { - stubForUpload() - } - - override class func tearDown() { - clearStubs() - } +private var isLinux: Bool { + #if os(Linux) + true + #else + false + #endif +} - func testRequest() throws { - let genbaNeko = try XCTUnwrap(genbaNeko) - let denwaNeko = try XCTUnwrap(denwaNeko) +struct MultipartFormDataParserTests { + @Test + func request() throws { + let genbaNeko = try #require(genbaNeko) + let denwaNeko = try #require(denwaNeko) let message = Data("Hello world!".utf8) let request = createRequest( genbaNeko: genbaNeko, @@ -31,14 +33,15 @@ final class MultipartFormDataParserTests: XCTestCase { message: message ) let data = try MultipartFormData.parse(from: request) - XCTAssertEqual(data.element(forName: "genbaNeko")?.data, genbaNeko) - XCTAssertEqual(data.element(forName: "denwaNeko")?.data, denwaNeko) - XCTAssertEqual(data.element(forName: "message")?.string, "Hello world!") + #expect(data.element(forName: "genbaNeko")?.data == genbaNeko) + #expect(data.element(forName: "denwaNeko")?.data == denwaNeko) + #expect(data.element(forName: "message")?.string == "Hello world!") } - func testSequence() throws { - let genbaNeko = try XCTUnwrap(genbaNeko) - let denwaNeko = try XCTUnwrap(denwaNeko) + @Test + func sequence() throws { + let genbaNeko = try #require(genbaNeko) + let denwaNeko = try #require(denwaNeko) let message = Data("Hello world!".utf8) let request = createRequest( genbaNeko: genbaNeko, @@ -47,155 +50,143 @@ final class MultipartFormDataParserTests: XCTestCase { message: message ) let data = try MultipartFormData.parse(from: request) - XCTAssertEqual(["genbaNeko", "denwaNeko", "pdf", "message"], data.map(\.name)) - XCTAssertEqual([genbaNeko, denwaNeko, pdf, Data("Hello world!".utf8)], data.map(\.data)) + #expect(["genbaNeko", "denwaNeko", "pdf", "message"] == data.map(\.name)) + #expect([genbaNeko, denwaNeko, pdf, Data("Hello world!".utf8)] == data.map(\.data)) } // MARK: Failure - func testEmptyBody() throws { + @Test + func emptyBody() throws { var request = URLRequest(url: URL(string: "https://localhost/empty")!) request.httpMethod = "POST" request.setValue("multipart/form-data; boundary=foobar", forHTTPHeaderField: "Content-Type") request.httpBody = Data("".utf8) - XCTAssertThrowsError(try MultipartFormData.parse(from: request)) { - XCTAssertEqual($0.localizedDescription, "HTTP body stream is empty.") + let error = try #require(throws: (any Error).self) { + try MultipartFormData.parse(from: request) } + #expect(error.localizedDescription == "HTTP body stream is empty.") } - func testNoContentType() throws { + @Test + func noContentType() throws { let request = URLRequest(url: URL(string: "https://localhost/empty")!) - XCTAssertThrowsError(try MultipartFormData.parse(from: request)) { - XCTAssertEqual($0.localizedDescription, "No Content-Type") + let error = try #require(throws: (any Error).self) { + try MultipartFormData.parse(from: request) } + #expect(error.localizedDescription == "No Content-Type") } - func testInvalidContentType() throws { + @Test + func invalidContentType() throws { var request = URLRequest(url: URL(string: "https://localhost/empty")!) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.httpBody = Data("".utf8) - XCTAssertThrowsError(try MultipartFormData.parse(from: request)) { - XCTAssertEqual($0.localizedDescription, "Invalid Content-Type: application/json") + let error = try #require(throws: (any Error).self) { + try MultipartFormData.parse(from: request) } + #expect(error.localizedDescription == "Invalid Content-Type: application/json") } - func testInvalidBody() throws { + @Test(arguments: [ + Data("--foobar".utf8), // body not contains `CRLF` + Data("foobar\r\n".utf8), // body not started with boundary + Data("--foobar\r\n".utf8), // body not end with `--{boundary}--` + ]) + func invalidBody(_ body: Data) throws { var request = URLRequest(url: URL(string: "https://localhost/empty")!) request.httpMethod = "POST" request.setValue("multipart/form-data; boundary=foobar", forHTTPHeaderField: "Content-Type") - - // body not contains `CRLF` - request.httpBody = Data("--foobar".utf8) - XCTAssertThrowsError(try MultipartFormData.parse(from: request)) { - XCTAssertEqual($0.localizedDescription, "Invalid stream.") - } - - // body not started with boundary - request.httpBody = Data("foobar\r\n".utf8) - XCTAssertThrowsError(try MultipartFormData.parse(from: request)) { - XCTAssertEqual($0.localizedDescription, "Invalid stream.") - } - - // body not end with `--{boundary}--` - request.httpBody = Data("--foobar\r\n".utf8) - XCTAssertThrowsError(try MultipartFormData.parse(from: request)) { - XCTAssertEqual($0.localizedDescription, "Invalid stream.") + request.httpBody = body + let error = try #require(throws: (any Error).self) { + try MultipartFormData.parse(from: request) } + #expect(error.localizedDescription == "Invalid stream.") } +} - // MARK: using 3rd-party libraries - #if canImport(Alamofire) - func testAlamofire() throws { - let genbaNeko = try XCTUnwrap(genbaNeko) - let denwaNeko = try XCTUnwrap(denwaNeko) +// MARK: using 3rd-party libraries +#if canImport(Alamofire) +extension MultipartFormDataParserTests { + @Test + func alamofire() async throws { + let genbaNeko = try #require(genbaNeko) + let denwaNeko = try #require(denwaNeko) let message = Data("Hello world!".utf8) - - let result = try XCTUnwrap( - uploadWithAlamoFire( - genbaNeko: genbaNeko, - denwaNeko: denwaNeko, - message: message - ) + let result = try await uploadWithAlamoFire( + session(configuration: .stubbed(for: UploadTestStubResponse.self)), + genbaNeko: genbaNeko, + denwaNeko: denwaNeko, + message: message ) - XCTAssertEqual(result.status, 200) - XCTAssertNil(result.error) - } - - func testAlamofireWithConcurrency() async throws { - let genbaNeko = try XCTUnwrap(genbaNeko) - let denwaNeko = try XCTUnwrap(denwaNeko) - let message = Data("Hello world!".utf8) - let result = try await uploadWithAlamoFireConcurrency(genbaNeko: genbaNeko, denwaNeko: denwaNeko, message: message) - XCTAssertEqual(result.status, 200) - XCTAssertNil(result.error) + #expect(result.status == 200) + #expect(result.error == nil) } - #endif +} +#endif - #if canImport(APIKit) - func testAPIKit() throws { - let genbaNeko = try XCTUnwrap(genbaNeko) - let denwaNeko = try XCTUnwrap(denwaNeko) +#if canImport(APIKit) +extension MultipartFormDataParserTests { + @Test + func apiKit() async throws { + let genbaNeko = try #require(genbaNeko) + let denwaNeko = try #require(denwaNeko) let message = Data("Hello world!".utf8) - try runActivity(named: "request") { - let request = try requestWithAPIKit( - genbaNeko: genbaNeko, - denwaNeko: denwaNeko, - pdf: pdf, - message: message - ) - let data = try MultipartFormData.parse(from: request) - XCTAssertEqual(data.element(forName: "genbaNeko")?.data, genbaNeko) - XCTAssertEqual(data.element(forName: "denwaNeko")?.data, denwaNeko) - XCTAssertEqual(data.element(forName: "message")?.string, "Hello world!") - } - - try runActivity(named: "stub") { - let result = try XCTUnwrap( - uploadWithAPIKit( - genbaNeko: genbaNeko, - denwaNeko: denwaNeko, - pdf: pdf, - message: message - ) - ) - XCTAssertEqual(result.status, 200) - XCTAssertNil(result.error) - } + let request = try requestWithAPIKit( + genbaNeko: genbaNeko, + denwaNeko: denwaNeko, + pdf: pdf, + message: message + ) + let data = try MultipartFormData.parse(from: request.buildURLRequest()) + #expect(data.element(forName: "genbaNeko")?.data == genbaNeko) + #expect(data.element(forName: "denwaNeko")?.data == denwaNeko) + #expect(data.element(forName: "message")?.string == "Hello world!") + + let result = try await uploadWithAPIKit( + session(configuration: .stubbed(for: UploadTestStubResponse.self)), + request: request, + ) + #expect(result.status == 200) + #expect(result.error == nil) } - #endif +} +#endif - // MARK: URLSession - func testURLSessionUploadTask() async throws { - #if os(Linux) - // FIXME: There is no way to get body stream with `URLSessionUploadTask`. - try XCTSkipIf(true, "Stubbing `URLSessionUploadTask` in Linux is not supported.") - #endif - let genbaNeko = try XCTUnwrap(genbaNeko) - let denwaNeko = try XCTUnwrap(denwaNeko) +// MARK: URLSession +extension MultipartFormDataParserTests { + // FIXME: There is no way to get body stream with `URLSessionUploadTask`. + @Test(.disabled(if: isLinux, "Stubbing `URLSessionUploadTask` in Linux is not supported.")) + func urlSessionUploadTask() async throws { + let genbaNeko = try #require(genbaNeko) + let denwaNeko = try #require(denwaNeko) let message = Data("Hello world!".utf8) let result = try await uploadURLSessionUpload( + URLSession(configuration: .stubbed(for: UploadTestStubResponse.self)), genbaNeko: genbaNeko, denwaNeko: denwaNeko, pdf: pdf, message: message ) - XCTAssertEqual(result.status, 200) - XCTAssertNil(result.error) + #expect(result.status == 200) + #expect(result.error == nil) } - func testURLSessionDataTask() async throws { - let genbaNeko = try XCTUnwrap(genbaNeko) - let denwaNeko = try XCTUnwrap(denwaNeko) + @Test + func urlSessionDataTask() async throws { + let genbaNeko = try #require(genbaNeko) + let denwaNeko = try #require(denwaNeko) let message = Data("Hello world!".utf8) let result = try await uploadURLSessionData( + URLSession(configuration: .stubbed(for: UploadTestStubResponse.self)), genbaNeko: genbaNeko, denwaNeko: denwaNeko, pdf: pdf, message: message ) - XCTAssertEqual(result.status, 200) - XCTAssertNil(result.error) + #expect(result.status == 200) + #expect(result.error == nil) } } diff --git a/Tests/MultipartFormDataParserTests/_TestFunctions/TestFunction_APIKit.swift b/Tests/MultipartFormDataParserTests/_TestFunctions/TestFunction_APIKit.swift index 71bce4ae..42be5370 100644 --- a/Tests/MultipartFormDataParserTests/_TestFunctions/TestFunction_APIKit.swift +++ b/Tests/MultipartFormDataParserTests/_TestFunctions/TestFunction_APIKit.swift @@ -1,83 +1,53 @@ import Foundation -import XCTest +import Testing #if canImport(APIKit) import APIKit -private let session: Session = { - let configuration = URLSessionConfiguration.default - configuration.protocolClasses = [StubURLProtocol.self] +func session(configuration: URLSessionConfiguration) -> Session { let adapter = URLSessionAdapter(configuration: configuration) return Session(adapter: adapter) -}() - -extension XCTestCase { - func requestWithAPIKit( - genbaNeko: Data, - denwaNeko: Data, - pdf: Data, - message: Data, - file: StaticString = #filePath, - line: UInt = #line - ) throws -> URLRequest { - try TestRequest( - genbaNeko: genbaNeko, - denwaNeko: denwaNeko, - pdf: pdf, - message: message, - file: file, - line: line - ).buildURLRequest() - } - - func uploadWithAPIKit( - genbaNeko: Data, - denwaNeko: Data, - pdf: Data, - message: Data, - retryCount: UInt = 3, - file: StaticString = #filePath, - line: UInt = #line - ) throws -> TestEntity { - let exp = expectation(description: "response") - let request = TestRequest( - genbaNeko: genbaNeko, - denwaNeko: denwaNeko, - pdf: pdf, - message: message, - file: file, - line: line - ) - var result: Result! - session.send(request, callbackQueue: nil) { - result = $0 - exp.fulfill() - } +} - wait(for: [exp], timeout: 10) +func requestWithAPIKit( + genbaNeko: Data, + denwaNeko: Data, + pdf: Data, + message: Data, + sourceLocation: SourceLocation = #_sourceLocation +) throws -> TestRequest { + TestRequest( + genbaNeko: genbaNeko, + denwaNeko: denwaNeko, + pdf: pdf, + message: message, + sourceLocation: sourceLocation + ) +} - switch result! { - case let .success(response): - return response - case let .failure(error): - if retryCount > 0 { - print("retry: \(retryCount)") - return try uploadWithAPIKit( - genbaNeko: genbaNeko, - denwaNeko: denwaNeko, - pdf: pdf, - message: message, - retryCount: retryCount - 1, - file: file, - line: line - ) - } - throw error +func uploadWithAPIKit( + _ session: Session, + request: R, + retryCount: UInt = 3, + sourceLocation: SourceLocation = #_sourceLocation +) async throws -> R.Response { + do { + return try await session.response(for: request) + } catch { + if retryCount > 0 { + print("retry: \(retryCount)") + return try await uploadWithAPIKit( + session, + request: request, + retryCount: retryCount - 1, + sourceLocation: sourceLocation + ) } + throw error } } -private struct TestRequest: APIKit.Request { +struct TestRequest: APIKit.Request { typealias Response = TestEntity var baseURL: URL { URL(string: "https://localhost")! } @@ -89,8 +59,7 @@ private struct TestRequest: APIKit.Request { var pdf: Data var message: Data - var file: StaticString - var line: UInt + var sourceLocation: SourceLocation var bodyParameters: (any BodyParameters)? { let parts: [MultipartFormDataBodyParameters.Part] = [ @@ -118,7 +87,7 @@ private struct TestRequest: APIKit.Request { } func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Response { - XCTAssertEqual(urlResponse.statusCode, 200, file: file, line: line) + #expect(urlResponse.statusCode == 200, sourceLocation: sourceLocation) switch object { case let data as Data: let decoder = JSONDecoder() diff --git a/Tests/MultipartFormDataParserTests/_TestFunctions/TestFunction_Alamofire.swift b/Tests/MultipartFormDataParserTests/_TestFunctions/TestFunction_Alamofire.swift index dbf6e983..36d02287 100644 --- a/Tests/MultipartFormDataParserTests/_TestFunctions/TestFunction_Alamofire.swift +++ b/Tests/MultipartFormDataParserTests/_TestFunctions/TestFunction_Alamofire.swift @@ -1,96 +1,47 @@ import Foundation -import XCTest +import Testing #if canImport(Alamofire) import Alamofire -private let session: Session = { - let configuration = URLSessionConfiguration.ephemeral - configuration.protocolClasses = [StubURLProtocol.self] - return Session(configuration: configuration) -}() - -extension XCTestCase { - func uploadWithAlamoFire( - genbaNeko: Data, - denwaNeko: Data, - message: Data, - retryCount: UInt = 3, - file: StaticString = #filePath, - line: UInt = #line - ) throws -> TestEntity? { - let exp = expectation(description: "response") - let task = session.upload( - multipartFormData: { formData in - formData.append( - genbaNeko, - withName: "genbaNeko", - fileName: "genbaNeko.jpeg", - mimeType: "image/jpeg" - ) - formData.append( - denwaNeko, - withName: "denwaNeko", - fileName: "denwaNeko.jpeg", - mimeType: "image/jpeg" - ) - formData.append(message, withName: "message") - }, - to: "https://localhost/upload", - interceptor: Interceptor() - ) - var response: AFDataResponse! - let decoder = JSONDecoder() - decoder.keyDecodingStrategy = .convertFromSnakeCase - task.responseDecodable(of: TestEntity.self, decoder: decoder) { - response = $0 - exp.fulfill() - } - wait(for: [exp], timeout: timeoutInterval) - - XCTAssertNotNil(response, file: file, line: line) - XCTAssertEqual(response?.response?.statusCode, 200, file: file, line: line) - switch response.result { - case let .success(entity): return entity - case let .failure(error): throw error - } - } +func session(configuration: URLSessionConfiguration) -> Session { + Session(configuration: configuration) +} - func uploadWithAlamoFireConcurrency( - genbaNeko: Data, - denwaNeko: Data, - message: Data, - retryCount: UInt = 3, - file: StaticString = #filePath, - line: UInt = #line - ) async throws -> TestEntity { - let decoder = JSONDecoder() - decoder.keyDecodingStrategy = .convertFromSnakeCase - return try await session.upload( - multipartFormData: { formData in - formData.append( - genbaNeko, - withName: "genbaNeko", - fileName: "genbaNeko.jpeg", - mimeType: "image/jpeg" - ) - formData.append( - denwaNeko, - withName: "denwaNeko", - fileName: "denwaNeko.jpeg", - mimeType: "image/jpeg" - ) - formData.append(message, withName: "message") - }, - to: "https://localhost/upload", - interceptor: Interceptor() - ) - .serializingDecodable(TestEntity.self, decoder: decoder) - .value - } +func uploadWithAlamoFire( + _ session: Session, + genbaNeko: Data, + denwaNeko: Data, + message: Data, + retryCount: UInt = 3, + sourceLocation: SourceLocation = #_sourceLocation +) async throws -> TestEntity { + let decoder = JSONDecoder() + decoder.keyDecodingStrategy = .convertFromSnakeCase + return try await session.upload( + multipartFormData: { formData in + formData.append( + genbaNeko, + withName: "genbaNeko", + fileName: "genbaNeko.jpeg", + mimeType: "image/jpeg" + ) + formData.append( + denwaNeko, + withName: "denwaNeko", + fileName: "denwaNeko.jpeg", + mimeType: "image/jpeg" + ) + formData.append(message, withName: "message") + }, + to: "https://localhost/upload", + interceptor: Interceptor() + ) + .serializingDecodable(TestEntity.self, decoder: decoder) + .value } -private class Interceptor: RequestInterceptor { +private final class Interceptor: RequestInterceptor { private let lock = NSLock() func retry(_ request: Request, for session: Session, dueTo error: any Error, completion: @escaping (RetryResult) -> Void) { diff --git a/Tests/MultipartFormDataParserTests/_TestFunctions/TestFunction_URLSession.swift b/Tests/MultipartFormDataParserTests/_TestFunctions/TestFunction_URLSession.swift index dba4e91c..7afa2cdf 100644 --- a/Tests/MultipartFormDataParserTests/_TestFunctions/TestFunction_URLSession.swift +++ b/Tests/MultipartFormDataParserTests/_TestFunctions/TestFunction_URLSession.swift @@ -2,107 +2,100 @@ import Foundation #if canImport(FoundationNetworking) import FoundationNetworking #endif -import XCTest -private let session: URLSession = { - let configuration = URLSessionConfiguration.ephemeral - configuration.protocolClasses = [StubURLProtocol.self] - return URLSession(configuration: configuration) -}() - -extension XCTestCase { - func uploadURLSessionData( - genbaNeko: Data, - denwaNeko: Data, - pdf: Data, - message: Data, - retryCount: UInt = 3, - file: StaticString = #filePath, - line: UInt = #line - ) async throws -> TestEntity { - let request = createRequest( +func uploadURLSessionData( + _ session: URLSession, + genbaNeko: Data, + denwaNeko: Data, + pdf: Data, + message: Data, + retryCount: UInt = 3, + file: StaticString = #filePath, + line: UInt = #line +) async throws -> TestEntity { + let request = createRequest( + genbaNeko: genbaNeko, + denwaNeko: denwaNeko, + pdf: pdf, + message: message + ) + do { + let (data, _) = try await session.data(for: request) + return try JSONDecoder().decode(TestEntity.self, from: data) + } catch { + guard retryCount > 0 else { throw error } + return try await uploadURLSessionData( + session, genbaNeko: genbaNeko, denwaNeko: denwaNeko, pdf: pdf, - message: message + message: message, + retryCount: retryCount - 1, + file: file, + line: line ) - do { - let (data, _) = try await session.data(for: request) - return try JSONDecoder().decode(TestEntity.self, from: data) - } catch { - guard retryCount > 0 else { throw error } - return try await uploadURLSessionData( - genbaNeko: genbaNeko, - denwaNeko: denwaNeko, - pdf: pdf, - message: message, - retryCount: retryCount - 1, - file: file, - line: line - ) - } } +} - func uploadURLSessionUpload( - genbaNeko: Data, - denwaNeko: Data, - pdf: Data, - message: Data, - retryCount: UInt = 3, - file: StaticString = #filePath, - line: UInt = #line - ) async throws -> TestEntity { - let boundary = "YoWatanabe0417" - var request = URLRequest(url: URL(string: "https://localhost/upload")!) - request.httpMethod = "POST" - request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") - let requestBody = createBody( - boundary: boundary, +func uploadURLSessionUpload( + _ session: URLSession, + genbaNeko: Data, + denwaNeko: Data, + pdf: Data, + message: Data, + retryCount: UInt = 3, + file: StaticString = #filePath, + line: UInt = #line +) async throws -> TestEntity { + let boundary = "YoWatanabe0417" + var request = URLRequest(url: URL(string: "https://localhost/upload")!) + request.httpMethod = "POST" + request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") + let requestBody = createBody( + boundary: boundary, + genbaNeko: genbaNeko, + denwaNeko: denwaNeko, + pdf: pdf, + message: message + ) + do { + let (data, _) = try await session.upload(for: request, from: requestBody) + return try JSONDecoder().decode(TestEntity.self, from: data) + } catch { + guard retryCount > 0 else { throw error } + return try await uploadURLSessionUpload( + session, genbaNeko: genbaNeko, denwaNeko: denwaNeko, pdf: pdf, - message: message + message: message, + retryCount: retryCount - 1, + file: file, + line: line ) - do { - let (data, _) = try await session.upload(for: request, from: requestBody) - return try JSONDecoder().decode(TestEntity.self, from: data) - } catch { - guard retryCount > 0 else { throw error } - return try await uploadURLSessionUpload( - genbaNeko: genbaNeko, - denwaNeko: denwaNeko, - pdf: pdf, - message: message, - retryCount: retryCount - 1, - file: file, - line: line - ) - } } } -extension XCTestCase { - func createRequest( - genbaNeko: Data, - denwaNeko: Data, - pdf: Data, - message: Data, - file: StaticString = #filePath, - line: UInt = #line - ) -> URLRequest { - let boundary = "YoWatanabe0417" - var request = URLRequest(url: URL(string: "https://localhost/upload")!) - request.httpMethod = "POST" - request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") - request.httpBody = createBody( - boundary: boundary, - genbaNeko: genbaNeko, - denwaNeko: denwaNeko, - pdf: pdf, - message: message - ) - return request - } +func createRequest( + genbaNeko: Data, + denwaNeko: Data, + pdf: Data, + message: Data, + file: StaticString = #filePath, + line: UInt = #line +) -> URLRequest { + let boundary = "YoWatanabe0417" + var request = URLRequest(url: URL(string: "https://localhost/upload")!) + request.httpMethod = "POST" + request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") + request.httpBody = createBody( + boundary: boundary, + genbaNeko: genbaNeko, + denwaNeko: denwaNeko, + pdf: pdf, + message: message + ) + return request } private func createBody( diff --git a/Tests/MultipartFormDataParserTests/_Util/StubURLProtocol.swift b/Tests/MultipartFormDataParserTests/_Util/StubURLProtocol.swift index e249ec9c..7bfdf98a 100644 --- a/Tests/MultipartFormDataParserTests/_Util/StubURLProtocol.swift +++ b/Tests/MultipartFormDataParserTests/_Util/StubURLProtocol.swift @@ -2,12 +2,22 @@ import Foundation #if canImport(FoundationNetworking) import FoundationNetworking #endif +import Testing -final class StubURLProtocol: URLProtocol { - typealias RequestHandler = (URLRequest) throws -> (Data?, HTTPURLResponse) +protocol StubResponseProvider { + static func stub(for request: URLRequest) throws -> (Data?, URLResponse) +} - static var requestHandler: RequestHandler? +extension URLSessionConfiguration { + static func stubbed(for type: S.Type) -> URLSessionConfiguration { + let configuration = URLSessionConfiguration.ephemeral + configuration.protocolClasses = [StubURLProtocol.self] + return configuration + } +} +// MARK: - +private final class StubURLProtocol: URLProtocol { override class func canInit(with request: URLRequest) -> Bool { true } @@ -17,20 +27,20 @@ final class StubURLProtocol: URLProtocol { } override func startLoading() { - guard let requestHandler = Self.requestHandler else { return } + guard let client else { return } do { - let (data, response) = try requestHandler(request) - client?.urlProtocol( + let (data, response) = try S.stub(for: request) + client.urlProtocol( self, didReceive: response, cacheStoragePolicy: .notAllowed ) if let data { - client?.urlProtocol(self, didLoad: data) + client.urlProtocol(self, didLoad: data) } - client?.urlProtocolDidFinishLoading(self) + client.urlProtocolDidFinishLoading(self) } catch { - client?.urlProtocol(self, didFailWithError: error) + client.urlProtocol(self, didFailWithError: error) } } diff --git a/Tests/MultipartFormDataParserTests/_Util/TestStub.swift b/Tests/MultipartFormDataParserTests/_Util/TestStub.swift index d44319c6..f7ee10f1 100644 --- a/Tests/MultipartFormDataParserTests/_Util/TestStub.swift +++ b/Tests/MultipartFormDataParserTests/_Util/TestStub.swift @@ -13,45 +13,38 @@ typealias Image = NSImage import MultipartFormDataParser -func stubForUpload() { - StubURLProtocol.requestHandler = uploadTestStubResponse -} - -func clearStubs() { - StubURLProtocol.requestHandler = nil -} - -// swiftlint:disable:next closure_body_length -private let uploadTestStubResponse: StubURLProtocol.RequestHandler = { request in - let errorResponse = { (message: String) -> (Data?, HTTPURLResponse) in - ( - Data(#"{"status": 403, "error": "\#(message)"}"#.utf8), - HTTPURLResponse( - url: request.url!, - statusCode: 403, - httpVersion: "HTTP/2", - headerFields: ["Content-Type": "application/json"] - )! - ) - } - do { - let data = try MultipartFormData.parse(from: request) - guard let genbaNeko = data.element(forName: "genbaNeko") else { return errorResponse("genbaNeko") } - guard let denwaNeko = data.element(forName: "denwaNeko") else { return errorResponse("denwaNeko") } - guard let message = data.element(forName: "message") else { return errorResponse("message") } - guard let _ = Image(data: genbaNeko.data) else { return errorResponse("Unexpected genbaNeko") } - guard let _ = Image(data: denwaNeko.data) else { return errorResponse("Unexpected denwaNeko") } - guard message.string == "Hello world!" else { return errorResponse("Unexpected message: \(message)") } - return ( - Data(#"{"status": 200}"#.utf8), - HTTPURLResponse( - url: request.url!, - statusCode: 200, - httpVersion: "HTTP/2", - headerFields: ["Content-Type": "application/json"] - )! - ) - } catch { - return errorResponse(error.localizedDescription) +enum UploadTestStubResponse: StubResponseProvider { + static func stub(for request: URLRequest) throws -> (Data?, URLResponse) { + let errorResponse = { (message: String) -> (Data?, HTTPURLResponse) in + ( + Data(#"{"status": 403, "error": "\#(message)"}"#.utf8), + HTTPURLResponse( + url: request.url!, + statusCode: 403, + httpVersion: "HTTP/2", + headerFields: ["Content-Type": "application/json"] + )! + ) + } + do { + let data = try MultipartFormData.parse(from: request) + guard let genbaNeko = data.element(forName: "genbaNeko") else { return errorResponse("genbaNeko") } + guard let denwaNeko = data.element(forName: "denwaNeko") else { return errorResponse("denwaNeko") } + guard let message = data.element(forName: "message") else { return errorResponse("message") } + guard let _ = Image(data: genbaNeko.data) else { return errorResponse("Unexpected genbaNeko") } + guard let _ = Image(data: denwaNeko.data) else { return errorResponse("Unexpected denwaNeko") } + guard message.string == "Hello world!" else { return errorResponse("Unexpected message: \(message)") } + return ( + Data(#"{"status": 200}"#.utf8), + HTTPURLResponse( + url: request.url!, + statusCode: 200, + httpVersion: "HTTP/2", + headerFields: ["Content-Type": "application/json"] + )! + ) + } catch { + return errorResponse(error.localizedDescription) + } } } From 9cd36f56b2d197e99adeb03d93c4214c6d8ac89d Mon Sep 17 00:00:00 2001 From: 417-72KI <417.72ki@gmail.com> Date: Sun, 25 Oct 2026 17:11:54 +0900 Subject: [PATCH 07/13] fix lint warnings --- .swiftlint.yml | 3 +++ .../MultipartFormDataParser/Extensions/Data+Util.swift | 2 +- .../MultipartFormDataParserTests.swift | 2 +- .../_Extension/XCTest+Activity.swift | 9 --------- .../_TestFunctions/TestFunction_APIKit.swift | 2 +- .../_TestFunctions/TestFunction_Alamofire.swift | 7 ++++++- .../_Util/StubURLProtocol.swift | 2 +- 7 files changed, 13 insertions(+), 14 deletions(-) delete mode 100644 Tests/MultipartFormDataParserTests/_Extension/XCTest+Activity.swift diff --git a/.swiftlint.yml b/.swiftlint.yml index 547f9780..9c5bc866 100644 --- a/.swiftlint.yml +++ b/.swiftlint.yml @@ -8,6 +8,7 @@ disabled_rules: - anonymous_argument_in_multiline_closure - conditional_returns_on_newline - contrasted_opening_brace + - discouraged_default_parameter - discouraged_optional_collection - explicit_acl - explicit_enum_raw_value @@ -39,9 +40,11 @@ disabled_rules: - strict_fileprivate - strong_iboutlet - switch_case_on_newline + - unneeded_throws_rethrows - unowned_variable_capture - unused_optional_binding - unused_parameter + - variable_shadowing - vertical_whitespace_between_cases line_length: warning: 180 diff --git a/Sources/MultipartFormDataParser/Extensions/Data+Util.swift b/Sources/MultipartFormDataParser/Extensions/Data+Util.swift index fba000e4..a7f22fd9 100644 --- a/Sources/MultipartFormDataParser/Extensions/Data+Util.swift +++ b/Sources/MultipartFormDataParser/Extensions/Data+Util.swift @@ -7,7 +7,7 @@ extension Data { extension Data { func split(separator: [UInt8]) -> [Data] { let bytes = self.bytes - var result = [Data]() + var result = [Self]() var position = 0 for i in 0..(named name: String, block: () throws -> Result) rethrows -> Result { - #if os(Linux) - return try block() - #else - return try XCTContext.runActivity(named: name) { _ in try block() } - #endif -} diff --git a/Tests/MultipartFormDataParserTests/_TestFunctions/TestFunction_APIKit.swift b/Tests/MultipartFormDataParserTests/_TestFunctions/TestFunction_APIKit.swift index 42be5370..1d43d503 100644 --- a/Tests/MultipartFormDataParserTests/_TestFunctions/TestFunction_APIKit.swift +++ b/Tests/MultipartFormDataParserTests/_TestFunctions/TestFunction_APIKit.swift @@ -15,7 +15,7 @@ func requestWithAPIKit( pdf: Data, message: Data, sourceLocation: SourceLocation = #_sourceLocation -) throws -> TestRequest { +) -> TestRequest { TestRequest( genbaNeko: genbaNeko, denwaNeko: denwaNeko, diff --git a/Tests/MultipartFormDataParserTests/_TestFunctions/TestFunction_Alamofire.swift b/Tests/MultipartFormDataParserTests/_TestFunctions/TestFunction_Alamofire.swift index 36d02287..aef5fd5a 100644 --- a/Tests/MultipartFormDataParserTests/_TestFunctions/TestFunction_Alamofire.swift +++ b/Tests/MultipartFormDataParserTests/_TestFunctions/TestFunction_Alamofire.swift @@ -44,7 +44,12 @@ func uploadWithAlamoFire( private final class Interceptor: RequestInterceptor { private let lock = NSLock() - func retry(_ request: Request, for session: Session, dueTo error: any Error, completion: @escaping (RetryResult) -> Void) { + func retry( + _ request: Request, + for session: Session, + dueTo error: any Error, + completion: (RetryResult) -> Void + ) { lock.lock(); defer { lock.unlock() } if request.retryCount < 3 { diff --git a/Tests/MultipartFormDataParserTests/_Util/StubURLProtocol.swift b/Tests/MultipartFormDataParserTests/_Util/StubURLProtocol.swift index 7bfdf98a..11c655ba 100644 --- a/Tests/MultipartFormDataParserTests/_Util/StubURLProtocol.swift +++ b/Tests/MultipartFormDataParserTests/_Util/StubURLProtocol.swift @@ -10,7 +10,7 @@ protocol StubResponseProvider { extension URLSessionConfiguration { static func stubbed(for type: S.Type) -> URLSessionConfiguration { - let configuration = URLSessionConfiguration.ephemeral + let configuration = Self.ephemeral configuration.protocolClasses = [StubURLProtocol.self] return configuration } From 3d674604e763276b8c3d85591568ba3cb4f85665 Mon Sep 17 00:00:00 2001 From: 417-72KI <417.72ki@gmail.com> Date: Sun, 25 Oct 2026 20:26:02 +0900 Subject: [PATCH 08/13] enable remaining flags --- Package.swift | 4 ++-- Sources/MultipartFormDataParser/Error.swift | 2 +- Sources/MultipartFormDataParser/MultipartFormData.swift | 4 ++-- .../MultipartFormDataParserTests.swift | 4 ++++ .../_Extension/URLSession+Linux.swift | 8 ++++---- 5 files changed, 13 insertions(+), 9 deletions(-) diff --git a/Package.swift b/Package.swift index 8b27e5a5..f5b4ff95 100644 --- a/Package.swift +++ b/Package.swift @@ -75,8 +75,8 @@ package.targets.forEach { .nonfrozenEnumExhaustivity, .globalActorIsolatedTypesUsability, .existentialAny, - // .internalImportsByDefault, - // .memberImportVisibility, + .internalImportsByDefault, + .memberImportVisibility, ] } diff --git a/Sources/MultipartFormDataParser/Error.swift b/Sources/MultipartFormDataParser/Error.swift index 99ebd716..6c85007e 100644 --- a/Sources/MultipartFormDataParser/Error.swift +++ b/Sources/MultipartFormDataParser/Error.swift @@ -1,4 +1,4 @@ -import Foundation +public import Foundation public enum MultipartFormDataError: LocalizedError { case noContentType diff --git a/Sources/MultipartFormDataParser/MultipartFormData.swift b/Sources/MultipartFormDataParser/MultipartFormData.swift index 269dae93..4f91d0d9 100644 --- a/Sources/MultipartFormDataParser/MultipartFormData.swift +++ b/Sources/MultipartFormDataParser/MultipartFormData.swift @@ -1,6 +1,6 @@ -import Foundation +public import Foundation #if canImport(FoundationNetworking) -import FoundationNetworking +public import FoundationNetworking #endif public struct MultipartFormData { diff --git a/Tests/MultipartFormDataParserTests/MultipartFormDataParserTests.swift b/Tests/MultipartFormDataParserTests/MultipartFormDataParserTests.swift index 64df021e..e9d4fbed 100644 --- a/Tests/MultipartFormDataParserTests/MultipartFormDataParserTests.swift +++ b/Tests/MultipartFormDataParserTests/MultipartFormDataParserTests.swift @@ -12,6 +12,10 @@ import UIKit import Cocoa #endif +#if canImport(APIKit) +import APIKit +#endif + private var isLinux: Bool { #if os(Linux) true diff --git a/Tests/MultipartFormDataParserTests/_Extension/URLSession+Linux.swift b/Tests/MultipartFormDataParserTests/_Extension/URLSession+Linux.swift index c53098ce..7038ec72 100644 --- a/Tests/MultipartFormDataParserTests/_Extension/URLSession+Linux.swift +++ b/Tests/MultipartFormDataParserTests/_Extension/URLSession+Linux.swift @@ -4,7 +4,7 @@ import FoundationNetworking // `URLSession` in `FoundationNetworking` does not support `async`/`await`. extension URLSession { - public func data(for request: URLRequest, delegate: (any URLSessionTaskDelegate)? = nil) async throws -> (Data, URLResponse) { + func data(for request: URLRequest, delegate: (any URLSessionTaskDelegate)? = nil) async throws -> (Data, URLResponse) { try await withCheckedThrowingContinuation { continuation in let task = dataTask(with: request) { data, res, err in if let err { @@ -20,11 +20,11 @@ extension URLSession { } } - public func data(from url: URL, delegate: (any URLSessionTaskDelegate)? = nil) async throws -> (Data, URLResponse) { + func data(from url: URL, delegate: (any URLSessionTaskDelegate)? = nil) async throws -> (Data, URLResponse) { try await data(for: URLRequest(url: url), delegate: delegate) } - public func upload(for request: URLRequest, fromFile fileURL: URL, delegate: (any URLSessionTaskDelegate)? = nil) async throws -> (Data, URLResponse) { + func upload(for request: URLRequest, fromFile fileURL: URL, delegate: (any URLSessionTaskDelegate)? = nil) async throws -> (Data, URLResponse) { try await withCheckedThrowingContinuation { continuation in let task = uploadTask(with: request, fromFile: fileURL) { data, res, err in if let err { @@ -40,7 +40,7 @@ extension URLSession { } } - public func upload(for request: URLRequest, from bodyData: Data, delegate: (any URLSessionTaskDelegate)? = nil) async throws -> (Data, URLResponse) { + func upload(for request: URLRequest, from bodyData: Data, delegate: (any URLSessionTaskDelegate)? = nil) async throws -> (Data, URLResponse) { try await withCheckedThrowingContinuation { continuation in let task = uploadTask(with: request, from: bodyData) { data, res, err in if let err { From edd3d3d2ff9e90766d6230a6085f47b5e55e0cd0 Mon Sep 17 00:00:00 2001 From: 417-72KI <417.72ki@gmail.com> Date: Sun, 25 Oct 2026 23:56:27 +0900 Subject: [PATCH 09/13] enable swift 6 mode --- Package.swift | 46 ++++------------------------------------------ 1 file changed, 4 insertions(+), 42 deletions(-) diff --git a/Package.swift b/Package.swift index f5b4ff95..2495d49a 100644 --- a/Package.swift +++ b/Package.swift @@ -28,7 +28,7 @@ let package = Package( .target(name: "MultipartFormDataParser"), .testTarget(name: "MultipartFormDataParserTests", dependencies: ["MultipartFormDataParser"]), ], - swiftLanguageModes: [.v5] + swiftLanguageModes: [.v6] ) // MARK: - develop @@ -59,21 +59,6 @@ if isDevelop { // MARK: - Upcoming feature flags for Swift 6 package.targets.forEach { $0.swiftSettings = [ - .conciseMagicFile, - .forwardTrailingClosures, - .strictConcurrency, - .bareSlashRegexLiterals, - .deprecateApplicationMain, - .importObjcForwardDeclarations, - .disableOutwardActorInference, - .isolatedDefaultValues, - .globalConcurrency, - .inferSendableFromCaptures, - .implicitOpenExistentials, - .regionBasedIsolation, - .dynamicActorIsolation, - .nonfrozenEnumExhaustivity, - .globalActorIsolatedTypesUsability, .existentialAny, .internalImportsByDefault, .memberImportVisibility, @@ -82,30 +67,7 @@ package.targets.forEach { // ref: https://github.com/treastrain/swift-upcomingfeatureflags-cheatsheet private extension SwiftSetting { - static let conciseMagicFile: Self = .enableUpcomingFeature("ConciseMagicFile") // SE-0274, Swift 5.8, SwiftPM 5.8+ - static let forwardTrailingClosures: Self = .enableUpcomingFeature("ForwardTrailingClosures") // SE-0286, Swift 5.3, SwiftPM 5.8+ - static let strictConcurrency: Self = .enableUpcomingFeature("StrictConcurrency") // SE-0337, Swift 6.0, SwiftPM 6.0+ - static let bareSlashRegexLiterals: Self = .enableUpcomingFeature("BareSlashRegexLiterals") // SE-0354, Swift 5.7, SwiftPM 5.8+ - static let deprecateApplicationMain: Self = .enableUpcomingFeature("DeprecateApplicationMain") // SE-0383, Swift 5.10, SwiftPM 5.10+ - static let importObjcForwardDeclarations: Self = .enableUpcomingFeature("ImportObjcForwardDeclarations") // SE-0384, Swift 5.9, SwiftPM 5.9+ - static let disableOutwardActorInference: Self = .enableUpcomingFeature("DisableOutwardActorInference") // SE-0401, Swift 5.9, SwiftPM 5.9+ - static let isolatedDefaultValues: Self = .enableUpcomingFeature("IsolatedDefaultValues") // SE-0411, Swift 5.10, SwiftPM 5.10+ - static let globalConcurrency: Self = .enableUpcomingFeature("GlobalConcurrency") // SE-0412, Swift 5.10, SwiftPM 5.10+ - static let inferSendableFromCaptures: Self = .enableUpcomingFeature("InferSendableFromCaptures") // SE-0418, Swift 6.0, SwiftPM 6.0+ - static let implicitOpenExistentials: Self = .enableUpcomingFeature("ImplicitOpenExistentials") // SE-0352, Swift 5.7, SwiftPM 6.0+ - static let regionBasedIsolation: Self = .enableUpcomingFeature("RegionBasedIsolation") // SE-0414, Swift 6.0, SwiftPM 6.0+ - static let dynamicActorIsolation: Self = .enableUpcomingFeature("DynamicActorIsolation") // SE-0423, Swift 6.0, SwiftPM 6.0+ - static let nonfrozenEnumExhaustivity: Self = .enableUpcomingFeature("NonfrozenEnumExhaustivity") // SE-0192, Swift 6.0, SwiftPM 6.0+ - static let globalActorIsolatedTypesUsability: Self = .enableUpcomingFeature("GlobalActorIsolatedTypesUsability") // SE-0434, Swift 6.0, SwiftPM 6.0+ - static let existentialAny: Self = .enableUpcomingFeature("ExistentialAny") // SE-0335, Swift 5.6, SwiftPM 5.8+ - static let internalImportsByDefault: Self = .enableUpcomingFeature("InternalImportsByDefault") // SE-0409, Swift 6.0, SwiftPM 6.0+ - static let memberImportVisibility: Self = .enableUpcomingFeature("MemberImportVisibility") // SE-0444, Swift 6.1, SwiftPM 6.1+ -} - -// MARK: - Enabling Complete Concurrency Checking for Swift 6 -// ref: https://www.swift.org/documentation/concurrency/ -package.targets.forEach { - var settings = $0.swiftSettings ?? [] - settings.append(.enableExperimentalFeature("StrictConcurrency")) - $0.swiftSettings = settings + static let existentialAny: Self = .enableUpcomingFeature("ExistentialAny") // SE-0335, Swift 5.6, SwiftPM 5.8+ + static let internalImportsByDefault: Self = .enableUpcomingFeature("InternalImportsByDefault") // SE-0409, Swift 6.0, SwiftPM 6.0+ + static let memberImportVisibility: Self = .enableUpcomingFeature("MemberImportVisibility") // SE-0444, Swift 6.1, SwiftPM 6.1+ } From 54f1f7542d9b20851802e38fd41ee1f69c4898fe Mon Sep 17 00:00:00 2001 From: 417-72KI <417.72ki@gmail.com> Date: Mon, 26 Oct 2026 00:19:40 +0900 Subject: [PATCH 10/13] remove unnecessary flag --- Package.swift | 51 +++++++++++++++++++++++++-------------------------- 1 file changed, 25 insertions(+), 26 deletions(-) diff --git a/Package.swift b/Package.swift index 2495d49a..33c7b98c 100644 --- a/Package.swift +++ b/Package.swift @@ -4,13 +4,6 @@ import PackageDescription let isDevelop = true -let isApplePlatform: Bool = { - #if canImport(Darwin) - true - #else - false - #endif -}() let package = Package( name: "MultipartFormDataParser", @@ -33,26 +26,32 @@ let package = Package( // MARK: - develop if isDevelop { - if isApplePlatform { - package.dependencies.append(contentsOf: [ - .package(url: "https://github.com/SimplyDanny/SwiftLintPlugins", exact: "0.65.1"), - .package(url: "https://github.com/Alamofire/Alamofire.git", from: "5.12.0"), - .package(url: "https://github.com/ishkawa/APIKit.git", from: "5.4.0"), - ]) - package.targets - .filter(\.isTest) - .forEach { - $0.dependencies.append(contentsOf: [ - "Alamofire", - "APIKit", - ]) - } - package.targets.forEach { - if $0.plugins == nil { - $0.plugins = [] - } - $0.plugins?.append(.plugin(name: "SwiftLintBuildToolPlugin", package: "SwiftLintPlugins")) + package.dependencies.append(contentsOf: [ + .package(url: "https://github.com/SimplyDanny/SwiftLintPlugins", exact: "0.65.1"), + .package(url: "https://github.com/Alamofire/Alamofire.git", from: "5.12.0"), + .package(url: "https://github.com/ishkawa/APIKit.git", from: "5.4.0"), + ]) + package.targets + .filter(\.isTest) + .forEach { + $0.dependencies.append(contentsOf: [ + .product( + name: "APIKit", + package: "APIKit", + condition: .when(platforms: [.macOS, .macCatalyst, .iOS, .tvOS]), + ), + .product( + name: "Alamofire", + package: "Alamofire", + condition: .when(platforms: [.macOS, .macCatalyst, .iOS, .tvOS]), + ) + ]) } + package.targets.forEach { + if $0.plugins == nil { + $0.plugins = [] + } + $0.plugins?.append(.plugin(name: "SwiftLintBuildToolPlugin", package: "SwiftLintPlugins")) } } From 3acec3a014c21c2c79cd658566fa4c70c0e4c3d1 Mon Sep 17 00:00:00 2001 From: 417-72KI <417.72ki@gmail.com> Date: Mon, 26 Oct 2026 01:01:19 +0900 Subject: [PATCH 11/13] fix: `error while loading shared libraries: libxml2.so.2: cannot open shared object file: No such file or directory` --- .github/workflows/pr.yml | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index e6d6cd42..ed81e359 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -125,6 +125,15 @@ jobs: key: ${{ runner.os }}-${{ matrix.swift }}-${{ hashFiles('Package.swift') }} restore-keys: | ${{ runner.os }}-${{ matrix.swift }}- + - name: Set up libxml if needed + run: | + # ref: https://discourse.ubuntu.com/t/psa-ubuntu-25-10-features-a-libxml2-version-with-api-breaking-changes/71783/2 + libxml2_paths=$(ldconfig -p | grep libxml2 | sed -E 's/(.*) => (.*)/\2/g') + if [ -z "$(echo "$libxml2_paths" | grep '.so.2')" ] && [ -n "$(echo "$libxml2_paths" | grep '.so.16')" ]; then + libxml2_16_path="$(echo "$libxml2_paths" | grep '.so.16')" + libxml2_2_path="$(echo "$libxml2_16_path" | sed 's/\.so\.16/\.so\.2/')" + ln -s "$libxml2_16_path" "$libxml2_2_path" + fi - name: Set up test package when repository is a template if: ${{ github.event.repository.is_template }} run: swift package init From c0d6e20b6b6ce08fbc3925d0b753b07c7bc11545 Mon Sep 17 00:00:00 2001 From: 417-72KI <417.72ki@gmail.com> Date: Mon, 26 Oct 2026 03:12:09 +0900 Subject: [PATCH 12/13] fix workflow https://github.com/417-72KI/MultipartFormDataParser/pull/122#discussion_r4371642467 https://github.com/417-72KI/MultipartFormDataParser/pull/122#discussion_r4371642486 --- .github/workflows/pr.yml | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index ed81e359..8b897c88 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -2,12 +2,6 @@ name: Pull Request on: pull_request: types: [opened, synchronize, reopened, edited] - paths: - - .github/workflows/pr.yml - - .github/create-matrix.sh - - .github/matrix.yml - - Package.* - - '**/*.swift' permissions: contents: read concurrency: @@ -142,6 +136,7 @@ jobs: danger: name: Danger needs: merge-xcresult + if: ${{ always() && !cancelled() }} runs-on: ubuntu-latest permissions: checks: write From 9353fb260824fbbd5b04cb00341580ab457e41aa Mon Sep 17 00:00:00 2001 From: 417-72KI <417.72ki@gmail.com> Date: Tue, 27 Oct 2026 00:20:13 +0900 Subject: [PATCH 13/13] apply suggestion https://github.com/417-72KI/MultipartFormDataParser/pull/122#discussion_r4371876043 Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- .github/workflows/pr.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 8b897c88..6e8f89c5 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -146,6 +146,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + continue-on-error: true with: name: merged-test-result path: test_output