GithubHelp home page GithubHelp logo

plu / vcrurlsession Goto Github PK

View Code? Open in Web Editor NEW
15.0 2.0 5.0 498 KB

Record your test suite's HTTP requests and responses. You can replay them during future test runs for fast, deterministic, accurate tests.

License: MIT License

Ruby 1.49% Objective-C 61.28% Swift 37.23%

vcrurlsession's Introduction

VCRURLSession

Build Status

Description

VCRURLSession let's you record your test suite's HTTP requests and responses. You can replay them during future test runs for fast, deterministic, accurate tests.

To use VCRURLSession you must configure your NSURLSession instances:

NSURLSession *session = [VCRURLSession prepareURLSession:[NSURLSession sharedSession]];

There is no swizzling involved!

Usage

Recording

- (void)record
{
    // Set up `protocolClasses` and return new session
    self.session = [VCRURLSession prepareURLSession:[NSURLSession sharedSession]];

    // Create new empty cassette to record HTTP requests on
    VCRURLSessionCassette *cassette = [[VCRURLSessionCassette alloc] init];

    // Start recording HTTP requests
    [VCRURLSession startRecordingOnCassette:cassette];

    // Make some HTTP request
    [[self.session dataTaskWithURL:[NSURL URLWithString:@"https://www.github.com"]
                 completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                     [VCRURLSession stopRecording];
                     [cassette writeToFile:self.path];
                 }] resume];
}

Replaying

- (void)replay
{
    // Set up `protocolClasses` and return new session
    self.session = [VCRURLSession prepareURLSession:[NSURLSession sharedSession]];

    // Load cassette
    VCRURLSessionCassette *cassette = [[VCRURLSessionCassette alloc] initWithContentsOfFile:self.path];
    [VCRURLSession startReplayingWithCassette:cassette mode:VCRURLSessionReplayModeStrict];

    // Make some HTTP request
    [[self.session dataTaskWithURL:[NSURL URLWithString:@"https://www.github.com"]
                 completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                     NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
                     NSLog(@"%zd - %@", httpResponse.statusCode, httpResponse.URL);
                 }] resume];
}

Features

Replaying consumes responses

Let's assume during recording there are several requests made to the same resource (GET /users). When replaying them, it will consume them in the same order they were recorded.

GET /users
200 OK
[]

POST /users?name=John
201 Created
{"id": 1, "name": "John"}

GET /users
200 OK
[{"id": 1, "name": "John"}]

DELETE /users/1
204 No Content

GET /users
200 OK
[]

Store in gzip format

VCRURLSessionCassette *cassette = [[VCRURLSessionCassette alloc] init];
[cassette writeCompressedToFile:@"/tmp/cassette.json.gz"];

Return static responses

[VCRURLSession setStaticResponseHandler:^VCRURLSessionResponse *_Nullable(NSURLRequest *_Nonnull request) {
  NSString *contentType = request.allHTTPHeaderFields[@"Content-Type"];
  if ([contentType hasPrefix:@"image/"]) {
      NSData *imageData = UIImagePNGRepresentation([UIImage imageNamed:@"test_image"]);
      return [VCRURLSessionResponse responseWithURL:request.URL statusCode:200 headerFields:nil data:imageData error:nil];
  }
  return nil;
}];

Recording filter

VCRURLSessionCassette *cassette = [[VCRURLSessionCassette alloc] init];
cassette.recordFilter = ^BOOL(NSURLRequest *request) {
  NSString *contentType = request.allHTTPHeaderFields[@"Content-Type"];
  // Do not record images
  return [contentType hasPrefix:@"image/"];
};

Replaying speed

During recording phase the response time of each request is saved. Later the responses are returned in the same time. This can be changed by setting the replaySpeed property on the cassette.

VCRURLSessionCassette *cassette = [[VCRURLSessionCassette alloc] initWithContentsOfFile:self.path];
// If a request took 500ms, now it will only take 50ms
cassette.replaySpeed = 10.0f;
[VCRURLSession startReplayingWithCassette:cassette mode:VCRURLSessionReplayModeStrict];

Logging

This will enable logging recorded and replayed requests/responses. This only works for DEBUG builds.

[VCRURLSession setLogLevel:VCRURLSessionLogLevelInfo];

License (MIT)

Copyright (C) 2016 Johannes Plunien

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

vcrurlsession's People

Contributors

igor-makarov avatar plu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

vcrurlsession's Issues

One unit test fails on 64bits simulator

This spec:

it("stores userInfo") {
  expect(result["userInfo"] as? String).to(equal(encodedUserInfo))
}

when the tests are ran on the iPhone6s+ and iPad Pro. Both are 64bits, so I believe that this is can be the problem.

Any prize for the 1st issue? :)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.