Swiftpack.co - Package - AliSoftware/OHHTTPStubs

OHHTTPStubs

Platform Language: Swift-2.x/3.x/4.x/5.x Build Status

Version Carthage Supported Swift Package Manager Supported

OHHTTPStubs is a library designed to stub your network requests very easily. It can help you:

  • test your apps with fake network data (stubbed from file) and simulate slow networks, to check your application behavior in bad network conditions
  • write unit tests that use fake network data from your fixtures.

It works with NSURLConnection, NSURLSession, AFNetworking, Alamofire or any networking framework that use Cocoa's URL Loading System.

Donate


Documentation & Usage Examples

OHHTTPStubs headers are fully documented using Appledoc-like / Headerdoc-like comments in the header files. You can also read the online documentation here.

Basic example

In Objective-C
[HTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) {
  return [request.URL.host isEqualToString:@"mywebservice.com"];
} withStubResponse:^HTTPStubsResponse*(NSURLRequest *request) {
  // Stub it with our "wsresponse.json" stub file (which is in same bundle as self)
  NSString* fixture = OHPathForFile(@"wsresponse.json", self.class);
  return [HTTPStubsResponse responseWithFileAtPath:fixture
            statusCode:200 headers:@{@"Content-Type":@"application/json"}];
}];
In Swift

This example is using the Swift helpers found in OHHTTPStubsSwift.swift provided by the OHHTTPStubs/Swift subspec or OHHTTPStubs package.

stub(condition: isHost("mywebservice.com")) { _ in
  // Stub it with our "wsresponse.json" stub file (which is in same bundle as self)
  let stubPath = OHPathForFile("wsresponse.json", type(of: self))
  return fixture(filePath: stubPath!, headers: ["Content-Type":"application/json"])
}

Note: if you're using OHHTTPStubs's Swiftier API (OHHTTPStubsSwift.swift and the Swift subspec or OHTTPStubsSwift package), you can also compose the matcher functions like this: stub(isScheme("http") && isHost("myhost")) { … }

More examples & Help Topics

Recording requests to replay them later

Instead of writing the content of the stubs you want to use manually, you can use tools like SWHttpTrafficRecorder to record network requests into files. This way you can later use those files as stub responses.
This tool can record all three formats that are supported by OHHTTPStubs (the HTTPMessage format, the simple response boby/content file, and the Mocktail format).

(There are also other ways to perform a similar task, including using curl -is <url> >foo.response to generate files compatible with the HTTPMessage format, or using other network recording libraries similar to SWHttpTrafficRecorder).

Compatibility

  • OHHTTPStubs is compatible with iOS5+, OS X 10.7+, tvOS.
  • OHHTTPStubs also works with NSURLSession as well as any network library wrapping them.
  • OHHTTPStubs is fully compatible with Swift 3.x, 4.x and Swift 5.x.

Nullability annotations have also been added to the ObjC API to allow a cleaner API when used from Swift even if you don't use the dedicated Swift API wrapper provided by OHHTTPStubsSwift.swift.

Updating to Version 9.0+
  • All classes dropped the OH prefix (OHHHTTPStubs -> HTTPStubs, OHHTTPStubsResponse -> HTTPStubsResponse, etc).
  • The OHPathHelpers class was renamed HTTPStubsPathHelpers.
  • No method and module names were changed.

Installing in your projects

CocoaPods

Using CocoaPods is the recommended way.

  • If you intend to use OHHTTPStubs from Objective-C only, add pod 'OHHTTPStubs' to your Podfile.
  • If you intend to use OHHTTPStubs from Swift, add pod 'OHHTTPStubs/Swift' to your Podfile instead.
pod 'OHHTTPStubs/Swift' # includes the Default subspec, with support for NSURLSession & JSON, and the Swiftier API wrappers

All available subspecs

OHHTTPStubs is split into subspecs so that when using Cocoapods, you can get only what you need, no more, no less.

  • The default subspec includes NSURLSession, JSON, and OHPathHelpers
  • The Swift subspec adds the Swiftier API to that default subspec
  • HTTPMessage and Mocktail are opt-in subspecs: list them explicitly if you need them
  • OHPathHelpers doesn't depend on Core and can be used independently of OHHTTPStubs altogether
List of all the subspecs & their dependencies

Here's a list of which subspecs are included for each of the different lines you could use in your Podfile:

