• Stars
    star
    932
  • Rank 47,026 (Top 1.0 %)
  • Language
    Elixir
  • License
    MIT License
  • Created over 8 years ago
  • Updated about 2 months ago

Reviews

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

Repository Details

Bypass provides a quick way to create a custom plug that can be put in place instead of an actual HTTP server to return prebaked responses to client requests.

Bypass

Build Status Module Version Hex Docs Total Download License Last Updated

Bypass provides a quick way to create a custom plug that can be put in place instead of an actual HTTP server to return prebaked responses to client requests. This is most useful in tests, when you want to create a mock HTTP server and test how your HTTP client handles different types of responses from the server.

Bypass supports Elixir 1.10 and OTP 21 and up. It works with Cowboy 2.

Usage

To use Bypass in a test case, open a connection and use its port to connect your client to it.

If you want to test what happens when the HTTP server goes down, use Bypass.down/1 to close the TCP socket and Bypass.up/1 to start listening on the same port again. Both functions block until the socket updates its state.

Expect Functions

You can take any of the following approaches:

  • expect/2 or expect_once/2 to install a generic function that all calls to bypass will use
  • expect/4 and/or expect_once/4 to install specific routes (method and path)
  • stub/4 to install specific routes without expectations
  • a combination of the above, where the routes will be used first, and then the generic version will be used as default

Example

In the following example TwitterClient.start_link() takes the endpoint URL as its argument allowing us to make sure it will connect to the running instance of Bypass.

defmodule TwitterClientTest do
  use ExUnit.Case, async: true

  setup do
    bypass = Bypass.open()
    {:ok, bypass: bypass}
  end

  test "client can handle an error response", %{bypass: bypass} do
    Bypass.expect_once(bypass, "POST", "/1.1/statuses/update.json", fn conn ->
      Plug.Conn.resp(conn, 429, ~s<{"errors": [{"code": 88, "message": "Rate limit exceeded"}]}>)
    end)

    {:ok, client} = TwitterClient.start_link(url: endpoint_url(bypass.port))
    assert {:error, :rate_limited} == TwitterClient.post_tweet(client, "Elixir is awesome!")
  end

  test "client can recover from server downtime", %{bypass: bypass} do
    Bypass.expect(bypass, fn conn ->
      # We don't care about `request_path` or `method` for this test.
      Plug.Conn.resp(conn, 200, "")
    end)

    {:ok, client} = TwitterClient.start_link(url: endpoint_url(bypass.port))

    assert :ok == TwitterClient.post_tweet(client, "Elixir is awesome!")

    # Blocks until the TCP socket is closed.
    Bypass.down(bypass)

    assert {:error, :noconnect} == TwitterClient.post_tweet(client, "Elixir is awesome!")

    Bypass.up(bypass)

    # When testing a real client that is using e.g. https://github.com/fishcakez/connection
    # with https://github.com/ferd/backoff to handle reconnecting, we'd have to loop for
    # a while until the client has reconnected.

    assert :ok == TwitterClient.post_tweet(client, "Elixir is awesome!")
  end

  defp endpoint_url(port), do: "http://localhost:#{port}/"
end

That's all you need to do. Bypass automatically sets up an on_exit hook to close its socket when the test finishes running.

Multiple concurrent Bypass instances are supported, all will have a different unique port. Concurrent requests are also supported on the same instance.

Note: Bypass.open/0 must not be called in a setup_all blocks due to the way Bypass verifies the expectations at the end of each test.

How to use with ESpec

While Bypass primarily targets ExUnit, the official Elixir builtin test framework, it can also be used with ESpec. The test configuration is basically the same, there are only two differences:

  1. In your Mix config file, you must declare which test framework Bypass is being used with (defaults to :ex_unit). This simply disables the automatic integration with some hooks provided by ExUnit.

    config :bypass, test_framework: :espec
  2. In your specs, you must explicitly verify the declared expectations. You can do it in the finally block.

    defmodule TwitterClientSpec do
      use ESpec, async: true
    
      before do
        bypass = Bypass.open()
        {:shared, bypass: bypass}
      end
    
      finally do
        Bypass.verify_expectations!(shared.bypass)
      end
    
      specify "the client can handle an error response" do
        Bypass.expect_once(shared.bypass, "POST", "/1.1/statuses/update.json", fn conn ->
          Plug.Conn.resp(conn, 429, ~s<{"errors": [{"code": 88, "message": "Rate limit exceeded"}]}>)
        end)
    
        {:ok, client} = TwitterClient.start_link(url: endpoint_url(shared.bypass.port))
        assert {:error, :rate_limited} == TwitterClient.post_tweet(client, "Elixir is awesome!")
      end
    
      defp endpoint_url(port), do: "http://localhost:#{port}/"
    end

Configuration options

Set :enable_debug_log to true in the application environment to make Bypass log what it's doing:

