diff --git a/config/config.exs b/config/config.exs index 54cb8d103..fb2f02328 100644 --- a/config/config.exs +++ b/config/config.exs @@ -67,7 +67,7 @@ config :code_corps, :corsica_log_level, [rejected: :warn] {:ok, pem} = (System.get_env("GITHUB_APP_PEM") || "") |> Base.decode64() config :code_corps, - github: CodeCorps.GitHub.API, + github: CodeCorps.GitHub.API.Gateway, github_app_id: System.get_env("GITHUB_APP_ID"), github_app_client_id: System.get_env("GITHUB_APP_CLIENT_ID"), github_app_client_secret: System.get_env("GITHUB_APP_CLIENT_SECRET"), diff --git a/lib/code_corps/cloudex/cloudex_test.ex b/lib/code_corps/cloudex/cloudex_test.ex index 14a07ba2f..eae55ec1f 100644 --- a/lib/code_corps/cloudex/cloudex_test.ex +++ b/lib/code_corps/cloudex/cloudex_test.ex @@ -14,7 +14,7 @@ defmodule CloudexTest do end end - @spec upload(String.t) :: Cloudex.UploadedImage.t + @spec upload(String.t) :: %Cloudex.UploadedImage{} def upload(_url) do [ok: %Cloudex.UploadedImage{public_id: fake_cloudinary_id()}] end diff --git a/lib/code_corps/github/api/api.ex b/lib/code_corps/github/api/api.ex index ef732c6e5..83d58b085 100644 --- a/lib/code_corps/github/api/api.ex +++ b/lib/code_corps/github/api/api.ex @@ -2,19 +2,37 @@ defmodule CodeCorps.GitHub.API do alias CodeCorps.{ GithubAppInstallation, GitHub, + GitHub.API.Pagination, GitHub.APIError, GitHub.HTTPClientError, User } + alias HTTPoison.{Error, Response} + + def gateway(), do: Application.get_env(:code_corps, :github) + @spec request(GitHub.method, String.t, GitHub.headers, GitHub.body, list) :: GitHub.response - def request(method, url, headers, body, options) do - method - |> :hackney.request(url, headers, body, options) + def request(method, url, body, headers, options) do + gateway().request(method, url, body, headers, options) |> marshall_response() end - defdelegate get_all(url, headers, opts), to: CodeCorps.GitHub.EagerAPI + @spec get_all(String.t, GitHub.headers, list) :: GitHub.response + def get_all(url, headers, options) do + {:ok, %Response{request_url: request_url, headers: response_headers}} = + gateway().request(:head, url, "", headers, options) + + response_headers + |> Pagination.retrieve_total_pages() + |> Pagination.to_page_numbers() + |> Enum.map(&Pagination.add_page_param(options, &1)) + |> Enum.map(&gateway().request(:get, url, "", headers, &1)) + |> Enum.map(&marshall_response/1) + |> Enum.map(&Tuple.to_list/1) + |> Enum.map(&List.last/1) + |> List.flatten + end @doc """ Get access token headers for a given `CodeCorps.User` and @@ -47,11 +65,11 @@ defmodule CodeCorps.GitHub.API do end end - @typep http_success :: {:ok, integer, [{String.t, String.t}], String.t} + @typep http_success :: {:ok, Response.t} @typep http_failure :: {:error, term} @spec marshall_response(http_success | http_failure) :: GitHub.response - defp marshall_response({:ok, status, _headers, body}) when status in 200..299 do + defp marshall_response({:ok, %Response{body: body, status_code: status}}) when status in 200..299 do case body |> Poison.decode do {:ok, json} -> {:ok, json} @@ -59,10 +77,10 @@ defmodule CodeCorps.GitHub.API do {:error, HTTPClientError.new(reason: :body_decoding_error)} end end - defp marshall_response({:ok, 404, _headers, body}) do + defp marshall_response({:ok, %Response{body: body, status_code: 404}}) do {:error, APIError.new({404, %{"message" => body}})} end - defp marshall_response({:ok, status, _headers, body}) when status in 400..599 do + defp marshall_response({:ok, %Response{body: body, status_code: status}}) when status in 400..599 do case body |> Poison.decode do {:ok, json} -> {:error, APIError.new({status, json})} @@ -70,6 +88,9 @@ defmodule CodeCorps.GitHub.API do {:error, HTTPClientError.new(reason: :body_decoding_error)} end end + defp marshall_response({:error, %Error{reason: reason}}) do + {:error, HTTPClientError.new(reason: reason)} + end defp marshall_response({:error, reason}) do {:error, HTTPClientError.new(reason: reason)} end diff --git a/lib/code_corps/github/api/comment.ex b/lib/code_corps/github/api/comment.ex index dbd15fae5..7d97f3729 100644 --- a/lib/code_corps/github/api/comment.ex +++ b/lib/code_corps/github/api/comment.ex @@ -32,7 +32,7 @@ defmodule CodeCorps.GitHub.API.Comment do attrs = comment |> GitHub.Adapters.Comment.to_api with opts when is_list(opts) <- GitHub.API.opts_for(user, installation) do - GitHub.request(:post, endpoint, %{}, attrs, opts) + GitHub.request(:post, endpoint, attrs, %{}, opts) else {:error, github_error} -> {:error, github_error} end @@ -56,7 +56,7 @@ defmodule CodeCorps.GitHub.API.Comment do attrs = comment |> GitHub.Adapters.Comment.to_api with opts when is_list(opts) <- GitHub.API.opts_for(user, installation) do - GitHub.request(:patch, endpoint, %{}, attrs, opts) + GitHub.request(:patch, endpoint, attrs, %{}, opts) else {:error, github_error} -> {:error, github_error} end diff --git a/lib/code_corps/github/api/eager_api.ex b/lib/code_corps/github/api/eager_api.ex deleted file mode 100644 index 38b9f8e17..000000000 --- a/lib/code_corps/github/api/eager_api.ex +++ /dev/null @@ -1,83 +0,0 @@ -defmodule CodeCorps.GitHub.EagerAPI do - @moduledoc """ - Eager loads a resource from the GitHub API by fetching all of its pages in - parallel. - """ - - def get_all(url, headers, options) do - HTTPoison.start - {:ok, response} = HTTPoison.get(url, headers, options) - - first_page = Poison.decode!(response.body) - case response.headers |> retrieve_total_pages do - 1 -> first_page - total -> - first_page ++ get_remaining_pages(total, url, headers, options) |> List.flatten - end - end - - defp get_remaining_pages(total, url, headers, options) do - 2..total - |> Enum.to_list - |> Enum.map(&Task.async(fn -> - params = options[:params] ++ [page: &1] - HTTPoison.get(url, headers, options ++ [params: params]) - end)) - |> Enum.map(&Task.await(&1, 10000)) - |> Enum.map(&handle_page_response/1) - end - - defp handle_page_response({:ok, %{body: body}}), do: Poison.decode!(body) - - def retrieve_total_pages(headers) do - case headers |> List.keyfind("Link", 0, nil) do - nil -> 1 - {"Link", value} -> value |> extract_total_pages - end - end - - defp extract_total_pages(links_string) do - # We use regex to parse the pagination info from the GitHub API response - # headers. - # - # The headers render pages in the following format: - # - # ``` - # {"Link", '; rel="next", - # ; rel="last", - # ; rel="first", - # ; rel="prev"' - # ``` - # - # If the response has no list header, then we have received all the records - # from the only possible page. - # - # If the response has a list header, the value will contain at least the - # "last" relation. - links_string - |> String.split(", ") - |> Enum.map(fn link -> - rel = get_rel(link) - page = get_page(link) - {rel, page} - end) - |> Enum.into(%{}) - |> Map.get("last") - end - - defp get_rel(link) do - # Searches for `rel=` - Regex.run(~r{rel="([a-z]+)"}, link) |> List.last() - end - - defp get_page(link) do - # Searches for the following variations: - # ``` - # ?page={match}> - # ?page={match}&... - # &page={match}> - # &page={match}&... - # ``` - Regex.run(~r{[&/?]page=([^>&]+)}, link) |> List.last |> String.to_integer - end -end diff --git a/lib/code_corps/github/api/gateway.ex b/lib/code_corps/github/api/gateway.ex new file mode 100644 index 000000000..d3d0c8c67 --- /dev/null +++ b/lib/code_corps/github/api/gateway.ex @@ -0,0 +1,16 @@ +defmodule CodeCorps.GitHub.API.Gateway do + @moduledoc ~S""" + The gate through which all communication with the GitHub API must go through. + + The purpose of this module is to centralize the most basic GitHub API request, + so the module can be injected into tests easily, giving full control to what + the tested response is. + """ + + alias CodeCorps.GitHub + + @spec request(GitHub.method, String.t, GitHub.body, GitHub.headers, list) :: GitHub.response + def request(method, url, body, headers, options) do + HTTPoison.request(method, url, body, headers, options) + end +end diff --git a/lib/code_corps/github/api/issue.ex b/lib/code_corps/github/api/issue.ex index 864fb47c8..fee9a5991 100644 --- a/lib/code_corps/github/api/issue.ex +++ b/lib/code_corps/github/api/issue.ex @@ -41,7 +41,7 @@ defmodule CodeCorps.GitHub.API.Issue do attrs = task |> GitHub.Adapters.Issue.to_api with opts when is_list(opts) <- GitHub.API.opts_for(user, installation) do - GitHub.request(:post, endpoint, %{}, attrs, opts) + GitHub.request(:post, endpoint, attrs, %{}, opts) else {:error, github_error} -> {:error, github_error} end @@ -63,7 +63,7 @@ defmodule CodeCorps.GitHub.API.Issue do attrs = task |> GitHub.Adapters.Issue.to_api with opts when is_list(opts) <- GitHub.API.opts_for(user, installation) do - GitHub.request(:patch, endpoint, %{}, attrs, opts) + GitHub.request(:patch, endpoint, attrs, %{}, opts) else {:error, github_error} -> {:error, github_error} end diff --git a/lib/code_corps/github/api/pagination.ex b/lib/code_corps/github/api/pagination.ex new file mode 100644 index 000000000..85d52c345 --- /dev/null +++ b/lib/code_corps/github/api/pagination.ex @@ -0,0 +1,92 @@ +defmodule CodeCorps.GitHub.API.Pagination do + @moduledoc ~S""" + Used to parse and build pagination data when fetching multiple pages from the GitHub API + """ + + @doc ~S""" + Parses a collection of response headers and determines the record page count for a GitHub endpoint. + + The response the headers are retrieved from is usually generated using a + `:head` request. + + The value of a "Link" header is used to determine the page count. + + If the "Link" header is not present in the collection, the count is assumed 1 + + If the "Link" header is present, we use regex to parse the pagination info + from its value. + + The format of the header is as follows: + + ``` + {"Link", '; rel="next", + ; rel="last", + ; rel="first", + ; rel="prev"' + ``` + + The page count is determind by locating the `rel="last"` url and extracting + the `page` query parameter from it. + """ + @spec retrieve_total_pages(list) :: integer + def retrieve_total_pages(headers) do + headers + |> List.keyfind("Link", 0, nil) + |> extract_total_pages + end + + @spec extract_total_pages(nil | String.t) :: integer + defp extract_total_pages(nil), do: 1 + defp extract_total_pages({"Link", value} = _header) do + value + |> String.split(", ") + |> Enum.map(fn link -> + rel = get_rel(link) + page = get_page(link) + {rel, page} + end) + |> Enum.into(%{}) + |> Map.get("last") + end + + @spec get_rel(String.t) :: String.t + defp get_rel(link) when is_binary(link) do + # Searches for `rel=` + Regex.run(~r{rel="([a-z]+)"}, link) |> List.last() + end + + @spec get_page(String.t) :: integer + defp get_page(link) when is_binary(link) do + # Searches for the following variations: + # ``` + # ?page={match}> + # ?page={match}&... + # &page={match}> + # &page={match}&... + # ``` + Regex.run(~r{[&/?]page=([^>&]+)}, link) |> List.last |> String.to_integer + end + + @doc ~S""" + From the specified page count, generates a list of integers, `1..count` + """ + @spec to_page_numbers(integer) :: list(integer) + def to_page_numbers(total) when is_integer(total), do: 1..total + + @doc ~S""" + Adds a `page` query parameter to an `options` `Keyword` list. + + For `HTTPPoison`, query parameters go under the `params` key of the `options` + argument, so this function also ensures the `params` key is present. + """ + @spec add_page_param(Keyword.t, integer) :: Keyword.t + def add_page_param(options, page) when is_list(options) when is_integer(page) do + params = + options + |> Keyword.get(:params, []) + |> Keyword.put(:page, page) + + options + |> Keyword.put(:params, params) + end +end diff --git a/lib/code_corps/github/api/user.ex b/lib/code_corps/github/api/user.ex index 5b226aa4d..2b97b352e 100644 --- a/lib/code_corps/github/api/user.ex +++ b/lib/code_corps/github/api/user.ex @@ -4,7 +4,7 @@ defmodule CodeCorps.GitHub.API.User do """ alias CodeCorps.{Accounts, GitHub, User} - alias Ecto.{Changeset} + alias Ecto.Changeset @single_endpoint "user" diff --git a/lib/code_corps/github/event/installation/matched_user.ex b/lib/code_corps/github/event/installation/matched_user.ex index 0dfd17b50..01122fdce 100644 --- a/lib/code_corps/github/event/installation/matched_user.ex +++ b/lib/code_corps/github/event/installation/matched_user.ex @@ -12,7 +12,7 @@ defmodule CodeCorps.GitHub.Event.Installation.MatchedUser do User } - @typep process_outcome :: {:ok, GithubAppInstallation.t} | {:error, Changeset.t} + @typep process_outcome :: {:ok, GithubAppInstallation.t} | {:error, Ecto.Changeset.t} @type outcome :: process_outcome | {:error, :too_many_unprocessed_installations} @doc """ diff --git a/lib/code_corps/github/event/installation/unmatched_user.ex b/lib/code_corps/github/event/installation/unmatched_user.ex index b99669cb4..e6441e8e3 100644 --- a/lib/code_corps/github/event/installation/unmatched_user.ex +++ b/lib/code_corps/github/event/installation/unmatched_user.ex @@ -9,7 +9,7 @@ defmodule CodeCorps.GitHub.Event.Installation.UnmatchedUser do Repo } - @typep process_outcome :: {:ok, GithubAppInstallation.t} | {:error, Changeset.t} + @typep process_outcome :: {:ok, GithubAppInstallation.t} | {:error, Ecto.Changeset.t} @type outcome :: process_outcome | {:error, :unexpected_installation_payload} @doc ~S""" @@ -41,14 +41,14 @@ defmodule CodeCorps.GitHub.Event.Installation.UnmatchedUser do end defp find_installation(_), do: :unexpected_installation_payload - @spec create_installation(map) :: {:ok, GithubAppInstallation.t} | {:error, Changeset.t} + @spec create_installation(map) :: {:ok, GithubAppInstallation.t} | {:error, Ecto.Changeset.t} defp create_installation(%{} = payload) do %GithubAppInstallation{} |> ChangesetBuilder.build_changeset(payload) |> Repo.insert() end - @spec update_installation(GithubAppInstallation.t, map) :: {:ok, GithubAppInstallation.t} | {:error, Changeset.t} + @spec update_installation(GithubAppInstallation.t, map) :: {:ok, GithubAppInstallation.t} | {:error, Ecto.Changeset.t} defp update_installation(%GithubAppInstallation{} = installation, %{} = payload) do installation |> ChangesetBuilder.build_changeset(payload) diff --git a/lib/code_corps/github/github.ex b/lib/code_corps/github/github.ex index 8994ff705..e92ef2e3d 100644 --- a/lib/code_corps/github/github.ex +++ b/lib/code_corps/github/github.ex @@ -1,5 +1,8 @@ defmodule CodeCorps.GitHub do - alias CodeCorps.GitHub.API.Headers + alias CodeCorps.GitHub.{ + API, + API.Headers + } defmodule APIErrorObject do @moduledoc """ @@ -82,7 +85,7 @@ defmodule CodeCorps.GitHub do end - @type method :: :get | :post | :put | :delete | :patch + @type method :: :get | :post | :put | :delete | :patch | :head @type body :: {:multipart, list} | map @type headers :: %{String.t => String.t} | %{} @@ -92,15 +95,16 @@ defmodule CodeCorps.GitHub do @doc """ A low level utility function to make a direct request to the GitHub API. """ - @spec request(method, String.t, headers, body, list) :: response - def request(method, endpoint, headers, body, options) do + @spec request(method, String.t, body, headers, list) :: response + def request(method, endpoint, body, headers, options) do with {:ok, encoded_body} <- body |> Poison.encode do - api().request( + API.request( method, api_url_for(endpoint), - headers |> Headers.user_request(options), encoded_body, - options |> add_default_options()) + headers |> Headers.user_request(options), + options + ) else _ -> {:error, HTTPClientError.new(reason: :body_encoding_error)} end @@ -110,25 +114,26 @@ defmodule CodeCorps.GitHub do A low level utility function to make an authenticated request to the GitHub API on behalf of a GitHub App or integration """ - @spec integration_request(method, String.t, headers, body, list) :: response - def integration_request(method, endpoint, headers, body, options) do + @spec integration_request(method, String.t, body, headers, list) :: response + def integration_request(method, endpoint, body, headers, options) do with {:ok, encoded_body} <- body |> Poison.encode do - api().request( + API.request( method, api_url_for(endpoint), - headers |> Headers.integration_request, encoded_body, - options |> add_default_options()) + headers |> Headers.integration_request, + options + ) else _ -> {:error, HTTPClientError.new(reason: :body_encoding_error)} end end def get_all(endpoint, headers, options) do - api().get_all( + API.get_all( api_url_for(endpoint), headers |> Headers.user_request(options), - options |> add_default_options() + options ) end @@ -140,20 +145,18 @@ defmodule CodeCorps.GitHub do @spec user_access_token_request(String.t, String.t) :: response def user_access_token_request(code, state) do with {:ok, encoded_body} <- code |> build_access_token_params(state) |> Poison.encode do - api().request( + API.request( :post, @token_url, - Headers.access_token_request, encoded_body, - [] |> add_default_options()) + Headers.access_token_request, + [] + ) else _ -> {:error, HTTPClientError.new(reason: :body_encoding_error)} end end - @spec api :: module - defp api, do: Application.get_env(:code_corps, :github) - @api_url "https://api.github.com/" @spec api_url_for(String.t) :: String.t @@ -161,11 +164,6 @@ defmodule CodeCorps.GitHub do @api_url |> URI.merge(endpoint) |> URI.to_string end - @spec add_default_options(list) :: list - defp add_default_options(opts) do - [:with_body | opts] - end - @spec build_access_token_params(String.t, String.t) :: map defp build_access_token_params(code, state) do %{ diff --git a/lib/code_corps/github/sync/comment/comment.ex b/lib/code_corps/github/sync/comment/comment.ex index 07bf3bd30..d555996d4 100644 --- a/lib/code_corps/github/sync/comment/comment.ex +++ b/lib/code_corps/github/sync/comment/comment.ex @@ -1,7 +1,8 @@ defmodule CodeCorps.GitHub.Sync.Comment do alias CodeCorps.{ GitHub, - GithubComment + GithubComment, + GithubIssue } alias GitHub.Sync.Comment.Comment, as: CommentCommentSyncer alias GitHub.Sync.Comment.GithubComment, as: CommentGithubCommentSyncer diff --git a/lib/code_corps/github/sync/pull_request/github_pull_request/github_pull_request.ex b/lib/code_corps/github/sync/pull_request/github_pull_request/github_pull_request.ex index b0ab39b18..6b6ff7c32 100644 --- a/lib/code_corps/github/sync/pull_request/github_pull_request/github_pull_request.ex +++ b/lib/code_corps/github/sync/pull_request/github_pull_request/github_pull_request.ex @@ -8,6 +8,7 @@ defmodule CodeCorps.GitHub.Sync.PullRequest.GithubPullRequest do alias CodeCorps.{ GitHub.Adapters, + GithubIssue, GithubPullRequest, GithubRepo, Repo diff --git a/lib/code_corps/github/sync/pull_request/pull_request.ex b/lib/code_corps/github/sync/pull_request/pull_request.ex index e5212043b..23f13557a 100644 --- a/lib/code_corps/github/sync/pull_request/pull_request.ex +++ b/lib/code_corps/github/sync/pull_request/pull_request.ex @@ -1,4 +1,5 @@ defmodule CodeCorps.GitHub.Sync.PullRequest do + alias CodeCorps.{GithubIssue, GithubRepo} alias CodeCorps.GitHub.Sync.PullRequest.GithubPullRequest, as: GithubPullRequestSyncer alias Ecto.Multi diff --git a/lib/code_corps/model/github_comment.ex b/lib/code_corps/model/github_comment.ex index 39332a9eb..cc7062ad1 100644 --- a/lib/code_corps/model/github_comment.ex +++ b/lib/code_corps/model/github_comment.ex @@ -3,6 +3,8 @@ defmodule CodeCorps.GithubComment do alias Ecto.Changeset + @type t :: %__MODULE__{} + schema "github_comments" do field :body, :string field :github_created_at, :utc_datetime diff --git a/lib/code_corps/model/github_issue.ex b/lib/code_corps/model/github_issue.ex index 9800790db..b647ddcd8 100644 --- a/lib/code_corps/model/github_issue.ex +++ b/lib/code_corps/model/github_issue.ex @@ -2,6 +2,8 @@ defmodule CodeCorps.GithubIssue do use Ecto.Schema import Ecto.Changeset + @type t :: %__MODULE__{} + schema "github_issues" do field :body, :string field :closed_at, :utc_datetime diff --git a/lib/code_corps/model/github_pull_request.ex b/lib/code_corps/model/github_pull_request.ex index 7a152e730..90d4b2f46 100644 --- a/lib/code_corps/model/github_pull_request.ex +++ b/lib/code_corps/model/github_pull_request.ex @@ -2,6 +2,8 @@ defmodule CodeCorps.GithubPullRequest do use Ecto.Schema import Ecto.Changeset + @type t :: %__MODULE__{} + schema "github_pull_requests" do field :additions, :integer field :body, :string diff --git a/lib/code_corps/task/query.ex b/lib/code_corps/task/query.ex index 82bb02510..9b80b970e 100644 --- a/lib/code_corps/task/query.ex +++ b/lib/code_corps/task/query.ex @@ -7,7 +7,7 @@ defmodule CodeCorps.Task.Query do import Ecto.Query import ScoutApm.Tracing - alias CodeCorps.{Helpers, Task, Repo} + alias CodeCorps.{Helpers, Project, Task, Repo} alias Ecto.Queryable @doc ~S""" diff --git a/mix.lock b/mix.lock index 69aadfb2b..bc9376f7c 100644 --- a/mix.lock +++ b/mix.lock @@ -1,12 +1,12 @@ -%{"approximate_histogram": {:hex, :approximate_histogram, "0.1.1", "198eb36681e763ed4baab6ca0682acec4ef642f60ba272f251d3059052f4f378", [], [], "hexpm"}, +%{"approximate_histogram": {:hex, :approximate_histogram, "0.1.1", "198eb36681e763ed4baab6ca0682acec4ef642f60ba272f251d3059052f4f378", [:mix], []}, "bamboo": {:hex, :bamboo, "0.8.0", "573889a3efcb906bb9d25a1c4caa4ca22f479235e1b8cc3260d8b88dabeb4b14", [:mix], [{:hackney, "~> 1.6", [hex: :hackney, optional: false]}, {:plug, "~> 1.0", [hex: :plug, optional: false]}, {:poison, ">= 1.5.0", [hex: :poison, optional: false]}]}, "bamboo_postmark": {:hex, :bamboo_postmark, "0.4.1", "2ec8fad4d221944f5169ea4346e6e1aef3578282c352c9f7184306d872aa1c26", [:mix], [{:bamboo, "~> 0.5", [hex: :bamboo, optional: false]}, {:hackney, "~> 1.6", [hex: :hackney, optional: false]}, {:plug, "~> 1.0", [hex: :plug, optional: false]}, {:poison, ">= 1.5.0", [hex: :poison, optional: false]}]}, "base64url": {:hex, :base64url, "0.0.1", "36a90125f5948e3afd7be97662a1504b934dd5dac78451ca6e9abf85a10286be", [], []}, "benchfella": {:hex, :benchfella, "0.3.5", "b2122c234117b3f91ed7b43b6e915e19e1ab216971154acd0a80ce0e9b8c05f5", [:mix], []}, "bunt": {:hex, :bunt, "0.2.0", "951c6e801e8b1d2cbe58ebbd3e616a869061ddadcc4863d0a2182541acae9a38", [:mix], []}, "bypass": {:hex, :bypass, "0.8.1", "16d409e05530ece4a72fabcf021a3e5c7e15dcc77f911423196a0c551f2a15ca", [:mix], [{:cowboy, "~> 1.0", [hex: :cowboy, optional: false]}, {:plug, "~> 1.0", [hex: :plug, optional: false]}]}, - "certifi": {:hex, :certifi, "2.0.0", "a0c0e475107135f76b8c1d5bc7efb33cd3815cb3cf3dea7aefdd174dabead064", [:rebar3], [], "hexpm"}, - "cloudex": {:hex, :cloudex, "0.2.2", "da554dab88672163346a1614917df2a27ae82d07e956ee31de758f0b04c163bf", [:mix], [{:httpoison, "~> 0.13.0", [repo: "hexpm", hex: :httpoison, optional: false]}, {:poison, "~> 3.1.0", [repo: "hexpm", hex: :poison, optional: false]}, {:timex, "~> 3.1.7", [repo: "hexpm", hex: :timex, optional: false]}, {:tzdata, "~> 0.5.11", [repo: "hexpm", hex: :tzdata, optional: false]}], "hexpm"}, + "certifi": {:hex, :certifi, "2.0.0", "a0c0e475107135f76b8c1d5bc7efb33cd3815cb3cf3dea7aefdd174dabead064", [:rebar3], []}, + "cloudex": {:hex, :cloudex, "0.2.2", "da554dab88672163346a1614917df2a27ae82d07e956ee31de758f0b04c163bf", [:mix], [{:httpoison, "~> 0.13.0", [hex: :httpoison, optional: false]}, {:poison, "~> 3.1.0", [hex: :poison, optional: false]}, {:timex, "~> 3.1.7", [hex: :timex, optional: false]}, {:tzdata, "~> 0.5.11", [hex: :tzdata, optional: false]}]}, "combine": {:hex, :combine, "0.10.0", "eff8224eeb56498a2af13011d142c5e7997a80c8f5b97c499f84c841032e429f", [:mix], []}, "comeonin": {:hex, :comeonin, "3.2.0", "cb10995a22aed6812667efb3856f548818c85d85394d8132bc116fbd6995c1ef", [:make, :mix], [{:elixir_make, "~> 0.4", [hex: :elixir_make, optional: false]}]}, "connection": {:hex, :connection, "1.0.4", "a1cae72211f0eef17705aaededacac3eb30e6625b04a6117c1b2db6ace7d5976", [], []}, @@ -29,9 +29,9 @@ "fs": {:hex, :fs, "0.9.2", "ed17036c26c3f70ac49781ed9220a50c36775c6ca2cf8182d123b6566e49ec59", [:rebar], []}, "gettext": {:hex, :gettext, "0.13.1", "5e0daf4e7636d771c4c71ad5f3f53ba09a9ae5c250e1ab9c42ba9edccc476263", [:mix], []}, "guardian": {:hex, :guardian, "0.14.5", "6d4e89b673accdacbc092ad000dc7494019426bd898eebf699caf1d19000cdcd", [:mix], [{:jose, "~> 1.8", [hex: :jose, optional: false]}, {:phoenix, "~> 1.2 and < 1.4.0", [hex: :phoenix, optional: true]}, {:plug, "~> 1.3", [hex: :plug, optional: false]}, {:poison, ">= 1.3.0 and < 4.0.0", [hex: :poison, optional: false]}, {:uuid, ">=1.1.1", [hex: :uuid, optional: false]}]}, - "hackney": {:hex, :hackney, "1.10.1", "c38d0ca52ea80254936a32c45bb7eb414e7a96a521b4ce76d00a69753b157f21", [:rebar3], [{:certifi, "2.0.0", [repo: "hexpm", hex: :certifi, optional: false]}, {:idna, "5.1.0", [repo: "hexpm", hex: :idna, optional: false]}, {:metrics, "1.0.1", [repo: "hexpm", hex: :metrics, optional: false]}, {:mimerl, "1.0.2", [repo: "hexpm", hex: :mimerl, optional: false]}, {:ssl_verify_fun, "1.1.1", [repo: "hexpm", hex: :ssl_verify_fun, optional: false]}], "hexpm"}, - "httpoison": {:hex, :httpoison, "0.13.0", "bfaf44d9f133a6599886720f3937a7699466d23bb0cd7a88b6ba011f53c6f562", [:mix], [{:hackney, "~> 1.8", [repo: "hexpm", hex: :hackney, optional: false]}], "hexpm"}, - "idna": {:hex, :idna, "5.1.0", "d72b4effeb324ad5da3cab1767cb16b17939004e789d8c0ad5b70f3cea20c89a", [:rebar3], [{:unicode_util_compat, "0.3.1", [repo: "hexpm", hex: :unicode_util_compat, optional: false]}], "hexpm"}, + "hackney": {:hex, :hackney, "1.10.1", "c38d0ca52ea80254936a32c45bb7eb414e7a96a521b4ce76d00a69753b157f21", [:rebar3], [{:certifi, "2.0.0", [hex: :certifi, optional: false]}, {:idna, "5.1.0", [hex: :idna, optional: false]}, {:metrics, "1.0.1", [hex: :metrics, optional: false]}, {:mimerl, "1.0.2", [hex: :mimerl, optional: false]}, {:ssl_verify_fun, "1.1.1", [hex: :ssl_verify_fun, optional: false]}]}, + "httpoison": {:hex, :httpoison, "0.13.0", "bfaf44d9f133a6599886720f3937a7699466d23bb0cd7a88b6ba011f53c6f562", [:mix], [{:hackney, "~> 1.8", [hex: :hackney, optional: false]}]}, + "idna": {:hex, :idna, "5.1.0", "d72b4effeb324ad5da3cab1767cb16b17939004e789d8c0ad5b70f3cea20c89a", [:rebar3], [{:unicode_util_compat, "0.3.1", [hex: :unicode_util_compat, optional: false]}]}, "inch_ex": {:hex, :inch_ex, "0.5.6", "418357418a553baa6d04eccd1b44171936817db61f4c0840112b420b8e378e67", [:mix], [{:poison, "~> 1.5 or ~> 2.0 or ~> 3.0", [hex: :poison, optional: false]}]}, "inflex": {:hex, :inflex, "1.8.1", "9fa9684ff1a872eab7415c0be500cc1b7782f28da6ed75423081e75f92831b1c", [:mix], []}, "ja_serializer": {:hex, :ja_serializer, "0.12.0", "ba4ec5fc7afa6daba815b5cb2b9bd0de410554ac4f0ed54e954d39decb353ca4", [:mix], [{:inflex, "~> 1.4", [hex: :inflex, optional: false]}, {:plug, "> 1.0.0", [hex: :plug, optional: false]}, {:poison, ">= 1.4.0", [hex: :poison, optional: false]}, {:scrivener, "~> 1.2 or ~> 2.0", [hex: :scrivener, optional: true]}]}, @@ -53,7 +53,7 @@ "poolboy": {:hex, :poolboy, "1.5.1", "6b46163901cfd0a1b43d692657ed9d7e599853b3b21b95ae5ae0a777cf9b6ca8", [], []}, "postgrex": {:hex, :postgrex, "0.13.3", "c277cfb2a9c5034d445a722494c13359e361d344ef6f25d604c2353185682bfc", [:mix], [{:connection, "~> 1.0", [hex: :connection, optional: false]}, {:db_connection, "~> 1.1", [hex: :db_connection, optional: false]}, {:decimal, "~> 1.0", [hex: :decimal, optional: false]}]}, "ranch": {:hex, :ranch, "1.3.2", "e4965a144dc9fbe70e5c077c65e73c57165416a901bd02ea899cfd95aa890986", [:rebar3], []}, - "scout_apm": {:hex, :scout_apm, "0.3.3", "8679378b624b502d7f6e8a1b023b57f4c7ab717380291e2b40ccdb2923457194", [], [{:approximate_histogram, "~>0.1.1", [hex: :approximate_histogram, repo: "hexpm", optional: false]}, {:hackney, "~> 1.0", [hex: :hackney, repo: "hexpm", optional: false]}, {:plug, "~>1.0", [hex: :plug, repo: "hexpm", optional: false]}, {:poison, ">= 0.0.0", [hex: :poison, repo: "hexpm", optional: false]}], "hexpm"}, + "scout_apm": {:hex, :scout_apm, "0.3.3", "8679378b624b502d7f6e8a1b023b57f4c7ab717380291e2b40ccdb2923457194", [:mix], [{:approximate_histogram, "~>0.1.1", [hex: :approximate_histogram, optional: false]}, {:hackney, "~> 1.0", [hex: :hackney, optional: false]}, {:plug, "~>1.0", [hex: :plug, optional: false]}, {:poison, ">= 0.0.0", [hex: :poison, optional: false]}]}, "scrivener": {:hex, :scrivener, "2.3.0", "16b1d744202d47233798205447b35592d96a209241c566304f84ddef63c718b2", [:mix], []}, "scrivener_ecto": {:hex, :scrivener_ecto, "1.2.3", "3255aee5cabfccedcb350f7e5f9f540fb72b8705a763612399264b11ae34faa9", [:mix], [{:ecto, "~> 2.0", [hex: :ecto, optional: false]}, {:postgrex, "~> 0.11.0 or ~> 0.12.0 or ~> 0.13.0", [hex: :postgrex, optional: true]}, {:scrivener, "~> 2.3", [hex: :scrivener, optional: false]}]}, "segment": {:hex, :segment, "0.1.1", "47bf9191590e7a533c105d1e21518e0d6da47c91e8d98ebb649c624db5dfc359", [:mix], [{:httpoison, "~> 0.8", [hex: :httpoison, optional: false]}, {:poison, "~> 1.3 or ~> 2.0", [hex: :poison, optional: false]}]}, diff --git a/priv/repo/structure.sql b/priv/repo/structure.sql index 551f8fb5f..e3ca24a60 100644 --- a/priv/repo/structure.sql +++ b/priv/repo/structure.sql @@ -2,7 +2,7 @@ -- PostgreSQL database dump -- --- Dumped from database version 9.5.9 +-- Dumped from database version 10.0 -- Dumped by pg_dump version 10.0 SET statement_timeout = 0; @@ -3681,5 +3681,5 @@ ALTER TABLE ONLY user_tasks -- PostgreSQL database dump complete -- -INSERT INTO "schema_migrations" (version) VALUES (20160723215749), (20160804000000), (20160804001111), (20160805132301), (20160805203929), (20160808143454), (20160809214736), (20160810124357), (20160815125009), (20160815143002), (20160816020347), (20160816034021), (20160817220118), (20160818000944), (20160818132546), (20160820113856), (20160820164905), (20160822002438), (20160822004056), (20160822011624), (20160822020401), (20160822044612), (20160830081224), (20160830224802), (20160911233738), (20160912002705), (20160912145957), (20160918003206), (20160928232404), (20161003185918), (20161019090945), (20161019110737), (20161020144622), (20161021131026), (20161031001615), (20161121005339), (20161121014050), (20161121043941), (20161121045709), (20161122015942), (20161123081114), (20161123150943), (20161124085742), (20161125200620), (20161126045705), (20161127054559), (20161205024856), (20161207112519), (20161209192504), (20161212005641), (20161214005935), (20161215052051), (20161216051447), (20161218005913), (20161219160401), (20161219163909), (20161220141753), (20161221085759), (20161226213600), (20161231063614), (20170102130055), (20170102181053), (20170104113708), (20170104212623), (20170104235423), (20170106013143), (20170115035159), (20170115230549), (20170121014100), (20170131234029), (20170201014901), (20170201025454), (20170201035458), (20170201183258), (20170220032224), (20170224233516), (20170226050552), (20170228085250), (20170308214128), (20170308220713), (20170308222552), (20170313130611), (20170318032449), (20170318082740), (20170324194827), (20170424215355), (20170501225441), (20170505224222), (20170526095401), (20170602000208), (20170622205732), (20170626231059), (20170628092119), (20170628213609), (20170629183404), (20170630140136), (20170706132431), (20170707213648), (20170711122252), (20170717092127), (20170725060612), (20170727052644), (20170731130121), (20170814131722), (20170913114958), (20170921014405), (20170925214512), (20170925230419), (20170926134646), (20170927100300), (20170928234412), (20171003134956), (20171003225853), (20171006063358), (20171006161407), (20171012215106), (20171012221231), (20171016125229), (20171016125516), (20171016223356), (20171016235656), (20171017235433), (20171019191035), (20171025184225), (20171026010933), (20171027061833); +INSERT INTO "schema_migrations" (version) VALUES (20160723215749), (20160804000000), (20160804001111), (20160805132301), (20160805203929), (20160808143454), (20160809214736), (20160810124357), (20160815125009), (20160815143002), (20160816020347), (20160816034021), (20160817220118), (20160818000944), (20160818132546), (20160820113856), (20160820164905), (20160822002438), (20160822004056), (20160822011624), (20160822020401), (20160822044612), (20160830081224), (20160830224802), (20160911233738), (20160912002705), (20160912145957), (20160918003206), (20160928232404), (20161003185918), (20161019090945), (20161019110737), (20161020144622), (20161021131026), (20161031001615), (20161121005339), (20161121014050), (20161121043941), (20161121045709), (20161122015942), (20161123081114), (20161123150943), (20161124085742), (20161125200620), (20161126045705), (20161127054559), (20161205024856), (20161207112519), (20161209192504), (20161212005641), (20161214005935), (20161215052051), (20161216051447), (20161218005913), (20161219160401), (20161219163909), (20161220141753), (20161221085759), (20161226213600), (20161231063614), (20170102130055), (20170102181053), (20170104113708), (20170104212623), (20170104235423), (20170106013143), (20170115035159), (20170115230549), (20170121014100), (20170131234029), (20170201014901), (20170201025454), (20170201035458), (20170201183258), (20170220032224), (20170224233516), (20170226050552), (20170228085250), (20170308214128), (20170308220713), (20170308222552), (20170313130611), (20170318032449), (20170318082740), (20170324194827), (20170424215355), (20170501225441), (20170505224222), (20170526095401), (20170602000208), (20170622205732), (20170626231059), (20170628092119), (20170628213609), (20170629183404), (20170630140136), (20170706132431), (20170707213648), (20170711122252), (20170717092127), (20170725060612), (20170727052644), (20170731130121), (20170814131722), (20170913114958), (20170921014405), (20170925214512), (20170925230419), (20170926134646), (20170927100300), (20170928234412), (20171003134956), (20171003225853), (20171006063358), (20171006161407), (20171012215106), (20171012221231), (20171016125229), (20171016125516), (20171016223356), (20171016235656), (20171017235433), (20171019191035), (20171025184225), (20171026010933), (20171027061833), (20171028011642), (20171028173508); diff --git a/test/lib/code_corps/comment/service_test.exs b/test/lib/code_corps/comment/service_test.exs index 678d2d29e..f8c0163b2 100644 --- a/test/lib/code_corps/comment/service_test.exs +++ b/test/lib/code_corps/comment/service_test.exs @@ -26,7 +26,7 @@ defmodule CodeCorps.Comment.ServiceTest do assert comment.markdown == @base_attrs["markdown"] assert comment.body - refute_received({:post, _string, {}, "{}", []}) + refute_received({:post, "https://api.github.com/" <> _rest, _body, _headers, _options}) end test "returns errored changeset if attributes are invalid" do @@ -34,7 +34,7 @@ defmodule CodeCorps.Comment.ServiceTest do refute changeset.valid? refute Repo.one(Comment) - refute_received({:post, _string, _headers, _body, _options}) + refute_received({:post, "https://api.github.com/" <> _rest, _body, _headers, _options}) end test "if comment is assigned a github repo, creates github comment on assigned issue" do @@ -54,7 +54,7 @@ defmodule CodeCorps.Comment.ServiceTest do assert comment.github_comment_id assert Repo.one(GithubComment) - assert_received({:post, "https://api.github.com/repos/foo/bar/issues/5/comments", _headers, _body, _options}) + assert_received({:post, "https://api.github.com/repos/foo/bar/issues/5/comments", _body, _headers, _options}) end test "if github process fails, returns {:error, :github}" do @@ -73,7 +73,7 @@ defmodule CodeCorps.Comment.ServiceTest do refute Repo.one(Comment) refute Repo.one(GithubComment) - assert_received({:post, "https://api.github.com/repos/foo/bar/issues/5/comments", _headers, _body, _options}) + assert_received({:post, "https://api.github.com/repos/foo/bar/issues/5/comments", _body, _headers, _options}) end end @@ -89,7 +89,7 @@ defmodule CodeCorps.Comment.ServiceTest do assert updated_comment.body != comment.body refute updated_comment.github_comment_id - refute_received({:post, _string, {}, "{}", []}) + refute_received({:patch, "https://api.github.com/" <> _rest, _body, _headers, _options}) end @preloads [task: [github_repo: :github_app_installation]] @@ -110,7 +110,7 @@ defmodule CodeCorps.Comment.ServiceTest do assert updated_comment.body != comment.body assert updated_comment.github_comment_id == github_comment.id - assert_received({:patch, "https://api.github.com/repos/foo/bar/issues/comments/6", _headers, _body, _options}) + assert_received({:patch, "https://api.github.com/repos/foo/bar/issues/comments/6", _body, _headers, _options}) end test "reports {:error, :github}, makes no changes at all if there is a github api error" do @@ -133,7 +133,7 @@ defmodule CodeCorps.Comment.ServiceTest do assert updated_comment.body == comment.body assert updated_comment.github_comment_id == github_comment.id - assert_received({:patch, "https://api.github.com/repos/foo/bar/issues/comments/6", _headers, _body, _options}) + assert_received({:patch, "https://api.github.com/repos/foo/bar/issues/comments/6", _body, _headers, _options}) end end end diff --git a/test/lib/code_corps/github/api/api_test.exs b/test/lib/code_corps/github/api/api_test.exs index e3af6a578..6b96a954d 100644 --- a/test/lib/code_corps/github/api/api_test.exs +++ b/test/lib/code_corps/github/api/api_test.exs @@ -4,87 +4,122 @@ defmodule CodeCorps.GitHub.APITest do use ExUnit.Case alias CodeCorps.GitHub.{API, APIError, HTTPClientError} - alias Plug.Conn - @port 12345 - @endpoint "http://localhost" |> URI.merge("") |> Map.put(:port, @port) |> URI.to_string - @body %{"bar" => "baz"} |> Poison.encode! + describe "request/5" do + defmodule MockAPI do + def request(_method, "/error", _body, _headers, _opts) do + {:error, %HTTPoison.Error{reason: "Intentional Test Error"}} + end + def request(_method, url, _body, _headers, _opts) do + response = + %HTTPoison.Response{} + |> Map.put(:body, url |> body()) + |> Map.put(:request_url, url) + |> Map.put(:status_code, url |> code) + + {:ok, response} + end + + defp body("/200"), do: %{"bar" => "baz"} |> Poison.encode! + defp body("/200-bad"), do: "bad" + defp body("/400"), do: %{"message" => "baz"} |> Poison.encode! + defp body("/400-bad"), do: "bad" + defp body("/404"), do: %{"message" => "Not Found"} |> Poison.encode! + + defp code("/200" <> _rest), do: 200 + defp code("/400" <> _rest), do: 400 + defp code("/404" <> _rest), do: 404 + end - defp url_for(path) do - URI.merge(@endpoint, path) |> URI.to_string - end + setup do + old_mock = Application.get_env(:code_corps, :github) + Application.put_env(:code_corps, :github, MockAPI) - setup do - bypass = Bypass.open(port: @port) - {:ok, bypass: bypass} - end + on_exit fn -> + Application.put_env(:code_corps, :github, old_mock) + end - describe "request/5" do - test "handles a 200..299 response", %{bypass: bypass} do - Bypass.expect(bypass, "GET", "/foo", fn %Conn{req_headers: headers} = conn -> - assert {"foo", "bar"} in headers - conn |> Conn.resp(200, @body) - end) - - {:ok, response} = API.request(:get, url_for("/foo"), [{"foo", "bar"}], @body, [:with_body]) - assert response == (@body |> Poison.decode!) + :ok end - test "handles a decode error for a 200..299 response", %{bypass: bypass} do - Bypass.expect(bypass, "GET", "/foo", fn %Conn{req_headers: headers} = conn -> - assert {"foo", "bar"} in headers - conn |> Conn.resp(200, "foo") - end) + test "handles a 200..299 response" do + {:ok, response} = API.request(:get, "/200", %{}, [], []) + assert response == %{"bar" => "baz"} + end - {:error, response} = API.request(:get, url_for("/foo"), [{"foo", "bar"}], @body, [:with_body]) + test "handles a decode error for a 200..299 response" do + {:error, response} = API.request(:get, "/200-bad", %{}, [], []) assert response == HTTPClientError.new([reason: :body_decoding_error]) end - test "handles a 404 response", %{bypass: bypass} do - Bypass.expect(bypass, "GET", "/foo", fn %Conn{req_headers: headers} = conn -> - assert {"foo", "bar"} in headers - conn |> Conn.resp(404, @body) - end) + test "handles a 404 response" do + {:error, response} = API.request(:get, "/404", %{}, [], []) + assert response == + APIError.new({404, %{"message" => "{\"message\":\"Not Found\"}"}}) + end - {:error, response} = API.request(:get, url_for("/foo"), [{"foo", "bar"}], @body, [:with_body]) - assert response == APIError.new({404, %{"message" => @body}}) + test "handles a 400 response" do + {:error, response} = API.request(:get, "/400", %{}, [], []) + assert response == APIError.new({400, %{"message" => "baz"}}) end - @generic_error %{"message" => "foo"} |> Poison.encode! + test "handles a decode error for a 400..599 response" do + {:error, response} = API.request(:get, "/400-bad", %{}, [], []) - test "handles a 400 response", %{bypass: bypass} do - Bypass.expect(bypass, "GET", "/foo", fn %Conn{req_headers: headers} = conn -> - assert {"foo", "bar"} in headers - conn |> Conn.resp(400, @generic_error) - end) + assert response == HTTPClientError.new([reason: :body_decoding_error]) + end - {:error, response} = API.request(:get, url_for("/foo"), [{"foo", "bar"}], @body, [:with_body]) - assert response == APIError.new({400, @generic_error |> Poison.decode!}) + test "handles a client error" do + {:error, %HTTPClientError{reason: reason}} = + API.request(:get, "/error", %{}, [], []) + + assert reason == "Intentional Test Error" end + end - test "handles a decode error for a 400..599 response", %{bypass: bypass} do - Bypass.expect(bypass, "GET", "/foo", fn %Conn{req_headers: headers} = conn -> - assert {"foo", "bar"} in headers - conn |> Conn.resp(400, "foo") - end) + describe "get_all/3" do + defmodule MockPaginationAPI do + def request(:head, "/one-page", _body, _headers, _opts) do + {:ok, %HTTPoison.Response{headers: [], status_code: 200}} + end + def request(:head, "/two-pages", _body, _headers, _opts) do + next = '; rel="next"' + last = '; rel="last"' + + headers = [{"Link", [next, last] |> Enum.join(", ")}] + {:ok, %HTTPoison.Response{headers: headers, status_code: 200}} + end + def request(:get, "/one-page", _body, _headers, [params: [page: 1]]) do + body = [1] |> Poison.encode! + {:ok, %HTTPoison.Response{body: body, status_code: 200}} + end + def request(:get, "/two-pages", _body, _headers, [params: [page: 1]]) do + body = [1, 2] |> Poison.encode! + {:ok, %HTTPoison.Response{body: body, status_code: 200}} + end + def request(:get, "/two-pages", _body, _headers, [params: [page: 2]]) do + body = [3] |> Poison.encode! + {:ok, %HTTPoison.Response{body: body, status_code: 200}} + end + end - {:error, response} = API.request(:get, url_for("/foo"), [{"foo", "bar"}], @body, [:with_body]) - assert response == HTTPClientError.new([reason: :body_decoding_error]) + setup do + old_mock = Application.get_env(:code_corps, :github) + Application.put_env(:code_corps, :github, MockPaginationAPI) + + on_exit fn -> + Application.put_env(:code_corps, :github, old_mock) + end + + :ok end - test "handles a network error", %{bypass: bypass} do - bypass |> Bypass.down - # bypass is simulating a connection timeout error, so we need to set a - # small value for hackney's request to avoid test hanging - {:error, %HTTPClientError{reason: reason}} = - API.request(:get, url_for("/foo"), [{"foo", "bar"}], @body, [:with_body, connect_timeout: 15]) - bypass |> Bypass.up - - # bypass wil localy throw a :connect_timeout when down, - # but it will be an _econnrefused on circle - # we just care that a client error is handled by creating the - # proper struct - assert reason in [:connect_timeout, :econnrefused] + test "works when there's just one page" do + assert [1] == API.get_all("/one-page", [], []) + end + + test "works with multiple pages" do + assert [1, 2, 3] == API.get_all("/two-pages", [], []) end end end diff --git a/test/lib/code_corps/github/api/comment_test.exs b/test/lib/code_corps/github/api/comment_test.exs index ae3240e6b..122b26d30 100644 --- a/test/lib/code_corps/github/api/comment_test.exs +++ b/test/lib/code_corps/github/api/comment_test.exs @@ -23,11 +23,11 @@ defmodule CodeCorps.GitHub.API.CommentTest do assert_received({ :post, "https://api.github.com/repos/foo/bar/issues/5/comments", + body, [ {"Accept", "application/vnd.github.machine-man-preview+json"}, {"Authorization", "token baz"} ], - body, _options }) @@ -46,11 +46,11 @@ defmodule CodeCorps.GitHub.API.CommentTest do assert_received({ :post, "https://api.github.com/repos/foo/bar/issues/5/comments", + body, [ {"Accept", "application/vnd.github.machine-man-preview+json"}, {"Authorization", "token" <> _tok} ], - body, _options }) @@ -71,11 +71,11 @@ defmodule CodeCorps.GitHub.API.CommentTest do assert_received({ :post, "https://api.github.com/repos/foo/bar/issues/5/comments", + body, [ {"Accept", "application/vnd.github.machine-man-preview+json"}, {"Authorization", "token" <> _tok} ], - body, _options }) @@ -98,11 +98,11 @@ defmodule CodeCorps.GitHub.API.CommentTest do assert_received({ :patch, "https://api.github.com/repos/foo/bar/issues/comments/6", + body, [ {"Accept", "application/vnd.github.machine-man-preview+json"}, {"Authorization", "token" <> _tok} ], - body, _options }) @@ -123,11 +123,11 @@ defmodule CodeCorps.GitHub.API.CommentTest do assert_received({ :patch, "https://api.github.com/repos/foo/bar/issues/comments/6", + body, [ {"Accept", "application/vnd.github.machine-man-preview+json"}, {"Authorization", "token" <> _tok} ], - body, _options }) @@ -150,11 +150,11 @@ defmodule CodeCorps.GitHub.API.CommentTest do assert_received({ :patch, "https://api.github.com/repos/foo/bar/issues/comments/6", + body, [ {"Accept", "application/vnd.github.machine-man-preview+json"}, {"Authorization", "token" <> _tok} ], - body, _options }) diff --git a/test/lib/code_corps/github/api/gateway_test.exs b/test/lib/code_corps/github/api/gateway_test.exs new file mode 100644 index 000000000..89ecdf949 --- /dev/null +++ b/test/lib/code_corps/github/api/gateway_test.exs @@ -0,0 +1,40 @@ +defmodule CodeCorps.GitHub.API.GatewayTest do + @moduledoc false + + use ExUnit.Case + + alias CodeCorps.GitHub.API.Gateway + + alias Plug.Conn + alias HTTPoison.Response + + @port 12345 + @endpoint "http://localhost" |> URI.merge("") |> Map.put(:port, @port) |> URI.to_string + @body %{"bar" => "baz"} |> Poison.encode! + @url @endpoint |> URI.merge("/foo") |> URI.to_string + + setup do + bypass = Bypass.open(port: @port) + {:ok, bypass: bypass} + end + + describe "request/5" do + [200, 201, 302, 401, 404, 500] |> Enum.each(fn code -> + @code code + + test "returns a HTTPoison.Response in case of #{code}", %{bypass: bypass} do + Bypass.expect(bypass, "GET", "/foo", fn %Conn{req_headers: req_headers} = conn -> + assert {"foo", "bar"} in req_headers + conn |> Conn.resp(@code, @body) + end) + + {:ok, %Response{} = response} = + Gateway.request(:get, @url, @body, [{"foo", "bar"}], []) + + assert response.body == @body + assert response.status_code == @code + assert response.request_url == @url + end + end) + end +end diff --git a/test/lib/code_corps/github/api/issue_test.exs b/test/lib/code_corps/github/api/issue_test.exs index 6ce1d938e..7e0c04824 100644 --- a/test/lib/code_corps/github/api/issue_test.exs +++ b/test/lib/code_corps/github/api/issue_test.exs @@ -19,11 +19,11 @@ defmodule CodeCorps.GitHub.API.IssueTest do assert_received({ :get, endpoint_url, + _body, [ {"Accept", "application/vnd.github.machine-man-preview+json"}, {"Authorization", "token" <> _tok} ], - _body, _options }) assert endpoint_url == url @@ -41,11 +41,11 @@ defmodule CodeCorps.GitHub.API.IssueTest do assert_received({ :post, "https://api.github.com/repos/foo/bar/issues", + body, [ {"Accept", "application/vnd.github.machine-man-preview+json"}, {"Authorization", "token baz"} ], - body, _options }) @@ -62,11 +62,11 @@ defmodule CodeCorps.GitHub.API.IssueTest do assert_received({ :post, "https://api.github.com/repos/foo/bar/issues", + body, [ {"Accept", "application/vnd.github.machine-man-preview+json"}, {"Authorization", "token" <> _tok} ], - body, _options }) @@ -85,11 +85,11 @@ defmodule CodeCorps.GitHub.API.IssueTest do assert_received({ :post, "https://api.github.com/repos/foo/bar/issues", + body, [ {"Accept", "application/vnd.github.machine-man-preview+json"}, {"Authorization", "token" <> _tok} ], - body, _options }) @@ -109,11 +109,11 @@ defmodule CodeCorps.GitHub.API.IssueTest do assert_received({ :patch, "https://api.github.com/repos/foo/bar/issues/5", + body, [ {"Accept", "application/vnd.github.machine-man-preview+json"}, {"Authorization", "token baz"} ], - body, _options }) @@ -131,11 +131,11 @@ defmodule CodeCorps.GitHub.API.IssueTest do assert_received({ :patch, "https://api.github.com/repos/foo/bar/issues/5", + body, [ {"Accept", "application/vnd.github.machine-man-preview+json"}, {"Authorization", "token" <> _tok} ], - body, _options }) @@ -155,11 +155,11 @@ defmodule CodeCorps.GitHub.API.IssueTest do assert_received({ :patch, "https://api.github.com/repos/foo/bar/issues/5", + body, [ {"Accept", "application/vnd.github.machine-man-preview+json"}, {"Authorization", "token" <> _tok} ], - body, _options }) diff --git a/test/lib/code_corps/github/api/pull_request_test.exs b/test/lib/code_corps/github/api/pull_request_test.exs index 1e25536d1..c427f72f9 100644 --- a/test/lib/code_corps/github/api/pull_request_test.exs +++ b/test/lib/code_corps/github/api/pull_request_test.exs @@ -16,11 +16,11 @@ defmodule CodeCorps.GitHub.API.PullRequestTest do assert_received({ :get, endpoint_url, + _body, [ {"Accept", "application/vnd.github.machine-man-preview+json"}, {"Authorization", "token" <> _tok} ], - _body, _options }) assert endpoint_url == url diff --git a/test/lib/code_corps/github/api/repository_test.exs b/test/lib/code_corps/github/api/repository_test.exs index 11abd5c62..d30aa27aa 100644 --- a/test/lib/code_corps/github/api/repository_test.exs +++ b/test/lib/code_corps/github/api/repository_test.exs @@ -20,15 +20,16 @@ defmodule CodeCorps.GitHub.API.RepositoryTest do {:ok, issues} = Repository.issues(github_repo) assert_received({ + :get, endpoint_url, + "", [ {"Accept", "application/vnd.github.machine-man-preview+json"}, {"Authorization", "token" <> _tok} ], [ - :with_body, - _headers, - {:params, [per_page: 100, state: "all"]} + {:params, [page: 1, per_page: 100, state: "all"]}, + {:access_token, "v1.1f699f1069f60xxx"} ] }) assert url == endpoint_url diff --git a/test/lib/code_corps/github/api/user_test.exs b/test/lib/code_corps/github/api/user_test.exs index 4c4302985..5e4524612 100644 --- a/test/lib/code_corps/github/api/user_test.exs +++ b/test/lib/code_corps/github/api/user_test.exs @@ -94,10 +94,11 @@ defmodule CodeCorps.GitHub.API.UserTest do @moduledoc false def request(:get, "https://api.github.com/user", _, _, _) do - {:error, GitHub.APIError.new({404, %{"message" => "{\"error\":\"Not Found\"}"}})} + {:ok, body} = %{"error" => "Not Found"} |> Poison.encode + {:ok, %HTTPoison.Response{status_code: 404, body: body}} end - def request(method, endpoint, headers, body, options) do - CodeCorps.GitHub.SuccessAPI.request(method, endpoint, headers, body, options) + def request(method, endpoint, body, headers, options) do + CodeCorps.GitHub.SuccessAPI.request(method, endpoint, body, headers, options) end end diff --git a/test/lib/code_corps/github/event/installation/installation_test.exs b/test/lib/code_corps/github/event/installation/installation_test.exs index d5ed3c2fa..777c7d23d 100644 --- a/test/lib/code_corps/github/event/installation/installation_test.exs +++ b/test/lib/code_corps/github/event/installation/installation_test.exs @@ -14,11 +14,11 @@ defmodule CodeCorps.GitHub.Event.InstallationTest do defmodule BadRepoRequest do def request(:get, "https://api.github.com/installation/repositories", _, _, _) do - body = load_endpoint_fixture("forbidden") - {:error, CodeCorps.GitHub.APIError.new({404, %{"message" => body}})} + {:ok, body} = load_endpoint_fixture("forbidden") |> Poison.encode + {:ok, %HTTPoison.Response{status_code: 404, body: body}} end - def request(method, endpoint, headers, body, options) do - CodeCorps.GitHub.SuccessAPI.request(method, endpoint, headers, body, options) + def request(method, endpoint, body, headers, options) do + CodeCorps.GitHub.SuccessAPI.request(method, endpoint, body, headers, options) end end @@ -32,10 +32,12 @@ defmodule CodeCorps.GitHub.Event.InstallationTest do bad_payload = good_payload |> Map.put("repositories", [bad_repo_1, repo_2]) - {:ok, bad_payload} + {:ok, body} = bad_payload |> Poison.encode + + {:ok, %HTTPoison.Response{status_code: 200, body: body}} end - def request(method, endpoint, headers, body, options) do - CodeCorps.GitHub.SuccessAPI.request(method, endpoint, headers, body, options) + def request(method, endpoint, body, headers, options) do + CodeCorps.GitHub.SuccessAPI.request(method, endpoint, body, headers, options) end end diff --git a/test/lib/code_corps/github/event/installation/repos_test.exs b/test/lib/code_corps/github/event/installation/repos_test.exs index 54ea17c04..aa3df5d97 100644 --- a/test/lib/code_corps/github/event/installation/repos_test.exs +++ b/test/lib/code_corps/github/event/installation/repos_test.exs @@ -28,10 +28,12 @@ defmodule CodeCorps.GitHub.Event.Installation.ReposTest do bad_payload = good_payload |> Map.put("repositories", [bad_repo_1, repo_2]) - {:ok, bad_payload} + {:ok, body} = bad_payload |> Poison.encode + + {:ok, %HTTPoison.Response{status_code: 200, body: body}} end - def request(method, endpoint, headers, body, options) do - CodeCorps.GitHub.SuccessAPI.request(method, endpoint, headers, body, options) + def request(method, endpoint, body, headers, options) do + CodeCorps.GitHub.SuccessAPI.request(method, endpoint, body, headers, options) end end diff --git a/test/lib/code_corps/github/github_test.exs b/test/lib/code_corps/github/github_test.exs index 30eac7696..14da54106 100644 --- a/test/lib/code_corps/github/github_test.exs +++ b/test/lib/code_corps/github/github_test.exs @@ -2,49 +2,62 @@ defmodule CodeCorps.GitHubTest do @moduledoc false use CodeCorps.DbAccessCase + import CodeCorps.GitHub.TestHelpers - alias CodeCorps.GitHub + + alias CodeCorps.{ + GitHub, + GitHub.APIError + } + + @response_body %{"foo" => "bar"} + + @error_body %{"message" => "bar"} + @error_code 401 + @error APIError.new({@error_code, @error_body}) defmodule BasicSuccessAPI do - def request(method, url, headers, body, options) do - send(self(), {method, url, headers, body, options}) - {:ok, "foo"} + def request(method, url, body, headers, options) do + send(self(), {method, url, body, headers, options}) + {:ok, body} = %{"foo" => "bar"} |> Poison.encode + {:ok, %HTTPoison.Response{body: body, status_code: 200}} end end defmodule BasicErrorAPI do - def request(method, url, headers, body, options) do - send(self(), {method, url, headers, body, options}) - {:error, "bar"} + def request(method, url, body, headers, options) do + send(self(), {method, url, body, headers, options}) + {:ok, body} = %{"message" => "bar"} |> Poison.encode + {:ok, %HTTPoison.Response{body: body, status_code: 401}} end end describe "request/5" do test "properly calls api and returns a successful response" do with_mock_api(BasicSuccessAPI) do - assert {:ok, "foo"} == GitHub.request(:get, "foo", %{}, %{}, []) + assert {:ok, @response_body} == GitHub.request(:get, "foo", %{}, %{}, []) end assert_received({ :get, "https://api.github.com/foo", - [{"Accept", "application/vnd.github.machine-man-preview+json"}], "{}", - [:with_body] + [{"Accept", "application/vnd.github.machine-man-preview+json"}], + [] }) end test "properly calls api and returns an error response" do with_mock_api(BasicErrorAPI) do - assert {:error, "bar"} = GitHub.request(:get, "bar", %{}, %{}, []) + assert {:error, @error} = GitHub.request(:get, "bar", %{}, %{}, []) end assert_received({ :get, "https://api.github.com/bar", - [{"Accept", "application/vnd.github.machine-man-preview+json"}], "{}", - [:with_body] + [{"Accept", "application/vnd.github.machine-man-preview+json"}], + [] }) end end @@ -52,15 +65,15 @@ defmodule CodeCorps.GitHubTest do describe "user_access_token_request/2" do test "properly calls api and returns a successful response" do with_mock_api(BasicSuccessAPI) do - assert {:ok, "foo"} == GitHub.user_access_token_request("foo_code", "foo_state") + assert {:ok, @response_body} == GitHub.user_access_token_request("foo_code", "foo_state") end assert_received({ :post, "https://github.com/login/oauth/access_token", - [{"Accept", "application/json"}, {"Content-Type", "application/json"}], body_text, - [:with_body] + [{"Accept", "application/json"}, {"Content-Type", "application/json"}], + [] }) body = body_text |> Poison.decode! @@ -72,14 +85,14 @@ defmodule CodeCorps.GitHubTest do test "properly calls api and returns an error response" do with_mock_api(BasicErrorAPI) do - assert {:error, "bar"} == GitHub.user_access_token_request("foo_code", "foo_state") + assert {:error, @error} == GitHub.user_access_token_request("foo_code", "foo_state") end assert_received({ :post, "https://github.com/login/oauth/access_token", - [{"Accept", "application/json"}, {"Content-Type", "application/json"}], body_text, - [:with_body] + [{"Accept", "application/json"}, {"Content-Type", "application/json"}], + [] }) body = body_text |> Poison.decode! @@ -93,29 +106,29 @@ defmodule CodeCorps.GitHubTest do describe "integration_request/5" do test "properly calls api and returns a successful response" do with_mock_api(BasicSuccessAPI) do - assert {:ok, "foo"} == GitHub.integration_request(:get, "foo", %{}, %{}, []) + assert {:ok, @response_body} == GitHub.integration_request(:get, "foo", %{}, %{}, []) end assert_received({ :get, "https://api.github.com/foo", - [{"Accept", "application/vnd.github.machine-man-preview+json"}, {"Authorization", "Bearer" <> _}], "{}", - [:with_body] + [{"Accept", "application/vnd.github.machine-man-preview+json"}, {"Authorization", "Bearer" <> _}], + [] }) end test "properly calls api and returns an error response" do with_mock_api(BasicErrorAPI) do - assert {:error, "bar"} = GitHub.integration_request(:get, "bar", %{}, %{}, []) + assert {:error, @error} = GitHub.integration_request(:get, "bar", %{}, %{}, []) end assert_received({ :get, "https://api.github.com/bar", - [{"Accept", "application/vnd.github.machine-man-preview+json"}, {"Authorization", "Bearer" <> _}], "{}", - [:with_body] + [{"Accept", "application/vnd.github.machine-man-preview+json"}, {"Authorization", "Bearer" <> _}], + [] }) end end diff --git a/test/lib/code_corps/task/service_test.exs b/test/lib/code_corps/task/service_test.exs index c67bceb2f..58b22702a 100644 --- a/test/lib/code_corps/task/service_test.exs +++ b/test/lib/code_corps/task/service_test.exs @@ -35,7 +35,7 @@ defmodule CodeCorps.Task.ServiceTest do refute task.github_issue_id refute task.github_repo_id - refute_received({:post, _string, {}, "{}", []}) + refute_received({:post, "https://api.github.com/" <> _rest, _body, _headers, _options}) end test "returns errored changeset if attributes are invalid" do @@ -43,7 +43,7 @@ defmodule CodeCorps.Task.ServiceTest do refute changeset.valid? refute Repo.one(Task) - refute_received({:post, _string, _headers, _body, _options}) + refute_received({:post, "https://api.github.com/" <> _rest, _body, _headers, _options}) end test "if task is assigned a github repo, creates github issue on assigned repo" do @@ -67,7 +67,7 @@ defmodule CodeCorps.Task.ServiceTest do assert task.github_issue_id assert task.github_repo_id == github_repo.id - assert_received({:post, "https://api.github.com/repos/foo/bar/issues", _headers, _body, _options}) + assert_received({:post, "https://api.github.com/repos/foo/bar/issues", _body, _headers, _options}) end test "if github process fails, returns {:error, :github}" do @@ -87,7 +87,7 @@ defmodule CodeCorps.Task.ServiceTest do end refute Repo.one(Task) - assert_received({:post, "https://api.github.com/repos/foo/bar/issues", _headers, _body, _options}) + assert_received({:post, "https://api.github.com/repos/foo/bar/issues", _body, _headers, _options}) end end @@ -105,7 +105,7 @@ defmodule CodeCorps.Task.ServiceTest do refute task.github_issue_id refute task.github_repo_id - refute_received({:post, _string, {}, "{}", []}) + refute_received({:patch, "https://api.github.com/" <> _rest, _body, _headers, _options}) end test "returns {:error, changeset} if there are validation errors" do @@ -114,7 +114,7 @@ defmodule CodeCorps.Task.ServiceTest do refute changeset.valid? - refute_received({:post, _string, {}, "{}", []}) + refute_received({:patch, "https://api.github.com/" <> _rest, _body, _headers, _options}) end test "creates a github issue if task is just now connected to a repo" do @@ -131,7 +131,7 @@ defmodule CodeCorps.Task.ServiceTest do assert updated_task.github_issue_id assert updated_task.github_repo_id == github_repo.id - assert_received({:post, "https://api.github.com/repos/foo/bar/issues", _headers, _body, _options}) + assert_received({:post, "https://api.github.com/repos/foo/bar/issues", _body, _headers, _options}) end test "propagates changes to github if task is synced to github issue" do @@ -151,7 +151,7 @@ defmodule CodeCorps.Task.ServiceTest do assert updated_task.github_issue_id assert updated_task.github_repo_id - assert_received({:patch, "https://api.github.com/repos/foo/bar/issues/5", _headers, _body, _options}) + assert_received({:patch, "https://api.github.com/repos/foo/bar/issues/5", _body, _headers, _options}) end test "reports {:error, :github}, makes no changes at all if there is a github api error" do @@ -175,7 +175,7 @@ defmodule CodeCorps.Task.ServiceTest do assert updated_task.github_issue_id == task.github_issue_id assert updated_task.github_repo_id == task.github_repo_id - assert_received({:patch, "https://api.github.com/repos/foo/bar/issues/5", _headers, _body, _options}) + assert_received({:patch, "https://api.github.com/repos/foo/bar/issues/5", _body, _headers, _options}) end end end diff --git a/test/support/github/failure_api.ex b/test/support/github/failure_api.ex index c7eeb9c27..971c6a862 100644 --- a/test/support/github/failure_api.ex +++ b/test/support/github/failure_api.ex @@ -15,14 +15,13 @@ defmodule CodeCorps.GitHub.FailureAPI do alias CodeCorps.GitHub.SuccessAPI - def request(method, url, headers, body, options) do + def request(method, url, body, headers, options) do case {method, url} |> for_access_token?() do - true -> SuccessAPI.request(method, url, headers, body, options) + true -> SuccessAPI.request(method, url, body, headers, options) false -> - send(self(), {method, url, headers, body, options}) - body = load_endpoint_fixture("forbidden") - error = CodeCorps.GitHub.APIError.new({401, body}) - {:error, error} + send(self(), {method, url, body, headers, options}) + {:ok, body} = load_endpoint_fixture("forbidden") |> Poison.encode + {:ok, %HTTPoison.Response{status_code: 401, body: body}} end end diff --git a/test/support/github/success_api.ex b/test/support/github/success_api.ex index 7c726d576..81fce875a 100644 --- a/test/support/github/success_api.ex +++ b/test/support/github/success_api.ex @@ -17,7 +17,7 @@ defmodule CodeCorps.GitHub.SuccessAPI do `assert_received` test helper can be used: ``` - assert_received({:get, "https://api.github.com/user", headers, body, options}) + assert_received({:get, "https://api.github.com/user", body, headers, options}) ``` """ @@ -27,60 +27,73 @@ defmodule CodeCorps.GitHub.SuccessAPI do defexception message: "You have a GitHub API endpoint that's unhandled in tests." end - def request(method, url, headers, body, options) do - send(self(), {method, url, headers, body, options}) - - {:ok, mock_response(method, url, headers, body, options)} + defmodule GitHubMockResponseError do + defexception message: "There was a problem in building a response for your mocked GitHub API." end - def get_all(url, headers, options) do - send(self(), {url, headers, options}) + def request(method, url, body, headers, options) do + send(self(), {method, url, body, headers, options}) - mock_response(:get, url, headers, %{}, options) + with {:ok, body} = get_body(method, url, body, headers, options) |> Poison.encode, + {:ok, code} = method |> success_code() + do + response = %HTTPoison.Response{body: body, request_url: url, status_code: code} + {:ok, response} + end end - defp mock_response(:post, "https://github.com/login/oauth/access_token", _, _, _) do + defp get_body(:head, _, _, _, _), do: "" + defp get_body(:post, "https://github.com/login/oauth/access_token", _, _, _) do %{"access_token" => "foo_auth_token"} end - defp mock_response(method, "https://api.github.com/" <> endpoint, headers, body, options) do - mock_response(method, endpoint |> String.split("/"), headers, body, options) + defp get_body(method, "https://api.github.com/" <> endpoint, body, headers, options) do + get_body(method, endpoint |> String.split("/"), body, headers, options) end - defp mock_response(:get, ["user"], _, _, _), do: load_endpoint_fixture("user") - defp mock_response(_method, ["installation", "repositories"], _, _, _) do + defp get_body(:get, ["user"], _, _, _), do: load_endpoint_fixture("user") + defp get_body(_method, ["installation", "repositories"], _, _, _) do load_endpoint_fixture("installation_repositories") end - defp mock_response(:post, ["installations", _id, "access_tokens"], _, _, _) do + defp get_body(:post, ["installations", _id, "access_tokens"], _, _, _) do %{ "token" => "v1.1f699f1069f60xxx", "expires_at" => Timex.now() |> Timex.shift(hours: 1) |> DateTime.to_iso8601 } end - defp mock_response(:get, ["repos", _owner, _repo, "issues", _number], _, _, _) do + defp get_body(:get, ["repos", _owner, _repo, "issues", _number], _, _, _) do load_endpoint_fixture("issue") end - defp mock_response(:post, ["repos", _owner, _repo, "issues"], _, _, _) do + defp get_body(:post, ["repos", _owner, _repo, "issues"], _, _, _) do load_endpoint_fixture("issue") end - defp mock_response(:patch, ["repos", _owner, _repo, "issues", _number], _, _, _) do + defp get_body(:patch, ["repos", _owner, _repo, "issues", _number], _, _, _) do load_endpoint_fixture("issue") end - defp mock_response(:post, ["repos", _owner, _repo, "issues", _number, "comments"], _, _, _) do + defp get_body(:post, ["repos", _owner, _repo, "issues", _number, "comments"], _, _, _) do load_endpoint_fixture("issue_comment") end - defp mock_response(:patch, ["repos", _owner, _repo, "issues", "comments", _id], _, _, _) do + defp get_body(:patch, ["repos", _owner, _repo, "issues", "comments", _id], _, _, _) do load_endpoint_fixture("issue_comment") end - defp mock_response(:get, ["repos", _owner, _repo, "issues"], _, _, _) do + defp get_body(:get, ["repos", _owner, _repo, "issues"], _, _, _) do load_endpoint_fixture("issues") end - defp mock_response(:get, ["repos", _owner, _repo, "pulls", _number], _, _, _) do + defp get_body(:get, ["repos", _owner, _repo, "pulls", _number], _, _, _) do load_endpoint_fixture("pull_request") end - defp mock_response(method, endpoint, _, _, _) when is_binary(endpoint) do + defp get_body(method, endpoint, _, _, _) when is_binary(endpoint) do raise UnhandledGitHubEndpointError, message: "You have an unhandled :#{method} request to #{endpoint}" end - defp mock_response(method, uri_parts, _, _, _) when is_list uri_parts do + defp get_body(method, uri_parts, _, _, _) when is_list uri_parts do endpoint = uri_parts |> Enum.join("/") raise UnhandledGitHubEndpointError, message: "You have an unhandled API :#{method} request to #{endpoint}" end + + @spec success_code(atom) :: integer + defp success_code(:get), do: {:ok, 200} + defp success_code(:post), do: {:ok, 201} + defp success_code(:patch), do: {:ok, 202} + defp success_code(:put), do: {:ok, 202} + defp success_code(:delete), do: {:ok, 204} + defp success_code(:head), do: {:ok, 204} + defp success_code(_), do: {:error, :unexpected_code} end diff --git a/test/support/github/test_helpers.ex b/test/support/github/test_helpers.ex index add673383..9be2a3adc 100644 --- a/test/support/github/test_helpers.ex +++ b/test/support/github/test_helpers.ex @@ -95,7 +95,7 @@ defmodule CodeCorps.GitHub.TestHelpers do defmacro with_real_api(do: block) do quote do old_mock = Application.get_env(:code_corps, :github) - Application.put_env(:code_corps, :github, CodeCorps.GitHub.API) + Application.put_env(:code_corps, :github, CodeCorps.GitHub.API.Gateway) unquote(block) diff --git a/test/support/test_helpers.ex b/test/support/test_helpers.ex index d203853e9..7aa51fe29 100644 --- a/test/support/test_helpers.ex +++ b/test/support/test_helpers.ex @@ -14,7 +14,7 @@ defmodule CodeCorps.TestHelpers do end def assert_ids_from_response(response, ids) do - assert ids_from_response(response) == ids + assert response |> ids_from_response() |> Enum.sort() == ids |> Enum.sort() response end