• Stars
    star
    1,096
  • Rank 42,298 (Top 0.9 %)
  • Language
    Swift
  • License
    MIT License
  • Created over 7 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Mock Alamofire and URLSession requests without touching your code implementation

Mocker is a library written in Swift which makes it possible to mock data requests using a custom URLProtocol.

Features

Run all your data request unit tests offline ๐ŸŽ‰

  • Create mocked data requests based on an URL
  • Create mocked data requests based on a file extension
  • Works with URLSession using a custom protocol class
  • Supports popular frameworks like Alamofire

Usage

Unit tests are written for the Mocker which can help you to see how it works.

Activating the Mocker

The mocker will automatically be activated for the default URL loading system like URLSession.shared after you've registered your first Mock.

Custom URLSessions

To make it work with your custom URLSession, the MockingURLProtocol needs to be registered:

let configuration = URLSessionConfiguration.default
configuration.protocolClasses = [MockingURLProtocol.self]
let urlSession = URLSession(configuration: configuration)
Alamofire

Quite similar like registering on a custom URLSession.

let configuration = URLSessionConfiguration.af.default
configuration.protocolClasses = [MockingURLProtocol.self]
let sessionManager = Alamofire.Session(configuration: configuration)

Register Mocks

Create your mocked data

It's recommended to create a class with all your mocked data accessible. An example of this can be found in the unit tests of this project:

public final class MockedData {
    public static let botAvatarImageResponseHead: Data = try! Data(contentsOf: Bundle(for: MockedData.self).url(forResource: "Resources/Responses/bot-avatar-image-head", withExtension: "data")!)
    public static let botAvatarImageFileUrl: URL = Bundle(for: MockedData.self).url(forResource: "wetransfer_bot_avater", withExtension: "png")!
    public static let exampleJSON: URL = Bundle(for: MockedData.self).url(forResource: "Resources/JSON Files/example", withExtension: "json")!
}
JSON Requests
let originalURL = URL(string: "https://www.wetransfer.com/example.json")!
    
let mock = Mock(url: originalURL, contentType: .json, statusCode: 200, data: [
    .get : try! Data(contentsOf: MockedData.exampleJSON) // Data containing the JSON response
])
mock.register()

URLSession.shared.dataTask(with: originalURL) { (data, response, error) in
    guard let data = data, let jsonDictionary = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String: Any] else {
        return
    }
    
    // jsonDictionary contains your JSON sample file data
    // ..
    
}.resume()
Empty Responses
let originalURL = URL(string: "https://www.wetransfer.com/api/foobar")!
var request = URLRequest(url: originalURL)
request.httpMethod = "PUT"
    
let mock = Mock(request: request, statusCode: 204)
mock.register()

URLSession.shared.dataTask(with: originalURL) { (data, response, error) in
    // ....
}.resume()
Ignoring the query

Some URLs like authentication URLs contain timestamps or UUIDs in the query. To mock these you can ignore the Query for a certain URL:

/// Would transform to "https://www.example.com/api/authentication" for example.
let originalURL = URL(string: "https://www.example.com/api/authentication?oauth_timestamp=151817037")!
    
let mock = Mock(url: originalURL, ignoreQuery: true, contentType: .json, statusCode: 200, data: [
    .get : try! Data(contentsOf: MockedData.exampleJSON) // Data containing the JSON response
])
mock.register()

URLSession.shared.dataTask(with: originalURL) { (data, response, error) in
    guard let data = data, let jsonDictionary = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String: Any] else {
        return
    }
    
    // jsonDictionary contains your JSON sample file data
    // ..
    
}.resume()
File extensions
let imageURL = URL(string: "https://www.wetransfer.com/sample-image.png")!

Mock(fileExtensions: "png", contentType: .imagePNG, statusCode: 200, data: [
    .get: try! Data(contentsOf: MockedData.botAvatarImageFileUrl)
]).register()

URLSession.shared.dataTask(with: imageURL) { (data, response, error) in
    let botAvatarImage: UIImage = UIImage(data: data!)! // This is the image from your resources.
}.resume()
Custom HEAD and GET response
let exampleURL = URL(string: "https://www.wetransfer.com/api/endpoint")!

