MultipartFormDataParser

2.2.1

Testing tool for `multipart/form-data`
417-72KI/MultipartFormDataParser

What's New

2.2.1

2024-04-23T04:06:11Z

What's Changed

  • Convert optional UTF8 String <-> Data conversion to non-optional ones by @417-72KI in #84
  • Add failure tests by @417-72KI in #85
  • Remove unused codes which depends on OHHttpStubs by @417-72KI in #86

Full Changelog: 2.2.0...2.2.1

MultipartFormDataParser

Actions Status Version Platform GitHub release Swift Package Manager GitHub license

MultipartFormDataParser is a testing tool for multipart/form-data request in Swift.

When to upload some files via API, we must use multipart/form-data for request. multipart/form-data is defined as RFC-2388

Most famous networking libraries (e.g. Alamofire, APIKit) can implement easily. However, to test if the created request is as expected is difficult and bothering.

This library provides a parser for multipart/form-data request to test it briefly.

let request: URLRequest = ...
do {
    let data = try MultipartFormData.parse(from: request)
    let genbaNeko = try XCTUnwrap(data.element(forName: "genbaNeko"))
    let message = try XCTUnwrap(data.element(forName: "message"))
    XCTAssertNotNil(Image(data: genbaNeko.data))
    XCTAssertEqual(genbaNeko.mimeType, "image/jpeg")
    XCTAssertEqual(message.string, "Hello world!")
} catch {
    XCTFail(error.localizedDescription)
}

Using OHHTTPStubs, we can test a request created by networking libraries easily.

let expectedGenbaNeko: Data = ...

let condition = isHost("localhost") && isPath("/upload")
stub(condition: condition) { request in
    let errorResponse = { (message: String) -> HTTPStubsResponse in
        .init(
            jsonObject: ["status": 403, "error": message],
            statusCode: 403, 
            headers: ["Content-Type": "application/json"]
        )
    }
    do {
        let data = try MultipartFormData.parse(from: request)
        guard let genbaNeko = data.element(forName: "genbaNeko"),
              genbaNeko.data == expectedGenbaNeko else { return errorResponse("Unexpected genbaNeko") }
        guard let message = data.element(forName: "message"),
              message.string == "Hello world!" else { return errorResponse("Unexpected message: \(message)") }
    } catch {
        return .init(error: error)
    }
    return .init(
        jsonObject: ["status": 200],
        statusCode: 200,
        headers: ["Content-Type": "application/json"]
    )
}

Installation

Swift Package Manager (recommended)

Package.swift

dependencies: [
    .package(url: "https://github.com/417-72KI/MultipartFormDataParser.git", from: "2.2.1")
]

CocoaPods

Podfile

pod 'MultipartFormDataParser'

Description

  • Swift Tools 5.8.0
View More Packages from this Author

Dependencies

  • None
Last updated: Tue Oct 29 2024 01:32:44 GMT-0900 (Hawaii-Aleutian Daylight Time)