| Subspec | Core | NSURLSession | JSON | Swift | OHPathHelpers | HTTPMessage | Mocktail | | --------------------------------- | :--: | :----------: | :--: | :---: | :-----------: | :---------: | :------: | | pod 'OHHTTPStubs' | ✅ | ✅ | ✅ | | ✅ | | | | pod 'OHHTTPStubs/Default' | ✅ | ✅ | ✅ | | ✅ | | | | pod 'OHHTTPStubs/Swift' | ✅ | ✅ | ✅ | ✅ | ✅ | | | | pod 'OHHTTPStubs/Core' | ✅ | | | | | | | | pod 'OHHTTPStubs/NSURLSession' | ✅ | ✅ | | | | | | | pod 'OHHTTPStubs/JSON' | ✅ | | ✅ | | | | | | pod 'OHHTTPStubs/OHPathHelpers' | | | | | ✅ | | | | pod 'OHHTTPStubs/HTTPMessage' | ✅ | | | | | ✅ | | | pod 'OHHTTPStubs/Mocktail' | ✅ | | | | | | ✅ |

Swift Package Manager

OHHTTPStubs is compatible with Swift Package Manager, and provides 2 targets for consumption: OHHTTPStubs and OHHTTPStubsSwift.

  • OHHTTPStubs is equivalent to the OHHTTPStubs subspec.
  • OHHTTPStubsSwift is equivalent to the OHHTTPStubs/Swift subspec.

Note: We currently do not have support for the HTTPMessage or Mocktail subspecs in Swift Package Manager. If you are interested in these, please open an issue to explain your needs.

Carthage

OHHTTPStubs is also compatible with Carthage. Just add it to your Cartfile.

Note: The OHHTTPStubs.framework built with Carthage will include all features of OHHTTPStubs turned on (in other words, all subspecs of the pod), including NSURLSession and JSON support, OHPathHelpers, HTTPMessage and Mocktail support, and the Swiftier API.

Using the right Swift version for your project

OHHTTPStubs supports Swift 3.0 (Xcode 8+), Swift 3.1 (Xcode 8.3+), Swift 3.2 (Xcode 9.0+), Swift 4.0 (Xcode 9.0+), Swift 4.1 (Xcode 9.3+), Swift 4.2 (Xcode 10+), Swift 5.0 (Xcode 10.2), and Swift 5.1 (Xcode 11) however we are only testing Swift 4.x (using Xcode 9.1 and 10.1) and Swift 5.x (using Xcode 10.2 AND 11) in CI.

Here are some details about the correct setup you need depending on how you integrated OHHTTPStubs into your project.

CocoaPods: nothing to do

If you use CocoaPods version 1.1.0.beta.1 or later, then CocoaPods will compile OHHTTPStubs with the right Swift Version matching the one you use for your project automatically. You have nothing to do! 🎉

For more info, see CocoaPods/CocoaPods#5540 and CocoaPods/CocoaPods#5760.

Carthage: choose the right version

The project is set up with SWIFT_VERSION=5.0 on master.

This means that the framework on master will build using:

  • Swift 5.1 on Xcode 11
  • Swift 5.0 on Xcode 10.2
  • Swift 4.2 on Xcode 10.1
  • Swift 4.0 on Xcode 9.1

If you want Carthage to build the framework with Swift 3.x you can:

  • either use an older Xcode version
  • or use the previous version of OHHTTPStubs (6.2.0) — whose master branch uses 3.0
  • or fork the repo just to change the SWIFT_VERSION build setting to 3.0
  • or build the framework passing a SWIFT_VERSION to carthage via XCODE_XCCONFIG_FILE=<config file declaring SWIFT_VERSION> carthage build

Special Considerations

Using OHHTTPStubs in your unit tests

OHHTTPStubs is ideal to write unit tests that normally would perform network requests. But if you use it in your unit tests, don't forget to:

  • remove any stubs you installed after each test — to avoid those stubs to still be installed when executing the next Test Case — by calling [HTTPStubs removeAllStubs] in your tearDown method. see this wiki page for more info
  • be sure to wait until the request has received its response before doing your assertions and letting the test case finish (like for any asynchronous test). see this wiki page for more info

Automatic loading

OHHTTPStubs is automatically loaded and installed (at the time the library is loaded in memory), both for:

  • requests made using NSURLConnection or [NSURLSession sharedSession]thanks to this code
  • requests made using a NSURLSession that was created via [NSURLSession sessionWithConfiguration:…] and using either [NSURLSessionConfiguration defaultSessionConfiguration] or [NSURLSessionConfiguration ephemeralSessionConfiguration] configuration — thanks to method swizzling done here in the code.

If you need to disable (and re-enable) OHHTTPStubs — globally or per NSURLSession — you can use [HTTPStubs setEnabled:] / [HTTPStubs setEnabled:forSessionConfiguration:].

