Skip to content

Instantly share code, notes, and snippets.

@fabjan
Created November 26, 2022 15:11
Show Gist options
  • Save fabjan/754840a6daf30058c00880b465448974 to your computer and use it in GitHub Desktop.
Save fabjan/754840a6daf30058c00880b465448974 to your computer and use it in GitHub Desktop.
a minimaler example_cth.erl
%%% See discussion in: https://github.com/erlang/otp/pull/6437
%%% Common Test Example Common Test Hook module.
-module(example_cth).
%% Mandatory Callbacks
-export([init/2]).
%% Optional Callbacks
-export([id/1]).
-export([pre_init_per_suite/3]).
-export([post_end_per_suite/4]).
-export([pre_init_per_testcase/4]).
-export([post_end_per_testcase/5]).
-export([terminate/1]).
-record(state, { file_handle, total, suite_total, ts, tcs, data }).
%% Return a unique id for this CTH.
%% See Installing a CTH for more information.
id(Opts) ->
proplists:get_value(filename, Opts, "/tmp/file.log").
%% Always called before any other callback function. Use this to initiate
%% any common state.
init(Id, _) ->
{ok,D} = file:open(Id,[write]),
{ok, #state{ file_handle = D, total = 0, data = [] }}.
%% Called before init_per_suite is called.
pre_init_per_suite(_,Config,State) ->
{Config, State#state{ suite_total = 0, tcs = [] }}.
%% Called after end_per_suite.
post_end_per_suite(Suite,_,Return,State) ->
Data = {suites, Suite, State#state.suite_total, lists:reverse(State#state.tcs)},
{Return, State#state{ data = [Data | State#state.data] ,
total = State#state.total + State#state.suite_total } }.
%% Called before each init_per_testcase.
pre_init_per_testcase(_,_,Config,State) ->
Now = erlang:monotonic_time(microsecond),
{Config, State#state{ ts = Now, total = State#state.suite_total + 1 } }.
%% Called after each end_per_testcase.
post_end_per_testcase(Suite,TC,_,Return,State) ->
Now = erlang:monotonic_time(microsecond),
TCInfo = {testcase, Suite, TC, Return, Now - State#state.ts},
{Return, State#state{ ts = undefined, tcs = [TCInfo | State#state.tcs] } }.
%% Called when the scope of the CTH is done
terminate(State) ->
io:format(State#state.file_handle, "~p.~n",
[{test_run, State#state.total, State#state.data}]),
file:close(State#state.file_handle),
ok.
@u3s
Copy link

u3s commented Dec 1, 2022

good idea to divide exports into mandatory and optional sections.

@u3s
Copy link

u3s commented Dec 1, 2022

Same comment as for other file:
I think bare '' is not good in example code. I think Suite is more informative for someone who tries to understand how to write a hook module.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment