From 8ad00ec428a01733a432f8e65534cff1159e85eb Mon Sep 17 00:00:00 2001 From: Son Tran-Nguyen Date: Mon, 1 Mar 2021 17:18:16 -0600 Subject: [PATCH] feat: send/3 to sends to a NNTP socket Similar to `gen_tcp:send/2`, but also wait for response from server. Commands are sent with newline appended. --- lib/gen_nntp.ex | 5 +++++ src/gen_nntp.erl | 17 ++++++++++++++++- test/gen_nntp_test.exs | 21 +++++++++++++++++++++ 3 files changed, 42 insertions(+), 1 deletion(-) diff --git a/lib/gen_nntp.ex b/lib/gen_nntp.ex index c52ff3b..29ab1ba 100644 --- a/lib/gen_nntp.ex +++ b/lib/gen_nntp.ex @@ -28,6 +28,11 @@ defmodule GenNNTP do """ defdelegate connect(address \\ "localhost", port \\ 119, options \\ []), to: :gen_nntp + @doc """ + Sends a command and receives server's response. + """ + defdelegate send(socket, command, args \\ []), to: :gen_nntp + @callback init(any()) :: {:ok, state} | {:ok, state, timeout | :hibernate} | :ignore | {:stop, reason :: term} diff --git a/src/gen_nntp.erl b/src/gen_nntp.erl index 0c9032e..7ee65b3 100644 --- a/src/gen_nntp.erl +++ b/src/gen_nntp.erl @@ -9,7 +9,9 @@ connect/0, connect/1, connect/2, - connect/3 + connect/3, + send/2, + send/3 ]). %% gen_server callbacks @@ -128,6 +130,19 @@ connect(Address, Port, _Options) -> {error, Reason} end. +%%------------------------------------------------------------------- +%% @doc Sends a command to a NNTP socket +%% +%% The function will also wait for the response from server. +%% @end +%%------------------------------------------------------------------- +send(Socket, Commamd) -> + send(Socket, Commamd, []). + +send(Socket, Command, _Args) when is_binary(Command) -> + ok = gen_tcp:send(Socket, <>), + gen_tcp:recv(Socket, 0, 1000). + %% ================================================================== %% ranch_protocol Callbacks %% ================================================================== diff --git a/test/gen_nntp_test.exs b/test/gen_nntp_test.exs index c08f1a3..3763c6c 100644 --- a/test/gen_nntp_test.exs +++ b/test/gen_nntp_test.exs @@ -75,6 +75,27 @@ defmodule GenNNTPTest do end + describe "send/3" do + + setup do + GenNNTP.start(TestNNTPServer, [], []) + {:ok, socket, _greeting} = GenNNTP.connect() + + %{socket: socket} + end + + test "sends QUIT command", %{socket: socket} do + assert {:ok, response} = GenNNTP.send(socket, "QUIT", []) + assert response =~ ~r/^205 / + end + + test "send/2 default to empty arguments", %{socket: socket} do + assert {:ok, response} = GenNNTP.send(socket, "QUIT") + assert response =~ ~r/^205 / + end + + end + describe "@callback init/1" do test "is called when a client connects to it" do