Known limitations

  • OHHTTPStubs can't work on background sessions (sessions created using [NSURLSessionConfiguration backgroundSessionConfiguration]) because background sessions don't allow the use of custom NSURLProtocols and are handled by the iOS Operating System itself.
  • OHHTTPStubs don't simulate data upload. The NSURLProtocolClient @protocol does not provide a way to signal the delegate that data has been sent (only that some has been loaded), so any data in the HTTPBody or HTTPBodyStream of an NSURLRequest, or data provided to -[NSURLSession uploadTaskWithRequest:fromData:]; will be ignored, and more importantly, the -URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend: delegate method will never be called when you stub the request using OHHTTPStubs.
  • OHTTPStubs has a known issue with redirects that we believe is an Apple bug. It has been discussed here and here. The actual result of this bug is that redirects with a zero second delay may nondeterministically end up with a null response.

As far as I know, there's nothing we can do about those three limitations. Please let me know if you know a solution that would make that possible anyway.

Submitting to the App Store

OHHTTPStubs can be used on apps submitted on the App Store. It does not use any private API and nothing prevents you from shipping it.

But you generally only use stubs during the development phase and want to remove your stubs when submitting to the App Store. So be careful to only include OHHTTPStubs when needed (only in your test targets, or only inside #if DEBUG sections, or by using per-Build-Configuration pods) to avoid forgetting to remove it when the time comes that you release for the App Store and you want your requests to hit the real network!

License and Credits

This project and library has been created by Olivier Halligon (@aligatr on Twitter) and is under the MIT License.

It has been inspired by this article from InfiniteLoop.dk.

I would also like to thank:

  • Sébastien Duperron (@Liquidsoul) for helping me maintaining this library, triaging and responding to issues and PRs
  • Kevin Harwood (@kcharwood) for migrating the code to NSInputStream
  • Jinlian Wang (@JinlianWang) for adding Mocktail support
  • and everyone else who contributed to this project on GitHub somehow.

If you want to support the development of this library, feel free to Donate. Thanks to all contributors so far!

Github

link
Stars: 4606

Dependencies

Used By

Total: 0

Releases

9.0.0 - 2020-01-24 02:57:00

  • Added support for Swift Package Manager and dropped OH from all class names.
    @jeffctown

8.0.0 - 2019-04-22 18:20:59

  • Update default Swift Version to 5.0 @croig

7.0.0 - 2019-03-14 18:16:44

  • Updating default Swift Version to 4.2.
    @jeffctown
  • Updating example projects to Swift 4.2 and Xcode 10.1.
    @jeffctown
  • Updating iOS Lib Tests to have a minimum iOS version of 8.0.
    @jeffctown

Notes:

  • Bumping this version to 7.0.0 because it's now using the Swift 4 APIs.
  • This version is still compatible with Swift 3.x when integrating with CocoaPods, as CocoaPods uses the same SWIFT_VERSION as your app project does so it adapts automatically and it's transparent for users.
  • If you're using Carthage and need Swift 3.x compatibility, you can follow the tips in the installation instructions of the README.md.
  • CI is now only testing Swift 4.x on Xcode 9.1 and 10.1.
  • Thank you to @hellensoloviy, @robertoferraz, @rckoenes, @NikSativa for their pull requests updating Swift!

6.2.0 - 2019-03-14 17:16:16

  • Enabled application extension API only.
    @lightsprint09
  • Disabled a flaky redirect test and adding the known issue with redirects to the README.
    @jeffctown #301
  • Added isMethodHEAD() to the Swift helpers.
    @Simon-Kaz #294
  • Fixed issue with not preserving correct headers when following 3xx redirects.
    @sberrevoets

- 2017-11-19 00:29:07

  • Updated deployment target for the pod to 7.0 to remove warning for old APIs.
    @AliSoftware
  • Fixed HTTP Method retention for 301,302,307,308 status redirects.
    @mikelupo
  • Added hasJsonBody(_:) matcher.
    @pimnijman
  • Added onStubMissing to report missing stubs.
    @c1ira #264
  • Fixed URLRequest.ohhttpStubs_httpBody function in Swift 3 and 4.
    @mplorentz
  • Added absolute url matcher.
    @victorg1991 #254
  • Fixed up empty lines with whitespace inside test case classes.
    @mikelupo #251
  • Fixed potential memory leaks with use of NSURLSession as detected by our devs.
    @mikelupo #250
  • Add precondition assertions in isScheme and isHost matchers and some documentation in isHost, isScheme and isPath.
    @Liquidsoul #248

- 2017-04-04 17:55:31

  • Made Swift 3 the default. master is now compatible with 3.0 and 3.1.
    @Liquidsoul @cohilla #240
  • The pod 'OHHTTPStubs/Swift' subspec now includes the URLSession and JSON subspecs.
    @AliSoftware
  • Added some matchers to the Swift APIs: hasBody(…), pathEndsWith(…) and pathMatches(…).
    @AliSoftware

Notes:

  • Bumping this version to 6.0.0 because it's now using the Swift 3 APIs, but in practice it's entirely retro-compatible with previous 5.2.3-swift3 branch
  • This version is still compatible with Swift 2.3 when integrating with CocoaPods, as CocoaPods uses the same SWIFT_VERSION as your app project does so it adapts automatically and it's transparent for users.
  • If you're using Carthage though, we stopped providing Swift-2.3-specific branches ourselves (too much maintainance work), but if you still need Swift 2.3 compatibility, you can follow the tips in the installation instructions of the README.md.

- 2016-11-29 19:47:51

  • Reverted #216 until better solution, as it was never active and can't make it compile for all subspec configurations.
  • Improved documentation about dynamicType: vs type(of:).
    Antondomashnev #221
  • Fixed a race condition that occasionally prevented redirect callbacks.
    @morrowa #224
  • Fixed response timing for zero-length stub data.
    @morrowa #224

- 2016-11-29 19:47:20

This is the same release as 5.2.3 below, except it has SWIFT_VERSION=3.0 set in the Xcode project so that Carthage users already using Swift 3 can build it with this configuration.

The sample projects also have been updated to Swift 3 in this branch.

Users of CocoaPods are not impacted by this and can use the main 5.2.3 version — this tag is only useful for Carthage users (until Carthage/#1445 is fixed)

- 2016-10-23 17:39:26

This is the same release as 5.2.2 below, except it has SWIFT_VERSION=3.0 set in the Xcode project so that Carthage users already using Swift 3 can build it with this configuration.

The sample projects also have been updated to Swift 3 in this branch.

Users of CocoaPods are not impacted by this and can use the main 5.2.2 version — this tag is only useful for Carthage users (until Carthage/#1445 is fixed)

- 2016-10-23 17:31:27

- 2016-09-09 18:08:01

This is the same release as 5.2.1 below, except it has SWIFT_VERSION=3.0 set in the Xcode project so that Carthage users already using Swift 3 can build it with this configuration.

Users of CocoaPods are not impacted by this and can use the main 5.2.1 version, this tag is only useful for Carthage users (until Carthage/#1445 is fixed)

- 2016-09-09 18:05:12

Reminder that this version is source-compatible compatible with ObjC, Swift 2.2, 2.3 and 3.0 all in master. You you're using CocoaPods you can use 5.2.0 directly. But if you're using Carthage, which builds the framework from the Xcode project, you should use the swift3 branch — whose only diff is the SWIFT_VERSION build setting being set to 3.0.

Note for Carthage users: The OHHTTPStubs.framework.zip pre-build binary is intentionally not included in this release, because we're in a transition period between Swift 2.2, 2.3 and 3.0. Carthage only let us provide one pre-build binary per version while we'd need one for each Swift ABI during that transition period. For more info, see the dedicated paragraph in README.

5.2.0 + Swift 3 enforced for Carthage - 2016-08-21 03:15:32

This is the same release as 5.2.0 below, except it has SWIFT_VERSION=3.0 set in the Xcode project so that Carthage users already using Swift 3 can build it with this configuration

5.2.0: Swift 2.3 & 3.0 support - 2016-08-21 02:40:51

  • Added Swift 2.3/Xcode 8 support. This is compatible both Swift 2.2/Xcode 7.3 and Swift 2.3/Xcode 8.
    @ikesyo, #184
  • Added Swift 3.0 support.
    @mxcl, @Liquidsoul, #192
  • Set deployment targets at the project level to be used in a universal target.
    @ikesyo, #185
  • Fix: Carthage support and Examples configurations.
    @Liquidsoul, #190

Note for Carthage users: The OHHTTPStubs.framework.zip pre-build binary is intentionally not included in this release, because we're in a transition period between Swift 2.2, 2.3 and 3.0. Carthage only let us provide one pre-build binary per version while we'd need one for each Swift ABI during that transition period. For more info, see the dedicated paragraph in README.

- 2016-06-06 19:42:56

  • Bugfix: task completion block never called when not following redirects.
    @adurdin, #175
  • Declare in the project settings that the library contains swift code.
    @rodericj, #173
  • Adjusted parsing of Mocktail files to allow headers to start on line 4.
    @Ashton-W, #172
  • Allows access to the HTTPBody of POST request when using NSURLSession (Wiki entry)
    @iosphere, #166 #180

- 2016-03-28 17:53:03

  • Added pathStartsWith(_:) to the Swift helpers.
    @sdduursma, #163
  • Added more logging blocks for debugging and better insight into when OHHTTPStubs returns stubs and redirects.
    @jzucker2, #161
  • Added matchers that check whether a request has a particular header present, and a matcher to check if a request has a header with a key and value.
    @hq-mobile, #160

Note that this last change also changed the signature of the onStubActivation: (hence the bump to 5.0.0) so you'll have to update your code if you used this for debugging your stubs.

- 2016-03-13 23:02:53

  • Added isEnabled and isEnabledForSessionConfiguration getter methods.
    @jzucker2, #159

- 2016-02-20 15:40:13

  • Bumps OSX Deployment Target to 10.9 to add Swift support.
    @JeanAzzopardi, #154
  • Added the ${CURRENT_PROJECT_VERSION} to the Info.plist files of theOHHTTPStubs.framework so it matches what is expected by iTunes Connect.
    @siemensikkema, #140

- 2015-12-20 17:55:05

  • Added isMethodPATCH() to the Swift helpers.
    @attheodo, #145
  • Fixed nullability annotation on onStubActivation: method parameter.
    @DerLobi, #144

New Swift Helper methods - 2015-11-05 18:57:12

  • Added isMethodGET(), isMethodPUT(), isMethodPOST() and isMethodDELETE() to the Swift helpers. (#137)

- 2015-11-03 14:36:08

  • Added missing tvOS and watchOS platforms to the Swift subspec.
    @pantuspavel, #136

tvOS Support - 2015-10-31 21:12:55

Fixing Umbrella headers + NSURL methods - 2015-10-24 12:08:31

  • Fixed issue with Umbrella Headers (#127, #131)
  • Added methods for creating OHHTTPStubsResponses from NSURLs that represent file system resources (@MaxGabriel, #129)
  • Bumped Swift subspec compatibility to OSX 10.9 instead of 10.7.

Xcode project typos + new speed constant - 2015-09-20 14:25:51

  • Fix the Examples Xcode project + lib Podfile that were referencing old target names (mikelupo, #117)
  • Added two new constants for download speed: OHHTTPStubsDownloadSpeed1KBPS = 1kbps and OHHTTPStubsDownloadSpeedSLOW = 1.5 kpbs. (mikelupo, #114)

Swift Helpers & Xcode 7 - 2015-09-20 14:25:02

  • Xcode projects updated to Xcode 7.0 Final
  • Added a Swift subspec that adds helper global functions to ease & make more compact the use of OHHTTPStubs from Swift 2.0 (#111)

If you're using OHHTTPStubs in a Swift 2.0 project, it's recommended to add pod 'OHHTTPStubs/Swift to your Podfile so you can use those handy helpers.

Mocktail support (+ Subspec split) - 2015-08-28 19:11:33

  • Added support for stubs written in the Mocktail format (@JinlianWang, #108)
  • The OHHTTPStubs spec has been splitted into multiple subspecs:
    • The default subspec (used when you simply use pod 'OHHTTPStubs' in your Podfile) contains the subspecs Core, NSURLSession, JSON & OHPathHelpers (so that it matches the features that most people use).
    • Other optional subspecs are HTTPMessage and Mocktail (which are opt-in because used by much less people). If you want to use them, you'll need to request them explicitly in your Podfile using pod 'OHHTTPStubs/Mocktail for example.
  • The iOS Unit Tests are now also run for the framework as well as for the static library, to ensure the tests pass in both contexts (because frameworks sometimes introduce subtleties like when using NSBundle, so it's worth testing in that context too)

- 2015-07-28 19:12:05

  • Added support for using OHHTTPStubs in watchOS 2.0 targets.
  • Improved compatibility macros (nullability annotations) — and tested against Xcode 7 beta 4.

Fix OHResourceBundle declaration - 2015-05-20 21:19:30

  • Fix OHResourceBundle name mismatch between header and implementation (@tibr, #103)

Fixed threading issue - 2015-05-13 20:27:42

  • Fix threading in NSURLProtocol subclass calling NSURLProtocolClient callbacks from wrong thread. (@nsprogrammer, #96)

Improvements in Swift API - 2015-05-13 20:27:20

  • Annotated the library with nullability attributes to generate a better API when used in Swift
  • Migrated the path utility macros to functions in OHPathHelpers.h, for Swift compatibility (#100).
  • Added a complete Swift Demo Project (#88)
  • Removed the XCTestExpectation subspec that was added for Xcode 5 support — Now that Xcode 6 is widely adopted, you shouldn't need this anymore.