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..6e8f89c5 --- /dev/null +++ b/.github/workflows/pr.yml @@ -0,0 +1,156 @@ +name: Pull Request +on: + pull_request: + types: [opened, synchronize, reopened, edited] +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 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 + - name: test + run: swift test + danger: + name: Danger + needs: merge-xcresult + if: ${{ always() && !cancelled() }} + 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 + continue-on-error: true + 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 diff --git a/.swiftlint.yml b/.swiftlint.yml index 973bee16..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 @@ -28,18 +29,22 @@ 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 - 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/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) + } +} diff --git a/Package.swift b/Package.swift index 71eba91b..33c7b98c 100644 --- a/Package.swift +++ b/Package.swift @@ -1,16 +1,9 @@ -// 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 let isDevelop = true -let isApplePlatform: Bool = { - #if canImport(Darwin) - true - #else - false - #endif -}() let package = Package( name: "MultipartFormDataParser", @@ -18,7 +11,7 @@ let package = Package( .macOS(.v13), .macCatalyst(.v16), .iOS(.v16), - .tvOS(.v16) + .tvOS(.v16), ], products: [ .library(name: "MultipartFormDataParser", targets: ["MultipartFormDataParser"]), @@ -27,66 +20,53 @@ let package = Package( targets: [ .target(name: "MultipartFormDataParser"), .testTarget(name: "MultipartFormDataParserTests", dependencies: ["MultipartFormDataParser"]), - ] + ], + swiftLanguageModes: [.v6] ) // 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")) + 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")) } } // MARK: - Upcoming feature flags for Swift 6 package.targets.forEach { $0.swiftSettings = [ - .forwardTrailingClosures, .existentialAny, - .bareSlashRegexLiterals, - .conciseMagicFile, - .importObjcForwardDeclarations, - .disableOutwardActorInference, - .deprecateApplicationMain, - .isolatedDefaultValues, - .globalConcurrency, + .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+ -} - -// 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+ } 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/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.. (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 { diff --git a/Tests/MultipartFormDataParserTests/_Extension/XCTest+Activity.swift b/Tests/MultipartFormDataParserTests/_Extension/XCTest+Activity.swift deleted file mode 100644 index 8b19d9ac..00000000 --- a/Tests/MultipartFormDataParserTests/_Extension/XCTest+Activity.swift +++ /dev/null @@ -1,9 +0,0 @@ -import XCTest - -func runActivity(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 71bce4ae..1d43d503 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 +) -> 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..aef5fd5a 100644 --- a/Tests/MultipartFormDataParserTests/_TestFunctions/TestFunction_Alamofire.swift +++ b/Tests/MultipartFormDataParserTests/_TestFunctions/TestFunction_Alamofire.swift @@ -1,99 +1,55 @@ 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) { + 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/_TestFunctions/TestFunction_URLSession.swift b/Tests/MultipartFormDataParserTests/_TestFunctions/TestFunction_URLSession.swift index db4c2b89..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( @@ -112,30 +105,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(), +) } diff --git a/Tests/MultipartFormDataParserTests/_Util/StubURLProtocol.swift b/Tests/MultipartFormDataParserTests/_Util/StubURLProtocol.swift index e249ec9c..11c655ba 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 = Self.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) + } } }