Network testing for Swift

Related tags

Testing DVR
Overview

DVR

Version Status Swift Version Carthage compatible Swift Package Manager

DVR is a simple Swift framework for making fake NSURLSession requests for iOS, watchOS, and OS X based on VCR.

Easy dependency injection is the main design goal. The API is the same as NSURLSession. DVR.Session is a subclass of NSURLSession so you can use it as a drop in replacement anywhere. (Currently only data tasks are supported.)

Usage

let session = Session(cassetteName: "example")
let task = session.dataTask(with: request) { data, response, error in
    // Do something with the response
}

// Nothing happens until you call `resume` as you'd expect.
task.resume()

This will playback the example cassette. The completion handler exactly the same way it normally would. In this example, DVR will look for a cassette named example.json in your test bundle.

If the recording of the request is missing, it will record and save it to disk. After saving to disk, it will assert with path of the recorded file. This causes the tests to stop so you can add the cassette to your test target and rerun your tests.

Recording Multiple Requests

By default, a DVR session only records one request. You can record multiple requests in the same cassette if you tell DVR when to start and stop recording.

let session = Session(cassetteName: "multiple")

// Begin recording multiple requests
session.beginRecording()

session.dataTask(with: URLRequest(url: URL(string: "http://apple.com")!)) { data, response, error in
    // Do something with the response

    session.dataTask(with: URLRequest(url: URL(string: "http://google.com")!)) { data, response, error in
        // Do something with the response
    }.resume()

    // Finish recording multiple requests
    session.endRecording() {
        // All requests have completed
    }
}.resume()

If you don't call beginRecording and endRecording, DVR will call these for your around the first request you make to a session. You can call endRecording immediately after you've submitted all of your requests to the session. The optional completion block that endRecording accepts will be called when all requests have finished. This is a good spot to fulfill XCTest expectations you've setup or do whatever else now that networking has finished.