Mock(url: exampleURL, contentType: .json, statusCode: 200, data: [
    .head: try! Data(contentsOf: MockedData.headResponse),
    .get: try! Data(contentsOf: MockedData.exampleJSON)
]).register()

URLSession.shared.dataTask(with: exampleURL) { (data, response, error) in
	// data is your mocked data
}.resume()
Custom DataType

In addition to the already build in static DataType implementations it is possible to create custom ones that will be used as the value to the Content-Type header key.

let xmlURL = URL(string: "https://www.wetransfer.com/sample-xml.xml")!

Mock(fileExtensions: "png", contentType: .init(name: "xml", headerValue: "text/xml"), statusCode: 200, data: [
    .get: try! Data(contentsOf: MockedData.sampleXML)
]).register()

URLSession.shared.dataTask(with: xmlURL) { (data, response, error) in
    let sampleXML: Data = data // This is the xml from your resources.
}.resume(
Delayed responses

Sometimes you want to test if the cancellation of requests is working. In that case, the mocked request should not finish immediately and you need a delay. This can be added easily:

let exampleURL = URL(string: "https://www.wetransfer.com/api/endpoint")!

var mock = Mock(url: exampleURL, contentType: .json, statusCode: 200, data: [
    .head: try! Data(contentsOf: MockedData.headResponse),
    .get: try! Data(contentsOf: MockedData.exampleJSON)
])
mock.delay = DispatchTimeInterval.seconds(5)
mock.register()
Redirect responses

Sometimes you want to mock short URLs or other redirect URLs. This is possible by saving the response and mocking the redirect location, which can be found inside the response:

Date: Tue, 10 Oct 2017 07:28:33 GMT
Location: https://wetransfer.com/redirect

By creating a mock for the short URL and the redirect URL, you can mock redirect and test this behavior:

let urlWhichRedirects: URL = URL(string: "https://we.tl/redirect")!
Mock(url: urlWhichRedirects, contentType: .html, statusCode: 200, data: [.get: try! Data(contentsOf: MockedData.redirectGET)]).register()
Mock(url: URL(string: "https://wetransfer.com/redirect")!, contentType: .json, statusCode: 200, data: [.get: try! Data(contentsOf: MockedData.exampleJSON)]).register()
Ignoring URLs

As the Mocker catches all URLs by default when registered, you might end up with a fatalError thrown in cases you don't need a mocked request. In that case, you can ignore the URL:

let ignoredURL = URL(string: "www.wetransfer.com")!
Mocker.ignore(ignoredURL)

However, if you need the Mocker to catch only mocked URLs and ignore every other URL, you can set the mode attribute to .optin.

Mocker.mode = .optin

If you want to set the original mode back, you have just to set it to .optout.

Mocker.mode = .optout
Mock errors

You can request a Mock to return an error, allowing testing of error handling.

Mock(url: originalURL, contentType: .json, statusCode: 500, data: [.get: Data()],
     requestError: TestExampleError.example).register()

URLSession.shared.dataTask(with: originalURL) { (data, urlresponse, err) in
    XCTAssertNil(data)
    XCTAssertNil(urlresponse)
    XCTAssertNotNil(err)
    if let err = err {
        // there's not a particularly elegant way to verify an instance
        // of an error, but this is a convenient workaround for testing
        // purposes
        XCTAssertEqual("example", String(describing: err))
    }

    expectation.fulfill()
}.resume()
Mock callbacks

You can register on Mock callbacks to make testing easier.

var mock = Mock(url: request.url!, contentType: .json, statusCode: 200, data: [.post: Data()])
mock.onRequestHandler = OnRequestHandler(httpBodyType: [[String:String]].self, callback: { request, postBodyArguments in
    XCTAssertEqual(request.url, mock.request.url)
    XCTAssertEqual(expectedParameters, postBodyArguments)
    onRequestExpectation.fulfill()
})
mock.completion = {
    endpointIsCalledExpectation.fulfill()
}
mock.register()
Mock expectations

Instead of setting the completion and onRequest you can also make use of expectations:

var mock = Mock(url: url, contentType: .json, statusCode: 200, data: [.get: Data()])
let requestExpectation = expectationForRequestingMock(&mock)
let completionExpectation = expectationForCompletingMock(&mock)
mock.register()

URLSession.shared.dataTask(with: URLRequest(url: url)).resume()

wait(for: [requestExpectation, completionExpectation], timeout: 2.0)

Unregister Mocks

Clear all registered mocks

You can clear all registered mocks:

Mocker.removeAll()

Communication

  • If you found a bug, open an issue.
  • If you have a feature request, open an issue.
  • If you want to contribute, submit a pull request.

Installation

Carthage

Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.

You can install Carthage with Homebrew using the following command:

$ brew update
$ brew install carthage

To integrate Mocker into your Xcode project using Carthage, specify it in your Cartfile:

github "WeTransfer/Mocker" ~> 3.0.0

Run carthage update to build the framework and drag the built Mocker.framework into your Xcode project.

Swift Package Manager

The Swift Package Manager is a tool for managing the distribution of Swift code. Itโ€™s integrated with the Swift build system to automate the process of downloading, compiling, and linking dependencies.

Manifest File

Add Mocker as a package to your Package.swift file and then specify it as a dependency of the Target in which you wish to use it.

import PackageDescription

let package = Package(
    name: "MyProject",
    platforms: [
       .macOS(.v10_15)
    ],
    dependencies: [
        .package(url: "https://github.com/WeTransfer/Mocker.git", .upToNextMajor(from: "3.0.0"))
    ],
    targets: [
        .target(
            name: "MyProject",
            dependencies: ["Mocker"]),
        .testTarget(
            name: "MyProjectTests",
            dependencies: ["MyProject"]),
    ]
)

Xcode

To add Mocker as a dependency to your Xcode project, select File > Swift Packages > Add Package Dependency and enter the repository URL.

Resolving Build Errors

If you get the following error: cannot find auto-link library XCTest and XCTestSwiftSupport, set the following property under Build Options from No to Yes.
ENABLE_TESTING_SEARCH_PATHS to YES

Manually

If you prefer not to use any of the aforementioned dependency managers, you can integrate Mocker into your project manually.

Embedded Framework

  • Open up Terminal, cd into your top-level project directory, and run the following command "if" your project is not initialized as a git repository:

    $ git init
  • Add Mocker as a git submodule by running the following command:

    $ git submodule add https://github.com/WeTransfer/Mocker.git
  • Open the new Mocker folder, and drag the Mocker.xcodeproj into the Project Navigator of your application's Xcode project.

    It should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter.

  • Select the Mocker.xcodeproj in the Project Navigator and verify the deployment target matches that of your application target.

  • Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the "Targets" heading in the sidebar.

  • In the tab bar at the top of that window, open the "General" panel.

  • Click on the + button under the "Embedded Binaries" section.

  • Select Mocker.framework.

  • And that's it!

    The Mocker.framework is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device.


Release Notes

See CHANGELOG.md for a list of changes.

License

Mocker is available under the MIT license. See the LICENSE file for more info.

More Repositories

1

WeScan

Document Scanning Made Easy for iOS
Swift
2,825
star
2

Diagnostics

Allow users to easily share Diagnostics with your support team to improve the flow of fixing bugs.
Swift
939
star
3

UINotifications

Present custom in-app notifications easily in Swift
Swift
394
star
4

zip_tricks

[DEPRECATED] Compact ZIP file writing/reading for Ruby, for streaming applications
Ruby
349
star
5

GitBuddy

Your buddy in managing and maintaining GitHub repositories, and releases. Automatically generate changelogs from issues and merged pull-requests.
Swift
240
star
6

WeTransfer-iOS-CI

Containing all the shared CI logic for WeTransfer repositories
Swift
223
star
7

prorate

Redis-based rate limiter (with a leaky bucket implementation in Lua)
Ruby
86
star
8

wt_activerecord_index_spy

A gem to spy queries running with Active Record and report missing indexes
Ruby
77
star
9

format_parser

file metadata parsing, done cheap
Ruby
62
star
10

wt-js-sdk

A JavaScript SDK for WeTransfer's Public API
JavaScript
47
star
11

WeTransfer-Swift-SDK

A Swift SDK for WeTransferโ€™s public API
Swift
39
star
12

Sketch-Plugin

Plugin to share artboards directly via WeTransfer. Share the link easily with your colleagues and friends.
Objective-C
39
star
13

sqewer

SQS queue processor engine
Ruby
30
star
14

wt_s3_signer

Fast S3 key urls signing
Ruby
26
star
15

cr_zip_tricks

Alternate ZIP writer for Crystal, ported from zip_tricks for Ruby
Crystal
25
star
16

image_vise

Image processing proxy that works via signed URLs
Ruby
20
star
17

ghost_adapter

Run ActiveRecord migrations through gh-ost
Ruby
19
star
18

concorde.js

A sexy pinnacle of engineering thatโ€™s nonetheless incredibly inefficient and expensive and goes out of business because it canโ€™t find enough use. It also provides some tools to deal with the browser.
JavaScript
17
star
19

fast_send

Send very large HTTP responses via file buffers
Ruby
16
star
20

apiculture

Honey-tasting REST API toolkit for Sinatra
Ruby
12
star
21

WeScanAndroid

The Android Implementation of WeScan https://github.com/wetransfer/wescan
11
star
22

wetransfer_ruby_sdk

A Ruby SDK for WeTransfer's Public API
Ruby
11
star
23

richurls

Service which enriches URLs fast and cheap
Ruby
10
star
24

measurometer

Minimum viable API for โฑ๐Ÿ“ˆ in ๐Ÿ’Ž libraries
Ruby
10
star
25

interval_response

Serve partial (Range) HTTP responses from ๐Ÿ’Ž applications
Ruby
9
star
26

activerecord_autoreplica

Simple read replica proxy for ActiveRecord
Ruby
7
star
27

wt-api-docs

Official documentation for WeTransfer's Public API
Ruby
7
star
28

product-engineering-career-framework

This repo holds discussion and the permalink to WeTransfer's internal Product Engineering Career Framework.
7
star
29

hash_tools

Do useful things to Ruby Hashes, without monkey-patches
Ruby
5
star
30

rational_choice

A fuzzy logic gate
Ruby
4
star
31

Xperiments

Simple A/B testing tool. Includes CMS and an experimentation engine.
JavaScript
4
star
32

amplitude-client-node

Node.js client for the Amplitude API
TypeScript
4
star
33

Danger

Contains our global Danger file.
Ruby
3
star
34

very_tiny_state_machine

For when you need it even smaller than you think you do
Ruby
3
star
35

eslint-config-wetransfer

ESLint shareable config used for WeTransfer JS projects.
JavaScript
3
star
36

wetransfer_style

At WeTransfer we code in style. This is our coding style for Ruby development.
Ruby
3
star
37

runaway

Controls child process execution, with hard limits on maximum runtime and heartbeat timings
Ruby
2
star
38

megabytes

Tiny byte size formatter
Ruby
1
star
39

Actions-Experiment

A Repo to experiment with github actions to build previews for the frontend.
JavaScript
1
star
40

strict_request_uri

Truncate and cleanup URLs with junk in Rack
Ruby
1
star
41

tdd-workshop

Repo to host the code for the TDD workshop
Kotlin
1
star
42

departure

WeTransfer's fork of departurerb/departure, to accelerate Rails 5.2 support. See the link for the original repo:
Ruby
1
star
43

sanitize_user_agent_header

Ensure User-Agent gets correctly UTF-8 encoded
Ruby
1
star
44

ks

Keyword-initialized Structs
Ruby
1
star
45

format_parser_pdf

file metadata parsing, for PDF
Ruby
1
star
46

EmbedExamples

Examples on how to use WeTransfer Embed
Ruby
1
star
47

simple_compress

GZIP compression to and from a String
Ruby
1
star