All Projects → PSPDFKit-labs → Bypass

PSPDFKit-labs / Bypass

Licence: mit
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.

Programming Languages

elixir
2628 projects

Projects that are alternatives of or similar to Bypass

jmitm
Java版本的mitmproxy,对本地浏览器所有的Http(s)请求和响应进行拦截并「重制」;也可充当轻量级B/S版抓包软件;
Stars: ✭ 19 (-97.4%)
Mutual labels:  mock, https
Python Mocket
a socket mock framework - for all kinds of socket animals, web-clients included
Stars: ✭ 209 (-71.41%)
Mutual labels:  https, mock
Interceptors
Low-level HTTP/HTTPS/XHR/fetch request interception library.
Stars: ✭ 100 (-86.32%)
Mutual labels:  https, mock
Stubmatic
Mock HTTP calls without coding. Designed specially for testing and testers.
Stars: ✭ 118 (-83.86%)
Mutual labels:  mock, https
Android Testing Guide
[Examples] Complete reference for Android Testing with examples.
Stars: ✭ 652 (-10.81%)
Mutual labels:  mock
Dockerswarm.rocks
Docker Swarm mode rocks! Ideas, tools and recipes. Get a production-ready, distributed, HTTPS served, cluster in minutes, not weeks.
Stars: ✭ 584 (-20.11%)
Mutual labels:  https
Http Client
Async HTTP/1.1+2 client for PHP based on Amp.
Stars: ✭ 553 (-24.35%)
Mutual labels:  https
Mmock
Mmock is an HTTP mocking application for testing and fast prototyping
Stars: ✭ 537 (-26.54%)
Mutual labels:  mock
Gun
HTTP/1.1, HTTP/2 and Websocket client for Erlang/OTP.
Stars: ✭ 710 (-2.87%)
Mutual labels:  https
Brynet
A Header-Only cross-platform C++ TCP network library . Can use vcpkg(https://github.com/Microsoft/vcpkg/tree/master/ports/brynet) install
Stars: ✭ 674 (-7.8%)
Mutual labels:  https
Ansible Role Nginx
Ansible Role - Nginx
Stars: ✭ 632 (-13.54%)
Mutual labels:  https
Blinksocks
A framework for building composable proxy protocol stack.
Stars: ✭ 587 (-19.7%)
Mutual labels:  https
Devcert
Local HTTPS development made easy
Stars: ✭ 655 (-10.4%)
Mutual labels:  https
Fes.js
Fes.js 是一套优秀的中后台前端解决方案。提供初始项目、开发调试、Mock接口、编译打包的命令行工具。内置布局、权限、数据字典、状态管理、存储、Api等多个模块。以约定、配置化、组件化的设计思想,让用户仅仅关心用组件搭建页面内容。基于Vue.js,上手简单。经过多个项目中打磨,趋于稳定。
Stars: ✭ 579 (-20.79%)
Mutual labels:  mock
Agoo
A High Performance HTTP Server for Ruby
Stars: ✭ 679 (-7.11%)
Mutual labels:  https
Hstspreload.org
🔒 Chromium's HSTS preload list submission website.
Stars: ✭ 548 (-25.03%)
Mutual labels:  https
Hiproxy
🛠 hiproxy is a lightweight proxy tool for Front-End developers based on Node.js that supports an NGINX-like configuration. 🔥
Stars: ✭ 629 (-13.95%)
Mutual labels:  https
Vue Admin Webapp
this is a admin project
Stars: ✭ 673 (-7.93%)
Mutual labels:  mock
Msw
Seamless REST/GraphQL API mocking library for browser and Node.js.
Stars: ✭ 7,830 (+971.14%)
Mutual labels:  mock
Pshtt
Scan domains and return data based on HTTPS best practices
Stars: ✭ 597 (-18.33%)
Mutual labels:  https

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.7 and OTP 20 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).

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].