• Stars
    star
    800
  • Rank 55,502 (Top 2 %)
  • Language
    Swift
  • License
    Apache License 2.0
  • Created over 5 years ago
  • Updated about 1 month ago

Reviews

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

Repository Details

Efficient Mock Generator for Swift

CII Best Practices Build Status License FOSSA Status

Welcome to Mockolo

Mockolo is an efficient mock generator for Swift. Swift doesn't provide mocking support, and Mockolo provides a fast and easy way to autogenerate mock objects that can be tested in your code. One of the main objectives of Mockolo is fast performance. Unlike other frameworks, Mockolo provides highly performant and scalable generation of mocks via a lightweight commandline tool, so it can run as part of a linter or a build if one chooses to do so. Try Mockolo and enhance your project's test coverage in an effective, performant way.

Motivation

One of the main objectives of this project is high performance. There aren't many 3rd party tools that perform fast on a large codebase containing, for example, over 2M LoC or over 10K protocols. They take several hours and even with caching enabled take several minutes. Mockolo was built to make highly performant generation of mocks possible (in the magnitude of seconds) on such large codebase. It uses a minimal set of frameworks necessary (mentioned in the Used libraries section) to keep the code lean and efficient.

Another objective is to enable flexibility in using or overriding types if needed. This allows use of some of the features that require deeper analysis such as protocols with associated types to be simpler, more straightforward, and less fragile.

Disclaimer

This project may contain unstable APIs which may not be ready for general use. Support and/or new releases may be limited.

System Requirements

  • Swift 5.7 or later
  • Xcode 14.2 or later
  • macOS 12.0 or later and Linux
  • Support is included for the Swift Package Manager

Build / Install

Option 1: By Mint

$ mint install uber/mockolo
$ mint run uber/mockolo mockolo -h // see commandline input options below

Option 2: Homebrew

$ brew install mockolo

Option 3: Use as Build Tools Plugin with Swift Package Manager

Add binaryTarget and plugin definition to your Package.swift. Binary url and checksum can be found in the releases page.

