2.0 KiB · text History 4b6fe3b
defmodule OhMyExOhIrcd.IRC.MessageTest do
  use ExUnit.Case, async: true

  alias OhMyExOhIrcd.IRC.Message

  describe "parse/1" do
    test "command + no params" do
      assert {:ok, %Message{prefix: nil, command: "PING", params: []}} = Message.parse("PING")
    end

    test "command + simple params" do
      assert {:ok, %Message{prefix: nil, command: "JOIN", params: ["#elixir"]}} =
               Message.parse("JOIN #elixir")
    end

    test "trailing param with spaces" do
      assert {:ok, %Message{command: "PRIVMSG", params: ["#elixir", "hello world"]}} =
               Message.parse("PRIVMSG #elixir :hello world")
    end

    test "prefix" do
      assert {:ok, %Message{prefix: "nick!user@host", command: "PRIVMSG", params: ["#x", "hi"]}} =
               Message.parse(":nick!user@host PRIVMSG #x :hi")
    end

    test "upcases command" do
      assert {:ok, %Message{command: "NICK"}} = Message.parse("nick foo")
    end

    test "empty line" do
      assert {:error, :empty} = Message.parse("")
      assert {:error, :empty} = Message.parse("   \r\n")
    end
  end

  describe "encode/1" do
    test "roundtrip with trailing param" do
      msg = %Message{prefix: "n!u@h", command: "PRIVMSG", params: ["#x", "hello world"]}
      out = msg |> Message.encode() |> IO.iodata_to_binary()
      assert out == ":n!u@h PRIVMSG #x :hello world"
    end

    test "last param without spaces does not get a colon" do
      out =
        %Message{command: "JOIN", params: ["#x"]}
        |> Message.encode()
        |> IO.iodata_to_binary()

      assert out == "JOIN #x"
    end

    test "last param starting with : is colon-quoted" do
      out =
        %Message{command: "QUIT", params: [":foo"]}
        |> Message.encode()
        |> IO.iodata_to_binary()

      assert out == "QUIT ::foo"
    end

    test "to_iodata appends CRLF" do
      out =
        %Message{command: "PING", params: ["server"]}
        |> Message.to_iodata()
        |> IO.iodata_to_binary()

      assert out == "PING server\r\n"
    end
  end
end