Giter Site home page Giter Site logo

test_server's Introduction

TestServer

Github CI hex.pm

No fuzz ExUnit test server to mock third party services.

Features:

  • HTTP/1
  • HTTP/2
  • WebSocket
  • Built-in TLS with self-signed certificates
  • Plug route matching

Installation

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

def deps do
  [
    {:test_server, "~> 0.1", only: [:test]}
  ]
end

Usage

test "fetch_url/0" do
  # The test server will autostart the current test server, if not already running
  TestServer.add("/", via: :get)

  # The URL is derived from the current test server instance
  Application.put_env(:my_app, :fetch_url, TestServer.url())

  {:ok, "HTTP"} = MyModule.fetch_url()
end

The TestServer.add/2 function can route a request to an anonymous function:

TestServer.add("/", to: fn conn ->
  Plug.Conn.send_resp(conn, 200, "success")
end)

It can also route to a plug:

TestServer.add("/", to: MyPlug)

The method to listen to can be defined with :via, by default it'll match any method:

TestServer.add("/", via: :post)

A custom match function can be set with :match option:

TestServer.add("/", match: fn
  %{params: %{"a" => 1}} = _conn -> true
  _conn -> false
end)

When a route is matched it'll be removed from active routes list. The route will be triggered in the order they were added:

TestServer.add("/", via: :get, to: &Plug.Conn.send_resp(&1, 200, "first"))
TestServer.add("/", via: :get, to: &Plug.Conn.send_resp(&1, 200, "second"))

{:ok, "first"} = fetch_request()
{:ok, "second"} = fetch_request()

Plugs can be added to process requests before it matches any routes. If no plugs are defined Plug.Conn.fetch_query_params/1 will be used.

TestServer.plug(fn conn ->
  Plug.Conn.fetch_query_params(conn)
end)

TestServer.plug(fn conn ->
  {:ok, body, _conn} = Plug.Conn.read_body(conn, [])

  %{conn | body_params: Jason.decode!(body)}
end)

TestServer.plug(MyPlug)

HTTPS

By default all routes are served as plain HTTP. HTTPS can be enabled with the :scheme option when starting the test server.

Custom SSL certificates can also be used by defining the cowboy options:

TestServer.start(scheme: :https, tls: [keyfile: key, certfile: cert])

A certificate suite will automatically generated if you don't include certificate:

{:ok, instance} = TestServer.start(scheme: :https)
cacerts = TestServer.x509_suite().cacerts

WebSocket

WebSocket endpoint can also be set up. By default the handler will echo what was received.

test "WebSocketClient" do
  {:ok, socket} = TestServer.websocket_init("/ws")

  :ok = TestServer.websocket_handle(socket)
  :ok = TestServer.websocket_handle(socket, to: fn {:text, "ping"}, state -> {:reply, {:text, "pong"}, state} end)
  :ok = TestServer.websocket_handle(socket, match: fn {:text, message}, _state -> message == "hi")

  {:ok, client} = WebSocketClient.start_link(TestServer.url("/ws"))

  :ok = WebSocketClient.send(client, "hello")
  {:ok, "hello"} = WebSocketClient.receive(client)

  :ok = WebSocketClient.send(client, "ping")
  {:ok, "pong"} = WebSocketClient.receive(client)

  :ok = WebSocketClient.send("hi")
  {:ok, "hi"} = WebSocketClient.receive(client)

  :ok = TestServer.websocket_info(socket, fn state -> {:reply, {:text, "ping"}, state} end)
  {:ok, "ping"} = WebSocketClient.receive(client)
end

Note: WebSocket is not supported by the :httpd adapter.

HTTP Server Adapter

TestServer supports Bandit, Plug.Cowboy, and :httpd out of the box. The HTTP adapter will be selected in this order depending which is available in the dependencies. You can also explicitly set the http server in the configuration:

TestServer.start(http_server: {Bandit, []})

You can create your own plug based HTTP Server Adapter by using the TestServer.HTTPServer behaviour.

IPv6

Use the :ipfamily option to test with IPv6 when you are starting the test server:

TestServer.start(ipfamily: :inet6)

LICENSE

(The MIT License)

Copyright (c) 2022 Dan Schultzer & the Contributors

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

test_server's People

Contributors

antedeguemon avatar danschultzer avatar kianmeng avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

test_server's Issues

Bandit `1.4.0` runtime error

When upgrading bandit to 1.4.0 I get the following error when running tests:

** (RuntimeError) Adapter functions must be called by stream owner

Support Bandit

Currently TestServer is built on Cowboy. I would like for the webserver being optional. TestServer should require either cowboy or Bandit to be installed. Most end-users will have one of them in their project so it'll be few users who will experience an issue. TestServer should throw a helpful error if neither exists in the project.

Unable to overwrite default WS connection timeout

Starting a server together with WS endpoint like:

{:ok, server} =
  TestServer.start(
    http_server:
      {TestServer.HTTPServer.Plug.Cowboy, protocol_options: [idle_timeout: 60_000]},
    scheme: :https,
    tls: [
      cacertfile: "/tmp/ca-cert.pem",
      certfile: "/tmp/server-cert.pem",
      keyfile: "/tmp/server-key.pem"
    ]
  )

{:ok, ws} = TestServer.websocket_init(server, "/ws")

and then connecting to /ws. Although the connection is established successfully, the client gets disconnected after a 1-second timeout.

At the same time, the established HTTPS connection doesn't get terminated until a 60-sec interval is passed.

Am I doing something wrong?

Thanks,
Alexey

Cannot mock 5xx responses

If I try to mock a 5xx response it blows up the entire test. I'm using the Bandit adapter.

e.g.,

    TestServer.add("/some/path",
      via: :get,
      to: fn conn ->
        Plug.Conn.send_resp(conn, 500, "")
      end
    )
14:20:45.892 [error] retry: got response with status 500, will retry in 1000ms, 3 attempts left
warning: ** (RuntimeError) TestServer.Instance #PID<0.628.0> received an unexpected GET request at /some/path.


No active routes. The following routes have been processed:

(list of all the routes here)

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.