summaryrefslogtreecommitdiff
path: root/test/http_test.exs
blob: b88e3b6053fb8f9025edf954320f51961cbae369 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# Pleroma: A lightweight social networking server
# Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only

defmodule Pleroma.HTTPTest do
  use Pleroma.DataCase
  import Tesla.Mock

  setup do
    mock(fn
      %{
        method: :get,
        url: "http://example.com/hello",
        headers: [{"content-type", "application/json"}]
      } ->
        json(%{"my" => "data"})

      %{method: :get, url: "http://example.com/hello"} ->
        %Tesla.Env{status: 200, body: "hello"}

      %{method: :post, url: "http://example.com/world"} ->
        %Tesla.Env{status: 200, body: "world"}
    end)

    :ok
  end

  describe "get/1" do
    test "returns successfully result" do
      assert Pleroma.HTTP.get("http://example.com/hello") == {
               :ok,
               %Tesla.Env{status: 200, body: "hello"}
             }
    end
  end

  describe "get/2 (with headers)" do
    test "returns successfully result for json content-type" do
      assert Pleroma.HTTP.get("http://example.com/hello", [{"content-type", "application/json"}]) ==
               {
                 :ok,
                 %Tesla.Env{
                   status: 200,
                   body: "{\"my\":\"data\"}",
                   headers: [{"content-type", "application/json"}]
                 }
               }
    end
  end

  describe "post/2" do
    test "returns successfully result" do
      assert Pleroma.HTTP.post("http://example.com/world", "") == {
               :ok,
               %Tesla.Env{status: 200, body: "world"}
             }
    end
  end

  @tag :integration
  test "get_conn_for_gun/3" do
    adapter = Application.get_env(:tesla, :adapter)
    Application.put_env(:tesla, :adapter, Tesla.Adapter.Gun)
    api = Pleroma.Config.get([Pleroma.Gun.API])
    Pleroma.Config.put([Pleroma.Gun.API], Pleroma.Gun.API.Gun)

    on_exit(fn ->
      Application.put_env(:tesla, :adapter, adapter)
      Pleroma.Config.put([Pleroma.Gun.API], api)
    end)

    options = [adapter: [pool: :federation]]

    assert {:ok, resp} = Pleroma.HTTP.get("https://httpbin.org/user-agent", [], options)

    adapter_opts = resp.opts[:adapter]

    assert resp.status == 200

    assert adapter_opts[:url] == "https://httpbin.org/user-agent"
    state = Pleroma.Gun.Connections.get_state(:federation)
    conn = state.conns["https:httpbin.org:443"]

    assert conn.conn_state == :idle
    assert conn.used_by == []
    assert state.queue == []
  end
end