~cosmicrose/liberator

liberator/test/liberator/resource_codec_test.exs -rw-r--r-- 2.2 KiB
95bf1d41Rosa Richter Credo fixes 2 months ago
                                                                                
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
# SPDX-FileCopyrightText: 2021 Rosa Richter
#
# SPDX-License-Identifier: MIT

defmodule Liberator.ResourceCodecTest do
  # Not async because some of these tests must manipulate the Application config
  use ExUnit.Case
  use Plug.Test

  defmodule BrokenMediaType do
    def encode!(_), do: %{a: 1, b: 2}
  end

  defmodule BadMediaTypeCodecResource do
    use Liberator.Resource

    @impl true
    def handle_ok(_), do: %{a: 1, b: 2}
  end

  test "if a media type codec does not return a binary, throws an exception with a nice message" do
    media_types = Application.fetch_env!(:liberator, :media_types)

    on_exit(fn ->
      Application.put_env(:liberator, :media_types, media_types)
    end)

    Application.put_env(:liberator, :media_types, %{
      "text/plain" => BrokenMediaType
    })

    expected_message = """
    The media type codec module Liberator.ResourceCodecTest.BrokenMediaType did not return a binary.
    Media type codecs must return a binary.

    Liberator.ResourceCodecTest.BrokenMediaType.encode!/1 returned %{a: 1, b: 2}
    """

    conn = conn(:get, "/")

    assert_raise Liberator.MediaTypeCodecInvalidResultException, expected_message, fn ->
      BadMediaTypeCodecResource.call(conn, [])
    end
  end

  defmodule BrokenEncoding do
    def encode!(_), do: %{a: 1, b: 2}
  end

  defmodule BadCompressionCodecResource do
    use Liberator.Resource

    @impl true
    def handle_ok(_), do: %{a: 1, b: 2}
  end

  test "if compression codec does not return a binary, throws an exception with a nice message" do
    encodings = Application.fetch_env!(:liberator, :encodings)

    on_exit(fn ->
      Application.put_env(:liberator, :encodings, encodings)
    end)

    Application.put_env(:liberator, :encodings, %{
      "identity" => BrokenEncoding
    })

    expected_message = """
    The compression codec module Liberator.ResourceCodecTest.BrokenEncoding did not return a binary.
    Compression codecs must return a binary.

    Liberator.ResourceCodecTest.BrokenEncoding.encode!/1 returned %{a: 1, b: 2}
    """

    conn = conn(:get, "/")

    assert_raise Liberator.CompressionCodecInvalidResultException, expected_message, fn ->
      BadCompressionCodecResource.call(conn, [])
    end
  end
end