Просмотр исходного кода

Add test cases for emqx_keepalive module (#2784)

* Improve the keepalive module
Feng Lee 6 лет назад
Родитель
Сommit
d63eccd8b8
2 измененных файлов с 22 добавлено и 16 удалено
  1. 18 16
      src/emqx_keepalive.erl
  2. 4 0
      test/emqx_keepalive_SUITE.erl

+ 18 - 16
src/emqx_keepalive.erl

@@ -25,14 +25,16 @@
 -export_type([keepalive/0]).
 
 -record(keepalive, {
-          statfun,
-          statval,
-          tsec,
-          tmsg,
-          tref,
-          repeat = 0
+          statfun    :: statfun(),
+          statval    :: integer(),
+          tsec       :: pos_integer(),
+          tmsg       :: term(),
+          tref       :: reference(),
+          repeat = 0 :: non_neg_integer()
          }).
 
+-type(statfun() :: fun(() -> {ok, integer()} | {error, term()})).
+
 -opaque(keepalive() :: #keepalive{}).
 
 %%--------------------------------------------------------------------
@@ -40,15 +42,17 @@
 %%--------------------------------------------------------------------
 
 %% @doc Start a keepalive
--spec(start(fun(), integer(), any()) -> {ok, keepalive()} | {error, term()}).
-start(_, 0, _) ->
-    {ok, #keepalive{}};
-start(StatFun, TimeoutSec, TimeoutMsg) ->
+-spec(start(statfun(), pos_integer(), term())
+      -> {ok, keepalive()} | {error, term()}).
+start(StatFun, TimeoutSec, TimeoutMsg) when TimeoutSec > 0 ->
     try StatFun() of
         {ok, StatVal} ->
-            {ok, #keepalive{statfun = StatFun, statval = StatVal,
-                            tsec = TimeoutSec, tmsg = TimeoutMsg,
-                            tref = timer(TimeoutSec, TimeoutMsg)}};
+            TRef = timer(TimeoutSec, TimeoutMsg),
+            {ok, #keepalive{statfun = StatFun,
+                            statval = StatVal,
+                            tsec = TimeoutSec,
+                            tmsg = TimeoutMsg,
+                            tref = TRef}};
         {error, Error} ->
             {error, Error}
     catch
@@ -82,9 +86,7 @@ resume(KeepAlive = #keepalive{tsec = TimeoutSec, tmsg = TimeoutMsg}) ->
 %% @doc Cancel Keepalive
 -spec(cancel(keepalive()) -> ok).
 cancel(#keepalive{tref = TRef}) when is_reference(TRef) ->
-    catch erlang:cancel_timer(TRef), ok;
-cancel(_) ->
-    ok.
+    catch erlang:cancel_timer(TRef), ok.
 
 timer(Secs, Msg) ->
     erlang:send_after(timer:seconds(Secs), self(), Msg).

+ 4 - 0
test/emqx_keepalive_SUITE.erl

@@ -35,3 +35,7 @@ keepalive_recv(KA, Acc) ->
         after 4000 -> Acc
     end.
 
+t_cancel(_) ->
+    {ok, KA} = emqx_keepalive:start(fun() -> {ok, 1} end, 1, {keepalive, timeout}),
+    ok = emqx_keepalive:cancel(KA).
+