Comments
  • Plain text serialization for JSON

    Plain text serialization for JSON

    Added different serialization to different data types. JSON is now serialized in plain text, so that it's more readable. Other types fall back to base64 as before. Includes tests.

    opened by czechboy0 14
  • Version 1.3.0 is breaking: cassettes cannot be found

    Version 1.3.0 is breaking: cassettes cannot be found

    Unfortunately I have not been able to pinpoint the issue yet (I have taken a look at the changes from 1.2.0 to 1.3.0) but I can share that I have a branch where all my tests correctly find the relevant cassettes on version 1.2.0 (and Xcode 9), but with 1.3.0 (and Xcode 10) the tests crash as the cassettes can't be found.

    Something about the diff between 1.2.0 and 1.3.0 is causing this change. Any ideas what may be the issue?

    If we can't pinpoint the problem, then maybe we should deprecate 1.3.0 and release it as 2.0.0 instead since the changes are seemingly breaking behavior.

    opened by loudmouth 13
  • Swift package manager support

    Swift package manager support

    This PR restructures the repo's directories to enable Swift Package Manager.

    It also adds a build job to the travis matrix that ensures swift build is working. Unfortunately, SPM does not enable including other resources (i.e. bundled content) like Xcode so therefore swift test fails as cassettes cannot be found. Once support for bundling other resources with swift build, then we should update the travis script to run swift test.

    Lastly, this fixes the travis builds that were broken on master.

    Addresses #67

    opened by loudmouth 12
  • Ignore BaseURL option

    Ignore BaseURL option

    This PR adds the possibility to ignore the parts of the url when comparing requests. I added ignoreURLComponents options to the Session. This is useful when you are using two environments, sandbox and production. And the request may have a different scheme, port or host.

    opened by mihaigeorgescu-newstore 6
  • Restore print() and abort() behavior

    Restore print() and abort() behavior

    See my comments on this commit https://github.com/venmo/DVR/commit/ecabe603c5b01bcb9f84ad8465e1a2f6d118fc75 which replaced print and abort with fatalError.

    opened by danthorpe 6
  • Handling nil response a bit more gracefully

    Handling nil response a bit more gracefully

    Made the problem when response is nil a bit more obvious (+ removed a forced unwrap, FTW!) I encountered this when https failed to validate a certificate - response was nil, which crashed on the force unwrap during the creation of Interaction. If this happens now, it should be a bit more obvy.

    opened by czechboy0 5
  • Debug status code not being recorded

    Debug status code not being recorded

    Fixes #74 & #69

    This PR fixes a regression that caused the http status code and http headers to not be recorded in the case of non-200 responses. I've added a test to avoid future regressions.

    opened by loudmouth 4
  • Alamofire Support

    Alamofire Support

    Note: This PR depends on the changes in @soffes's Swift 3 branch (#60), once that's merged I'll rebase this on master.

    This PR makes it possible to use DVR in projects that use Alamofire to do their networking. The Alamofire team got us most of the way towards supporting this (see https://github.com/Alamofire/Alamofire/pull/795) by allowing users to inject the URLSession and Alamofire.SessionDelegate used by a manager, but we still need to do some work on DVR's side to ensure it's calling the appropriate delegate methods and whatnot.

    In a broader sense, this PR does the following:

    • Gives every data task has a unique task identifier
    • Ensures that the backing session's delegate receives the appropriate delegate callbacks
    • Implements the currentRequest and originalRequest properties on the DVR session
    • Makes the state property accurate enough to satisfy Alamofire

    It might also be worth updating the docs to include some instructions on using DVR with Alamofire since there's some stuff about it that's non-obvious. I'd be happy to write those if there's interest around this PR.

    I've been using this in a production app's tests for a couple of days now and it works fantastically.

    opened by rhysforyou 4
  • Testing api failures

    Testing api failures

    Hi there, I'm using DVR, and so far I've managed successfully to create tests when api requests return success. But now I want to test the failure of the same requests. So I'm facing a problem when using DVR to test failures (401, 404 etc)..

    When run for 2nd time (first time is to record the response), instead of failure callback, success callback is called with the error response inside of it. Any idea why?

    Using Alamofire. Example code (creating and executing any request):

    request.validate().responseJSON(completionHandler: {
        response in
        switch response.result {
    
             case .success(let JSON):
    // This is what gets called instead of failure. Response code is 401 and the JSON contains error message.
    
                  callback(true, JSON, nil)
    
             case .failure(let error):
                  if let data = response.data, data.count > 0 {
                      let JSON = try! JSONSerialization.jsonObject(with: data, options: .allowFragments)
                      callback(false, JSON, error as NSError?)
                  } else {
                      callback(false, nil, error as NSError?)
                  }
         }
    }).resume()
    
    opened by OliverDimitrov 3
  • Running tests with DVR crashes Xcode

    Running tests with DVR crashes Xcode

    Seems to be a new issue in 0.2.0. I get either Invalid request. The request was not found in the cassette. or Something has gone horribly wrong. before Xcode hits a breakpoint and promptly crashes.

    opened by jordanekay 3
  • Xcode crashes right after new cassette recorded

    Xcode crashes right after new cassette recorded

    Both my Xcode's (7.1 and 7.2-beta.3) crash when I run a test that uses DVR where no cassette exists yet. Crash happens right after DVR records the request, logs the fact to console and then aborts to stop running - immediately after or maybe even at the time of the abort there's a crash.

    Here's a snippet from the crash log:

    Crashed Thread:        38  <DBGLLDBSessionThread (pid=2221)>  Dispatch queue: DVTInvalidationPreventionQueue
    

    DVR is probably not at fault here, but has anyone experienced this and been able to fix or workaround the crash?

    opened by ksm 3
  • Improve README documentation

    Improve README documentation

    Right now, our README is fairly sparse. It might be good to pull out some examples from our tests cases and document how DVR can be used in those situations.

    enhancement 
    opened by eliperkins 0
  • Fix unrecognized selector error for 'taskIdentifier' and 'originalRequest' methods

    Fix unrecognized selector error for 'taskIdentifier' and 'originalRequest' methods

    Adds support to integrate DVR with Alamofire. Fix: https://github.com/venmo/DVR/pull/41#issuecomment-171917800.

    I made a little code snippet about it: https://coderwall.com/p/sd7i2g/my-alamofire-dvr-recipe-for-network-testing-in-swift

    opened by nebiros 7
  • Swift Package Manager

    Swift Package Manager

    I'm writing an API wrapper as a library and just started using DVR in my tests, loving it! I'd really love my library staying compatible with Cocoapods, Carthage and Swift Package Manager. This world of three different package managers to support is really something in this ecosystem ๐Ÿ˜ƒ. My dependencies are declared and integrated via Carthage, which works just fine. Cocoapods doesn't really need to know about DVR since that never runs my tests anyhow. Buuut I kinda still want to be able to run swift test... Is there any way to currently accomplish this? I don't think SPM supports private/dev/test dependencies, does it? Or would it make sense to include DVR as a normal dependency but only require it in test files? Not sure how Swift handles that...

    Nevertheless, support for SPM here would be superb and much appreciated. If it makes sense of course. Thanks! ๐Ÿ˜Š

    opened by kiliankoe 3
  • Rename start/end recording to begin/finish batch

    Rename start/end recording to begin/finish batch

    I was thinking having startRecording/stopRecording in a test is weird since you only record once. Those methods are used for batch requests in one cassette. It would probably be best if these were renamed to beginBatch and finishBatch (or endBatch).

    enhancement 
    opened by soffes 2
  • Added ability to set cassette options [Tests Required]

    Added ability to set cassette options [Tests Required]

    The options added so far allow a user to select what attributes a request should be matched on.

    Request matching options include URL, Path, HTTPMethod and HTTPBody.

    I have added one test but this really needs more, I will add more once I find some time.

    opened by pnicholls 1
Releases(v2.1.0)
Switchboard - easy and super light weight A/B testing for your mobile iPhone or android app. This mobile A/B testing framework allows you with minimal servers to run large amounts of mobile users.

Switchboard - easy A/B testing for your mobile app What it does Switchboard is a simple way to remote control your mobile application even after you'v

Keepsafe 287 Nov 19, 2022
Network testing for Swift

DVR DVR is a simple Swift framework for making fake NSURLSession requests for iOS, watchOS, and OS X based on VCR. Easy dependency injection is the ma

Venmo 650 Nov 3, 2022
Network testing ร  la VCR in Swift

Vinyl Vinyl is a simple, yet flexible library used for replaying HTTP requests while unit testing. It takes heavy inspiration from DVR and VCR. Vinyl

null 271 Dec 21, 2022
Stub your network requests easily! Test your apps with fake network data and custom response time, response code and headers!

OHHTTPStubs OHHTTPStubs is a library designed to stub your network requests very easily. It can help you: test your apps with fake network data (stubb

Olivier Halligon 4.9k Dec 29, 2022
The Swift (and Objective-C) testing framework.

Quick is a behavior-driven development framework for Swift and Objective-C. Inspired by RSpec, Specta, and Ginkgo. // Swift import Quick import Nimbl

Quick 9.6k Dec 31, 2022
Implementing and testing In-App Purchases with StoreKit2 in Xcode 13, Swift 5.5 and iOS 15.

StoreHelper Demo Implementing and testing In-App Purchases with StoreKit2 in Xcode 13, Swift 5.5, iOS 15. See also In-App Purchases with Xcode 12 and

Russell Archer 192 Dec 17, 2022
๐Ÿ“ธ Delightful Swift snapshot testing.

?? SnapshotTesting Delightful Swift snapshot testing. Usage Once installed, no additional configuration is required. You can import the SnapshotTestin

Point-Free 3k Jan 3, 2023
Snapshot testing tool for iOS and tvOS

SnapshotTest is a simple view testing tool written completely in Swift to aid with development for Apple platforms. It's like unit testing for views.

Pรคr Strindevall 44 Sep 29, 2022
UI Testing Cheat Sheet and Examples.

UI Testing Cheat Sheet This repository is complementary code for my post, UI Testing Cheat Sheet and Examples. The post goes into more detail with exa

Joe Masilotti 2.1k Dec 25, 2022
Mockingbird was designed to simplify software testing, by easily mocking any system using HTTP/HTTPS

Mockingbird Mockingbird was designed to simplify software testing, by easily mocking any system using HTTP/HTTPS, allowing a team to test and develop

FARFETCH 183 Dec 24, 2022
Automatic testing of your Pull Requests on GitHub and BitBucket using Xcode Server. Keep your team productive and safe. Get up and running in minutes. @buildasaur

Buildasaur Automatic testing of your Pull Requests on GitHub and BitBucket using Xcode Server. Keep your team productive and safe. Get up and running

Buildasaurs 774 Dec 11, 2022
Fastbot is a model-based testing tool for modeling GUI transitions to discover app stability problems

Fastbot is a model-based testing tool for modeling GUI transitions to discover app stability problems. It combines machine learning and reinforcement learning techniques to assist discovery in a more intelligent way.

Bytedance Inc. 446 Dec 29, 2022
Genything is a framework for random testing of a program properties.

Genything is a framework for random testing of a program properties. It provides way to random data based on simple and complex types.

Just Eat Takeaway.com 25 Jun 13, 2022
For Testing APIs of NYTimes

NYTimes-APIs For Testing APIs of NYTimes Mark Dennis Diwa ?? To run the app: Open terminal first then run pod install. Open workspace. Run the app on

Mark Dennis Diwa 0 Nov 23, 2021
A Mac and iOS Playgrounds Unit Testing library based on Nimble.

Spry Spry is a Swift Playgrounds Unit Testing library based on Nimble. The best thing about Spry is that the API matches Nimble perfectly. Which means

Quick 327 Jul 24, 2022
Multivariate & A/B Testing for iOS and Mac

This library is no longer being maintained. You can continue to use SkyLab in your projects, but we recommend switching another solution whenever you

Mattt 792 Dec 15, 2022
Remote configuration and A/B Testing framework for iOS

MSActiveConfig v1.0.1 Remote configuration and A/B Testing framework for iOS. Documentation available online. MSActiveConfig at a glance One of the bi

Elevate 78 Jan 13, 2021
AB testing framework for iOS

ABKit Split Testing for Swift. ABKit is a library for implementing a simple Split Test that: Doesn't require an HTTP client written in Pure Swift Inst

Recruit Marketing Partners Co.,Ltd 113 Nov 11, 2022
AppiumLibrary is an appium testing library for RobotFramework

Appium library for RobotFramework Introduction AppiumLibrary is an appium testing library for Robot Framework. Library can be downloaded from PyPI. It

Serhat Bolsu 327 Dec 25, 2022