config :bypass, enable_debug_log: true

Installation

Add :bypass to your list of dependencies in mix.exs:

def deps do
  [
    {:bypass, "~> 2.1", only: :test}
  ]
end

We do not recommended adding :bypass to the list of applications in your mix.exs.

License

This software is licensed under the MIT license.

About

This project is maintained and funded by PSPDFKit.

Please ensure you signed our CLA so we can accept your contributions.

See our other open source projects, read our blog or say hello on Twitter (@PSPDFKit).

More Repositories

1

PSTModernizer

Makes it easier to support older versions of iOS by fixing things and adding missing methods
Objective-C++
215
star
2

pdfkit-invoice

Generate PDF Invoices with PDFKit
JavaScript
195
star
3

QuickDemo

Android QuickDemo
Kotlin
139
star
4

VanGogh

💥 Android view animations powered by RxJava 2
Java
95
star
5

radar.apple.com

Sample Projects for Apple Feedback from PSPDFKit
Objective-C
85
star
6

browserslist.dev

A website to display compatible browsers from browserslist string.
TypeScript
69
star
7

sidetask

:awesome = Elixir's Task ++ Basho's sidejob library
Elixir
69
star
8

pspdfkit-webassembly-benchmark

Source for the PSPDFKit WebAssembly Benchmark: http://iswebassemblyfastyet.com
JavaScript
48
star
9

PDFViewerSwiftUI

A PDF Viewer built in SwiftUI and PSPDFKit
Swift
43
star
10

reviewbot

Reviewbot is a Slack bot that shows reviewable pull requests.
Ruby
40
star
11

lager_logger

A lager backend that forwards all log messages to Elixir's Logger
Elixir
27
star
12

clang-tidy-to-junit

A little script that can convert Clang-Tidy output to a JUnit XML file.
Python
27
star
13

HEIC-Benchmark

HEIC/HEIF Benchmark for iOS
Objective-C
21
star
14

native-module-electron

JavaScript
20
star
15

iOS-UI-Testing-Comparison

Demo project to show how UI testing frameworks compare to each other. Here we are comparing EarlGrey, KIF and XCUI.
Swift
20
star
16

libdispatch

C
19
star
17

cobertura_cover

Output test coverage information in Cobertura-compatible format
Elixir
12
star
18

webpack-express-examples

Example apps using express server and webpack-dev-server for serving the client code.
JavaScript
12
star
19

zbase32

Human-oriented base-32 encoding
Elixir
9
star
20

pdfjs-web-example-javascript

JavaScript
8
star
21

wasm-worker-example

JavaScript
7
star
22

pspdfkit-tauri-react-example

PSPDFKit Web SDK React example running on Tauri
JavaScript
6
star
23

jest-measure

A library to introduce measuring APIs to Jest
JavaScript
6
star
24

react-pdf-demo

JavaScript
5
star
25

pspdfkit-maui7-example

.NET7 MAUI Blazor application using PSPDFKit Web SDK
JavaScript
5
star
26

pspdfkit-jetpack-compose-example

Example app showcasing how to use PSPDFKit for Android within Jetpack Compose
Kotlin
4
star
27

pspdfkit-processor-invoice-from-html

Project showcasing creation of invoices from a HTML with PSPDFKit Processor
JavaScript
4
star
28

pspdfkit-template-generation-from-pdf

Generate PDFs from a Template Using JavaScript
JavaScript
3
star
29

pdfjs-web-example-bootstrap

HTML
2
star
30

pspdfkit-server-invoice

Project showcasing creation of invoices from a template with PSPDFKit Server
JavaScript
2
star
31

github-to-jira

A set of hacks for easier GitHub to Jira migration
Ruby
2
star
32

pdfjs-web-component

A simple web component that uses PDF.js to display a document. Demo included.
TypeScript
2
star
33

libkqueue

C
2
star
34

android-threejs-example

Companion example for the blog post ...
JavaScript
2
star
35

html-to-image-laravel

PHP
1
star
36

pspdfkit-receipt-template

Create Receipts using PSPDFKit PDF Generator API
HTML
1
star
37

SQLiteCpp

C
1
star
38

UsingSharedBufferWithUWP

Sample repository that demonstrates how to share large data from UWP to WebView2
C#
1
star
39

cpp-exceptions-testing

Some benchmark and bin size tests for blog post.
C++
1
star
40

libpthread_workqueue

C
1
star
41

ng2-web-example-angular

How to build an Angular PDF viewer with ng2-pdf-viewer
TypeScript
1
star
42

pdfvuer-web-example-vue

HTML
1
star
43

swig-cpp-blog-example

C++
1
star
44

pspdfkit-pdf-generator-java

PDF Generation with Java and PSPDFKit API
Java
1
star
45

ReactiveCocoa

Objective-C
1
star