targets: [
    ...
    .plugin(
        name: "RunMockolo",
        capability: .buildTool(),
        dependencies: [.target(name: "mockolo")]
    ),
    .binaryTarget(
        name: "mockolo",
        url: "...",
        checksum: "..."
    ),

Implement the plugin and specify necessary directories in the arguments.

  • Plugins/RunMockolo/RunMockoloPlugin.swift
import PackagePlugin

@main struct RunMockoloPlugin: BuildToolPlugin {
    func createBuildCommands(context: PluginContext, target: Target) async throws -> [Command] {
        let generatedSourcePath = context.pluginWorkDirectory.appending("GeneratedMocks.swift")
        let packageRoot = context.package.directory

        return [
            .prebuildCommand(
                displayName: "Run mockolo",
                executable: try context.tool(named: "mockolo").path,
                arguments: [
                    "-s", packageRoot.appending("Sources", "MyModule").string,
                    "-d", generatedSourcePath,
                ],
                outputFilesDirectory: context.pluginWorkDirectory
            ),
        ]
    }
}

Finally, add the plugin to the target requiring mockolo.

.target(
    name: "MyTarget",
    dependencies: [
        ...
    ],
    plugins: [
        .plugin(name: "RunMockolo"),
    ]
),

Option 4: Use the binary

Go to the Release tab and download/install the binary directly.

Option 5: Clone and build/run

$ git clone https://github.com/uber/mockolo.git
$ cd mockolo
$ swift build -c release
$ .build/release/mockolo -h  // see commandline input options below

To call mockolo from any location, copy the executable into a directory that is part of your PATH environment variable.

Run

Mockolo is a commandline executable. To run it, pass in a list of the source file directories or file paths of a build target, and the destination filepath for the mock output. To see other arguments to the commandline, run mockolo --help.

./mockolo -s myDir -d ./OutputMocks.swift -x Images Strings

This parses all the source files in myDir directory, excluding any files ending with Images or Strings in the file name (e.g. MyImages.swift), and generates mocks to a file at OutputMocks.swift in the current directory.

Use --help to see the complete argument options.

./mockolo -h  // or --help

OVERVIEW: Mockolo: Swift mock generator.

USAGE: mockolo [<options>] --destination <destination>

OPTIONS:
  --allow-set-call-count  If set, generated *CallCount vars will be allowed to set manually.
  --annotation <annotation>
                          A custom annotation string used to indicate if a type should be mocked (default = @mockable). (default: @mockable)
  -j, --concurrency-limit <n>
                          Maximum number of threads to execute concurrently (default = number of cores on the running machine).
  --custom-imports <custom-imports>
                          If set, custom module imports (separated by a space) will be added to the final import statement list.
  --enable-args-history   Whether to enable args history for all functions (default = false). To enable history per function, use the 'history' keyword in the annotation argument.
  --disable-combine-default-values
                          Whether to disable generating Combine streams in mocks (default = false). Set this to true to control how your streams are created in your mocks.
  --exclude-imports <exclude-imports>
                          If set, listed modules (separated by a space) will be excluded from the import statements in the mock output.
  -x, --exclude-suffixes <exclude-suffixes>
                          List of filename suffix(es) without the file extensions to exclude from parsing (separated by a space).
  --header <header>       A custom header documentation to be added to the beginning of a generated mock file.
  -l, --logging-level <n> The logging level to use. Default is set to 0 (info only). Set 1 for verbose, 2 for warning, and 3 for error. (default: 0)
  --macro <macro>         If set, #if [macro] / #endif will be added to the generated mock file content to guard compilation.
  --mock-all              If set, it will mock all types (protocols and classes) with a mock annotation (default is set to false and only mocks protocols with a mock annotation).
  --mock-filelist <mock-filelist>
                          Path to a file containing a list of dependent files (separated by a new line) of modules this target depends on.
  --mock-final            If set, generated mock classes will have the 'final' attributes (default is set to false).
  -mocks, --mockfiles <mocks>
                          List of mock files (separated by a space) from modules this target depends on. If the --mock-filelist value exists, this will be ignored.
  -d, --destination <destination>
                          Output file path containing the generated Swift mock classes. If no value is given, the program will exit.
  -s, --sourcedirs <sourcedirs>
                          Paths to the directories containing source files to generate mocks for (separated by a space). If the --filelist or --sourcefiles values exist, they will be ignored.
  -f, --filelist <filelist>
                          Path to a file containing a list of source file paths (delimited by a new line). If the --sourcedirs value exists, this will be ignored.
  -srcs, --sourcefiles <srcs>
                          List of source files (separated by a space) to generate mocks for. If the --sourcedirs or --filelist value exists, this will be ignored.
  -i, --testable-imports <testable-imports>
                          If set, @testable import statements will be added for each module name in this list (separated by a space).
  --use-mock-observable   If set, a property wrapper will be used to mock RxSwift Observable variables (default is set to false).
  --use-template-func     If set, a common template function will be called from all functions in mock classes (default is set to false).
  -h, --help              Show help information.

Distribution

The install-script.sh will build and package up the mockolo binary and other necessary resources in the same bundle.

$ ./install-script.sh -h  // see input options
$ ./install-script.sh -s [source dir] -t mockolo -d [destination dir] -o [output filename].tar.gz

This will create a tarball for distribution, which contains the mockolo executable.

How to use

For example, Foo.swift contains:

/// @mockable
public protocol Foo {
    var num: Int { get set }
    func bar(arg: Float) -> String
}

Running ./mockolo -srcs Foo.swift -d ./OutputMocks.swift will output:

public class FooMock: Foo {
    init() {}
    init(num: Int = 0) {
        self.num = num
    }

    var numSetCallCount = 0
    var underlyingNum: Int = 0
    var num: Int {
        get {
            return underlyingNum
        }
        set {
            underlyingNum = newValue
            numSetCallCount += 1
        }
    }

    var barCallCount = 0
    var barHandler: ((Float) -> (String))?
    func bar(arg: Float) -> String {
        barCallCount += 1
        if let barHandler = barHandler {
            return barHandler(arg)
        }
        return ""
    }
}

The above mock can now be used in a test as follows:

func testMock() {
    let mock = FooMock(num: 5)
    XCTAssertEqual(mock.numSetCallCount, 1)
    mock.barHandler = { arg in
        return String(arg)
    }
    XCTAssertEqual(mock.barCallCount, 1)
}

Arguments

A list of override arguments can be passed in (delimited by a semicolon) to the annotation to set var types, typealiases, module names, etc.

Module

/// @mockable(module: prefix = Bar)
public protocol Foo {
    ...
}

This will generate:

public class FooMock: Bar.Foo {
    ...
}

Typealias

/// @mockable(typealias: T = AnyObject; U = StringProtocol)
public protocol Foo {
    associatedtype T
    associatedtype U: Collection where U.Element == T
    associatedtype W
    ...
}

This will generate the following mock output:

public class FooMock: Foo {
    typealias T = AnyObject // overridden
    typealias U = StringProtocol // overridden
    typealias W = Any // default placeholder type for typealias
    ...
}

RxSwift

For a var type such as an RxSwift observable:

/// @mockable(rx: intStream = ReplaySubject; doubleStream = BehaviorSubject)
public protocol Foo {
    var intStream: Observable<Int> { get }
    var doubleStream: Observable<Double> { get }
}

This will generate:

public class FooMock: Foo {
    var intStreamSubject = ReplaySubject<Int>.create(bufferSize: 1)
    var intStream: Observable<Int> { /* use intStreamSubject */ }
    var doubleStreamSubject = BehaviorSubject<Int>(value: 0)
    var doubleStream: Observable<Int> { /* use doubleStreamSubject */ }
}

Function Argument History

To capture function arguments history:

/// @mockable(history: fooFunc = true)
public protocol Foo {
    func fooFunc(val: Int)
    func barFunc(_ val: (a: String, Float))
    func bazFunc(val1: Int, val2: String)
}

This will generate:

public class FooMock: Foo {
    var fooFuncCallCount = 0
    var fooFuncArgValues = [Int]() // arguments captor
    var fooFuncHandler: ((Int) -> ())?
    func fooFunc(val: Int) {
        fooFuncCallCount += 1
        fooFuncArgValues.append(val)   // capture arguments

        if fooFuncHandler = fooFuncHandler {
            fooFuncHandler(val)
        }
    }

    ...
    var barFuncArgValues = [(a: String, Float)]() // tuple is also supported.
    ...

    ...
    var bazFuncArgValues = [(Int, String)]()
    ...
}

and also, enable the arguments captor for all functions if you passed --enable-args-history arg to mockolo command.

NOTE: The arguments captor only supports singular types (e.g. variable, tuple). The closure variable is not supported.

Combine's AnyPublisher

To generate mocks for Combine's AnyPublisher:

/// @mockable(combine: fooPublisher = PassthroughSubject; barPublisher = CurrentValueSubject)
public protocol Foo {
    var fooPublisher: AnyPublisher<String, Never> { get }
    var barPublisher: AnyPublisher<Int, CustomError> { get }
}

This will generate:

public class FooMock: Foo {
    public init() { }

    public var fooPublisher: AnyPublisher<String, Never> { return self.fooPublisherSubject.eraseToAnyPublisher() }
    public private(set) var fooPublisherSubject = PassthroughSubject<String, Never>()

    public var barPublisher: AnyPublisher<Int, CustomError> { return self.barPublisherSubject.eraseToAnyPublisher() }
    public private(set) var barPublisherSubject = CurrentValueSubject<Int, CustomError>(0)
}

You can also connect an AnyPublisher to a property within the protocol.

For example:

/// @mockable(combine: fooPublisher = @Published foo)
public protocol Foo {
    var foo: String { get }
    var fooPublisher: AnyPublisher<String, Never> { get }
}

This will generate:

public class FooMock: Foo {
    public init() { }
    public init(foo: String = "") {
        self.foo = foo
    }

    public private(set) var fooSetCallCount = 0
    @Published public var foo: String = "" { didSet { fooSetCallCount += 1 } }

    public var fooPublisher: AnyPublisher<String, Never> { return self.$foo.setFailureType(to: Never.self).eraseToAnyPublisher() }
}

Overrides

To override the generated mock name:

/// @mockable(override: name = FooMock)
public protocol FooProtocol { ... }

This will generate:

public class FooMock: FooProtocol { ... }

Used libraries

SwiftSyntax |

How to contribute to Mockolo

See CONTRIBUTING for more info.

Report any issues

If you run into any problems, please file a git issue. Please include:

  • The OS version (e.g. macOS 10.14.6)
  • The Swift version installed on your machine (from swift --version)
  • The Xcode version
  • The specific release version of this source code (you can use git tag to get a list of all the release versions or git log to get a specific commit sha)
  • Any local changes on your machine

License

Mockolo is licensed under Apache License 2.0. See LICENSE for more information.

Copyright (C) 2017 Uber Technologies

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

More Repositories

1

react-vis

Data Visualization Components
JavaScript
8,691
star
2

baseweb

A React Component library implementing the Base design language
TypeScript
8,647
star
3

cadence

Cadence is a distributed, scalable, durable, and highly available orchestration engine to execute asynchronous long-running business logic in a scalable and resilient way.
Go
7,956
star
4

RIBs

Uber's cross-platform mobile architecture framework.
Kotlin
7,706
star
5

kraken

P2P Docker registry capable of distributing TBs of data in seconds
Go
5,941
star
6

prototool

Your Swiss Army Knife for Protocol Buffers
Go
5,047
star
7

causalml

Uplift modeling and causal inference with machine learning algorithms
Python
4,851
star
8

h3

Hexagonal hierarchical geospatial indexing system
C
4,672
star
9

NullAway

A tool to help eliminate NullPointerExceptions (NPEs) in your Java code with low build-time overhead
Java
3,585
star
10

AutoDispose

Automatic binding+disposal of RxJava streams.
Java
3,363
star
11

aresdb

A GPU-powered real-time analytics storage and query engine.
Go
2,992
star
12

react-digraph

A library for creating directed graph editors
JavaScript
2,597
star
13

piranha

A tool for refactoring code related to feature flag APIs
Java
2,241
star
14

orbit

A Python package for Bayesian forecasting with object-oriented design and probabilistic models under the hood.
Python
1,820
star
15

ios-snapshot-test-case

Snapshot view unit tests for iOS
Objective-C
1,779
star
16

needle

Compile-time safe Swift dependency injection framework
Swift
1,773
star
17

petastorm

Petastorm library enables single machine or distributed training and evaluation of deep learning models from datasets in Apache Parquet format. It supports ML frameworks such as Tensorflow, Pytorch, and PySpark and can be used from pure Python code.
Python
1,762
star
18

manifold

A model-agnostic visual debugging tool for machine learning
JavaScript
1,640
star
19

okbuck

OkBuck is a gradle plugin that lets developers utilize the Buck build system on a gradle project.
Java
1,535
star
20

UberSignature

Provides an iOS view controller allowing a user to draw their signature with their finger in a realistic style.
Objective-C
1,285
star
21

nanoscope

An extremely accurate Android method tracing tool.
HTML
1,243
star
22

tchannel

network multiplexing and framing protocol for RPC
Thrift
1,152
star
23

queryparser

Parsing and analysis of Vertica, Hive, and Presto SQL.
Haskell
1,070
star
24

fiber

Distributed Computing for AI Made Simple
Python
1,040
star
25

neuropod

A uniform interface to run deep learning models from multiple frameworks
C++
932
star
26

uReplicator

Improvement of Apache Kafka Mirrormaker
Java
905
star
27

pam-ussh

uber's ssh certificate pam module
Go
836
star
28

ringpop-go

Scalable, fault-tolerant application-layer sharding for Go applications
Go
819
star
29

h3-js

h3-js provides a JavaScript version of H3, a hexagon-based geospatial indexing system.
JavaScript
816
star
30

h3-py

Python bindings for H3, a hierarchical hexagonal geospatial indexing system
Python
779
star
31

xviz

A protocol for real-time transfer and visualization of autonomy data
JavaScript
760
star
32

streetscape.gl

Visualization framework for autonomy and robotics data encoded in XVIZ
JavaScript
702
star
33

react-view

React View is an interactive playground, documentation and code generator for your components.
TypeScript
690
star
34

nebula.gl

A suite of 3D-enabled data editing overlays, suitable for deck.gl
TypeScript
677
star
35

RxDogTag

Automatic tagging of RxJava 2+ originating subscribe points for onError() investigation.
Java
645
star
36

peloton

Unified Resource Scheduler to co-schedule mixed types of workloads such as batch, stateless and stateful jobs in a single cluster for better resource utilization.
Go
638
star
37

motif

A simple DI API for Android / Java
Kotlin
530
star
38

signals-ios

Typeful eventing
Objective-C
527
star
39

tchannel-go

Go implementation of a multiplexing and framing protocol for RPC calls
Go
482
star
40

grafana-dash-gen

grafana dash dash dash gen
JavaScript
480
star
41

marmaray

Generic Data Ingestion & Dispersal Library for Hadoop
Java
475
star
42

zanzibar

A build system & configuration system to generate versioned API gateways.
Go
453
star
43

clay

Clay is a framework for building RESTful backend services using best practices. It’s a wrapper around Flask.
Python
441
star
44

astro

Astro is a tool for managing multiple Terraform executions as a single command
Go
432
star
45

NEAL

πŸ”ŽπŸž A language-agnostic linting platform
OCaml
426
star
46

react-vis-force

d3-force graphs as React Components.
JavaScript
403
star
47

arachne

An always-on framework that performs end-to-end functional network testing for reachability, latency, and packet loss
Go
391
star
48

cadence-web

Web UI for visualizing workflows on Cadence
JavaScript
379
star
49

Python-Sample-Application

Python
375
star
50

rides-ios-sdk

Uber Rides iOS SDK (beta)
Swift
368
star
51

stylist

A stylist creates cool styles. Stylist is a Gradle plugin that codegens a base set of Android XML themes.
Kotlin
356
star
52

storagetapper

StorageTapper is a scalable realtime MySQL change data streaming, logical backup and logical replication service
Go
335
star
53

swift-concurrency

Concurrency utilities for Swift
Swift
325
star
54

RemoteShuffleService

Remote shuffle service for Apache Spark to store shuffle data on remote servers.
Java
319
star
55

cyborg

Display Android Vectordrawables on iOS.
Swift
300
star
56

rides-android-sdk

Uber Rides Android SDK (beta)
Java
290
star
57

h3-go

Go bindings for H3, a hierarchical hexagonal geospatial indexing system
Go
285
star
58

h3-java

Java bindings for H3, a hierarchical hexagonal geospatial indexing system
Java
266
star
59

hermetic_cc_toolchain

Bazel C/C++ toolchain for cross-compiling C/C++ programs
Starlark
263
star
60

h3-py-notebooks

Jupyter notebooks for h3-py, a hierarchical hexagonal geospatial indexing system
Jupyter Notebook
250
star
61

geojson2h3

Conversion utilities between H3 indexes and GeoJSON
JavaScript
220
star
62

artist

An artist creates views. Artist is a Gradle plugin that codegens a base set of Android Views.
Kotlin
211
star
63

tchannel-node

JavaScript
205
star
64

RxCentralBle

A reactive, interface-driven central role Bluetooth LE library for Android
Java
197
star
65

uberalls

Track code coverage metrics with Jenkins and Phabricator
Go
187
star
66

SwiftCodeSan

SwiftCodeSan is a tool that "sanitizes" code written in Swift.
Swift
174
star
67

rides-python-sdk

Uber Rides Python SDK (beta)
Python
170
star
68

doubles

Test doubles for Python.
Python
165
star
69

logtron

A logging MACHINE
JavaScript
158
star
70

athenadriver

A fully-featured AWS Athena database driver (+ athenareader https://github.com/uber/athenadriver/tree/master/athenareader)
Go
144
star
71

cadence-java-client

Java framework for Cadence Workflow Service
Java
140
star
72

cassette

Store and replay HTTP requests made in your Python app
Python
138
star
73

UBTokenBar

Flexible and extensible UICollectionView based TokenBar written in Swift
Swift
136
star
74

bayesmark

Benchmark framework to easily compare Bayesian optimization methods on real machine learning tasks
Python
133
star
75

tchannel-java

A Java implementation of the TChannel protocol.
Java
132
star
76

android-template

This template provides a starting point for open source Android projects at Uber.
Java
128
star
77

crumb

An annotation processor for breadcrumbing metadata across compilation boundaries.
Kotlin
122
star
78

py-find-injection

Look for SQL injection attacks in python source code
Python
119
star
79

rides-java-sdk

Uber Rides Java SDK (beta)
Java
104
star
80

startup-reason-reporter

Reports the reason why an iOS App started.
Objective-C
97
star
81

cadence-java-samples

Java
95
star
82

uber-poet

A mock swift project generator & build runner to help benchmark various module dependency graphs.
Python
95
star
83

charlatan

A Python library to efficiently manage and install database fixtures
Python
89
star
84

swift-abstract-class

Compile-time abstract class validation for Swift
Swift
84
star
85

simple-store

Simple yet performant asynchronous file storage for Android
Java
83
star
86

tchannel-python

Python implementation of the TChannel protocol.
Python
77
star
87

client-platform-engineering

A collection of cookbooks, scripts and binaries used to manage our macOS, Ubuntu and Windows endpoints
Ruby
71
star
88

eight-track

Record and playback HTTP requests
JavaScript
70
star
89

lint-checks

A set of opinionated and useful lint checks
Kotlin
70
star
90

multidimensional_urlencode

Python library to urlencode a multidimensional dict
Python
67
star
91

uncaught-exception

Handle uncaught exceptions.
JavaScript
66
star
92

swift-common

Common code used by various Uber open source projects
Swift
66
star
93

uberscriptquery

UberScriptQuery, a SQL-like DSL to make writing Spark jobs super easy
Java
59
star
94

sentry-logger

A Sentry transport for Winston
JavaScript
55
star
95

graph.gl

WebGL2-Powered Visualization Components for Graph Visualization
JavaScript
53
star
96

nanoscope-art

C++
49
star
97

assume-role-cli

CLI for AssumeRole is a tool for running programs with temporary credentials from AWS's AssumeRole API.
Go
47
star
98

airlock

A prober to probe HTTP based backends for health
JavaScript
47
star
99

mutornadomon

Easy-to-install monitor endpoint for Tornado applications
Python
46
star
100

kafka-logger

A kafka logger for winston
JavaScript
45
star