From 08c84df61cdebef5599685d36095c010ca0a53d1 Mon Sep 17 00:00:00 2001 From: Pierre de Lacroix Date: Tue, 5 May 2020 20:53:20 +0200 Subject: Initial commit --- .formatter.exs | 4 ++ .gitignore | 28 ++++++++ README.md | 18 ++++++ config/config.exs | 28 ++++++++ config/dev.exs | 48 ++++++++++++++ config/prod.exs | 55 ++++++++++++++++ config/prod.secret.exs | 29 +++++++++ config/test.exs | 10 +++ lib/matrix_app_service.ex | 9 +++ lib/matrix_app_service/application.ex | 32 ++++++++++ lib/matrix_app_service_web.ex | 74 ++++++++++++++++++++++ lib/matrix_app_service_web/channels/user_socket.ex | 35 ++++++++++ lib/matrix_app_service_web/endpoint.ex | 45 +++++++++++++ lib/matrix_app_service_web/router.ex | 11 ++++ lib/matrix_app_service_web/telemetry.ex | 46 ++++++++++++++ lib/matrix_app_service_web/views/error_helpers.ex | 16 +++++ lib/matrix_app_service_web/views/error_view.ex | 16 +++++ mix.exs | 55 ++++++++++++++++ mix.lock | 15 +++++ .../views/error_view_test.exs | 15 +++++ test/support/channel_case.ex | 34 ++++++++++ test/support/conn_case.ex | 37 +++++++++++ test/test_helper.exs | 1 + 23 files changed, 661 insertions(+) create mode 100644 .formatter.exs create mode 100644 .gitignore create mode 100644 README.md create mode 100644 config/config.exs create mode 100644 config/dev.exs create mode 100644 config/prod.exs create mode 100644 config/prod.secret.exs create mode 100644 config/test.exs create mode 100644 lib/matrix_app_service.ex create mode 100644 lib/matrix_app_service/application.ex create mode 100644 lib/matrix_app_service_web.ex create mode 100644 lib/matrix_app_service_web/channels/user_socket.ex create mode 100644 lib/matrix_app_service_web/endpoint.ex create mode 100644 lib/matrix_app_service_web/router.ex create mode 100644 lib/matrix_app_service_web/telemetry.ex create mode 100644 lib/matrix_app_service_web/views/error_helpers.ex create mode 100644 lib/matrix_app_service_web/views/error_view.ex create mode 100644 mix.exs create mode 100644 mix.lock create mode 100644 test/matrix_app_service_web/views/error_view_test.exs create mode 100644 test/support/channel_case.ex create mode 100644 test/support/conn_case.ex create mode 100644 test/test_helper.exs diff --git a/.formatter.exs b/.formatter.exs new file mode 100644 index 0000000..4761678 --- /dev/null +++ b/.formatter.exs @@ -0,0 +1,4 @@ +[ + import_deps: [:phoenix], + inputs: ["*.{ex,exs}", "{config,lib,test}/**/*.{ex,exs}"] +] diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b386c97 --- /dev/null +++ b/.gitignore @@ -0,0 +1,28 @@ +# The directory Mix will write compiled artifacts to. +/_build/ + +# If you run "mix test --cover", coverage assets end up here. +/cover/ + +# The directory Mix downloads your dependencies sources to. +/deps/ + +# Where 3rd-party dependencies like ExDoc output generated docs. +/doc/ + +# Ignore .fetch files in case you like to edit your project deps locally. +/.fetch + +# If the VM crashes, it generates a dump, let's ignore it too. +erl_crash.dump + +# Also ignore archive artifacts (built via "mix archive.build"). +*.ez + +# Ignore package tarball (built via "mix hex.build"). +matrix_app_service-*.tar + +# Since we are building assets from assets/, +# we ignore priv/static. You may want to comment +# this depending on your deployment strategy. +/priv/static/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..97cc456 --- /dev/null +++ b/README.md @@ -0,0 +1,18 @@ +# MatrixAppService + +To start your Phoenix server: + + * Setup the project with `mix setup` + * Start Phoenix endpoint with `mix phx.server` + +Now you can visit [`localhost:4000`](http://localhost:4000) from your browser. + +Ready to run in production? Please [check our deployment guides](https://hexdocs.pm/phoenix/deployment.html). + +## Learn more + + * Official website: https://www.phoenixframework.org/ + * Guides: https://hexdocs.pm/phoenix/overview.html + * Docs: https://hexdocs.pm/phoenix + * Forum: https://elixirforum.com/c/phoenix-forum + * Source: https://github.com/phoenixframework/phoenix diff --git a/config/config.exs b/config/config.exs new file mode 100644 index 0000000..00d01a6 --- /dev/null +++ b/config/config.exs @@ -0,0 +1,28 @@ +# This file is responsible for configuring your application +# and its dependencies with the aid of the Mix.Config module. +# +# This configuration file is loaded before any dependency and +# is restricted to this project. + +# General application configuration +use Mix.Config + +# Configures the endpoint +config :matrix_app_service, MatrixAppServiceWeb.Endpoint, + url: [host: "localhost"], + secret_key_base: "o53gWptgO8ItBlXMZaps/r/y/iQuZPuB/YkKl7H2UfTVkaQVDqR+3LtFLUWvVUtb", + render_errors: [view: MatrixAppServiceWeb.ErrorView, accepts: ~w(json), layout: false], + pubsub_server: MatrixAppService.PubSub, + live_view: [signing_salt: "FhCM5pjr"] + +# Configures Elixir's Logger +config :logger, :console, + format: "$time $metadata[$level] $message\n", + metadata: [:request_id] + +# Use Jason for JSON parsing in Phoenix +config :phoenix, :json_library, Jason + +# Import environment specific config. This must remain at the bottom +# of this file so it overrides the configuration defined above. +import_config "#{Mix.env()}.exs" diff --git a/config/dev.exs b/config/dev.exs new file mode 100644 index 0000000..32db45e --- /dev/null +++ b/config/dev.exs @@ -0,0 +1,48 @@ +use Mix.Config + +# For development, we disable any cache and enable +# debugging and code reloading. +# +# The watchers configuration can be used to run external +# watchers to your application. For example, we use it +# with webpack to recompile .js and .css sources. +config :matrix_app_service, MatrixAppServiceWeb.Endpoint, + http: [port: 4000], + debug_errors: true, + code_reloader: true, + check_origin: false, + watchers: [] + +# ## SSL Support +# +# In order to use HTTPS in development, a self-signed +# certificate can be generated by running the following +# Mix task: +# +# mix phx.gen.cert +# +# Note that this task requires Erlang/OTP 20 or later. +# Run `mix help phx.gen.cert` for more information. +# +# The `http:` config above can be replaced with: +# +# https: [ +# port: 4001, +# cipher_suite: :strong, +# keyfile: "priv/cert/selfsigned_key.pem", +# certfile: "priv/cert/selfsigned.pem" +# ], +# +# If desired, both `http:` and `https:` keys can be +# configured to run both http and https servers on +# different ports. + +# Do not include metadata nor timestamps in development logs +config :logger, :console, format: "[$level] $message\n" + +# Set a higher stacktrace during development. Avoid configuring such +# in production as building large stacktraces may be expensive. +config :phoenix, :stacktrace_depth, 20 + +# Initialize plugs at runtime for faster development compilation +config :phoenix, :plug_init_mode, :runtime diff --git a/config/prod.exs b/config/prod.exs new file mode 100644 index 0000000..1bb706e --- /dev/null +++ b/config/prod.exs @@ -0,0 +1,55 @@ +use Mix.Config + +# For production, don't forget to configure the url host +# to something meaningful, Phoenix uses this information +# when generating URLs. +# +# Note we also include the path to a cache manifest +# containing the digested version of static files. This +# manifest is generated by the `mix phx.digest` task, +# which you should run after static files are built and +# before starting your production server. +config :matrix_app_service, MatrixAppServiceWeb.Endpoint, + url: [host: "example.com", port: 80], + cache_static_manifest: "priv/static/cache_manifest.json" + +# Do not print debug messages in production +config :logger, level: :info + +# ## SSL Support +# +# To get SSL working, you will need to add the `https` key +# to the previous section and set your `:url` port to 443: +# +# config :matrix_app_service, MatrixAppServiceWeb.Endpoint, +# ... +# url: [host: "example.com", port: 443], +# https: [ +# port: 443, +# cipher_suite: :strong, +# keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"), +# certfile: System.get_env("SOME_APP_SSL_CERT_PATH"), +# transport_options: [socket_opts: [:inet6]] +# ] +# +# The `cipher_suite` is set to `:strong` to support only the +# latest and more secure SSL ciphers. This means old browsers +# and clients may not be supported. You can set it to +# `:compatible` for wider support. +# +# `:keyfile` and `:certfile` expect an absolute path to the key +# and cert in disk or a relative path inside priv, for example +# "priv/ssl/server.key". For all supported SSL configuration +# options, see https://hexdocs.pm/plug/Plug.SSL.html#configure/1 +# +# We also recommend setting `force_ssl` in your endpoint, ensuring +# no data is ever sent via http, always redirecting to https: +# +# config :matrix_app_service, MatrixAppServiceWeb.Endpoint, +# force_ssl: [hsts: true] +# +# Check `Plug.SSL` for all available options in `force_ssl`. + +# Finally import the config/prod.secret.exs which loads secrets +# and configuration from environment variables. +import_config "prod.secret.exs" diff --git a/config/prod.secret.exs b/config/prod.secret.exs new file mode 100644 index 0000000..a20e76d --- /dev/null +++ b/config/prod.secret.exs @@ -0,0 +1,29 @@ +# In this file, we load production configuration and secrets +# from environment variables. You can also hardcode secrets, +# although such is generally not recommended and you have to +# remember to add this file to your .gitignore. +use Mix.Config + +secret_key_base = + System.get_env("SECRET_KEY_BASE") || + raise """ + environment variable SECRET_KEY_BASE is missing. + You can generate one by calling: mix phx.gen.secret + """ + +config :matrix_app_service, MatrixAppServiceWeb.Endpoint, + http: [ + port: String.to_integer(System.get_env("PORT") || "4000"), + transport_options: [socket_opts: [:inet6]] + ], + secret_key_base: secret_key_base + +# ## Using releases (Elixir v1.9+) +# +# If you are doing OTP releases, you need to instruct Phoenix +# to start each relevant endpoint: +# +# config :matrix_app_service, MatrixAppServiceWeb.Endpoint, server: true +# +# Then you can assemble a release by calling `mix release`. +# See `mix help release` for more information. diff --git a/config/test.exs b/config/test.exs new file mode 100644 index 0000000..aa8991c --- /dev/null +++ b/config/test.exs @@ -0,0 +1,10 @@ +use Mix.Config + +# We don't run a server during test. If one is required, +# you can enable the server option below. +config :matrix_app_service, MatrixAppServiceWeb.Endpoint, + http: [port: 4002], + server: false + +# Print only warnings and errors during test +config :logger, level: :warn diff --git a/lib/matrix_app_service.ex b/lib/matrix_app_service.ex new file mode 100644 index 0000000..769a9f0 --- /dev/null +++ b/lib/matrix_app_service.ex @@ -0,0 +1,9 @@ +defmodule MatrixAppService do + @moduledoc """ + MatrixAppService keeps the contexts that define your domain + and business logic. + + Contexts are also responsible for managing your data, regardless + if it comes from the database, an external API or others. + """ +end diff --git a/lib/matrix_app_service/application.ex b/lib/matrix_app_service/application.ex new file mode 100644 index 0000000..648cc70 --- /dev/null +++ b/lib/matrix_app_service/application.ex @@ -0,0 +1,32 @@ +defmodule MatrixAppService.Application do + # See https://hexdocs.pm/elixir/Application.html + # for more information on OTP Applications + @moduledoc false + + use Application + + def start(_type, _args) do + children = [ + # Start the Telemetry supervisor + MatrixAppServiceWeb.Telemetry, + # Start the PubSub system + {Phoenix.PubSub, name: MatrixAppService.PubSub}, + # Start the Endpoint (http/https) + MatrixAppServiceWeb.Endpoint + # Start a worker by calling: MatrixAppService.Worker.start_link(arg) + # {MatrixAppService.Worker, arg} + ] + + # See https://hexdocs.pm/elixir/Supervisor.html + # for other strategies and supported options + opts = [strategy: :one_for_one, name: MatrixAppService.Supervisor] + Supervisor.start_link(children, opts) + end + + # Tell Phoenix to update the endpoint configuration + # whenever the application is updated. + def config_change(changed, _new, removed) do + MatrixAppServiceWeb.Endpoint.config_change(changed, removed) + :ok + end +end diff --git a/lib/matrix_app_service_web.ex b/lib/matrix_app_service_web.ex new file mode 100644 index 0000000..e388fee --- /dev/null +++ b/lib/matrix_app_service_web.ex @@ -0,0 +1,74 @@ +defmodule MatrixAppServiceWeb do + @moduledoc """ + The entrypoint for defining your web interface, such + as controllers, views, channels and so on. + + This can be used in your application as: + + use MatrixAppServiceWeb, :controller + use MatrixAppServiceWeb, :view + + The definitions below will be executed for every view, + controller, etc, so keep them short and clean, focused + on imports, uses and aliases. + + Do NOT define functions inside the quoted expressions + below. Instead, define any helper function in modules + and import those modules here. + """ + + def controller do + quote do + use Phoenix.Controller, namespace: MatrixAppServiceWeb + + import Plug.Conn + alias MatrixAppServiceWeb.Router.Helpers, as: Routes + end + end + + def view do + quote do + use Phoenix.View, + root: "lib/matrix_app_service_web/templates", + namespace: MatrixAppServiceWeb + + # Import convenience functions from controllers + import Phoenix.Controller, only: [get_flash: 1, get_flash: 2, view_module: 1] + + # Include shared imports and aliases for views + unquote(view_helpers()) + end + end + + def router do + quote do + use Phoenix.Router + + import Plug.Conn + import Phoenix.Controller + end + end + + def channel do + quote do + use Phoenix.Channel + end + end + + defp view_helpers do + quote do + # Import basic rendering functionality (render, render_layout, etc) + import Phoenix.View + + import MatrixAppServiceWeb.ErrorHelpers + alias MatrixAppServiceWeb.Router.Helpers, as: Routes + end + end + + @doc """ + When used, dispatch to the appropriate controller/view/etc. + """ + defmacro __using__(which) when is_atom(which) do + apply(__MODULE__, which, []) + end +end diff --git a/lib/matrix_app_service_web/channels/user_socket.ex b/lib/matrix_app_service_web/channels/user_socket.ex new file mode 100644 index 0000000..ec2e9fb --- /dev/null +++ b/lib/matrix_app_service_web/channels/user_socket.ex @@ -0,0 +1,35 @@ +defmodule MatrixAppServiceWeb.UserSocket do + use Phoenix.Socket + + ## Channels + # channel "room:*", MatrixAppServiceWeb.RoomChannel + + # Socket params are passed from the client and can + # be used to verify and authenticate a user. After + # verification, you can put default assigns into + # the socket that will be set for all channels, ie + # + # {:ok, assign(socket, :user_id, verified_user_id)} + # + # To deny connection, return `:error`. + # + # See `Phoenix.Token` documentation for examples in + # performing token verification on connect. + @impl true + def connect(_params, socket, _connect_info) do + {:ok, socket} + end + + # Socket id's are topics that allow you to identify all sockets for a given user: + # + # def id(socket), do: "user_socket:#{socket.assigns.user_id}" + # + # Would allow you to broadcast a "disconnect" event and terminate + # all active sockets and channels for a given user: + # + # MatrixAppServiceWeb.Endpoint.broadcast("user_socket:#{user.id}", "disconnect", %{}) + # + # Returning `nil` makes this socket anonymous. + @impl true + def id(_socket), do: nil +end diff --git a/lib/matrix_app_service_web/endpoint.ex b/lib/matrix_app_service_web/endpoint.ex new file mode 100644 index 0000000..0ee00fc --- /dev/null +++ b/lib/matrix_app_service_web/endpoint.ex @@ -0,0 +1,45 @@ +defmodule MatrixAppServiceWeb.Endpoint do + use Phoenix.Endpoint, otp_app: :matrix_app_service + + # The session will be stored in the cookie and signed, + # this means its contents can be read but not tampered with. + # Set :encryption_salt if you would also like to encrypt it. + @session_options [ + store: :cookie, + key: "_matrix_app_service_key", + signing_salt: "zE7AHynD" + ] + + socket "/socket", MatrixAppServiceWeb.UserSocket, + websocket: true, + longpoll: false + + # Serve at "/" the static files from "priv/static" directory. + # + # You should set gzip to true if you are running phx.digest + # when deploying your static files in production. + plug Plug.Static, + at: "/", + from: :matrix_app_service, + gzip: false, + only: ~w(css fonts images js favicon.ico robots.txt) + + # Code reloading can be explicitly enabled under the + # :code_reloader configuration of your endpoint. + if code_reloading? do + plug Phoenix.CodeReloader + end + + plug Plug.RequestId + plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint] + + plug Plug.Parsers, + parsers: [:urlencoded, :multipart, :json], + pass: ["*/*"], + json_decoder: Phoenix.json_library() + + plug Plug.MethodOverride + plug Plug.Head + plug Plug.Session, @session_options + plug MatrixAppServiceWeb.Router +end diff --git a/lib/matrix_app_service_web/router.ex b/lib/matrix_app_service_web/router.ex new file mode 100644 index 0000000..3a24510 --- /dev/null +++ b/lib/matrix_app_service_web/router.ex @@ -0,0 +1,11 @@ +defmodule MatrixAppServiceWeb.Router do + use MatrixAppServiceWeb, :router + + pipeline :api do + plug :accepts, ["json"] + end + + scope "/api", MatrixAppServiceWeb do + pipe_through :api + end +end diff --git a/lib/matrix_app_service_web/telemetry.ex b/lib/matrix_app_service_web/telemetry.ex new file mode 100644 index 0000000..de3ec2d --- /dev/null +++ b/lib/matrix_app_service_web/telemetry.ex @@ -0,0 +1,46 @@ +defmodule MatrixAppServiceWeb.Telemetry do + use Supervisor + import Telemetry.Metrics + + def start_link(arg) do + Supervisor.start_link(__MODULE__, arg, name: __MODULE__) + end + + @impl true + def init(_arg) do + children = [ + {:telemetry_poller, measurements: periodic_measurements(), period: 10_000} + # Add reporters as children of your supervision tree. + # {Telemetry.Metrics.ConsoleReporter, metrics: metrics()} + ] + + Supervisor.init(children, strategy: :one_for_one) + end + + def metrics do + [ + # Phoenix Metrics + summary("phoenix.endpoint.stop.duration", + unit: {:native, :millisecond} + ), + summary("phoenix.router_dispatch.stop.duration", + tags: [:route], + unit: {:native, :millisecond} + ), + + # VM Metrics + summary("vm.memory.total", unit: {:byte, :kilobyte}), + summary("vm.total_run_queue_lengths.total"), + summary("vm.total_run_queue_lengths.cpu"), + summary("vm.total_run_queue_lengths.io") + ] + end + + defp periodic_measurements do + [ + # A module, function and arguments to be invoked periodically. + # This function must call :telemetry.execute/3 and a metric must be added above. + # {MatrixAppServiceWeb, :count_users, []} + ] + end +end diff --git a/lib/matrix_app_service_web/views/error_helpers.ex b/lib/matrix_app_service_web/views/error_helpers.ex new file mode 100644 index 0000000..4eff422 --- /dev/null +++ b/lib/matrix_app_service_web/views/error_helpers.ex @@ -0,0 +1,16 @@ +defmodule MatrixAppServiceWeb.ErrorHelpers do + @moduledoc """ + Conveniences for translating and building error messages. + """ + + @doc """ + Translates an error message. + """ + def translate_error({msg, opts}) do + # Because the error messages we show in our forms and APIs + # are defined inside Ecto, we need to translate them dynamically. + Enum.reduce(opts, msg, fn {key, value}, acc -> + String.replace(acc, "%{#{key}}", to_string(value)) + end) + end +end diff --git a/lib/matrix_app_service_web/views/error_view.ex b/lib/matrix_app_service_web/views/error_view.ex new file mode 100644 index 0000000..2358355 --- /dev/null +++ b/lib/matrix_app_service_web/views/error_view.ex @@ -0,0 +1,16 @@ +defmodule MatrixAppServiceWeb.ErrorView do + use MatrixAppServiceWeb, :view + + # If you want to customize a particular status code + # for a certain format, you may uncomment below. + # def render("500.json", _assigns) do + # %{errors: %{detail: "Internal Server Error"}} + # end + + # By default, Phoenix returns the status message from + # the template name. For example, "404.json" becomes + # "Not Found". + def template_not_found(template, _assigns) do + %{errors: %{detail: Phoenix.Controller.status_message_from_template(template)}} + end +end diff --git a/mix.exs b/mix.exs new file mode 100644 index 0000000..04d0bf4 --- /dev/null +++ b/mix.exs @@ -0,0 +1,55 @@ +defmodule MatrixAppService.MixProject do + use Mix.Project + + def project do + [ + app: :matrix_app_service, + version: "0.1.0", + elixir: "~> 1.7", + elixirc_paths: elixirc_paths(Mix.env()), + compilers: [:phoenix] ++ Mix.compilers(), + start_permanent: Mix.env() == :prod, + aliases: aliases(), + deps: deps() + ] + end + + # Configuration for the OTP application. + # + # Type `mix help compile.app` for more information. + def application do + [ + mod: {MatrixAppService.Application, []}, + extra_applications: [:logger, :runtime_tools] + ] + end + + # Specifies which paths to compile per environment. + defp elixirc_paths(:test), do: ["lib", "test/support"] + defp elixirc_paths(_), do: ["lib"] + + # Specifies your project dependencies. + # + # Type `mix help deps` for examples and options. + defp deps do + [ + {:phoenix, "~> 1.5.1"}, + {:telemetry_metrics, "~> 0.4"}, + {:telemetry_poller, "~> 0.4"}, + {:jason, "~> 1.0"}, + {:plug_cowboy, "~> 2.0"} + ] + end + + # Aliases are shortcuts or tasks specific to the current project. + # For example, to install project dependencies and perform other setup tasks, run: + # + # $ mix setup + # + # See the documentation for `Mix` for more info on aliases. + defp aliases do + [ + setup: ["deps.get"] + ] + end +end diff --git a/mix.lock b/mix.lock new file mode 100644 index 0000000..cd49cb0 --- /dev/null +++ b/mix.lock @@ -0,0 +1,15 @@ +%{ + "cowboy": {:hex, :cowboy, "2.7.0", "91ed100138a764355f43316b1d23d7ff6bdb0de4ea618cb5d8677c93a7a2f115", [:rebar3], [{:cowlib, "~> 2.8.0", [hex: :cowlib, repo: "hexpm", optional: false]}, {:ranch, "~> 1.7.1", [hex: :ranch, repo: "hexpm", optional: false]}], "hexpm", "04fd8c6a39edc6aaa9c26123009200fc61f92a3a94f3178c527b70b767c6e605"}, + "cowlib": {:hex, :cowlib, "2.8.0", "fd0ff1787db84ac415b8211573e9a30a3ebe71b5cbff7f720089972b2319c8a4", [:rebar3], [], "hexpm", "79f954a7021b302186a950a32869dbc185523d99d3e44ce430cd1f3289f41ed4"}, + "jason": {:hex, :jason, "1.2.0", "10043418c42d2493d0ee212d3fddd25d7ffe484380afad769a0a38795938e448", [:mix], [{:decimal, "~> 1.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "116747dbe057794c3a3e4e143b7c8390b29f634e16c78a7f59ba75bfa6852e7f"}, + "mime": {:hex, :mime, "1.3.1", "30ce04ab3175b6ad0bdce0035cba77bba68b813d523d1aac73d9781b4d193cf8", [:mix], [], "hexpm", "6cbe761d6a0ca5a31a0931bf4c63204bceb64538e664a8ecf784a9a6f3b875f1"}, + "phoenix": {:hex, :phoenix, "1.5.1", "95156589879dc69201d5fc0ebdbfdfc7901a09a3616ea611ec297f81340275a2", [:mix], [{:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:phoenix_html, "~> 2.13", [hex: :phoenix_html, repo: "hexpm", optional: true]}, {:phoenix_pubsub, "~> 2.0", [hex: :phoenix_pubsub, repo: "hexpm", optional: false]}, {:plug, "~> 1.10", [hex: :plug, repo: "hexpm", optional: false]}, {:plug_cowboy, "~> 1.0 or ~> 2.2", [hex: :plug_cowboy, repo: "hexpm", optional: true]}, {:plug_crypto, "~> 1.1.2 or ~> 1.2", [hex: :plug_crypto, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "fc272b38e79d2881790fccae6f67a9fbe9b790103d6878175ea03d23003152eb"}, + "phoenix_pubsub": {:hex, :phoenix_pubsub, "2.0.0", "a1ae76717bb168cdeb10ec9d92d1480fec99e3080f011402c0a2d68d47395ffb", [:mix], [], "hexpm", "c52d948c4f261577b9c6fa804be91884b381a7f8f18450c5045975435350f771"}, + "plug": {:hex, :plug, "1.10.0", "6508295cbeb4c654860845fb95260737e4a8838d34d115ad76cd487584e2fc4d", [:mix], [{:mime, "~> 1.0", [hex: :mime, repo: "hexpm", optional: false]}, {:plug_crypto, "~> 1.1.1 or ~> 1.2", [hex: :plug_crypto, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4", [hex: :telemetry, repo: "hexpm", optional: true]}], "hexpm", "422a9727e667be1bf5ab1de03be6fa0ad67b775b2d84ed908f3264415ef29d4a"}, + "plug_cowboy": {:hex, :plug_cowboy, "2.2.1", "fcf58aa33227a4322a050e4783ee99c63c031a2e7f9a2eb7340d55505e17f30f", [:mix], [{:cowboy, "~> 2.7", [hex: :cowboy, repo: "hexpm", optional: false]}, {:plug, "~> 1.7", [hex: :plug, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "3b43de24460d87c0971887286e7a20d40462e48eb7235954681a20cee25ddeb6"}, + "plug_crypto": {:hex, :plug_crypto, "1.1.2", "bdd187572cc26dbd95b87136290425f2b580a116d3fb1f564216918c9730d227", [:mix], [], "hexpm", "6b8b608f895b6ffcfad49c37c7883e8df98ae19c6a28113b02aa1e9c5b22d6b5"}, + "ranch": {:hex, :ranch, "1.7.1", "6b1fab51b49196860b733a49c07604465a47bdb78aa10c1c16a3d199f7f8c881", [:rebar3], [], "hexpm", "451d8527787df716d99dc36162fca05934915db0b6141bbdac2ea8d3c7afc7d7"}, + "telemetry": {:hex, :telemetry, "0.4.1", "ae2718484892448a24470e6aa341bc847c3277bfb8d4e9289f7474d752c09c7f", [:rebar3], [], "hexpm", "4738382e36a0a9a2b6e25d67c960e40e1a2c95560b9f936d8e29de8cd858480f"}, + "telemetry_metrics": {:hex, :telemetry_metrics, "0.4.2", "1de986fad9aa6bf81f8a33ddfd16e5d8ab0dec6272e624eb517c1a92a44d41a9", [:mix], [{:telemetry, "~> 0.4", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "e56ffed2dbe293ab6cf7c94980faeb368cb360662c1927f54fc634a4ca55362e"}, + "telemetry_poller": {:hex, :telemetry_poller, "0.5.0", "4770888ef85599ead39c7f51d6b4b62306e602d96c69b2625d54dea3d9a5204b", [:rebar3], [{:telemetry, "~> 0.4", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "69e4e8e65b0ae077c9e14cd5f42c7cc486de0e07ac6e3409e6f0e52699a7872c"}, +} diff --git a/test/matrix_app_service_web/views/error_view_test.exs b/test/matrix_app_service_web/views/error_view_test.exs new file mode 100644 index 0000000..fb0d11e --- /dev/null +++ b/test/matrix_app_service_web/views/error_view_test.exs @@ -0,0 +1,15 @@ +defmodule MatrixAppServiceWeb.ErrorViewTest do + use MatrixAppServiceWeb.ConnCase, async: true + + # Bring render/3 and render_to_string/3 for testing custom views + import Phoenix.View + + test "renders 404.json" do + assert render(MatrixAppServiceWeb.ErrorView, "404.json", []) == %{errors: %{detail: "Not Found"}} + end + + test "renders 500.json" do + assert render(MatrixAppServiceWeb.ErrorView, "500.json", []) == + %{errors: %{detail: "Internal Server Error"}} + end +end diff --git a/test/support/channel_case.ex b/test/support/channel_case.ex new file mode 100644 index 0000000..069b724 --- /dev/null +++ b/test/support/channel_case.ex @@ -0,0 +1,34 @@ +defmodule MatrixAppServiceWeb.ChannelCase do + @moduledoc """ + This module defines the test case to be used by + channel tests. + + Such tests rely on `Phoenix.ChannelTest` and also + import other functionality to make it easier + to build common data structures and query the data layer. + + Finally, if the test case interacts with the database, + we enable the SQL sandbox, so changes done to the database + are reverted at the end of every test. If you are using + PostgreSQL, you can even run database tests asynchronously + by setting `use MatrixAppServiceWeb.ChannelCase, async: true`, although + this option is not recommended for other databases. + """ + + use ExUnit.CaseTemplate + + using do + quote do + # Import conveniences for testing with channels + import Phoenix.ChannelTest + import MatrixAppServiceWeb.ChannelCase + + # The default endpoint for testing + @endpoint MatrixAppServiceWeb.Endpoint + end + end + + setup _tags do + :ok + end +end diff --git a/test/support/conn_case.ex b/test/support/conn_case.ex new file mode 100644 index 0000000..478e03f --- /dev/null +++ b/test/support/conn_case.ex @@ -0,0 +1,37 @@ +defmodule MatrixAppServiceWeb.ConnCase do + @moduledoc """ + This module defines the test case to be used by + tests that require setting up a connection. + + Such tests rely on `Phoenix.ConnTest` and also + import other functionality to make it easier + to build common data structures and query the data layer. + + Finally, if the test case interacts with the database, + we enable the SQL sandbox, so changes done to the database + are reverted at the end of every test. If you are using + PostgreSQL, you can even run database tests asynchronously + by setting `use MatrixAppServiceWeb.ConnCase, async: true`, although + this option is not recommended for other databases. + """ + + use ExUnit.CaseTemplate + + using do + quote do + # Import conveniences for testing with connections + import Plug.Conn + import Phoenix.ConnTest + import MatrixAppServiceWeb.ConnCase + + alias MatrixAppServiceWeb.Router.Helpers, as: Routes + + # The default endpoint for testing + @endpoint MatrixAppServiceWeb.Endpoint + end + end + + setup _tags do + {:ok, conn: Phoenix.ConnTest.build_conn()} + end +end diff --git a/test/test_helper.exs b/test/test_helper.exs new file mode 100644 index 0000000..869559e --- /dev/null +++ b/test/test_helper.exs @@ -0,0 +1 @@ +ExUnit.start() -- cgit v1.2.3