Coder Social home page Coder Social logo

db-in / localserver Goto Github PK

View Code? Open in Web Editor NEW
7.0 4.0 4.0 2.1 MB

Simulate your Server APIs locally without Internet connectivity required

Home Page: https://db-in.github.io/LocalServer/

License: MIT License

Swift 40.94% Ruby 1.02% Objective-C 0.19% HTML 57.29% Shell 0.56%
stub-server uitest-server localserver swift urlsession alamofire mock stub network request

localserver's Introduction

LocalServer

Build Status codecov codebeat badge Version Platform CocoaPods Compatible Carthage compatible

Description

LocalServer is a framework that provides various options to create a Swift Stub Local Server right into the code, that can independently run on simulators and devices, supporting Xcode Parallel Testing. It's made in Swift to create Stub Servers, UITest Servers and providing an easy way to Mock capabilities to create Testing doubles (fakes, stubs, spies and mocks). It supports all Apple platform iOS, MacOS, WatchOS and TVOS.

It's also fully compatible with most the Networking libraries like Alamofire, Moya, AFNetworking or the native URLSession and NSURLConnection. Check the Programming Guide section for examples.

Features

  • Create Stub servers without changing or injecting any of your existing URLSession code
  • Create Stub versions for WKWebView
  • Supports Xcode Parallel Testing in simulators and devices
  • Stub Server for Unit Testing
  • UITest Stub Server for UI Testing
Running App UITest with Local Server
Random Users are generated Only the mocked users are generated
Sample App Sample App

Installation

You can use LocalServer straight into your Unit Testing target, without any extra code to your main target. Once the Unit Test runs within the main target.

Only for UI Testing targets, it's required some extra code in the main target.

Using CocoaPods

Add to your Podfile file

pod 'LocalServer'

Using Carthage

Add to your Cartfile or Cartfile.private file

github "db-in/LocalServer"

Add to your Package.swift file

let package = Package(
    name: "myproject",
    dependencies: [
        .package(url: "https://github.com/db-in/LocalServer"),
    ],
    targets: [
        .target(
            name: "myproject",
            dependencies: ["LocalServer"]),
    ]
)

Programming Guide

The features provided are:

  • Third party Networking Libraries
  • Stub Server
  • UITest Server

Third party Networking Libraries (Alamofire, Moya, and others)

Mocking your Unit Test Target without modifying a single line of code in yourmain target! You don't need to polute your production code with testing libraries or create any architecture specifically for allowing testability.

Keep your production networking code the way you prefer and just to your Unit Test Target you add:

import LocalServer

...

StubResponse(json: ["param" : "value"])
    .withStatusCode(200)
    .send(to: "apple")

This code above is enough to mock any calls matching anything containing "apple" in the URL and returning 200 HTTP status code with the JSON mock defined above.

Stub Server

The Stub Server is the base for the Local Server. It can intercept any network call made with the URLSession.

Stub Server

These are some of the handful functions for creating StubResponse:

StubResponse(string: "UTF8 string to become body")
StubResponse(json: ["param" : "value", "number": 1])
StubResponse(filename: "file", ofType: "html")
StubResponse(filename: "file", ofType: "json", bundle: myBundle)
StubResponse(data: myBodyData)

For a more granular and specific approach, defining a different response for each HTTP:

import LocalServer

...

func startMyLocalServer() {
    let server = StubServer()
		
	server.route([.GET], url: "https://apple.com") { (request, parameters) -> StubResponse in
		return StubResponse().withStatusCode(204)
	}
	
	server.route([.POST], url: "https://apple.com") { _,_ in
		return StubResponse().withStatusCode(206)
	}
		
	StubServer.instance = server
}

You can also test Network errors:

StubResponse()
    .withError(MyMockNetworkError.noInternet)
    .send(to: "https://apple.com")

IMPORTANT: When defining the mock URL for the same HTTP method, remember that the URL uses regex to evaluate, which means regexes may override each other mistakenly and cause wrong behaviors. Also the send(to:) is a convenient method and thus uses a shared server under the hood. It's reset everytime you set the StubServer.instance to nil.

Once the StubServer.instance is defined as non-nil, it will spin the Local Server. To stop the Local Server just set it back to nil, which is the default value.

UITest Server

As per Apple design, the UITest target runs on a separated application, which means it can't have access to the code in the main application or perform any programaticaly action. The UITest Server used the ProcessInfo bridge to send data from the UITest target to the main application on every launch.

As per Testing best practices, every UITest case should restart the main Application.

UITest Server

Project Structure

// UITest Target
 |-- LocalServer
 |-- JsonFile1.json
 |-- JsonFile2.json
 |-- JsonFile2.json
 
// Main Target
 |-- LocalServer

Required Code

// UITest Target
UITestResponse()
    .withStatusCode(201)
    .send(to: "google.com")

// Main Target
UITestServer.start() 

FAQ

Can I ship LocalServer to production (App Store)?

  • Yes, absolutely. The main goal is to provide Mock and Stub capabilities, but nothing stops you to use it in production if required.

If I'm only using it for Debug purpose, shall I use #if DEBUG?

  • As a dynamic Swift framework, LocalServer will only be loaded in runtime at the moment it's first called. So if your production code never makes use of any LocalServer API, it will not even be loaded. #if DEBUG can be used, but as per UITest Standards, you can also consider the usage of something like XCUIApplication().launchArguments + if ProcessInfo().arguments.contains("-UITests") { ... }
  • UI Testing Quick Guide/
  • Getting Started With Xcode UI Testing In Swift

Can I simulate a slow network response?

  • Yes, you can use the delay property in any response object to simulate that.

localserver's People

Contributors

dineybomfim avatar markus-mohemian avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

localserver's Issues

Cannot add SPM version

Hi, tried to add the SPM version of LocalServer. Unfortunately, that does not work in Xcode 14.1.

Xcode responds with a missing swift tools version in your Package.swift.

Screenshot 2022-11-04 at 10 43 11

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.