├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── demo.gif ├── rebar ├── rebar.config ├── rebar.lock ├── src ├── binomial_heap.erl ├── eunit_formatters.app.src └── eunit_progress.erl ├── test ├── capture_io.erl ├── capture_io_tests.erl └── eunit_progress_tests.erl └── tools.mk /.gitignore: -------------------------------------------------------------------------------- 1 | .rebar3 2 | _build 3 | .DS_Store 4 | ebin/* 5 | .eunit 6 | deps 7 | *.sublime-project 8 | *.sublime-workspace 9 | log 10 | .local_dialyzer_plt 11 | erln8.config 12 | .rebar 13 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. 10 | 11 | "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. 12 | 13 | "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. 14 | 15 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. 16 | 17 | "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. 18 | 19 | "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. 20 | 21 | "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). 22 | 23 | "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. 24 | 25 | "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." 26 | 27 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 28 | 29 | 2. Grant of Copyright License. 30 | 31 | Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 32 | 33 | 3. Grant of Patent License. 34 | 35 | Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 36 | 37 | 4. Redistribution. 38 | 39 | You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: 40 | 41 | You must give any other recipients of the Work or Derivative Works a copy of this License; and 42 | You must cause any modified files to carry prominent notices stating that You changed the files; and 43 | You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and 44 | If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. 45 | You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 46 | 47 | 5. Submission of Contributions. 48 | 49 | Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 50 | 51 | 6. Trademarks. 52 | 53 | This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 54 | 55 | 7. Disclaimer of Warranty. 56 | 57 | Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 58 | 59 | 8. Limitation of Liability. 60 | 61 | In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 62 | 63 | 9. Accepting Warranty or Additional Liability. 64 | 65 | While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. 66 | 67 | END OF TERMS AND CONDITIONS -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: deps test 2 | 3 | all: compile 4 | 5 | compile: 6 | ./rebar compile 7 | 8 | # deps: 9 | # ./rebar get-deps 10 | 11 | clean: 12 | ./rebar clean 13 | 14 | DIALYZER_APPS = kernel stdlib sasl erts eunit 15 | 16 | include tools.mk 17 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # eunit_formatters 2 | 3 | Because eunit's output sucks. Let's make it better. 4 | 5 | Here's the progress formatter running with profiling and ANSI colors 6 | turned on: 7 | 8 | ![neotoma eunit](demo.gif) 9 | 10 | ## Setup 11 | 12 | ### Rebar 3 13 | 14 | [rebar3](https://github.com/erlang/rebar3) already includes this 15 | library! There's no need for special configuration at all. 16 | 17 | ### erlang.mk 18 | 19 | For erlang.mk, add the following before `include erlang.mk`: 20 | 21 | ``` Makefile 22 | TEST_DEPS = eunit_formatters 23 | 24 | EUNIT_OPTS = no_tty, {report, {eunit_progress, [colored, profile]}} 25 | ``` 26 | 27 | ### Rebar 2 (legacy) 28 | Add `eunit_formatters` as a dep in your `rebar.config`. Now configure 29 | eunit to use one of the output formatters (currently only 30 | `eunit_progress`): 31 | 32 | ```erlang 33 | {eunit_opts, [ 34 | no_tty, %% This turns off the default output, MUST HAVE 35 | {report, {eunit_progress, [colored, profile]}} %% Use `profile' to see test timing information 36 | %% Uses the progress formatter with ANSI-colored output 37 | ]}. 38 | ``` 39 | 40 | ## License 41 | 42 | Copyright 2014 Sean Cribbs 43 | 44 | Licensed under the Apache License, Version 2.0 (the "License"); 45 | you may not use this file except in compliance with the License. 46 | You may obtain a copy of the License at 47 | 48 | http://www.apache.org/licenses/LICENSE-2.0 49 | 50 | Unless required by applicable law or agreed to in writing, software 51 | distributed under the License is distributed on an "AS IS" BASIS, 52 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 53 | See the License for the specific language governing permissions and 54 | limitations under the License. 55 | -------------------------------------------------------------------------------- /demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seancribbs/eunit_formatters/7b229bd3e03a66696bf761dca731c40540955db7/demo.gif -------------------------------------------------------------------------------- /rebar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seancribbs/eunit_formatters/7b229bd3e03a66696bf761dca731c40540955db7/rebar -------------------------------------------------------------------------------- /rebar.config: -------------------------------------------------------------------------------- 1 | %% Dogfooding 2 | {eunit_opts, [no_tty, {report, {eunit_progress, [colored, profile]}}]}. 3 | -------------------------------------------------------------------------------- /rebar.lock: -------------------------------------------------------------------------------- 1 | []. 2 | -------------------------------------------------------------------------------- /src/binomial_heap.erl: -------------------------------------------------------------------------------- 1 | %% Copyright 2014 Sean Cribbs 2 | %% 3 | %% Licensed under the Apache License, Version 2.0 (the "License"); 4 | %% you may not use this file except in compliance with the License. 5 | %% You may obtain a copy of the License at 6 | %% 7 | %% http://www.apache.org/licenses/LICENSE-2.0 8 | %% 9 | %% Unless required by applicable law or agreed to in writing, software 10 | %% distributed under the License is distributed on an "AS IS" BASIS, 11 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | %% See the License for the specific language governing permissions and 13 | %% limitations under the License. 14 | 15 | %% @doc Binomial heap based on Okasaki 6.2.2 16 | -module(binomial_heap). 17 | -export([new/0, insert/2, insert/3, merge/2, delete/1, to_list/1, take/2, size/1]). 18 | -compile({no_auto_import,[link/2]}). 19 | 20 | -record(node,{ 21 | rank = 0 :: non_neg_integer(), 22 | key :: term(), 23 | value :: term(), 24 | children = new() :: binomial_heap() 25 | }). 26 | 27 | -export_type([binomial_heap/0, heap_node/0]). 28 | -type binomial_heap() :: [ heap_node() ]. 29 | -type heap_node() :: #node{}. 30 | 31 | -spec new() -> binomial_heap(). 32 | new() -> 33 | []. 34 | 35 | % Inserts a new pair into the heap (or creates a new heap) 36 | -spec insert(term(), term()) -> binomial_heap(). 37 | insert(Key,Value) -> 38 | insert(Key,Value,[]). 39 | 40 | -spec insert(term(), term(), binomial_heap()) -> binomial_heap(). 41 | insert(Key,Value,Forest) -> 42 | insTree(#node{key=Key,value=Value},Forest). 43 | 44 | % Merges two heaps 45 | -spec merge(binomial_heap(), binomial_heap()) -> binomial_heap(). 46 | merge(TS1,[]) when is_list(TS1) -> TS1; 47 | merge([],TS2) when is_list(TS2) -> TS2; 48 | merge([#node{rank=R1}=T1|TS1]=F1,[#node{rank=R2}=T2|TS2]=F2) -> 49 | if 50 | R1 < R2 -> 51 | [T1 | merge(TS1,F2)]; 52 | R2 < R1 -> 53 | [T2 | merge(F1, TS2)]; 54 | true -> 55 | insTree(link(T1,T2),merge(TS1,TS2)) 56 | end. 57 | 58 | % Deletes the top entry from the heap and returns it 59 | -spec delete(binomial_heap()) -> {{term(), term()}, binomial_heap()}. 60 | delete(TS) -> 61 | {#node{key=Key,value=Value,children=TS1},TS2} = getMin(TS), 62 | {{Key,Value},merge(lists:reverse(TS1),TS2)}. 63 | 64 | % Turns the heap into list in heap order 65 | -spec to_list(binomial_heap()) -> [{term(), term()}]. 66 | to_list([]) -> []; 67 | to_list(List) when is_list(List) -> 68 | to_list([],List). 69 | to_list(Acc, []) -> 70 | lists:reverse(Acc); 71 | to_list(Acc,Forest) -> 72 | {Next, Trees} = delete(Forest), 73 | to_list([Next|Acc], Trees). 74 | 75 | % Take N elements from the top of the heap 76 | -spec take(non_neg_integer(), binomial_heap()) -> [{term(), term()}]. 77 | take(N,Trees) when is_integer(N), is_list(Trees) -> 78 | take(N,Trees,[]). 79 | take(0,_Trees,Acc) -> 80 | lists:reverse(Acc); 81 | take(_N,[],Acc)-> 82 | lists:reverse(Acc); 83 | take(N,Trees,Acc) -> 84 | {Top,T2} = delete(Trees), 85 | take(N-1,T2,[Top|Acc]). 86 | 87 | % Get an estimate of the size based on the binomial property 88 | -spec size(binomial_heap()) -> non_neg_integer(). 89 | size(Forest) -> 90 | erlang:trunc(lists:sum([math:pow(2,R) || #node{rank=R} <- Forest])). 91 | 92 | %% Private API 93 | -spec link(heap_node(), heap_node()) -> heap_node(). 94 | link(#node{rank=R,key=X1,children=C1}=T1,#node{key=X2,children=C2}=T2) -> 95 | case X1 < X2 of 96 | true -> 97 | T1#node{rank=R+1,children=[T2|C1]}; 98 | _ -> 99 | T2#node{rank=R+1,children=[T1|C2]} 100 | end. 101 | 102 | insTree(Tree, []) -> 103 | [Tree]; 104 | insTree(#node{rank=R1}=T1, [#node{rank=R2}=T2|Rest] = TS) -> 105 | case R1 < R2 of 106 | true -> 107 | [T1|TS]; 108 | _ -> 109 | insTree(link(T1,T2),Rest) 110 | end. 111 | 112 | getMin([T]) -> 113 | {T,[]}; 114 | getMin([#node{key=K} = T|TS]) -> 115 | {#node{key=K1} = T1,TS1} = getMin(TS), 116 | case K < K1 of 117 | true -> {T,TS}; 118 | _ -> {T1,[T|TS1]} 119 | end. 120 | -------------------------------------------------------------------------------- /src/eunit_formatters.app.src: -------------------------------------------------------------------------------- 1 | %% Copyright 2014 Sean Cribbs 2 | %% 3 | %% Licensed under the Apache License, Version 2.0 (the "License"); 4 | %% you may not use this file except in compliance with the License. 5 | %% You may obtain a copy of the License at 6 | %% 7 | %% http://www.apache.org/licenses/LICENSE-2.0 8 | %% 9 | %% Unless required by applicable law or agreed to in writing, software 10 | %% distributed under the License is distributed on an "AS IS" BASIS, 11 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | %% See the License for the specific language governing permissions and 13 | %% limitations under the License. 14 | {application, eunit_formatters, 15 | [ 16 | {description, "Better output for eunit suites"}, 17 | {vsn, git}, 18 | {applications, [ 19 | kernel, 20 | stdlib, 21 | eunit 22 | ]}, 23 | {env, []}, 24 | 25 | {maintainers, ["Sean Cribbs", "Tristan Sloughter"]}, 26 | {licenses, ["Apache2"]}, 27 | {links, [{"Github", "https://github.com/seancribbs/eunit_formatters"}]} 28 | ]}. 29 | -------------------------------------------------------------------------------- /src/eunit_progress.erl: -------------------------------------------------------------------------------- 1 | %% Copyright 2014 Sean Cribbs 2 | %% 3 | %% Licensed under the Apache License, Version 2.0 (the "License"); 4 | %% you may not use this file except in compliance with the License. 5 | %% You may obtain a copy of the License at 6 | %% 7 | %% http://www.apache.org/licenses/LICENSE-2.0 8 | %% 9 | %% Unless required by applicable law or agreed to in writing, software 10 | %% distributed under the License is distributed on an "AS IS" BASIS, 11 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | %% See the License for the specific language governing permissions and 13 | %% limitations under the License. 14 | 15 | 16 | %% @doc A listener/reporter for eunit that prints '.' for each 17 | %% success, 'F' for each failure, and 'E' for each error. It can also 18 | %% optionally summarize the failures at the end. 19 | -module(eunit_progress). 20 | -behaviour(eunit_listener). 21 | -define(NOTEST, true). 22 | -include_lib("eunit/include/eunit.hrl"). 23 | 24 | -define(RED, "\e[0;31m"). 25 | -define(GREEN, "\e[0;32m"). 26 | -define(YELLOW, "\e[0;33m"). 27 | -define(WHITE, "\e[0;37m"). 28 | -define(CYAN, "\e[0;36m"). 29 | -define(RESET, "\e[0m"). 30 | 31 | %% eunit_listener callbacks 32 | -export([ 33 | init/1, 34 | handle_begin/3, 35 | handle_end/3, 36 | handle_cancel/3, 37 | terminate/2 38 | ]). 39 | 40 | -export([ 41 | start/0, 42 | start/1 43 | ]). 44 | 45 | -record(state, { 46 | status = #{} :: map(), 47 | failures = [] :: [[pos_integer()]], 48 | skips = [] :: [[pos_integer()]], 49 | timings = binomial_heap:new() :: binomial_heap:binomial_heap(), 50 | colored = true :: boolean(), 51 | profile = false :: boolean() 52 | }). 53 | 54 | %% Startup 55 | start() -> 56 | start([]). 57 | 58 | start(Options) -> 59 | eunit_listener:start(?MODULE, Options). 60 | 61 | %%------------------------------------------ 62 | %% eunit_listener callbacks 63 | %%------------------------------------------ 64 | init(Options) -> 65 | #state{colored=proplists:get_bool(colored, Options), 66 | profile=proplists:get_bool(profile, Options)}. 67 | 68 | handle_begin(group, Data, St) -> 69 | GID = proplists:get_value(id, Data), 70 | Status = St#state.status, 71 | St#state{status=Status#{ GID => orddict:from_list([{type, group}|Data])}}; 72 | handle_begin(test, Data, St) -> 73 | TID = proplists:get_value(id, Data), 74 | Status = St#state.status, 75 | St#state{status=Status#{ TID => orddict:from_list([{type, test}|Data])}}. 76 | 77 | handle_end(group, Data, St) -> 78 | St#state{status=merge_on_end(Data, St#state.status)}; 79 | handle_end(test, Data, St) -> 80 | NewStatus = merge_on_end(Data, St#state.status), 81 | St1 = print_progress(Data, St), 82 | St2 = record_timing(Data, St1), 83 | St2#state{status=NewStatus}. 84 | 85 | handle_cancel(_, Data, #state{status=Status, skips=Skips}=St) -> 86 | Status1 = merge_on_end(Data, Status), 87 | ID = proplists:get_value(id, Data), 88 | St#state{status=Status1, skips=[ID|Skips]}. 89 | 90 | terminate({ok, Data}, St) -> 91 | print_failures(St), 92 | print_pending(St), 93 | print_profile(St), 94 | print_timing(St), 95 | print_results(Data, St); 96 | terminate({error, Reason}, St) -> 97 | io:nl(), io:nl(), 98 | print_colored(io_lib:format("Eunit failed: ~25p~n", [Reason]), ?RED, St), 99 | sync_end(error). 100 | 101 | sync_end(Result) -> 102 | receive 103 | {stop, Reference, ReplyTo} -> 104 | ReplyTo ! {result, Reference, Result}, 105 | ok 106 | end. 107 | 108 | %%------------------------------------------ 109 | %% Print and collect information during run 110 | %%------------------------------------------ 111 | print_progress(Data, St) -> 112 | TID = proplists:get_value(id, Data), 113 | case proplists:get_value(status, Data) of 114 | ok -> 115 | print_progress_success(St), 116 | St; 117 | {skipped, _Reason} -> 118 | print_progress_skipped(St), 119 | St#state{skips=[TID|St#state.skips]}; 120 | {error, Exception} -> 121 | print_progress_failed(Exception, St), 122 | St#state{failures=[TID|St#state.failures]} 123 | end. 124 | 125 | record_timing(Data, State=#state{timings=T, profile=true}) -> 126 | TID = proplists:get_value(id, Data), 127 | case lists:keyfind(time, 1, Data) of 128 | {time, Int} -> 129 | %% It's a min-heap, so we insert negative numbers instead 130 | %% of the actuals and normalize when we report on them. 131 | T1 = binomial_heap:insert(-Int, TID, T), 132 | State#state{timings=T1}; 133 | false -> 134 | State 135 | end; 136 | record_timing(_Data, State) -> 137 | State. 138 | 139 | print_progress_success(St) -> 140 | print_colored(".", ?GREEN, St). 141 | 142 | print_progress_skipped(St) -> 143 | print_colored("*", ?YELLOW, St). 144 | 145 | print_progress_failed(_Exc, St) -> 146 | print_colored("F", ?RED, St). 147 | 148 | merge_on_end(Data, Status) -> 149 | ID = proplists:get_value(id, Data), 150 | #{ ID := Old } = Status, 151 | Status#{ ID := orddict:merge(fun merge_data/3, Old, orddict:from_list(Data)) }. 152 | 153 | merge_data(_K, undefined, X) -> X; 154 | merge_data(_K, X, undefined) -> X; 155 | merge_data(_K, _, X) -> X. 156 | 157 | %%------------------------------------------ 158 | %% Print information at end of run 159 | %%------------------------------------------ 160 | print_failures(#state{failures=[]}) -> 161 | ok; 162 | print_failures(#state{failures=Fails}=State) -> 163 | io:nl(), 164 | io:fwrite("Failures:~n~n",[]), 165 | lists:foldr(print_failure_fun(State), 1, Fails), 166 | ok. 167 | 168 | print_failure_fun(#state{status=Status}=State) -> 169 | fun(Key, Count) -> 170 | #{ Key := TestData } = Status, 171 | TestId = format_test_identifier(TestData), 172 | io:fwrite(" ~p) ~ts~n", [Count, TestId]), 173 | print_failure_reason(proplists:get_value(status, TestData), 174 | proplists:get_value(output, TestData), 175 | State), 176 | io:nl(), 177 | Count + 1 178 | end. 179 | 180 | print_failure_reason({skipped, Reason}, _Output, State) -> 181 | print_colored(io_lib:format(" ~ts~n", [format_pending_reason(Reason)]), 182 | ?RED, State); 183 | print_failure_reason({error, {_Class, Term, Stack}}, Output, State) when 184 | is_tuple(Term), tuple_size(Term) == 2, is_list(element(2, Term)) -> 185 | print_assertion_failure(Term, Stack, Output, State), 186 | print_failure_output(5, Output, State); 187 | print_failure_reason({error, Reason}, Output, State) -> 188 | print_colored(indent(5, "Failure/Error: ~p~n", [Reason]), ?RED, State), 189 | print_failure_output(5, Output, State). 190 | 191 | print_failure_output(_, <<>>, _) -> ok; 192 | print_failure_output(_, [<<>>], _) -> ok; 193 | print_failure_output(_, undefined, _) -> ok; 194 | print_failure_output(Indent, Output, State) -> 195 | print_colored(indent(Indent, "Output: ~ts", [Output]), ?CYAN, State). 196 | 197 | print_assertion_failure({Type, Props}, Stack, Output, State) -> 198 | FailureDesc = format_assertion_failure(Type, Props, 5), 199 | {M,F,A,Loc} = lists:last(prune_trace(Stack)), 200 | LocationText = io_lib:format(" %% ~ts:~p:in `~ts`", [proplists:get_value(file, Loc), 201 | proplists:get_value(line, Loc), 202 | format_function_name(M,F,A)]), 203 | print_colored(FailureDesc, ?RED, State), 204 | io:nl(), 205 | print_colored(LocationText, ?CYAN, State), 206 | io:nl(), 207 | print_failure_output(5, Output, State), 208 | io:nl(). 209 | 210 | %% This is a simplified version of eunit_test:prune_trace/2 211 | prune_trace([Entry | _]) when element(1, Entry) =:= eunit_test -> 212 | [Entry]; 213 | prune_trace(Stack) -> 214 | lists:takewhile(fun(Entry) -> element(1, Entry) =/= eunit_test end, Stack). 215 | 216 | print_pending(#state{skips=[]}) -> 217 | ok; 218 | print_pending(#state{status=Status, skips=Skips}=State) -> 219 | io:nl(), 220 | io:fwrite("Pending:~n", []), 221 | lists:foreach(fun(ID) -> 222 | #{ ID := Info } = Status, 223 | case proplists:get_value(reason, Info) of 224 | undefined -> 225 | ok; 226 | Reason -> 227 | print_pending_reason(Reason, Info, State) 228 | end 229 | end, lists:reverse(Skips)), 230 | io:nl(). 231 | 232 | print_pending_reason(Reason0, Data, State) -> 233 | Text = case proplists:get_value(type, Data) of 234 | group -> 235 | io_lib:format(" ~ts~n", [proplists:get_value(desc, Data)]); 236 | test -> 237 | io_lib:format(" ~ts~n", [format_test_identifier(Data)]) 238 | end, 239 | Reason = io_lib:format(" %% ~ts~n", [format_pending_reason(Reason0)]), 240 | print_colored(Text, ?YELLOW, State), 241 | print_colored(Reason, ?CYAN, State). 242 | 243 | print_profile(#state{timings=T, status=Status, profile=true}=State) -> 244 | TopN = binomial_heap:take(10, T), 245 | TopNTime = abs(lists:sum([ Time || {Time, _} <- TopN ])), 246 | #{ [] := TLG } = Status, 247 | TotalTime = proplists:get_value(time, TLG), 248 | if TotalTime =/= undefined andalso TotalTime > 0 andalso TopN =/= [] -> 249 | TopNPct = (TopNTime / TotalTime) * 100, 250 | io:nl(), io:nl(), 251 | io:fwrite("Top ~p slowest tests (~ts, ~.1f% of total time):", [length(TopN), format_time(TopNTime), TopNPct]), 252 | lists:foreach(print_timing_fun(State), TopN), 253 | io:nl(); 254 | true -> ok 255 | end; 256 | print_profile(#state{profile=false}) -> 257 | ok. 258 | 259 | print_timing(#state{status=Status}) -> 260 | #{ [] := TLG } = Status, 261 | Time = proplists:get_value(time, TLG), 262 | io:nl(), 263 | io:fwrite("Finished in ~ts~n", [format_time(Time)]), 264 | ok. 265 | 266 | print_results(Data, State) -> 267 | Pass = proplists:get_value(pass, Data, 0), 268 | Fail = proplists:get_value(fail, Data, 0), 269 | Skip = proplists:get_value(skip, Data, 0), 270 | Cancel = proplists:get_value(cancel, Data, 0), 271 | Total = Pass + Fail + Skip + Cancel, 272 | {Color, Result} = if Fail > 0 -> {?RED, error}; 273 | Skip > 0; Cancel > 0 -> {?YELLOW, error}; 274 | Pass =:= 0 -> {?YELLOW, ok}; 275 | true -> {?GREEN, ok} 276 | end, 277 | print_results(Color, Total, Fail, Skip, Cancel, State), 278 | sync_end(Result). 279 | 280 | print_results(Color, 0, _, _, _, State) -> 281 | print_colored(Color, "0 tests\n", State); 282 | print_results(Color, Total, Fail, Skip, Cancel, State) -> 283 | SkipText = format_optional_result(Skip, "skipped"), 284 | CancelText = format_optional_result(Cancel, "cancelled"), 285 | Text = io_lib:format("~p tests, ~p failures~ts~ts~n", [Total, Fail, SkipText, CancelText]), 286 | print_colored(Text, Color, State). 287 | 288 | print_timing_fun(#state{status=Status}=State) -> 289 | fun({Time, Key}) -> 290 | #{ Key := TestData } = Status, 291 | TestId = format_test_identifier(TestData), 292 | io:nl(), 293 | io:fwrite(" ~ts~n", [TestId]), 294 | print_colored([" "|format_time(abs(Time))], ?CYAN, State) 295 | end. 296 | 297 | %%------------------------------------------ 298 | %% Print to the console with the given color 299 | %% if enabled. 300 | %%------------------------------------------ 301 | print_colored(Text, Color, #state{colored=true}) -> 302 | io:fwrite("~s~ts~s", [Color, Text, ?RESET]); 303 | print_colored(Text, _Color, #state{colored=false}) -> 304 | io:fwrite("~ts", [Text]). 305 | 306 | %%------------------------------------------ 307 | %% Generic data formatters 308 | %%------------------------------------------ 309 | format_function_name(M, F, A) -> 310 | io_lib:format("~ts:~ts/~p", [M, F, A]). 311 | 312 | format_optional_result(0, _) -> 313 | []; 314 | format_optional_result(Count, Text) -> 315 | io_lib:format(", ~p ~ts", [Count, Text]). 316 | 317 | format_test_identifier(Data) -> 318 | {Mod, Fun, Arity} = proplists:get_value(source, Data), 319 | Line = case proplists:get_value(line, Data) of 320 | 0 -> ""; 321 | L -> io_lib:format(":~p", [L]) 322 | end, 323 | Desc = case proplists:get_value(desc, Data) of 324 | undefined -> ""; 325 | DescText -> io_lib:format(": ~ts", [DescText]) 326 | end, 327 | io_lib:format("~ts~ts~ts", [format_function_name(Mod, Fun, Arity), Line, Desc]). 328 | 329 | format_time(undefined) -> 330 | "? seconds"; 331 | format_time(Time) -> 332 | io_lib:format("~.3f seconds", [Time / 1000]). 333 | 334 | format_pending_reason({module_not_found, M}) -> 335 | io_lib:format("Module '~ts' missing", [M]); 336 | format_pending_reason({no_such_function, {M,F,A}}) -> 337 | io_lib:format("Function ~ts undefined", [format_function_name(M,F,A)]); 338 | format_pending_reason({exit, Reason}) -> 339 | io_lib:format("Related process exited with reason: ~p", [Reason]); 340 | format_pending_reason(Reason) -> 341 | io_lib:format("Unknown error: ~p", [Reason]). 342 | 343 | %% @doc Formats all the known eunit assertions, you're on your own if 344 | %% you make an assertion yourself. 345 | format_assertion_failure(Type, Props, I) when Type =:= assertion_failed 346 | ; Type =:= assert -> 347 | Keys = proplists:get_keys(Props), 348 | HasEUnitProps = ([expression, value] -- Keys) =:= [], 349 | HasHamcrestProps = ([expected, actual, matcher] -- Keys) =:= [], 350 | if 351 | HasEUnitProps -> 352 | Expected = proplists:get_value(expected, Props), 353 | AssertMacro = case Expected of 354 | true -> assert; 355 | false -> assertNot 356 | end, 357 | [indent(I, "Failure/Error: ?~p(~ts)~n", [AssertMacro, proplists:get_value(expression, Props)]), 358 | indent(I, " expected: ~p~n", [Expected]), 359 | case proplists:get_value(value, Props) of 360 | Bool when is_boolean(Bool) -> 361 | indent(I, " got: ~p", [Bool]); 362 | {not_a_boolean, V} -> 363 | indent(I, " got: ~p", [V]) 364 | end]; 365 | HasHamcrestProps -> 366 | [indent(I, "Failure/Error: ?assertThat(~p)~n", [proplists:get_value(matcher, Props)]), 367 | indent(I, " expected: ~p~n", [proplists:get_value(expected, Props)]), 368 | indent(I, " got: ~p", [proplists:get_value(actual, Props)])]; 369 | true -> 370 | [indent(I, "Failure/Error: unknown assert: ~p", [Props])] 371 | end; 372 | 373 | format_assertion_failure(Type, Props, I) when Type =:= assertMatch_failed 374 | ; Type =:= assertMatch -> 375 | Expr = proplists:get_value(expression, Props), 376 | Pattern = proplists:get_value(pattern, Props), 377 | Value = proplists:get_value(value, Props), 378 | [indent(I, "Failure/Error: ?assertMatch(~ts, ~ts)~n", [Pattern, Expr]), 379 | indent(I, " expected: = ~ts~n", [Pattern]), 380 | indent(I, " got: ~p", [Value])]; 381 | 382 | format_assertion_failure(Type, Props, I) when Type =:= assertNotMatch_failed 383 | ; Type =:= assertNotMatch -> 384 | Expr = proplists:get_value(expression, Props), 385 | Pattern = proplists:get_value(pattern, Props), 386 | Value = proplists:get_value(value, Props), 387 | [indent(I, "Failure/Error: ?assertNotMatch(~ts, ~ts)~n", [Pattern, Expr]), 388 | indent(I, " expected not: = ~ts~n", [Pattern]), 389 | indent(I, " got: ~p", [Value])]; 390 | 391 | format_assertion_failure(Type, Props, I) when Type =:= assertEqual_failed 392 | ; Type =:= assertEqual -> 393 | Expr = proplists:get_value(expression, Props), 394 | Expected = proplists:get_value(expected, Props), 395 | Value = proplists:get_value(value, Props), 396 | [indent(I, "Failure/Error: ?assertEqual(~w, ~ts)~n", [Expected, 397 | Expr]), 398 | indent(I, " expected: ~p~n", [Expected]), 399 | indent(I, " got: ~p", [Value])]; 400 | 401 | format_assertion_failure(Type, Props, I) when Type =:= assertNotEqual_failed 402 | ; Type =:= assertNotEqual -> 403 | Expr = proplists:get_value(expression, Props), 404 | Value = proplists:get_value(value, Props), 405 | [indent(I, "Failure/Error: ?assertNotEqual(~p, ~ts)~n", 406 | [Value, Expr]), 407 | indent(I, " expected not: == ~p~n", [Value]), 408 | indent(I, " got: ~p", [Value])]; 409 | 410 | format_assertion_failure(Type, Props, I) when Type =:= assertException_failed 411 | ; Type =:= assertException -> 412 | Expr = proplists:get_value(expression, Props), 413 | Pattern = proplists:get_value(pattern, Props), 414 | {Class, Term} = extract_exception_pattern(Pattern), % I hate that we have to do this, why not just give DATA 415 | [indent(I, "Failure/Error: ?assertException(~ts, ~ts, ~ts)~n", [Class, Term, Expr]), 416 | case proplists:is_defined(unexpected_success, Props) of 417 | true -> 418 | [indent(I, " expected: exception ~ts but nothing was raised~n", [Pattern]), 419 | indent(I, " got: value ~p", [proplists:get_value(unexpected_success, Props)])]; 420 | false -> 421 | Ex = proplists:get_value(unexpected_exception, Props), 422 | [indent(I, " expected: exception ~ts~n", [Pattern]), 423 | indent(I, " got: exception ~p", [Ex])] 424 | end]; 425 | 426 | format_assertion_failure(Type, Props, I) when Type =:= assertNotException_failed 427 | ; Type =:= assertNotException -> 428 | Expr = proplists:get_value(expression, Props), 429 | Pattern = proplists:get_value(pattern, Props), 430 | {Class, Term} = extract_exception_pattern(Pattern), % I hate that we have to do this, why not just give DAT 431 | Ex = proplists:get_value(unexpected_exception, Props), 432 | [indent(I, "Failure/Error: ?assertNotException(~ts, ~ts, ~ts)~n", [Class, Term, Expr]), 433 | indent(I, " expected not: exception ~ts~n", [Pattern]), 434 | indent(I, " got: exception ~p", [Ex])]; 435 | 436 | format_assertion_failure(Type, Props, I) when Type =:= command_failed 437 | ; Type =:= command -> 438 | Cmd = proplists:get_value(command, Props), 439 | Expected = proplists:get_value(expected_status, Props), 440 | Status = proplists:get_value(status, Props), 441 | [indent(I, "Failure/Error: ?cmdStatus(~p, ~p)~n", [Expected, Cmd]), 442 | indent(I, " expected: status ~p~n", [Expected]), 443 | indent(I, " got: status ~p", [Status])]; 444 | 445 | format_assertion_failure(Type, Props, I) when Type =:= assertCmd_failed 446 | ; Type =:= assertCmd -> 447 | Cmd = proplists:get_value(command, Props), 448 | Expected = proplists:get_value(expected_status, Props), 449 | Status = proplists:get_value(status, Props), 450 | [indent(I, "Failure/Error: ?assertCmdStatus(~p, ~p)~n", [Expected, Cmd]), 451 | indent(I, " expected: status ~p~n", [Expected]), 452 | indent(I, " got: status ~p", [Status])]; 453 | 454 | format_assertion_failure(Type, Props, I) when Type =:= assertCmdOutput_failed 455 | ; Type =:= assertCmdOutput -> 456 | Cmd = proplists:get_value(command, Props), 457 | Expected = proplists:get_value(expected_output, Props), 458 | Output = proplists:get_value(output, Props), 459 | [indent(I, "Failure/Error: ?assertCmdOutput(~p, ~p)~n", [Expected, Cmd]), 460 | indent(I, " expected: ~p~n", [Expected]), 461 | indent(I, " got: ~p", [Output])]; 462 | 463 | format_assertion_failure(Type, Props, I) -> 464 | indent(I, "~p", [{Type, Props}]). 465 | 466 | indent(I, Fmt, Args) -> 467 | io_lib:format("~" ++ integer_to_list(I) ++ "s" ++ Fmt, [" "|Args]). 468 | 469 | extract_exception_pattern(Str) -> 470 | ["{", Class, Term|_] = re:split(Str, "[, ]{1,2}", [unicode,{return,list}]), 471 | {Class, Term}. 472 | -------------------------------------------------------------------------------- /test/capture_io.erl: -------------------------------------------------------------------------------- 1 | %% Copyright 2014 Sean Cribbs 2 | %% 3 | %% Licensed under the Apache License, Version 2.0 (the "License"); 4 | %% you may not use this file except in compliance with the License. 5 | %% You may obtain a copy of the License at 6 | %% 7 | %% http://www.apache.org/licenses/LICENSE-2.0 8 | %% 9 | %% Unless required by applicable law or agreed to in writing, software 10 | %% distributed under the License is distributed on an "AS IS" BASIS, 11 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | %% See the License for the specific language governing permissions and 13 | %% limitations under the License. 14 | 15 | 16 | %% 17 | %% @doc Simple IO device for capturing test output. 18 | %% 19 | -module(capture_io). 20 | -export([start_link/0, get_output/1, get_stop/1, reset/1, stop/1, capture/1]). 21 | -export([init/1, loop/1]). 22 | 23 | -record(state, { 24 | leader, 25 | output 26 | }). 27 | 28 | 29 | %% ============================================================================= 30 | %% Public API. 31 | %% ============================================================================= 32 | 33 | %% 34 | %% Start the capturing process. 35 | %% 36 | start_link() -> 37 | OldLeader = erlang:group_leader(), 38 | Pid = spawn_link(?MODULE,init,[OldLeader]), 39 | true = erlang:group_leader(Pid, self()), 40 | {ok, Pid}. 41 | 42 | 43 | %% 44 | %% Get captured data. 45 | %% 46 | get_output(Pid) -> 47 | Pid ! {get_output, self()}, 48 | receive 49 | {output, IoList} -> 50 | {ok, IoList} 51 | after 5000 -> 52 | {error, timeout} 53 | end. 54 | 55 | 56 | %% 57 | %% Get captured data and stop capturing. 58 | %% 59 | get_stop(Pid) -> 60 | Pid ! {get_stop, self()}, 61 | receive 62 | {output, IoList, OldLeader} -> 63 | true = erlang:group_leader(OldLeader, self()), 64 | {ok, IoList} 65 | after 5000 -> 66 | {error, timeout} 67 | end. 68 | 69 | 70 | %% 71 | %% Reset the captured data. 72 | %% 73 | reset(Pid) -> 74 | Pid ! reset, 75 | ok. 76 | 77 | 78 | %% 79 | %% Stop the IO device. 80 | %% 81 | stop(Pid) -> 82 | unlink(Pid), 83 | Pid ! {stop, self()}, 84 | receive 85 | {stopped, OldLeader} -> 86 | true = erlang:group_leader(OldLeader, self()), 87 | ok 88 | after 5000 -> 89 | {error, timeout} 90 | end. 91 | 92 | 93 | %% 94 | %% Capture output of a function. 95 | %% 96 | capture(Fun) -> 97 | {ok, Capture} = start_link(), 98 | Result = Fun(), 99 | {ok, Output} = get_stop(Capture), 100 | {ok, Output, Result}. 101 | 102 | 103 | %% ============================================================================= 104 | %% IO Device implementation. 105 | %% See `http://erlang.org/doc/apps/stdlib/io_protocol.html` for more details. 106 | %% ============================================================================= 107 | 108 | %% 109 | %% Initialization. 110 | %% 111 | init(OldLeader) -> 112 | ?MODULE:loop(#state{leader = OldLeader, output = []}). 113 | 114 | 115 | %% 116 | %% Main loop. 117 | %% 118 | loop(State = #state{leader = OldLeader, output = Output}) -> 119 | receive 120 | {io_request, From, ReplyAs, Request} -> 121 | case handle_request(Request, State) of 122 | {reply, Reply, NewState} -> 123 | From ! {io_reply, ReplyAs, Reply}, 124 | ?MODULE:loop(NewState) 125 | end; 126 | {get_output, From} -> 127 | From ! {output, unicode:characters_to_binary(lists:reverse(Output))}, 128 | ?MODULE:loop(State); 129 | {get_stop, From} -> 130 | From ! {output, unicode:characters_to_binary(lists:reverse(Output)), OldLeader}, 131 | exit(normal); 132 | reset -> 133 | ?MODULE:loop(State#state{output = []}); 134 | {stop, From} -> 135 | From ! {stopped, OldLeader}, 136 | exit(normal); 137 | _Unknown -> 138 | ?MODULE:loop(State) 139 | end. 140 | 141 | 142 | %% 143 | %% Handle output requests. 144 | %% 145 | handle_request({put_chars, _Encoding, Chars}, State = #state{output = Output}) -> 146 | {reply, ok, State#state{output = [Chars | Output]}}; 147 | 148 | handle_request({put_chars, Encoding, Module, Function, Args}, State) -> 149 | handle_request({put_chars, Encoding, apply(Module, Function, Args)}, State); 150 | 151 | handle_request({put_chars, Characters}, State) -> 152 | handle_request({put_chars, latin1, Characters}, State); 153 | 154 | handle_request({put_chars, Module, Function, Args}, State) -> 155 | handle_request({put_chars, latin1, Module, Function, Args}, State); 156 | 157 | handle_request(_, State) -> 158 | {reply, {error, unsupported}, State}. 159 | 160 | 161 | -------------------------------------------------------------------------------- /test/capture_io_tests.erl: -------------------------------------------------------------------------------- 1 | %% Copyright 2014 Sean Cribbs 2 | %% 3 | %% Licensed under the Apache License, Version 2.0 (the "License"); 4 | %% you may not use this file except in compliance with the License. 5 | %% You may obtain a copy of the License at 6 | %% 7 | %% http://www.apache.org/licenses/LICENSE-2.0 8 | %% 9 | %% Unless required by applicable law or agreed to in writing, software 10 | %% distributed under the License is distributed on an "AS IS" BASIS, 11 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | %% See the License for the specific language governing permissions and 13 | %% limitations under the License. 14 | -module(capture_io_tests). 15 | -include_lib("eunit/include/eunit.hrl"). 16 | 17 | 18 | basic_output_capture_test() -> 19 | {ok, Capture} = capture_io:start_link(), 20 | {ok, <<"">>} = capture_io:get_output(Capture), 21 | io:format("~s test ", ["some"]), 22 | io:format("~s test ", ["other"]), 23 | {ok, <<"some test other test ">>} = capture_io:get_output(Capture), 24 | ok = capture_io:reset(Capture), 25 | {ok, <<"">>} = capture_io:get_output(Capture), 26 | ok = capture_io:stop(Capture), 27 | ok. 28 | 29 | 30 | get_stop_test() -> 31 | {ok, Capture} = capture_io:start_link(), 32 | MonitorRef = erlang:monitor(process, Capture), 33 | io:format("~s test", ["this"]), 34 | {ok, <<"this test">>} = capture_io:get_stop(Capture), 35 | ok = receive {'DOWN', MonitorRef, process, Capture, _} -> ok after 1000 -> error end, 36 | ok. 37 | 38 | 39 | capture_fun_test() -> 40 | {ok, <<"fun test">>, ok} = capture_io:capture(fun () -> 41 | io:format("~s test", ["fun"]), ok 42 | end). 43 | 44 | 45 | -------------------------------------------------------------------------------- /test/eunit_progress_tests.erl: -------------------------------------------------------------------------------- 1 | %% Copyright 2014 Sean Cribbs 2 | %% 3 | %% Licensed under the Apache License, Version 2.0 (the "License"); 4 | %% you may not use this file except in compliance with the License. 5 | %% You may obtain a copy of the License at 6 | %% 7 | %% http://www.apache.org/licenses/LICENSE-2.0 8 | %% 9 | %% Unless required by applicable law or agreed to in writing, software 10 | %% distributed under the License is distributed on an "AS IS" BASIS, 11 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | %% See the License for the specific language governing permissions and 13 | %% limitations under the License. 14 | -module(eunit_progress_tests). 15 | -include_lib("eunit/include/eunit.hrl"). 16 | 17 | 18 | %% 19 | %% Check if `.` and `F` are printed. 20 | %% 21 | basic_test() -> 22 | {ok, Output, error} = capture_io:capture(fun () -> 23 | Tests = [ 24 | fun () -> ?assert(true) end, 25 | fun () -> ?assert(false) end, 26 | fun () -> ?assertNot(true) end, 27 | fun () -> error(some) end 28 | ], 29 | eunit:test(Tests, [no_tty, {report, {eunit_progress, [colored, profile]}}]) 30 | end), 31 | ?assertMatch(match, re:run(Output, "^.*\\..*F.*F.*F.*\nFailures.*", [{capture, none}])). 32 | 33 | 34 | %% 35 | %% Check if hamcrest assert failures are handled properly. 36 | %% 37 | hamcrest_assert_test() -> 38 | {ok, Output, error} = capture_io:capture(fun () -> 39 | Props = [{matcher, some}, {expected, other}, {actual, this}], 40 | Test = fun () -> erlang:error({assertion_failed, Props}) end, 41 | eunit:test(Test, [no_tty, {report, {eunit_progress, [colored, profile]}}]) 42 | end), 43 | Pattern = "\\?assertThat\\(some\\)(.|\n)*expected:.*other(.|\n)*got:.*this", 44 | ?assertMatch(match, re:run(Output, Pattern, [{capture, none}])). 45 | 46 | 47 | %% 48 | %% Check if unknown assert failures are handled properly. 49 | %% 50 | unknown_assert_test() -> 51 | {ok, Output, error} = capture_io:capture(fun () -> 52 | Props = [{my_description, is_much_better}], 53 | Test = fun () -> erlang:error({assertion_failed, Props}) end, 54 | eunit:test(Test, [no_tty, {report, {eunit_progress, [colored, profile]}}]) 55 | end), 56 | Pattern = "unknown assert:(.|\n)*my_description(.|\n)*is_much_better", 57 | ?assertMatch(match, re:run(Output, Pattern, [{capture, none}])). 58 | 59 | 60 | %% 61 | %% Check if exit reason is printed in the case, when a process linked with 62 | %% the test process is terminated. 63 | %% 64 | print_process_exit_test() -> 65 | {ok, Output, error} = capture_io:capture(fun () -> 66 | Proc = fun () -> exit(my_error) end, 67 | Test = fun () -> erlang:spawn_link(Proc), ok = receive after 100 -> error end end, 68 | eunit:test(Test, [no_tty, {report, {eunit_progress, [colored, profile]}}]) 69 | end), 70 | Pattern = "Related process exited with reason(.|\n)*my_error", 71 | ?assertMatch(match, re:run(Output, Pattern, [{capture, none}])). 72 | 73 | %% 74 | %% Unicode binaries and atoms should print correctly. We are not 75 | %% setting the console IO option for utf8, but at least we won't crash 76 | %% on badarg. For example, instead of the "ą" in the test, you will 77 | %% see << "\x{105}" / utf8 >> printed. 78 | %% 79 | print_unicode_values_test() -> 80 | {ok, Output, error} = capture_io:capture(fun () -> 81 | Test = ?_assertMatch(<<"ą"/utf8>>, <<"a"/utf8>>), 82 | eunit:test(Test, [no_tty, {report, {eunit_progress, [colored, profile]}}]) 83 | end), 84 | io:format("%%%%%%%%%%%%%%%%~n~ts~n%%%%%%%%%%%%%%%%~n", [Output]), 85 | Pattern = "\\{badarg,\\[\\{io_lib,format,", 86 | ?assertMatch(nomatch, re:run(Output, Pattern, [{capture, none}, unicode])). 87 | -------------------------------------------------------------------------------- /tools.mk: -------------------------------------------------------------------------------- 1 | REBAR ?= ./rebar 2 | 3 | compile-no-deps: 4 | ${REBAR} compile skip_deps=true 5 | 6 | test: compile 7 | ${REBAR} eunit skip_deps=true 8 | 9 | docs: 10 | ${REBAR} doc skip_deps=true 11 | 12 | xref: compile 13 | ${REBAR} xref skip_deps=true 14 | 15 | PLT ?= $(HOME)/.combo_dialyzer_plt 16 | LOCAL_PLT = .local_dialyzer_plt 17 | DIALYZER_FLAGS ?= -Wunmatched_returns 18 | 19 | ${PLT}: compile 20 | @if [ -f $(PLT) ]; then \ 21 | dialyzer --check_plt --plt $(PLT) --apps $(DIALYZER_APPS) && \ 22 | dialyzer --add_to_plt --plt $(PLT) --output_plt $(PLT) --apps $(DIALYZER_APPS) ; test $$? -ne 1; \ 23 | else \ 24 | dialyzer --build_plt --output_plt $(PLT) --apps $(DIALYZER_APPS); test $$? -ne 1; \ 25 | fi 26 | 27 | ${LOCAL_PLT}: compile 28 | @if [ -d deps ]; then \ 29 | if [ -f $(LOCAL_PLT) ]; then \ 30 | dialyzer --check_plt --plt $(LOCAL_PLT) deps/*/ebin && \ 31 | dialyzer --add_to_plt --plt $(LOCAL_PLT) --output_plt $(LOCAL_PLT) deps/*/ebin ; test $$? -ne 1; \ 32 | else \ 33 | dialyzer --build_plt --output_plt $(LOCAL_PLT) deps/*/ebin ; test $$? -ne 1; \ 34 | fi \ 35 | fi 36 | 37 | dialyzer-run: 38 | @echo "==> $(shell basename $(shell pwd)) (dialyzer)" 39 | @if [ -f $(LOCAL_PLT) ]; then \ 40 | PLTS="$(PLT) $(LOCAL_PLT)"; \ 41 | else \ 42 | PLTS=$(PLT); \ 43 | fi; \ 44 | if [ -f dialyzer.ignore-warnings ]; then \ 45 | if [ $$(grep -cvE '[^[:space:]]' dialyzer.ignore-warnings) -ne 0 ]; then \ 46 | echo "ERROR: dialyzer.ignore-warnings contains a blank/empty line, this will match all messages!"; \ 47 | exit 1; \ 48 | fi; \ 49 | dialyzer $(DIALYZER_FLAGS) --plts $${PLTS} -c ebin > dialyzer_warnings ; \ 50 | egrep -v "^\s*(done|Checking|Proceeding|Compiling)" dialyzer_warnings | grep -F -f dialyzer.ignore-warnings -v > dialyzer_unhandled_warnings ; \ 51 | cat dialyzer_unhandled_warnings ; \ 52 | [ $$(cat dialyzer_unhandled_warnings | wc -l) -eq 0 ] ; \ 53 | else \ 54 | dialyzer $(DIALYZER_FLAGS) --plts $${PLTS} -c ebin; \ 55 | fi 56 | 57 | dialyzer-quick: compile-no-deps dialyzer-run 58 | 59 | dialyzer: ${PLT} ${LOCAL_PLT} dialyzer-run 60 | 61 | cleanplt: 62 | @echo 63 | @echo "Are you sure? It takes several minutes to re-build." 64 | @echo Deleting $(PLT) and $(LOCAL_PLT) in 5 seconds. 65 | @echo 66 | sleep 5 67 | rm $(PLT) 68 | rm $(LOCAL_PLT) 69 | 70 | --------------------------------------------------------------------------------