You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@couchdb.apache.org by ja...@apache.org on 2019/02/21 03:52:30 UTC
[couchdb-ets-lru] branch time-unit-parameterization created (now
1794143)
This is an automated email from the ASF dual-hosted git repository.
jaydoane pushed a change to branch time-unit-parameterization
in repository https://gitbox.apache.org/repos/asf/couchdb-ets-lru.git.
at 1794143 Remove unnecessary modules application property
This branch includes the following new commits:
new 208d376 Initial import
new f64b413 Some PropEr tests
new d7f227f Just use ETap
new 3f2bae1 Refactor ets_lru into a gen_server
new 5aab9df Don't confuse argument ordering
new 9bcc758 Remove Cloudant build system remnants
new 24d5bce New build system for ets_lru
new c51bbec Fix up copyright headers
new d0e4594 Build with rebar
new aa817bd Add license headers
new cd8777b Fix a bug related to the change in 5aab9df
new 807c21a Add new match and match_object functions
new 4af7633 set module version to 1
new e9a75fb Allow direct access when using a registered process
new 359f637 add license file
new fb44bea Migrate the tests from etap to eunit
new 8a50cf5 Add Makefile
new 0912804 Integrate with Travis CI
new c05488c Fix flaky limits test.
new 80cc7e1 Allow an ets_lru to be completely disabled
new 1376e50 Merge branch '559-disable-ddoc-cache'
new 8c64f20 Fix flaky tests
new c952e2c Merge branch '670-fix-flaky-test'
new a954200 Remove unused var in tests
new 8f21319 Ignore build artefacts
new 15a7640 Remove unnecessary export_all
new 5891eee Drop support for Erlang versions pre OTP 19
new 40d705d Parameterize time unit
new 70abf79 Change ctime to strict monotonic time
new 1794143 Remove unnecessary modules application property
The 30 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
[couchdb-ets-lru] 29/30: Change ctime to strict monotonic time
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jaydoane pushed a commit to branch time-unit-parameterization
in repository https://gitbox.apache.org/repos/asf/couchdb-ets-lru.git
commit 70abf7929a03e3a6c0469d054aedd33f75001a32
Author: Jay Doane <ja...@apache.org>
AuthorDate: Wed Feb 20 19:48:29 2019 -0800
Change ctime to strict monotonic time
---
src/ets_lru.erl | 18 ++++++++----------
1 file changed, 8 insertions(+), 10 deletions(-)
diff --git a/src/ets_lru.erl b/src/ets_lru.erl
index 7db0c19..0f6fdb2 100644
--- a/src/ets_lru.erl
+++ b/src/ets_lru.erl
@@ -12,7 +12,7 @@
-module(ets_lru).
-behaviour(gen_server).
--vsn(1).
+-vsn(2).
-export([
@@ -53,7 +53,7 @@
key :: term(),
val :: term(),
atime :: strict_monotonic_time(),
- ctime :: time_value()
+ ctime :: strict_monotonic_time()
}).
-record(st, {
@@ -179,11 +179,10 @@ handle_call({insert, Key, Val}, _From, St) ->
true = ets:delete(St#st.atimes, ATime),
true = ets:insert(St#st.atimes, {NewATime, Key});
[] ->
- NewCTime = element(1, NewATime),
- Entry = #entry{key=Key, val=Val, atime=NewATime, ctime=NewCTime},
+ Entry = #entry{key=Key, val=Val, atime=NewATime, ctime=NewATime},
true = ets:insert(St#st.objects, Entry),
true = ets:insert(St#st.atimes, {NewATime, Key}),
- true = ets:insert(St#st.ctimes, {NewCTime, Key})
+ true = ets:insert(St#st.ctimes, {NewATime, Key})
end,
{reply, ok, St, 0};
@@ -286,9 +285,8 @@ trim_lifetime(#st{max_lifetime=Max}=St) ->
case ets:first(St#st.ctimes) of
'$end_of_table' ->
ok;
- CTime ->
- TimeDiff = Now - CTime,
- case TimeDiff > Max of
+ CTime = {Time, _} ->
+ case Now - Time > Max of
true ->
[{CTime, Key}] = ets:lookup(St#st.ctimes, CTime),
Pattern = #entry{key=Key, atime='$1', _='_'},
@@ -324,9 +322,9 @@ next_timeout(St) ->
case ets:first(St#st.ctimes) of
'$end_of_table' ->
infinity;
- CTime ->
+ {Time, _} ->
Now = erlang:monotonic_time(St#st.time_unit),
- TimeDiff = Now - CTime,
+ TimeDiff = Now - Time,
erlang:max(St#st.max_lifetime - TimeDiff, 0)
end.
[couchdb-ets-lru] 01/30: Initial import
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jaydoane pushed a commit to branch time-unit-parameterization
in repository https://gitbox.apache.org/repos/asf/couchdb-ets-lru.git
commit 208d376766457b29de225b69e5bd9e132464acf0
Author: Paul J. Davis <pa...@gmail.com>
AuthorDate: Mon Dec 17 23:25:30 2012 -0600
Initial import
---
.gitignore | 1 +
rebar | Bin 0 -> 119440 bytes
src/ets_lru.app.src | 11 +++
src/ets_lru.erl | 200 ++++++++++++++++++++++++++++++++++++++++++++++++++++
4 files changed, 212 insertions(+)
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..fc83a9a
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+ebin/
diff --git a/rebar b/rebar
new file mode 100755
index 0000000..ceabf62
Binary files /dev/null and b/rebar differ
diff --git a/src/ets_lru.app.src b/src/ets_lru.app.src
new file mode 100644
index 0000000..e7ebdcd
--- /dev/null
+++ b/src/ets_lru.app.src
@@ -0,0 +1,11 @@
+% Copyright 2012 Cloudant. All rights reserved.
+
+{application, ets_lru, [
+ {description, "ETS Base LRU Cache"},
+ {vsn, git},
+ {registered, []},
+ {applications, [
+ kernel,
+ stdlib
+ ]}
+]}.
diff --git a/src/ets_lru.erl b/src/ets_lru.erl
new file mode 100644
index 0000000..e74c343
--- /dev/null
+++ b/src/ets_lru.erl
@@ -0,0 +1,200 @@
+% Copyright 2012 Cloudant. All rights reserved.
+
+-module(ets_lru).
+
+
+-export([
+ create/2,
+ destroy/1,
+
+ insert/3,
+ lookup/2,
+ member/2,
+ remove/2,
+ hit/2,
+ expire/1,
+ clear/1
+]).
+
+
+-record(entry, {
+ key,
+ val,
+ atime
+}).
+
+-record(ets_lru, {
+ objects,
+ atimes,
+ named=false,
+
+ max_objs,
+ max_size,
+
+ lifetime
+}).
+
+
+create(Name, Options) ->
+ LRU = set_options(#ets_lru{}, Options),
+ Opts = case LRU#ets_lru.named of
+ true -> [named_table];
+ false -> []
+ end,
+ {OName, ATName} = table_names(Name),
+ {ok, LRU#ets_lru{
+ objects = ets:new(OName,
+ [set, protected, {keypos, #entry.key}] ++ Opts),
+ atimes = ets:new(ATName,
+ [ordered_set, protected] ++ Opts)
+ }}.
+
+
+destroy(#ets_lru{objects=Objs, atimes=ATimes}) ->
+ true = ets:delete(Objs),
+ true = ets:delete(ATimes),
+ ok.
+
+
+insert(#ets_lru{objects=Objs, atimes=ATs}=LRU, Key, Val) ->
+ NewATime = erlang:now(),
+ Pattern = #entry{key=Key, atime='$1', _='_'},
+ case ets:match(Objs, Pattern) of
+ [[ATime]] ->
+ true = ets:delete(ATs, ATime),
+ true = ets:insert(ATs, {NewATime, Key}),
+ true = ets:update_element(Objs, Key, {#entry.val, Val});
+ [] ->
+ true = ets:insert(ATs, {NewATime, Key}),
+ true = ets:insert(Objs, #entry{key=Key, val=Val, atime=NewATime})
+ end,
+ trim(LRU).
+
+
+lookup(#ets_lru{objects=Objs}=LRU, Key) ->
+ case ets:lookup(Objs, Key) of
+ [#entry{val=Val}] ->
+ hit(LRU, Key),
+ {ok, Val};
+ [] ->
+ not_found
+ end.
+
+
+member(#ets_lru{objects=Objs}, Key) ->
+ ets:member(Objs, Key).
+
+
+remove(#ets_lru{objects=Objs, atimes=ATs}=LRU, Key) ->
+ case ets:match(Objs, #entry{key=Key, atime='$1', _='_'}) of
+ [[ATime]] ->
+ true = ets:delete(ATs, ATime),
+ true = ets:delete(Objs, Key),
+ ok;
+ [] ->
+ ok
+ end,
+ false = member(LRU, Key),
+ ok.
+
+
+hit(#ets_lru{objects=Objs, atimes=ATs}=LRU, Key) ->
+ case ets:match(Objs, #entry{key=Key, atime='$1', _='_'}) of
+ [[ATime]] ->
+ NewATime = erlang:now(),
+ true = ets:delete(ATs, ATime),
+ true = ets:insert(ATs, {NewATime, Key}),
+ true = ets:update_element(Objs, Key, {#entry.atime, NewATime}),
+ ok;
+ [] ->
+ ok
+ end.
+
+
+expire(#ets_lru{lifetime=undefined}) ->
+ ok;
+expire(#ets_lru{objects=Objs, atimes=ATs, lifetime=LT}=LRU) ->
+ LTMicro = LT * 1000,
+ case ets:first(ATs) of
+ '$end_of_table' ->
+ ok;
+ ATime ->
+ case timer:now_diff(erlang:now(), ATime) > LTMicro of
+ true ->
+ [{ATime, Key}] = ets:lookup(ATs, ATime),
+ true = ets:delete(ATs, ATime),
+ true = ets:delete(Objs, Key),
+ expire(LRU);
+ false ->
+ ok
+ end
+ end.
+
+
+clear(#ets_lru{objects=Objs, atimes=ATs}) ->
+ true = ets:delete_all_objects(Objs),
+ true = ets:delete_all_objects(ATs),
+ ok.
+
+
+trim(#ets_lru{}=LRU) ->
+ case trim_count(LRU) of
+ trimmed -> trim(LRU);
+ _ -> ok
+ end,
+ case trim_size(LRU) of
+ trimmed -> trim(LRU);
+ _ -> ok
+ end.
+
+
+trim_count(#ets_lru{max_objs=undefined}) ->
+ ok;
+trim_count(#ets_lru{objects=Objs, max_objs=MO}=LRU) ->
+ case ets:info(Objs, size) > MO of
+ true -> drop_entry(LRU);
+ false -> ok
+ end.
+
+
+trim_size(#ets_lru{max_size=undefined}) ->
+ ok;
+trim_size(#ets_lru{objects=Objs, max_size=MS}=LRU) ->
+ case ets:info(Objs, memory) > MS of
+ true -> drop_entry(LRU);
+ false -> ok
+ end.
+
+
+drop_entry(#ets_lru{objects=Objs, atimes=ATs}) ->
+ case ets:first(ATs) of
+ '$end_of_table' ->
+ empty;
+ ATime ->
+ [{ATime, Key}] = ets:lookup(ATs, ATime),
+ true = ets:delete(ATs, ATime),
+ true = ets:delete(Objs, Key),
+ trimmed
+ end.
+
+
+set_options(LRU, []) ->
+ LRU;
+set_options(LRU, [named_tables | Rest]) ->
+ set_options(LRU#ets_lru{named=true}, Rest);
+set_options(LRU, [{max_objects, N} | Rest]) when is_integer(N), N > 0 ->
+ set_options(LRU#ets_lru{max_objs=N}, Rest);
+set_options(LRU, [{max_size, N} | Rest]) when is_integer(N), N > 0 ->
+ set_options(LRU#ets_lru{max_size=N}, Rest);
+set_options(LRU, [{lifetime, N} | Rest]) when is_integer(N), N > 0 ->
+ set_options(LRU#ets_lru{lifetime=N}, Rest);
+set_options(_, [Opt | _]) ->
+ throw({invalid_option, Opt}).
+
+
+table_names(Base) when is_atom(Base) ->
+ BList = atom_to_list(Base),
+ OName = list_to_atom(BList ++ "_objects"),
+ ATName = list_to_atom(BList ++ "_atimes"),
+ {OName, ATName}.
+
[couchdb-ets-lru] 28/30: Parameterize time unit
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jaydoane pushed a commit to branch time-unit-parameterization
in repository https://gitbox.apache.org/repos/asf/couchdb-ets-lru.git
commit 40d705dc585f07ecb1cbe6c2c75026a13fc8e339
Author: Jay Doane <ja...@gmail.com>
AuthorDate: Sat Dec 22 20:45:17 2018 -0800
Parameterize time unit
Previously, time values took the form {MegaSec, Sec, MicroSec}, and
erlang:now/0 was used to guarantee strict monotonic uniqueness for
access time. With the deprecation of erlang:now/0, tuples of the form
{time_value, unique_monotonic_integer} now guarantee uniqueness of
access time. By default, the time unit for internal comparison remains
'millisecond', although it can now be optionally parameterized by any
time unit supported by erlang:monotonic_time/1.
---
src/ets_lru.erl | 48 +++++++++++++++++++++++++++++++-----------------
test/ets_lru_test.erl | 13 +++++++++++++
2 files changed, 44 insertions(+), 17 deletions(-)
diff --git a/src/ets_lru.erl b/src/ets_lru.erl
index 7a366ba..7db0c19 100644
--- a/src/ets_lru.erl
+++ b/src/ets_lru.erl
@@ -44,11 +44,16 @@
]).
+-define(DEFAULT_TIME_UNIT, millisecond).
+
+-type time_value() :: integer().
+-type strict_monotonic_time() :: {time_value(), integer()}.
+
-record(entry, {
- key,
- val,
- atime,
- ctime
+ key :: term(),
+ val :: term(),
+ atime :: strict_monotonic_time(),
+ ctime :: time_value()
}).
-record(st, {
@@ -56,9 +61,10 @@
atimes,
ctimes,
- max_objs,
- max_size,
- max_lifetime
+ max_objs :: non_neg_integer() | undefined,
+ max_size :: non_neg_integer() | undefined,
+ max_lifetime :: non_neg_integer() | undefined,
+ time_unit = ?DEFAULT_TIME_UNIT :: atom()
}).
@@ -164,7 +170,7 @@ handle_call({match, KeySpec, ValueSpec}, _From, St) ->
{reply, Values, St, 0};
handle_call({insert, Key, Val}, _From, St) ->
- NewATime = erlang:now(),
+ NewATime = strict_monotonic_time(St#st.time_unit),
Pattern = #entry{key=Key, atime='$1', _='_'},
case ets:match(St#st.objects, Pattern) of
[[ATime]] ->
@@ -173,10 +179,11 @@ handle_call({insert, Key, Val}, _From, St) ->
true = ets:delete(St#st.atimes, ATime),
true = ets:insert(St#st.atimes, {NewATime, Key});
[] ->
- Entry = #entry{key=Key, val=Val, atime=NewATime, ctime=NewATime},
+ NewCTime = element(1, NewATime),
+ Entry = #entry{key=Key, val=Val, atime=NewATime, ctime=NewCTime},
true = ets:insert(St#st.objects, Entry),
true = ets:insert(St#st.atimes, {NewATime, Key}),
- true = ets:insert(St#st.ctimes, {NewATime, Key})
+ true = ets:insert(St#st.ctimes, {NewCTime, Key})
end,
{reply, ok, St, 0};
@@ -233,7 +240,7 @@ accessed(Key, St) ->
Pattern = #entry{key=Key, atime='$1', _='_'},
case ets:match(St#st.objects, Pattern) of
[[ATime]] ->
- NewATime = erlang:now(),
+ NewATime = strict_monotonic_time(St#st.time_unit),
Update = {#entry.atime, NewATime},
true = ets:update_element(St#st.objects, Key, Update),
true = ets:delete(St#st.atimes, ATime),
@@ -275,13 +282,13 @@ trim_size(#st{max_size=Max}=St) ->
trim_lifetime(#st{max_lifetime=undefined}) ->
ok;
trim_lifetime(#st{max_lifetime=Max}=St) ->
- Now = os:timestamp(),
+ Now = erlang:monotonic_time(St#st.time_unit),
case ets:first(St#st.ctimes) of
'$end_of_table' ->
ok;
CTime ->
- DiffInMilli = timer:now_diff(Now, CTime) div 1000,
- case DiffInMilli > Max of
+ TimeDiff = Now - CTime,
+ case TimeDiff > Max of
true ->
[{CTime, Key}] = ets:lookup(St#st.ctimes, CTime),
Pattern = #entry{key=Key, atime='$1', _='_'},
@@ -318,9 +325,9 @@ next_timeout(St) ->
'$end_of_table' ->
infinity;
CTime ->
- Now = os:timestamp(),
- DiffInMilli = timer:now_diff(Now, CTime) div 1000,
- erlang:max(St#st.max_lifetime - DiffInMilli, 0)
+ Now = erlang:monotonic_time(St#st.time_unit),
+ TimeDiff = Now - CTime,
+ erlang:max(St#st.max_lifetime - TimeDiff, 0)
end.
@@ -332,6 +339,8 @@ set_options(St, [{max_size, N} | Rest]) when is_integer(N), N >= 0 ->
set_options(St#st{max_size=N}, Rest);
set_options(St, [{max_lifetime, N} | Rest]) when is_integer(N), N >= 0 ->
set_options(St#st{max_lifetime=N}, Rest);
+set_options(St, [{time_unit, T} | Rest]) when is_atom(T) ->
+ set_options(St#st{time_unit=T}, Rest);
set_options(_, [Opt | _]) ->
throw({invalid_option, Opt}).
@@ -350,3 +359,8 @@ ct_table(Name) ->
table_name(Name, Ext) ->
list_to_atom(atom_to_list(Name) ++ Ext).
+
+
+-spec strict_monotonic_time(atom()) -> strict_monotonic_time().
+strict_monotonic_time(TimeUnit) ->
+ {erlang:monotonic_time(TimeUnit), erlang:unique_integer([monotonic])}.
diff --git a/test/ets_lru_test.erl b/test/ets_lru_test.erl
index 0f1cc4a..f54299a 100644
--- a/test/ets_lru_test.erl
+++ b/test/ets_lru_test.erl
@@ -325,3 +325,16 @@ stop_lru({ok, LRU}) ->
receive {'DOWN', Ref, process, LRU, Reason} -> Reason end;
stop_lru({error, _}) ->
ok.
+
+valid_parameterized_time_unit_test() ->
+ Opts = [{time_unit, microsecond}],
+ {ok, LRU} = ets_lru:start_link(lru_test, Opts),
+ ?assert(is_process_alive(LRU)),
+ ok = ets_lru:insert(LRU, foo, bar),
+ ?assertEqual({ok, bar}, ets_lru:lookup(LRU, foo)),
+ ?assertEqual(ok, ets_lru:stop(LRU)).
+
+invalid_parameterized_time_unit_test() ->
+ Opts = [{time_unit, invalid}],
+ {ok, LRU} = ets_lru:start_link(lru_test, Opts),
+ ?assertExit(_, ets_lru:insert(LRU, foo, bar)).
[couchdb-ets-lru] 06/30: Remove Cloudant build system remnants
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jaydoane pushed a commit to branch time-unit-parameterization
in repository https://gitbox.apache.org/repos/asf/couchdb-ets-lru.git
commit 9bcc75825385e01b9bd015eaa724dde91dacf38e
Author: Paul J. Davis <pa...@gmail.com>
AuthorDate: Wed Mar 20 05:04:53 2013 -0500
Remove Cloudant build system remnants
---
Makefile | 39 ---------------------------------------
rebar | Bin 119440 -> 0 bytes
2 files changed, 39 deletions(-)
diff --git a/Makefile b/Makefile
deleted file mode 100644
index f476779..0000000
--- a/Makefile
+++ /dev/null
@@ -1,39 +0,0 @@
-REBAR?=./rebar
-
-
-all: build
-
-
-clean:
- $(REBAR) clean
- rm -rf logs
- rm -rf .eunit
- rm -f test/*.beam
-
-
-distclean: clean
- git clean -fxd
-
-
-deps:
- @if test ! -d ./deps; then \
- $(REBAR) get-deps; \
- fi
-
-
-build: deps
- $(REBAR) compile
-
-
-etap: test/etap.beam test/tutil.beam
- prove test/*.t
-
-
-check: build etap
-
-
-%.beam: %.erl
- erlc -o test/ $<
-
-
-.PHONY: all clean distclean deps build eunit check
diff --git a/rebar b/rebar
deleted file mode 100755
index ceabf62..0000000
Binary files a/rebar and /dev/null differ
[couchdb-ets-lru] 21/30: Merge branch '559-disable-ddoc-cache'
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jaydoane pushed a commit to branch time-unit-parameterization
in repository https://gitbox.apache.org/repos/asf/couchdb-ets-lru.git
commit 1376e50b82571d98bb2cbd96f27d370b20b9fc24
Merge: c05488c 80cc7e1
Author: Joan Touzet <jo...@atypical.net>
AuthorDate: Fri Jun 2 16:30:56 2017 -0400
Merge branch '559-disable-ddoc-cache'
src/ets_lru.erl | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
[couchdb-ets-lru] 15/30: add license file
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jaydoane pushed a commit to branch time-unit-parameterization
in repository https://gitbox.apache.org/repos/asf/couchdb-ets-lru.git
commit 359f637a92c9b64e98affe9b6b8786a2aab0b1f6
Author: Robert Kowalski <ro...@kowalski.gd>
AuthorDate: Sat Mar 14 20:01:02 2015 +0100
add license file
---
LICENSE | 202 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 202 insertions(+)
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..f6cd2bc
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "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.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "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.
+
+ "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).
+
+ "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.
+
+ "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."
+
+ "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.
+
+ 2. Grant of Copyright License. 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.
+
+ 3. Grant of Patent License. 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.
+
+ 4. Redistribution. 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:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) 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
+
+ (d) 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.
+
+ 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.
+
+ 5. Submission of Contributions. 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.
+
+ 6. Trademarks. 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.
+
+ 7. Disclaimer of Warranty. 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.
+
+ 8. Limitation of Liability. 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.
+
+ 9. Accepting Warranty or Additional Liability. 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.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
[couchdb-ets-lru] 27/30: Drop support for Erlang versions pre OTP 19
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jaydoane pushed a commit to branch time-unit-parameterization
in repository https://gitbox.apache.org/repos/asf/couchdb-ets-lru.git
commit 5891eee9aeb66b46d932d4bdcd806accc1d1ead2
Author: Jay Doane <ja...@gmail.com>
AuthorDate: Sat Dec 22 18:04:11 2018 -0800
Drop support for Erlang versions pre OTP 19
---
.travis.yml | 10 +++-------
1 file changed, 3 insertions(+), 7 deletions(-)
diff --git a/.travis.yml b/.travis.yml
index 99e6cb3..6a3648b 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,10 +1,6 @@
language: erlang
otp_release:
- - 17.5
- - 17.4
- - 17.1
- - 17.0
- - R16B03-1
- - R14B04
- - R14B02
+ - 21.2
+ - 20.3
+ - 19.3
[couchdb-ets-lru] 23/30: Merge branch '670-fix-flaky-test'
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jaydoane pushed a commit to branch time-unit-parameterization
in repository https://gitbox.apache.org/repos/asf/couchdb-ets-lru.git
commit c952e2cf819613d0e406e430758405fac4d54431
Merge: 1376e50 8c64f20
Author: Paul J. Davis <pa...@gmail.com>
AuthorDate: Thu Jul 13 11:34:20 2017 -0500
Merge branch '670-fix-flaky-test'
test/ets_lru_test.erl | 27 ++++++++++++++++++++++++---
1 file changed, 24 insertions(+), 3 deletions(-)
[couchdb-ets-lru] 11/30: Fix a bug related to the change in 5aab9df
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jaydoane pushed a commit to branch time-unit-parameterization
in repository https://gitbox.apache.org/repos/asf/couchdb-ets-lru.git
commit cd8777bcc754e32fe64d58d57fbc516934f9738e
Author: Brian Mitchell <br...@cloudant.com>
AuthorDate: Tue Oct 15 10:02:55 2013 -0400
Fix a bug related to the change in 5aab9df
---
src/ets_lru.erl | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/ets_lru.erl b/src/ets_lru.erl
index 5880bd5..dc68fb8 100644
--- a/src/ets_lru.erl
+++ b/src/ets_lru.erl
@@ -114,8 +114,8 @@ terminate(_Reason, St) ->
handle_call({lookup, Key}, _From, St) ->
Reply = case ets:lookup(St#st.objects, Key) of
- [#entry{val=Val}] ->
- accessed(St, Key),
+ [#entry{val=Val} | _] ->
+ accessed(Key, St),
{ok, Val};
[] ->
not_found
[couchdb-ets-lru] 07/30: New build system for ets_lru
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jaydoane pushed a commit to branch time-unit-parameterization
in repository https://gitbox.apache.org/repos/asf/couchdb-ets-lru.git
commit 24d5bce4c668724459cb03e5834c14a74d41cfe0
Author: Paul J. Davis <pa...@gmail.com>
AuthorDate: Tue Mar 5 17:03:02 2013 -0600
New build system for ets_lru
---
Makefile.am | 34 ++++++++++++++++++++++++++++++++++
src/ets_lru.app.src | 5 ++++-
2 files changed, 38 insertions(+), 1 deletion(-)
diff --git a/Makefile.am b/Makefile.am
new file mode 100644
index 0000000..5fd6c7b
--- /dev/null
+++ b/Makefile.am
@@ -0,0 +1,34 @@
+## Licensed under the Apache License, Version 2.0 (the "License"); you may not
+## use this file except in compliance with the License. You may obtain a copy
+## of the License at
+##
+## http://www.apache.org/licenses/LICENSE-2.0
+##
+## Unless required by applicable law or agreed to in writing, software
+## distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+## WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+## License for the specific language governing permissions and limitations under
+## the License.
+
+ets_lruebindir = $(localerlanglibdir)/ets_lru/ebin
+
+ets_lruebin_DATA = $(compiled_files)
+
+source_files = \
+ src/ets_lru.app.src \
+ src/ets_lru.erl
+
+compiled_files = \
+ ebin/ets_lru.app \
+ ebin/ets_lru.beam
+
+EXTRA_DIST = $(source_files)
+CLEANFILES = $(compiled_files)
+
+ebin/%.app: src/%.app.src
+ @mkdir -p ebin/
+ sed -e "s|%version%|@version@|g" < $< > $@
+
+ebin/%.beam: src/%.erl
+ @mkdir -p ebin/
+ $(ERLC) -Wall -I$(top_srcdir)/src -o ebin/ $(ERLC_FLAGS) $<
diff --git a/src/ets_lru.app.src b/src/ets_lru.app.src
index e7ebdcd..3287e88 100644
--- a/src/ets_lru.app.src
+++ b/src/ets_lru.app.src
@@ -2,7 +2,10 @@
{application, ets_lru, [
{description, "ETS Base LRU Cache"},
- {vsn, git},
+ {vsn, "%version%"},
+ {modules, [
+ ets_lru
+ ]},
{registered, []},
{applications, [
kernel,
[couchdb-ets-lru] 25/30: Ignore build artefacts
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jaydoane pushed a commit to branch time-unit-parameterization
in repository https://gitbox.apache.org/repos/asf/couchdb-ets-lru.git
commit 8f213194f00e100a58a35b4f0d4e364ac2a93f4d
Author: Joan Touzet <jo...@atypical.net>
AuthorDate: Fri Oct 20 16:22:28 2017 -0400
Ignore build artefacts
---
.gitignore | 3 +++
1 file changed, 3 insertions(+)
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..3164eee
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,3 @@
+.rebar
+ebin/
+*~
[couchdb-ets-lru] 05/30: Don't confuse argument ordering
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jaydoane pushed a commit to branch time-unit-parameterization
in repository https://gitbox.apache.org/repos/asf/couchdb-ets-lru.git
commit 5aab9df4f452126aa2763eafdb8dff930f8c9712
Author: Paul J. Davis <pa...@gmail.com>
AuthorDate: Wed Jan 23 16:04:05 2013 -0600
Don't confuse argument ordering
---
src/ets_lru.erl | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/ets_lru.erl b/src/ets_lru.erl
index 4aecabf..b373f89 100644
--- a/src/ets_lru.erl
+++ b/src/ets_lru.erl
@@ -178,7 +178,7 @@ code_change(_OldVsn, St, _Extra) ->
{ok, St}.
-accessed(St, Key) ->
+accessed(Key, St) ->
Pattern = #entry{key=Key, atime='$1', _='_'},
case ets:match(St#st.objects, Pattern) of
[[ATime]] ->
[couchdb-ets-lru] 09/30: Build with rebar
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jaydoane pushed a commit to branch time-unit-parameterization
in repository https://gitbox.apache.org/repos/asf/couchdb-ets-lru.git
commit d0e45945606c5b9afc3a89a5184d713c6082367b
Author: Robert Newson <rn...@apache.org>
AuthorDate: Wed Dec 18 14:04:59 2013 +0000
Build with rebar
---
.gitignore | 5 -----
Makefile.am | 34 ----------------------------------
src/ets_lru.app.src | 2 +-
3 files changed, 1 insertion(+), 40 deletions(-)
diff --git a/.gitignore b/.gitignore
deleted file mode 100644
index 90bd4cb..0000000
--- a/.gitignore
+++ /dev/null
@@ -1,5 +0,0 @@
-erl_crash.dump
-
-.eunit/
-ebin/
-test/*.beam
diff --git a/Makefile.am b/Makefile.am
deleted file mode 100644
index 5fd6c7b..0000000
--- a/Makefile.am
+++ /dev/null
@@ -1,34 +0,0 @@
-## Licensed under the Apache License, Version 2.0 (the "License"); you may not
-## use this file except in compliance with the License. You may obtain a copy
-## of the License at
-##
-## http://www.apache.org/licenses/LICENSE-2.0
-##
-## Unless required by applicable law or agreed to in writing, software
-## distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-## WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-## License for the specific language governing permissions and limitations under
-## the License.
-
-ets_lruebindir = $(localerlanglibdir)/ets_lru/ebin
-
-ets_lruebin_DATA = $(compiled_files)
-
-source_files = \
- src/ets_lru.app.src \
- src/ets_lru.erl
-
-compiled_files = \
- ebin/ets_lru.app \
- ebin/ets_lru.beam
-
-EXTRA_DIST = $(source_files)
-CLEANFILES = $(compiled_files)
-
-ebin/%.app: src/%.app.src
- @mkdir -p ebin/
- sed -e "s|%version%|@version@|g" < $< > $@
-
-ebin/%.beam: src/%.erl
- @mkdir -p ebin/
- $(ERLC) -Wall -I$(top_srcdir)/src -o ebin/ $(ERLC_FLAGS) $<
diff --git a/src/ets_lru.app.src b/src/ets_lru.app.src
index 603c5d6..2573a0f 100644
--- a/src/ets_lru.app.src
+++ b/src/ets_lru.app.src
@@ -12,7 +12,7 @@
{application, ets_lru, [
{description, "ETS Base LRU Cache"},
- {vsn, "%version%"},
+ {vsn, git},
{modules, [
ets_lru
]},
[couchdb-ets-lru] 14/30: Allow direct access when using a
registered process
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jaydoane pushed a commit to branch time-unit-parameterization
in repository https://gitbox.apache.org/repos/asf/couchdb-ets-lru.git
commit e9a75fb72400044a04a36441a920016dce4ff84c
Author: Brian Mitchell <br...@p2p.io>
AuthorDate: Fri Dec 6 11:07:09 2013 -0500
Allow direct access when using a registered process
The match_object API currently takes both atoms and pids.
This change allows the atom case to skip a synchronous call
to the gen_server state. The old path remains to allow pids
to continue to work through the old call path since it
can't easily infer the lru objects table name.
BugzId: 26105
---
src/ets_lru.erl | 7 +++++++
test/06-match.t | 7 +++++--
2 files changed, 12 insertions(+), 2 deletions(-)
diff --git a/src/ets_lru.erl b/src/ets_lru.erl
index dbf3402..0c94e17 100644
--- a/src/ets_lru.erl
+++ b/src/ets_lru.erl
@@ -96,6 +96,13 @@ match(LRU, KeySpec, ValueSpec) ->
%% capturing placeholders will be aliased between the key and value
%% parts.
-spec match_object(atom() | pid(), term(), term()) -> [any()].
+match_object(Name, KeySpec, ValueSpec) when is_atom(Name) ->
+ Pattern = #entry{key=KeySpec, val=ValueSpec, _='_'},
+ Entries = ets:match_object(obj_table(Name), Pattern),
+ lists:map(fun(#entry{key=Key,val=Val}) ->
+ gen_server:cast(Name, {accessed, Key}),
+ Val
+ end, Entries);
match_object(LRU, KeySpec, ValueSpec) ->
gen_server:call(LRU, {match_object, KeySpec, ValueSpec}).
diff --git a/test/06-match.t b/test/06-match.t
index 907ae78..c409e8d 100644
--- a/test/06-match.t
+++ b/test/06-match.t
@@ -5,7 +5,7 @@
main([]) ->
code:add_pathz("test"),
code:add_pathz("ebin"),
- tutil:run(6, fun() -> test() end).
+ tutil:run(7, fun() -> test() end).
test() ->
?WITH_LRU(test_match_zero_values),
@@ -35,7 +35,10 @@ test_match_zero_objects(LRU) ->
test_match_one_object(LRU) ->
ets_lru:insert(LRU, ans, 42),
- etap:is(ets_lru:match_object(LRU, ans, '$1'), [42], "Single match_object").
+ ViaRegistered = ets_lru:match_object(test_lru, ans, '$1'),
+ etap:is(ViaRegistered, [42], "Single match_object (registered)"),
+ ViaPid = ets_lru:match_object(LRU, ans, '$1'),
+ etap:is(ViaPid, [42], "Single match_object (pid)").
test_match_many_objects(LRU) ->
ets_lru:insert(LRU, {color, blue}, a),
[couchdb-ets-lru] 10/30: Add license headers
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jaydoane pushed a commit to branch time-unit-parameterization
in repository https://gitbox.apache.org/repos/asf/couchdb-ets-lru.git
commit aa817bd22eb0ecc95180a1f386856a2e7da4b12f
Author: Paul J. Davis <pa...@gmail.com>
AuthorDate: Tue Feb 11 01:54:01 2014 -0600
Add license headers
---
test/01-basic-behavior.t | 11 +++++++++++
test/02-lru-options.t | 11 +++++++++++
test/03-limit-max-objects.t | 11 +++++++++++
test/04-limit-max-size.t | 11 +++++++++++
test/05-limit-lifetime.t | 11 +++++++++++
test/tutil.erl | 12 ++++++++++++
6 files changed, 67 insertions(+)
diff --git a/test/01-basic-behavior.t b/test/01-basic-behavior.t
index 7e87a5d..0015998 100755
--- a/test/01-basic-behavior.t
+++ b/test/01-basic-behavior.t
@@ -1,4 +1,15 @@
#! /usr/bin/env escript
+% Licensed under the Apache License, Version 2.0 (the "License"); you may not
+% use this file except in compliance with the License. You may obtain a copy of
+% the License at
+%
+% http://www.apache.org/licenses/LICENSE-2.0
+%
+% Unless required by applicable law or agreed to in writing, software
+% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+% License for the specific language governing permissions and limitations under
+% the License.
-define(WITH_LRU(F), tutil:with_lru(fun(LRU) -> F(LRU) end)).
diff --git a/test/02-lru-options.t b/test/02-lru-options.t
index 59d0ba1..c9fb721 100755
--- a/test/02-lru-options.t
+++ b/test/02-lru-options.t
@@ -1,4 +1,15 @@
#! /usr/bin/env escript
+% Licensed under the Apache License, Version 2.0 (the "License"); you may not
+% use this file except in compliance with the License. You may obtain a copy of
+% the License at
+%
+% http://www.apache.org/licenses/LICENSE-2.0
+%
+% Unless required by applicable law or agreed to in writing, software
+% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+% License for the specific language governing permissions and limitations under
+% the License.
main([]) ->
code:add_pathz("test"),
diff --git a/test/03-limit-max-objects.t b/test/03-limit-max-objects.t
index bd4e793..00a40a8 100755
--- a/test/03-limit-max-objects.t
+++ b/test/03-limit-max-objects.t
@@ -1,4 +1,15 @@
#! /usr/bin/env escript
+% Licensed under the Apache License, Version 2.0 (the "License"); you may not
+% use this file except in compliance with the License. You may obtain a copy of
+% the License at
+%
+% http://www.apache.org/licenses/LICENSE-2.0
+%
+% Unless required by applicable law or agreed to in writing, software
+% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+% License for the specific language governing permissions and limitations under
+% the License.
objs() -> 25.
diff --git a/test/04-limit-max-size.t b/test/04-limit-max-size.t
index 5cdf0ce..a54cdf0 100755
--- a/test/04-limit-max-size.t
+++ b/test/04-limit-max-size.t
@@ -1,4 +1,15 @@
#! /usr/bin/env escript
+% Licensed under the Apache License, Version 2.0 (the "License"); you may not
+% use this file except in compliance with the License. You may obtain a copy of
+% the License at
+%
+% http://www.apache.org/licenses/LICENSE-2.0
+%
+% Unless required by applicable law or agreed to in writing, software
+% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+% License for the specific language governing permissions and limitations under
+% the License.
max_size() -> 1024.
diff --git a/test/05-limit-lifetime.t b/test/05-limit-lifetime.t
index 95effb2..eb6d54d 100755
--- a/test/05-limit-lifetime.t
+++ b/test/05-limit-lifetime.t
@@ -1,4 +1,15 @@
#! /usr/bin/env escript
+% Licensed under the Apache License, Version 2.0 (the "License"); you may not
+% use this file except in compliance with the License. You may obtain a copy of
+% the License at
+%
+% http://www.apache.org/licenses/LICENSE-2.0
+%
+% Unless required by applicable law or agreed to in writing, software
+% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+% License for the specific language governing permissions and limitations under
+% the License.
lifetime() -> 100.
diff --git a/test/tutil.erl b/test/tutil.erl
index 3e4bd68..3bf154b 100644
--- a/test/tutil.erl
+++ b/test/tutil.erl
@@ -1,3 +1,15 @@
+% Licensed under the Apache License, Version 2.0 (the "License"); you may not
+% use this file except in compliance with the License. You may obtain a copy of
+% the License at
+%
+% http://www.apache.org/licenses/LICENSE-2.0
+%
+% Unless required by applicable law or agreed to in writing, software
+% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+% License for the specific language governing permissions and limitations under
+% the License.
+
-module(tutil).
-export([
[couchdb-ets-lru] 30/30: Remove unnecessary modules application
property
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jaydoane pushed a commit to branch time-unit-parameterization
in repository https://gitbox.apache.org/repos/asf/couchdb-ets-lru.git
commit 17941431843df6bd930b1483f8446638f361cfae
Author: Jay Doane <ja...@apache.org>
AuthorDate: Wed Feb 20 19:49:21 2019 -0800
Remove unnecessary modules application property
---
src/ets_lru.app.src | 3 ---
1 file changed, 3 deletions(-)
diff --git a/src/ets_lru.app.src b/src/ets_lru.app.src
index 2573a0f..c81ce11 100644
--- a/src/ets_lru.app.src
+++ b/src/ets_lru.app.src
@@ -13,9 +13,6 @@
{application, ets_lru, [
{description, "ETS Base LRU Cache"},
{vsn, git},
- {modules, [
- ets_lru
- ]},
{registered, []},
{applications, [
kernel,
[couchdb-ets-lru] 19/30: Fix flaky limits test.
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jaydoane pushed a commit to branch time-unit-parameterization
in repository https://gitbox.apache.org/repos/asf/couchdb-ets-lru.git
commit c05488c8b1d7ec1c3554a828e0c9bf2888932ed6
Author: Nick Vatamaniuc <va...@gmail.com>
AuthorDate: Wed Oct 7 13:09:33 2015 -0400
Fix flaky limits test.
In the limits test we check statistics with ets:info right after
eviction. Sometimes ets:info does not update immediately.
On first failure, delay for 1ms, then try again.
---
test/ets_lru_test.erl | 10 +++++++++-
1 file changed, 9 insertions(+), 1 deletion(-)
diff --git a/test/ets_lru_test.erl b/test/ets_lru_test.erl
index 8cfefcc..50ba1b6 100644
--- a/test/ets_lru_test.erl
+++ b/test/ets_lru_test.erl
@@ -286,7 +286,15 @@ insert_kvs(_, _, 0, _) ->
insert_kvs(Info, LRU, Count, Limit) ->
ets_lru:insert(LRU, Count, 1.5234),
case ets:info(lru_objects, Info) > Limit of
- true -> erlang:error(exceeded_limit);
+ true ->
+ % Retry again as eviction statistics
+ % returned by ets:info() can be delayed.
+ timer:sleep(1),
+ case ets:info(lru_objects, Info) > Limit of
+ true ->
+ erlang:error(exceeded_limit);
+ false -> true
+ end;
false -> true
end,
insert_kvs(Info, LRU, Count - 1, Limit).
[couchdb-ets-lru] 08/30: Fix up copyright headers
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jaydoane pushed a commit to branch time-unit-parameterization
in repository https://gitbox.apache.org/repos/asf/couchdb-ets-lru.git
commit c51bbec990bd9adbc408f9eda59d27e2caed2f52
Author: Robert Newson <rn...@apache.org>
AuthorDate: Thu Jun 13 13:42:11 2013 +0100
Fix up copyright headers
---
src/ets_lru.app.src | 12 +++++++++++-
src/ets_lru.erl | 12 +++++++++++-
2 files changed, 22 insertions(+), 2 deletions(-)
diff --git a/src/ets_lru.app.src b/src/ets_lru.app.src
index 3287e88..603c5d6 100644
--- a/src/ets_lru.app.src
+++ b/src/ets_lru.app.src
@@ -1,4 +1,14 @@
-% Copyright 2012 Cloudant. All rights reserved.
+% Licensed under the Apache License, Version 2.0 (the "License"); you may not
+% use this file except in compliance with the License. You may obtain a copy of
+% the License at
+%
+% http://www.apache.org/licenses/LICENSE-2.0
+%
+% Unless required by applicable law or agreed to in writing, software
+% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+% License for the specific language governing permissions and limitations under
+% the License.
{application, ets_lru, [
{description, "ETS Base LRU Cache"},
diff --git a/src/ets_lru.erl b/src/ets_lru.erl
index b373f89..5880bd5 100644
--- a/src/ets_lru.erl
+++ b/src/ets_lru.erl
@@ -1,4 +1,14 @@
-% Copyright 2012 Cloudant. All rights reserved.
+% Licensed under the Apache License, Version 2.0 (the "License"); you may not
+% use this file except in compliance with the License. You may obtain a copy of
+% the License at
+%
+% http://www.apache.org/licenses/LICENSE-2.0
+%
+% Unless required by applicable law or agreed to in writing, software
+% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+% License for the specific language governing permissions and limitations under
+% the License.
-module(ets_lru).
-behavior(gen_server).
[couchdb-ets-lru] 22/30: Fix flaky tests
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jaydoane pushed a commit to branch time-unit-parameterization
in repository https://gitbox.apache.org/repos/asf/couchdb-ets-lru.git
commit 8c64f20565bed7599ec8e2b7561f0636ccee2bb5
Author: Paul J. Davis <pa...@gmail.com>
AuthorDate: Thu Jul 13 11:24:45 2017 -0500
Fix flaky tests
The bad options test had a race condition between the process exit and
the unregistering of the name. If the unregister didn't happen quickly
enough then the next bad options test would break with an
already_started error.
Fixes apache/couchdb#670
---
test/ets_lru_test.erl | 27 ++++++++++++++++++++++++---
1 file changed, 24 insertions(+), 3 deletions(-)
diff --git a/test/ets_lru_test.erl b/test/ets_lru_test.erl
index 50ba1b6..912f6b7 100644
--- a/test/ets_lru_test.erl
+++ b/test/ets_lru_test.erl
@@ -138,9 +138,9 @@ basic_behavior_test_() ->
}
}.
-lru_options_test_() ->
+lru_good_options_test_() ->
{
- "Test LRU options",
+ "Test good LRU options",
{foreachx,
fun(Opts) ->
process_flag(trap_exit,true),
@@ -156,7 +156,28 @@ lru_options_test_() ->
{[{max_size, 2342923423942309423094}], fun test_good_opts/2},
{[{max_lifetime, 1}], fun test_good_opts/2},
{[{max_lifetime, 5}], fun test_good_opts/2},
- {[{max_lifetime, 1244209909180928348}], fun test_good_opts/2},
+ {[{max_lifetime, 1244209909180928348}], fun test_good_opts/2}
+ ]
+ }
+ }.
+
+lru_bad_options_test_() ->
+ {
+ "Test bad LRU options",
+ {foreachx,
+ fun(Opts) ->
+ process_flag(trap_exit,true),
+ ets_lru:start_link(?MODULE, Opts)
+ end,
+ fun(_, Cfg) ->
+ case whereis(?MODULE) of
+ Pid when is_pid(Pid) ->
+ stop_lru({ok, Pid});
+ undefined ->
+ ok
+ end
+ end,
+ [
{[{bingo, bango}], fun test_bad_opts/2},
{[12], fun test_bad_opts/2},
{[true], fun test_bad_opts/2}
[couchdb-ets-lru] 26/30: Remove unnecessary export_all
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jaydoane pushed a commit to branch time-unit-parameterization
in repository https://gitbox.apache.org/repos/asf/couchdb-ets-lru.git
commit 15a76408cb22a1629229cd19c029dccc18e8fbf7
Author: Jay Doane <ja...@gmail.com>
AuthorDate: Sat Dec 22 18:00:41 2018 -0800
Remove unnecessary export_all
---
test/ets_lru_test.erl | 1 -
1 file changed, 1 deletion(-)
diff --git a/test/ets_lru_test.erl b/test/ets_lru_test.erl
index 21d8e28..0f1cc4a 100644
--- a/test/ets_lru_test.erl
+++ b/test/ets_lru_test.erl
@@ -1,6 +1,5 @@
-module(ets_lru_test).
--compile([export_all]).
-include_lib("eunit/include/eunit.hrl").
[couchdb-ets-lru] 24/30: Remove unused var in tests
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jaydoane pushed a commit to branch time-unit-parameterization
in repository https://gitbox.apache.org/repos/asf/couchdb-ets-lru.git
commit a954200017683b887a545aadbf8d21aa26d3672a
Author: Eric Avdey <ei...@eiri.ca>
AuthorDate: Fri Sep 1 11:17:38 2017 -0300
Remove unused var in tests
---
test/ets_lru_test.erl | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/test/ets_lru_test.erl b/test/ets_lru_test.erl
index 912f6b7..21d8e28 100644
--- a/test/ets_lru_test.erl
+++ b/test/ets_lru_test.erl
@@ -169,7 +169,7 @@ lru_bad_options_test_() ->
process_flag(trap_exit,true),
ets_lru:start_link(?MODULE, Opts)
end,
- fun(_, Cfg) ->
+ fun(_, _) ->
case whereis(?MODULE) of
Pid when is_pid(Pid) ->
stop_lru({ok, Pid});
[couchdb-ets-lru] 03/30: Just use ETap
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jaydoane pushed a commit to branch time-unit-parameterization
in repository https://gitbox.apache.org/repos/asf/couchdb-ets-lru.git
commit d7f227f01946b6fe70cea4c88a1f6dde1a2aacee
Author: Paul J. Davis <pa...@gmail.com>
AuthorDate: Mon Dec 24 13:13:11 2012 -0600
Just use ETap
PropEr is fun and all but its super hard to debug failing tests and its
really not buying me that much in this case because I'm not really using
its generators for anything. ETap is good enough here.
---
.gitignore | 2 +-
Makefile | 10 +-
rebar.config | 12 -
src/ets_lru.erl | 5 +-
test/01-basic-behavior.t | 72 +++++
test/02-lru-options.t | 69 +++++
test/03-limit-max-objects.t | 26 ++
test/04-limit-max-size.t | 26 ++
test/05-limit-lifetime.t | 15 +
test/etap.erl | 612 +++++++++++++++++++++++++++++++++++++
test/ets_lru_behavior_tests.erl | 195 ------------
test/ets_lru_constraints_tests.erl | 120 --------
test/tutil.erl | 26 ++
13 files changed, 857 insertions(+), 333 deletions(-)
diff --git a/.gitignore b/.gitignore
index 9287ed2..f218820 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,3 @@
.eunit/
-deps/
ebin/
+test/*.beam
diff --git a/Makefile b/Makefile
index 77f45fd..f476779 100644
--- a/Makefile
+++ b/Makefile
@@ -25,11 +25,15 @@ build: deps
$(REBAR) compile
-eunit:
- $(REBAR) eunit skip_deps=true
+etap: test/etap.beam test/tutil.beam
+ prove test/*.t
-check: build eunit
+check: build etap
+
+
+%.beam: %.erl
+ erlc -o test/ $<
.PHONY: all clean distclean deps build eunit check
diff --git a/rebar.config b/rebar.config
deleted file mode 100644
index 660dc25..0000000
--- a/rebar.config
+++ /dev/null
@@ -1,12 +0,0 @@
-% Copyright 2012 Cloudant. All rights reserved.
-
-{deps, [
- {proper, ".*", {git, "https://github.com/manopapad/proper.git", "master"}}
-]}.
-
-{eunit_opts, [
- verbose,
- {report, {
- eunit_surefire, [{dir,"."}]
- }}
-]}.
diff --git a/src/ets_lru.erl b/src/ets_lru.erl
index e74c343..73398d9 100644
--- a/src/ets_lru.erl
+++ b/src/ets_lru.erl
@@ -98,7 +98,7 @@ remove(#ets_lru{objects=Objs, atimes=ATs}=LRU, Key) ->
ok.
-hit(#ets_lru{objects=Objs, atimes=ATs}=LRU, Key) ->
+hit(#ets_lru{objects=Objs, atimes=ATs}, Key) ->
case ets:match(Objs, #entry{key=Key, atime='$1', _='_'}) of
[[ATime]] ->
NewATime = erlang:now(),
@@ -114,12 +114,13 @@ hit(#ets_lru{objects=Objs, atimes=ATs}=LRU, Key) ->
expire(#ets_lru{lifetime=undefined}) ->
ok;
expire(#ets_lru{objects=Objs, atimes=ATs, lifetime=LT}=LRU) ->
+ Now = os:timestamp(),
LTMicro = LT * 1000,
case ets:first(ATs) of
'$end_of_table' ->
ok;
ATime ->
- case timer:now_diff(erlang:now(), ATime) > LTMicro of
+ case timer:now_diff(Now, ATime) > LTMicro of
true ->
[{ATime, Key}] = ets:lookup(ATs, ATime),
true = ets:delete(ATs, ATime),
diff --git a/test/01-basic-behavior.t b/test/01-basic-behavior.t
new file mode 100755
index 0000000..a35a944
--- /dev/null
+++ b/test/01-basic-behavior.t
@@ -0,0 +1,72 @@
+#! /usr/bin/env escript
+
+-define(WITH_LRU(F), tutil:with_lru(fun(LRU) -> F(LRU) end)).
+
+main([]) ->
+ code:add_pathz("test"),
+ code:add_pathz("ebin"),
+
+ tutil:run(12, fun() -> test() end).
+
+
+test() ->
+ test_lifecycle(),
+ ?WITH_LRU(test_insert_lookup),
+ ?WITH_LRU(test_insert_overwrite),
+ ?WITH_LRU(test_insert_remove),
+ ?WITH_LRU(test_member),
+ ?WITH_LRU(test_clear),
+
+ ok.
+
+
+test_lifecycle() ->
+ Resp = ets_lru:create(?MODULE, []),
+ etap:fun_is(
+ fun({ok, _LRU}) -> true; (_) -> false end,
+ Resp,
+ "ets_lru:create/2 returned an LRU"
+ ),
+ {ok, LRU} = Resp,
+ etap:is(ok, ets_lru:destroy(LRU), "Destroyed the LRU ok").
+
+
+test_insert_lookup(LRU) ->
+ ok = ets_lru:insert(LRU, foo, bar),
+ Resp = ets_lru:lookup(LRU, foo),
+ etap:is(Resp, {ok, bar}, "Lookup returned the inserted value").
+
+
+test_insert_overwrite(LRU) ->
+ ok = ets_lru:insert(LRU, foo, bar),
+ Resp1 = ets_lru:lookup(LRU, foo),
+ etap:is(Resp1, {ok, bar}, "Lookup returned the inserted value"),
+ ok = ets_lru:insert(LRU, foo, bam),
+ Resp2 = ets_lru:lookup(LRU, foo),
+ etap:is(Resp2, {ok, bam}, "Lookup returned the newly inserted value").
+
+
+test_insert_remove(LRU) ->
+ ok = ets_lru:insert(LRU, foo, bar),
+ Resp1 = ets_lru:lookup(LRU, foo),
+ etap:is(Resp1, {ok, bar}, "Lookup returned the inserted value"),
+ ok = ets_lru:remove(LRU, foo),
+ Resp2 = ets_lru:lookup(LRU, foo),
+ etap:is(Resp2, not_found, "Lookup returned not_found for removed value").
+
+
+test_member(LRU) ->
+ etap:is(false, ets_lru:member(LRU, foo), "Not yet a member: foo"),
+ ok = ets_lru:insert(LRU, foo, bar),
+ etap:is(true, ets_lru:member(LRU, foo), "Now a member: foo"),
+ ok = ets_lru:remove(LRU, foo),
+ etap:is(false, ets_lru:member(LRU, foo), "No longer a member: foo").
+
+
+test_clear(LRU) ->
+ ok = ets_lru:insert(LRU, foo, bar),
+ Resp1 = ets_lru:lookup(LRU, foo),
+ etap:is(Resp1, {ok, bar}, "Lookup returned the inserted value"),
+ ok = ets_lru:clear(LRU),
+ Resp2 = ets_lru:lookup(LRU, foo),
+ etap:is(Resp2, not_found, "Lookup returned not_found after a clear").
diff --git a/test/02-lru-options.t b/test/02-lru-options.t
new file mode 100755
index 0000000..7dbec8f
--- /dev/null
+++ b/test/02-lru-options.t
@@ -0,0 +1,69 @@
+#! /usr/bin/env escript
+
+main([]) ->
+ code:add_pathz("test"),
+ code:add_pathz("ebin"),
+
+ tutil:run(unknown, fun() -> test() end).
+
+
+test() ->
+ test_named_tables(),
+ test_max_objects(),
+ test_max_size(),
+ test_lifetime(),
+ test_bad_option(),
+
+ ok.
+
+
+test_named_tables() ->
+ {ok, LRU} = ets_lru:create(foo, [named_tables]),
+ etap:is(ets:info(foo_objects, size), 0, "foo_objects table exists"),
+ etap:is(ets:info(foo_atimes, size), 0, "foo_atimes table exists"),
+ ok = ets_lru:destroy(LRU),
+ etap:isnt(catch ets:info(foo_objects, size), 0, "foo_objects is gone"),
+ etap:isnt(catch ets:info(foo_atimes, size), 0, "foo_atimes is gone"),
+ ok.
+
+
+test_max_objects() ->
+ % See also: 03-limit-max-objects.t
+ test_good([{max_objects, 5}]),
+ test_good([{max_objects, 1}]),
+ test_good([{max_objects, 923928342098203942}]).
+
+
+test_max_size() ->
+ % See also: 04-limit-max-size.t
+ test_good([{max_size, 1}]),
+ test_good([{max_size, 5}]),
+ test_good([{max_size, 23423409090923423942309423094}]).
+
+
+test_lifetime() ->
+ % See also: 05-limit-lifetime.t
+ test_good([{lifetime, 1}]),
+ test_good([{lifetime, 5}]),
+ test_good([{lifetime, 1244209909182409328409283409238}]).
+
+
+test_bad_option() ->
+ test_bad([{bingo, bango}]),
+ test_bad([12]),
+ test_bad([true]).
+
+
+test_good(Options) ->
+ etap:fun_is(fun
+ ({ok, LRU}) -> ets_lru:destroy(LRU), true;
+ (_) -> false
+ end, ets_lru:create(?MODULE, Options), "LRU created ok with options").
+
+
+test_bad(Options) ->
+ etap:fun_is(fun
+ ({invalid_option, _}) -> true;
+ ({ok, LRU}) -> ets_lru:destroy(LRU), false;
+ (_) -> false
+ end, catch ets_lru:create(?MODULE, Options), "LRU error with options").
\ No newline at end of file
diff --git a/test/03-limit-max-objects.t b/test/03-limit-max-objects.t
new file mode 100755
index 0000000..ccf9e7d
--- /dev/null
+++ b/test/03-limit-max-objects.t
@@ -0,0 +1,26 @@
+#! /usr/bin/env escript
+
+objs() -> 25.
+
+main([]) ->
+ code:add_pathz("test"),
+ code:add_pathz("ebin"),
+
+ tutil:run(1, fun() -> test() end).
+
+
+test() ->
+ {ok, LRU} = ets_lru:create(lru, [named_tables, {max_objects, objs()}]),
+ etap:is(insert_kvs(LRU, 100 * objs()), ok, "Max object count ok"),
+ ok = ets_lru:destroy(LRU).
+
+
+insert_kvs(LRU, 0) ->
+ ok;
+insert_kvs(LRU, Count) ->
+ ets_lru:insert(LRU, Count, bar),
+ case ets:info(lru_objects, size) > objs() of
+ true -> erlang:error(exceeded_max_objects);
+ false -> ok
+ end,
+ insert_kvs(LRU, Count-1).
diff --git a/test/04-limit-max-size.t b/test/04-limit-max-size.t
new file mode 100755
index 0000000..b318e27
--- /dev/null
+++ b/test/04-limit-max-size.t
@@ -0,0 +1,26 @@
+#! /usr/bin/env escript
+
+max_size() -> 1024.
+
+main([]) ->
+ code:add_pathz("test"),
+ code:add_pathz("ebin"),
+
+ tutil:run(1, fun() -> test() end).
+
+
+test() ->
+ {ok, LRU} = ets_lru:create(lru, [named_tables, {max_size, max_size()}]),
+ etap:is(insert_kvs(LRU, 10000), ok, "Max size ok"),
+ ok = ets_lru:destroy(LRU).
+
+
+insert_kvs(LRU, 0) ->
+ ok;
+insert_kvs(LRU, Count) ->
+ ets_lru:insert(LRU, Count, 1.5234),
+ case ets:info(lru_objects, memory) > max_size() of
+ true -> erlang:error(exceeded_max_size);
+ false -> ok
+ end,
+ insert_kvs(LRU, Count-1).
diff --git a/test/05-limit-lifetime.t b/test/05-limit-lifetime.t
new file mode 100755
index 0000000..2421579
--- /dev/null
+++ b/test/05-limit-lifetime.t
@@ -0,0 +1,15 @@
+#! /usr/bin/env escript
+
+lifetime() -> 1024.
+
+main([]) ->
+ code:add_pathz("test"),
+ code:add_pathz("ebin"),
+
+ tutil:run(unknown, fun() -> test() end).
+
+
+test() ->
+ {ok, LRU} = ets_lru:create(lru, [named_tables, {lifetime, lifetime()}]),
+ % Figure out how to test this.
+ ok = ets_lru:destroy(LRU).
diff --git a/test/etap.erl b/test/etap.erl
new file mode 100644
index 0000000..6924d09
--- /dev/null
+++ b/test/etap.erl
@@ -0,0 +1,612 @@
+%% Copyright (c) 2008-2009 Nick Gerakines <ni...@gerakines.net>
+%%
+%% Permission is hereby granted, free of charge, to any person
+%% obtaining a copy of this software and associated documentation
+%% files (the "Software"), to deal in the Software without
+%% restriction, including without limitation the rights to use,
+%% copy, modify, merge, publish, distribute, sublicense, and/or sell
+%% copies of the Software, and to permit persons to whom the
+%% Software is furnished to do so, subject to the following
+%% conditions:
+%%
+%% The above copyright notice and this permission notice shall be
+%% included in all copies or substantial portions of the Software.
+%%
+%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+%% EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+%% OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+%% NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+%% HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+%% WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+%% FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+%% OTHER DEALINGS IN THE SOFTWARE.
+%%
+%% @author Nick Gerakines <ni...@gerakines.net> [http://socklabs.com/]
+%% @author Jeremy Wall <je...@marzhillstudios.com>
+%% @version 0.3.4
+%% @copyright 2007-2008 Jeremy Wall, 2008-2009 Nick Gerakines
+%% @reference http://testanything.org/wiki/index.php/Main_Page
+%% @reference http://en.wikipedia.org/wiki/Test_Anything_Protocol
+%% @todo Finish implementing the skip directive.
+%% @todo Document the messages handled by this receive loop.
+%% @todo Explain in documentation why we use a process to handle test input.
+%% @doc etap is a TAP testing module for Erlang components and applications.
+%% This module allows developers to test their software using the TAP method.
+%%
+%% <blockquote cite="http://en.wikipedia.org/wiki/Test_Anything_Protocol"><p>
+%% TAP, the Test Anything Protocol, is a simple text-based interface between
+%% testing modules in a test harness. TAP started life as part of the test
+%% harness for Perl but now has implementations in C/C++, Python, PHP, Perl
+%% and probably others by the time you read this.
+%% </p></blockquote>
+%%
+%% The testing process begins by defining a plan using etap:plan/1, running
+%% a number of etap tests and then calling eta:end_tests/0. Please refer to
+%% the Erlang modules in the t directory of this project for example tests.
+-module(etap).
+-vsn("0.3.4").
+
+-export([
+ ensure_test_server/0,
+ start_etap_server/0,
+ test_server/1,
+ msg/1, msg/2,
+ diag/1, diag/2,
+ expectation_mismatch_message/3,
+ plan/1,
+ end_tests/0,
+ not_ok/2, ok/2, is_ok/2, is/3, isnt/3, any/3, none/3,
+ fun_is/3, expect_fun/3, expect_fun/4,
+ is_greater/3,
+ skip/1, skip/2,
+ datetime/1,
+ skip/3,
+ bail/0, bail/1,
+ test_state/0, failure_count/0
+]).
+
+-export([
+ contains_ok/3,
+ is_before/4
+]).
+
+-export([
+ is_pid/2,
+ is_alive/2,
+ is_mfa/3
+]).
+
+-export([
+ loaded_ok/2,
+ can_ok/2, can_ok/3,
+ has_attrib/2, is_attrib/3,
+ is_behaviour/2
+]).
+
+-export([
+ dies_ok/2,
+ lives_ok/2,
+ throws_ok/3
+]).
+
+
+-record(test_state, {
+ planned = 0,
+ count = 0,
+ pass = 0,
+ fail = 0,
+ skip = 0,
+ skip_reason = ""
+}).
+
+%% @spec plan(N) -> Result
+%% N = unknown | skip | {skip, string()} | integer()
+%% Result = ok
+%% @doc Create a test plan and boot strap the test server.
+plan(unknown) ->
+ ensure_test_server(),
+ etap_server ! {self(), plan, unknown},
+ ok;
+plan(skip) ->
+ io:format("1..0 # skip~n");
+plan({skip, Reason}) ->
+ io:format("1..0 # skip ~s~n", [Reason]);
+plan(N) when is_integer(N), N > 0 ->
+ ensure_test_server(),
+ etap_server ! {self(), plan, N},
+ ok.
+
+%% @spec end_tests() -> ok
+%% @doc End the current test plan and output test results.
+%% @todo This should probably be done in the test_server process.
+end_tests() ->
+ case whereis(etap_server) of
+ undefined -> self() ! true;
+ _ -> etap_server ! {self(), state}
+ end,
+ State = receive X -> X end,
+ if
+ State#test_state.planned == -1 ->
+ io:format("1..~p~n", [State#test_state.count]);
+ true ->
+ ok
+ end,
+ case whereis(etap_server) of
+ undefined -> ok;
+ _ -> etap_server ! done, ok
+ end.
+
+bail() ->
+ bail("").
+
+bail(Reason) ->
+ etap_server ! {self(), diag, "Bail out! " ++ Reason},
+ etap_server ! done, ok,
+ ok.
+
+%% @spec test_state() -> Return
+%% Return = test_state_record() | {error, string()}
+%% @doc Return the current test state
+test_state() ->
+ etap_server ! {self(), state},
+ receive
+ X when is_record(X, test_state) -> X
+ after
+ 1000 -> {error, "Timed out waiting for etap server reply.~n"}
+ end.
+
+%% @spec failure_count() -> Return
+%% Return = integer() | {error, string()}
+%% @doc Return the current failure count
+failure_count() ->
+ case test_state() of
+ #test_state{fail=FailureCount} -> FailureCount;
+ X -> X
+ end.
+
+%% @spec msg(S) -> ok
+%% S = string()
+%% @doc Print a message in the test output.
+msg(S) -> etap_server ! {self(), diag, S}, ok.
+
+%% @spec msg(Format, Data) -> ok
+%% Format = atom() | string() | binary()
+%% Data = [term()]
+%% UnicodeList = [Unicode]
+%% Unicode = int()
+%% @doc Print a message in the test output.
+%% Function arguments are passed through io_lib:format/2.
+msg(Format, Data) -> msg(io_lib:format(Format, Data)).
+
+%% @spec diag(S) -> ok
+%% S = string()
+%% @doc Print a debug/status message related to the test suite.
+diag(S) -> msg("# " ++ S).
+
+%% @spec diag(Format, Data) -> ok
+%% Format = atom() | string() | binary()
+%% Data = [term()]
+%% UnicodeList = [Unicode]
+%% Unicode = int()
+%% @doc Print a debug/status message related to the test suite.
+%% Function arguments are passed through io_lib:format/2.
+diag(Format, Data) -> diag(io_lib:format(Format, Data)).
+
+%% @spec expectation_mismatch_message(Got, Expected, Desc) -> ok
+%% Got = any()
+%% Expected = any()
+%% Desc = string()
+%% @doc Print an expectation mismatch message in the test output.
+expectation_mismatch_message(Got, Expected, Desc) ->
+ msg(" ---"),
+ msg(" description: ~p", [Desc]),
+ msg(" found: ~p", [Got]),
+ msg(" wanted: ~p", [Expected]),
+ msg(" ..."),
+ ok.
+
+% @spec evaluate(Pass, Got, Expected, Desc) -> Result
+%% Pass = true | false
+%% Got = any()
+%% Expected = any()
+%% Desc = string()
+%% Result = true | false
+%% @doc Evaluate a test statement, printing an expectation mismatch message
+%% if the test failed.
+evaluate(Pass, Got, Expected, Desc) ->
+ case mk_tap(Pass, Desc) of
+ false ->
+ expectation_mismatch_message(Got, Expected, Desc),
+ false;
+ true ->
+ true
+ end.
+
+%% @spec ok(Expr, Desc) -> Result
+%% Expr = true | false
+%% Desc = string()
+%% Result = true | false
+%% @doc Assert that a statement is true.
+ok(Expr, Desc) -> evaluate(Expr == true, Expr, true, Desc).
+
+%% @spec not_ok(Expr, Desc) -> Result
+%% Expr = true | false
+%% Desc = string()
+%% Result = true | false
+%% @doc Assert that a statement is false.
+not_ok(Expr, Desc) -> evaluate(Expr == false, Expr, false, Desc).
+
+%% @spec is_ok(Expr, Desc) -> Result
+%% Expr = any()
+%% Desc = string()
+%% Result = true | false
+%% @doc Assert that two values are the same.
+is_ok(Expr, Desc) -> evaluate(Expr == ok, Expr, ok, Desc).
+
+%% @spec is(Got, Expected, Desc) -> Result
+%% Got = any()
+%% Expected = any()
+%% Desc = string()
+%% Result = true | false
+%% @doc Assert that two values are the same.
+is(Got, Expected, Desc) -> evaluate(Got == Expected, Got, Expected, Desc).
+
+%% @spec isnt(Got, Expected, Desc) -> Result
+%% Got = any()
+%% Expected = any()
+%% Desc = string()
+%% Result = true | false
+%% @doc Assert that two values are not the same.
+isnt(Got, Expected, Desc) -> evaluate(Got /= Expected, Got, Expected, Desc).
+
+%% @spec is_greater(ValueA, ValueB, Desc) -> Result
+%% ValueA = number()
+%% ValueB = number()
+%% Desc = string()
+%% Result = true | false
+%% @doc Assert that an integer is greater than another.
+is_greater(ValueA, ValueB, Desc) when is_integer(ValueA), is_integer(ValueB) ->
+ mk_tap(ValueA > ValueB, Desc).
+
+%% @spec any(Got, Items, Desc) -> Result
+%% Got = any()
+%% Items = [any()]
+%% Desc = string()
+%% Result = true | false
+%% @doc Assert that an item is in a list.
+any(Got, Items, Desc) when is_function(Got) ->
+ is(lists:any(Got, Items), true, Desc);
+any(Got, Items, Desc) ->
+ is(lists:member(Got, Items), true, Desc).
+
+%% @spec none(Got, Items, Desc) -> Result
+%% Got = any()
+%% Items = [any()]
+%% Desc = string()
+%% Result = true | false
+%% @doc Assert that an item is not in a list.
+none(Got, Items, Desc) when is_function(Got) ->
+ is(lists:any(Got, Items), false, Desc);
+none(Got, Items, Desc) ->
+ is(lists:member(Got, Items), false, Desc).
+
+%% @spec fun_is(Fun, Expected, Desc) -> Result
+%% Fun = function()
+%% Expected = any()
+%% Desc = string()
+%% Result = true | false
+%% @doc Use an anonymous function to assert a pattern match.
+fun_is(Fun, Expected, Desc) when is_function(Fun) ->
+ is(Fun(Expected), true, Desc).
+
+%% @spec expect_fun(ExpectFun, Got, Desc) -> Result
+%% ExpectFun = function()
+%% Got = any()
+%% Desc = string()
+%% Result = true | false
+%% @doc Use an anonymous function to assert a pattern match, using actual
+%% value as the argument to the function.
+expect_fun(ExpectFun, Got, Desc) ->
+ evaluate(ExpectFun(Got), Got, ExpectFun, Desc).
+
+%% @spec expect_fun(ExpectFun, Got, Desc, ExpectStr) -> Result
+%% ExpectFun = function()
+%% Got = any()
+%% Desc = string()
+%% ExpectStr = string()
+%% Result = true | false
+%% @doc Use an anonymous function to assert a pattern match, using actual
+%% value as the argument to the function.
+expect_fun(ExpectFun, Got, Desc, ExpectStr) ->
+ evaluate(ExpectFun(Got), Got, ExpectStr, Desc).
+
+%% @equiv skip(TestFun, "")
+skip(TestFun) when is_function(TestFun) ->
+ skip(TestFun, "").
+
+%% @spec skip(TestFun, Reason) -> ok
+%% TestFun = function()
+%% Reason = string()
+%% @doc Skip a test.
+skip(TestFun, Reason) when is_function(TestFun), is_list(Reason) ->
+ begin_skip(Reason),
+ catch TestFun(),
+ end_skip(),
+ ok.
+
+%% @spec skip(Q, TestFun, Reason) -> ok
+%% Q = true | false | function()
+%% TestFun = function()
+%% Reason = string()
+%% @doc Skips a test conditionally. The first argument to this function can
+%% either be the 'true' or 'false' atoms or a function that returns 'true' or
+%% 'false'.
+skip(QFun, TestFun, Reason) when is_function(QFun), is_function(TestFun), is_list(Reason) ->
+ case QFun() of
+ true -> begin_skip(Reason), TestFun(), end_skip();
+ _ -> TestFun()
+ end,
+ ok;
+
+skip(Q, TestFun, Reason) when is_function(TestFun), is_list(Reason), Q == true ->
+ begin_skip(Reason),
+ TestFun(),
+ end_skip(),
+ ok;
+
+skip(_, TestFun, Reason) when is_function(TestFun), is_list(Reason) ->
+ TestFun(),
+ ok.
+
+%% @private
+begin_skip(Reason) ->
+ etap_server ! {self(), begin_skip, Reason}.
+
+%% @private
+end_skip() ->
+ etap_server ! {self(), end_skip}.
+
+%% @spec contains_ok(string(), string(), string()) -> true | false
+%% @doc Assert that a string is contained in another string.
+contains_ok(Source, String, Desc) ->
+ etap:isnt(
+ string:str(Source, String),
+ 0,
+ Desc
+ ).
+
+%% @spec is_before(string(), string(), string(), string()) -> true | false
+%% @doc Assert that a string comes before another string within a larger body.
+is_before(Source, StringA, StringB, Desc) ->
+ etap:is_greater(
+ string:str(Source, StringB),
+ string:str(Source, StringA),
+ Desc
+ ).
+
+%% @doc Assert that a given variable is a pid.
+is_pid(Pid, Desc) when is_pid(Pid) -> etap:ok(true, Desc);
+is_pid(_, Desc) -> etap:ok(false, Desc).
+
+%% @doc Assert that a given process/pid is alive.
+is_alive(Pid, Desc) ->
+ etap:ok(erlang:is_process_alive(Pid), Desc).
+
+%% @doc Assert that the current function of a pid is a given {M, F, A} tuple.
+is_mfa(Pid, MFA, Desc) ->
+ etap:is({current_function, MFA}, erlang:process_info(Pid, current_function), Desc).
+
+%% @spec loaded_ok(atom(), string()) -> true | false
+%% @doc Assert that a module has been loaded successfully.
+loaded_ok(M, Desc) when is_atom(M) ->
+ etap:fun_is(fun({module, _}) -> true; (_) -> false end, code:load_file(M), Desc).
+
+%% @spec can_ok(atom(), atom()) -> true | false
+%% @doc Assert that a module exports a given function.
+can_ok(M, F) when is_atom(M), is_atom(F) ->
+ Matches = [X || {X, _} <- M:module_info(exports), X == F],
+ etap:ok(Matches > 0, lists:concat([M, " can ", F])).
+
+%% @spec can_ok(atom(), atom(), integer()) -> true | false
+%% @doc Assert that a module exports a given function with a given arity.
+can_ok(M, F, A) when is_atom(M); is_atom(F), is_number(A) ->
+ Matches = [X || X <- M:module_info(exports), X == {F, A}],
+ etap:ok(Matches > 0, lists:concat([M, " can ", F, "/", A])).
+
+%% @spec has_attrib(M, A) -> true | false
+%% M = atom()
+%% A = atom()
+%% @doc Asserts that a module has a given attribute.
+has_attrib(M, A) when is_atom(M), is_atom(A) ->
+ etap:isnt(
+ proplists:get_value(A, M:module_info(attributes), 'asdlkjasdlkads'),
+ 'asdlkjasdlkads',
+ lists:concat([M, " has attribute ", A])
+ ).
+
+%% @spec has_attrib(M, A. V) -> true | false
+%% M = atom()
+%% A = atom()
+%% V = any()
+%% @doc Asserts that a module has a given attribute with a given value.
+is_attrib(M, A, V) when is_atom(M) andalso is_atom(A) ->
+ etap:is(
+ proplists:get_value(A, M:module_info(attributes)),
+ [V],
+ lists:concat([M, "'s ", A, " is ", V])
+ ).
+
+%% @spec is_behavior(M, B) -> true | false
+%% M = atom()
+%% B = atom()
+%% @doc Asserts that a given module has a specific behavior.
+is_behaviour(M, B) when is_atom(M) andalso is_atom(B) ->
+ is_attrib(M, behaviour, B).
+
+%% @doc Assert that an exception is raised when running a given function.
+dies_ok(F, Desc) ->
+ case (catch F()) of
+ {'EXIT', _} -> etap:ok(true, Desc);
+ _ -> etap:ok(false, Desc)
+ end.
+
+%% @doc Assert that an exception is not raised when running a given function.
+lives_ok(F, Desc) ->
+ etap:is(try_this(F), success, Desc).
+
+%% @doc Assert that the exception thrown by a function matches the given exception.
+throws_ok(F, Exception, Desc) ->
+ try F() of
+ _ -> etap:ok(nok, Desc)
+ catch
+ _:E ->
+ etap:is(E, Exception, Desc)
+ end.
+
+%% @private
+%% @doc Run a function and catch any exceptions.
+try_this(F) when is_function(F, 0) ->
+ try F() of
+ _ -> success
+ catch
+ throw:E -> {throw, E};
+ error:E -> {error, E};
+ exit:E -> {exit, E}
+ end.
+
+%% @private
+%% @doc Start the etap_server process if it is not running already.
+ensure_test_server() ->
+ case whereis(etap_server) of
+ undefined ->
+ proc_lib:start(?MODULE, start_etap_server,[]);
+ _ ->
+ diag("The test server is already running.")
+ end.
+
+%% @private
+%% @doc Start the etap_server loop and register itself as the etap_server
+%% process.
+start_etap_server() ->
+ catch register(etap_server, self()),
+ proc_lib:init_ack(ok),
+ etap:test_server(#test_state{
+ planned = 0,
+ count = 0,
+ pass = 0,
+ fail = 0,
+ skip = 0,
+ skip_reason = ""
+ }).
+
+
+%% @private
+%% @doc The main etap_server receive/run loop. The etap_server receive loop
+%% responds to seven messages apperatining to failure or passing of tests.
+%% It is also used to initiate the testing process with the {_, plan, _}
+%% message that clears the current test state.
+test_server(State) ->
+ NewState = receive
+ {_From, plan, unknown} ->
+ io:format("# Current time local ~s~n", [datetime(erlang:localtime())]),
+ io:format("# Using etap version ~p~n", [ proplists:get_value(vsn, proplists:get_value(attributes, etap:module_info())) ]),
+ State#test_state{
+ planned = -1,
+ count = 0,
+ pass = 0,
+ fail = 0,
+ skip = 0,
+ skip_reason = ""
+ };
+ {_From, plan, N} ->
+ io:format("# Current time local ~s~n", [datetime(erlang:localtime())]),
+ io:format("# Using etap version ~p~n", [ proplists:get_value(vsn, proplists:get_value(attributes, etap:module_info())) ]),
+ io:format("1..~p~n", [N]),
+ State#test_state{
+ planned = N,
+ count = 0,
+ pass = 0,
+ fail = 0,
+ skip = 0,
+ skip_reason = ""
+ };
+ {_From, begin_skip, Reason} ->
+ State#test_state{
+ skip = 1,
+ skip_reason = Reason
+ };
+ {_From, end_skip} ->
+ State#test_state{
+ skip = 0,
+ skip_reason = ""
+ };
+ {_From, pass, Desc} ->
+ FullMessage = skip_diag(
+ " - " ++ Desc,
+ State#test_state.skip,
+ State#test_state.skip_reason
+ ),
+ io:format("ok ~p ~s~n", [State#test_state.count + 1, FullMessage]),
+ State#test_state{
+ count = State#test_state.count + 1,
+ pass = State#test_state.pass + 1
+ };
+
+ {_From, fail, Desc} ->
+ FullMessage = skip_diag(
+ " - " ++ Desc,
+ State#test_state.skip,
+ State#test_state.skip_reason
+ ),
+ io:format("not ok ~p ~s~n", [State#test_state.count + 1, FullMessage]),
+ State#test_state{
+ count = State#test_state.count + 1,
+ fail = State#test_state.fail + 1
+ };
+ {From, state} ->
+ From ! State,
+ State;
+ {_From, diag, Message} ->
+ io:format("~s~n", [Message]),
+ State;
+ {From, count} ->
+ From ! State#test_state.count,
+ State;
+ {From, is_skip} ->
+ From ! State#test_state.skip,
+ State;
+ done ->
+ exit(normal)
+ end,
+ test_server(NewState).
+
+%% @private
+%% @doc Process the result of a test and send it to the etap_server process.
+mk_tap(Result, Desc) ->
+ IsSkip = lib:sendw(etap_server, is_skip),
+ case [IsSkip, Result] of
+ [_, true] ->
+ etap_server ! {self(), pass, Desc},
+ true;
+ [1, _] ->
+ etap_server ! {self(), pass, Desc},
+ true;
+ _ ->
+ etap_server ! {self(), fail, Desc},
+ false
+ end.
+
+%% @private
+%% @doc Format a date/time string.
+datetime(DateTime) ->
+ {{Year, Month, Day}, {Hour, Min, Sec}} = DateTime,
+ io_lib:format("~4.10.0B-~2.10.0B-~2.10.0B ~2.10.0B:~2.10.0B:~2.10.0B", [Year, Month, Day, Hour, Min, Sec]).
+
+%% @private
+%% @doc Craft an output message taking skip/todo into consideration.
+skip_diag(Message, 0, _) ->
+ Message;
+skip_diag(_Message, 1, "") ->
+ " # SKIP";
+skip_diag(_Message, 1, Reason) ->
+ " # SKIP : " ++ Reason.
diff --git a/test/ets_lru_behavior_tests.erl b/test/ets_lru_behavior_tests.erl
deleted file mode 100644
index cd65ab2..0000000
--- a/test/ets_lru_behavior_tests.erl
+++ /dev/null
@@ -1,195 +0,0 @@
--module(ets_lru_behavior_tests).
--behaviour(proper_statem).
-
-
--include_lib("proper/include/proper.hrl").
--include_lib("eunit/include/eunit.hrl").
-
-
--export([
- initial_state/0,
- command/1,
- precondition/2,
- postcondition/3,
- next_state/3,
- random_key/1
-]).
-
-
--export([
- kvs_insert/4,
- kvs_lookup/2,
- kvs_remove/2,
- kvs_hit/2
-]).
-
-
--record(st, {
- ets_lru,
- kvs_lru
-}).
-
-
-proper_test_() ->
- PropErOpts = [
- {to_file, user},
- {max_size, 20},
- {numtests, 1000}
- ],
- {timeout, 3600, ?_assertEqual([], proper:module(?MODULE, PropErOpts))}.
-
-
-prop_lru() ->
- Fmt = "History: ~p~nState: ~p~nRes: ~p~nCmds:~n~p~n",
- ?FORALL(Cmds, commands(?MODULE),
- begin
- {H, S, R} = run_commands(?MODULE, Cmds),
- cleanup(S),
- ?WHENFAIL(
- io:format(standard_error, Fmt, [H, S, R, Cmds]),
- R =:= ok
- )
- end
- ).
-
-
-initial_state() ->
- #st{}.
-
-
-command(#st{ets_lru=undefined}=S) ->
- MaxObjs = 1 + random:uniform(5),
- Opts = [{max_objects, MaxObjs}],
- {call, ets_lru, create, [proper_ets_lru_tab, Opts]};
-command(S) ->
- Key = {call, ?MODULE, random_key, [S]},
- frequency([
- % Common operations
- {50, {call, ets_lru, insert, [S#st.ets_lru, key(), val()]}},
- {5, {call, ets_lru, lookup, [S#st.ets_lru, Key]}},
-
- % Make removes less common so we hit limits
- {3, {call, ets_lru, remove, [S#st.ets_lru, Key]}},
-
- {1, {call, ets_lru, insert, [S#st.ets_lru, Key, val()]}},
- {1, {call, ets_lru, lookup, [S#st.ets_lru, key()]}},
- {1, {call, ets_lru, remove, [S#st.ets_lru, key()]}},
-
- {1, {call, ets_lru, hit, [S#st.ets_lru, Key]}},
- {1, {call, ets_lru, clear, [S#st.ets_lru]}}
- ]).
-
-
-precondition(_, _) ->
- true.
-
-
-postcondition(_S, {call, _, create, [_, _]}, {ok, _}) ->
- true;
-postcondition(S, {call, _, insert, [_, _Key, _]}, ok) ->
- check_constraints(S);
-postcondition(S, {call, _, lookup, [_, Key]}, Val) ->
- case lists:keysearch(Key, 1, S#st.kvs_lru) of
- {value, {Key, V}} when {ok, V} == Val ->
- check_constraints(S);
- false when Val == not_found ->
- check_constraints(S);
- E ->
- io:format(standard_error, "Bad lookup: ~p ~p~n",
- [E, Val]),
- false
- end;
-postcondition(S, {call, _, remove, [_, _Key]}, ok) ->
- check_constraints(S);
-postcondition(S, {call, _, hit, [_, _Key]}, ok) ->
- check_constraints(S);
-postcondition(S, {call, _, clear, [_]}, ok) ->
- check_constraints(S);
-postcondition(_S, _C, _V) ->
- io:format(standard_error, "BAD CALL: ~p ~p~n", [_C, _V]),
- false.
-
-
-check_constraints(S) ->
- ELRU = S#st.ets_lru,
- Count = ets:info(element(2, ELRU), size),
- MaxCount = element(5, ELRU),
- case Count > MaxCount of
- true ->
- io:format(standard_error, "Max count exceeded: ~p ~p~n",
- [Count, MaxCount]);
- false ->
- ok
- end,
- Count =< MaxCount.
-
-
-next_state(S, V, {call, _, create, [_, _]}) ->
- S#st{
- ets_lru={call, erlang, element, [2, V]},
- kvs_lru=[]
- };
-next_state(#st{kvs_lru=KVs}=S, _V, {call, _, insert, [_, Key, Val]}) ->
- S#st{
- kvs_lru={call, ?MODULE, kvs_insert, [KVs, Key, Val, S#st.ets_lru]}
- };
-next_state(#st{kvs_lru=KVs}=S, _V, {call, _, lookup, [_, Key]}) ->
- S#st{
- kvs_lru={call, ?MODULE, kvs_lookup, [KVs, Key]}
- };
-next_state(#st{kvs_lru=KVs}=S, _V, {call, _, remove, [_, Key]}) ->
- S#st{
- kvs_lru={call, ?MODULE, kvs_remove, [KVs, Key]}
- };
-next_state(#st{kvs_lru=KVs}=S, _V, {call, _, hit, [_, Key]}) ->
- S#st{
- kvs_lru={call, ?MODULE, kvs_hit, [KVs, Key]}
- };
-next_state(S, _V, {call, _, clear, [_]}) ->
- S#st{
- kvs_lru=[]
- }.
-
-
-cleanup(#st{ets_lru=undefined}) ->
- ok;
-cleanup(S) ->
- ets_lru:destroy(S#st.ets_lru).
-
-
-random_key(#st{kvs_lru=KVs}) ->
- Keys = [foo] ++ [K || {K, _V, _T} <- KVs],
- NumKeys = erlang:length(Keys),
- KeyPos = random:uniform(NumKeys),
- lists:nth(KeyPos, Keys).
-
-
-% Simple inefficient LRU implementation
-
-kvs_insert(KVs, K, V, ELRU) ->
- Max = element(5, ELRU),
- NewKVs = [{K, V} | lists:keydelete(K, 1, KVs)],
- lists:sublist(NewKVs, Max).
-
-
-kvs_lookup(KVs, K) ->
- case lists:keysearch(K, 1, KVs) of
- {value, {K, V}} ->
- TmpKVs = lists:keydelete(K, 1, KVs),
- [{K, V} | TmpKVs];
- false ->
- KVs
- end.
-
-
-kvs_remove(KVs, K) ->
- lists:keydelete(K, 1, KVs).
-
-
-kvs_hit(S, K) ->
- kvs_lookup(S, K).
-
-
-key() -> any().
-val() -> any().
-
diff --git a/test/ets_lru_constraints_tests.erl b/test/ets_lru_constraints_tests.erl
deleted file mode 100644
index ebd2f37..0000000
--- a/test/ets_lru_constraints_tests.erl
+++ /dev/null
@@ -1,120 +0,0 @@
--module(ets_lru_max_count_tests).
--behaviour(proper_statem).
-
-
--include_lib("proper/include/proper.hrl").
--include_lib("eunit/include/eunit.hrl").
-
-
--export([
- initial_state/0,
- command/1,
- precondition/2,
- postcondition/3,
- next_state/3,
- random_key/1
-]).
-
-
--record(st, {lru, keys}).
-
-
-proper_test_() ->
- PropErOpts = [
- {to_file, user},
- {max_size, 25},
- {numtests, 1000}
- ],
- {timeout, 3600, ?_assertEqual([], proper:module(?MODULE, PropErOpts))}.
-
-
-prop_lru() ->
- Fmt = "History: ~p~nState: ~p~nRes: ~p~nCmds:~n~p~n",
- ?FORALL(Cmds, commands(?MODULE),
- begin
- {H, S, R} = run_commands(?MODULE, Cmds),
- cleanup(S),
- ?WHENFAIL(
- io:format(standard_error, Fmt, [H, S, R, Cmds]),
- R =:= ok
- )
- end
- ).
-
-
-initial_state() ->
- #st{keys=[]}.
-
-
-command(#st{lru=undefined}=S) ->
- MaxObjs = 1 + random:uniform(10),
- MaxSize = 512 + random:uniform(128),
- Opts = [{max_objects, MaxObjs}, {max_size, MaxSize}],
- {call, ets_lru, create, [proper_ets_lru_tab, Opts]};
-command(S) ->
- Key = {call, ?MODULE, random_key, [S#st.keys]},
- frequency([
- {50, {call, ets_lru, insert, [S#st.lru, key(), val()]}},
- {1, {call, ets_lru, lookup, [S#st.lru, Key]}},
- {1, {call, ets_lru, remove, [S#st.lru, Key]}},
- {1, {call, ets_lru, hit, [S#st.lru, Key]}}
- ]).
-
-
-precondition(_, _) ->
- true.
-
-
-postcondition(_S, {call, _, create, [_, _]}, {ok, _}) ->
- true;
-postcondition(S, _C, _V) ->
- check_constraints(S).
-
-
-check_constraints(S) ->
- Count = ets:info(element(2, S#st.lru), size),
- MaxCount = element(5, S#st.lru),
- case Count > MaxCount of
- true ->
- io:format(standard_error, "Max count exceeded: ~p ~p~n",
- [Count, MaxCount]);
- false ->
- ok
- end,
- Size = ets:info(element(2, S#st.lru), memory),
- MaxSize = element(6, S#st.lru),
- case Size > MaxSize of
- true ->
- io:format(standard_error, "Max size exceeded: ~p ~p~n",
- [Size, MaxSize]);
- false ->
- ok
- end,
- Count =< MaxCount andalso Size =< MaxSize.
-
-
-next_state(S, V, {call, _, create, [_, _]}) ->
- S#st{
- lru={call, erlang, element, [2, V]}
- };
-next_state(S, _V, {call, _, insert, [_, Key, _Val]}) ->
- S#st{keys=[Key | S#st.keys]};
-next_state(S, _V, _C) ->
- S.
-
-
-cleanup(#st{lru=undefined}) ->
- ok;
-cleanup(S) ->
- ets_lru:destroy(S#st.lru).
-
-
-random_key(Keys0) ->
- Keys = [foo] ++ Keys0,
- NumKeys = erlang:length(Keys),
- KeyPos = random:uniform(NumKeys),
- lists:nth(KeyPos, Keys).
-
-
-key() -> any().
-val() -> any().
diff --git a/test/tutil.erl b/test/tutil.erl
new file mode 100644
index 0000000..ac258e6
--- /dev/null
+++ b/test/tutil.erl
@@ -0,0 +1,26 @@
+-module(tutil).
+
+-export([
+ run/2,
+ with_lru/1
+]).
+
+
+run(Plan, Fun) ->
+ etap:plan(Plan),
+ case (catch Fun()) of
+ ok ->
+ etap:end_tests();
+ Error ->
+ Msg = lists:flatten(io_lib:format("Error: ~p", [Error])),
+ etap:bail(Msg)
+ end.
+
+
+with_lru(Fun) ->
+ {ok, LRU} = ets_lru:create(?MODULE, []),
+ try
+ Fun(LRU)
+ after
+ ets_lru:destroy(LRU)
+ end.
\ No newline at end of file
[couchdb-ets-lru] 20/30: Allow an ets_lru to be completely disabled
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jaydoane pushed a commit to branch time-unit-parameterization
in repository https://gitbox.apache.org/repos/asf/couchdb-ets-lru.git
commit 80cc7e1a21e35a643c7b9f26b9939ac6af0cc5ce
Author: Joan Touzet <jo...@atypical.net>
AuthorDate: Fri Jun 2 03:09:13 2017 -0400
Allow an ets_lru to be completely disabled
---
src/ets_lru.erl | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/src/ets_lru.erl b/src/ets_lru.erl
index 0c94e17..7a366ba 100644
--- a/src/ets_lru.erl
+++ b/src/ets_lru.erl
@@ -326,11 +326,11 @@ next_timeout(St) ->
set_options(St, []) ->
St;
-set_options(St, [{max_objects, N} | Rest]) when is_integer(N), N > 0 ->
+set_options(St, [{max_objects, N} | Rest]) when is_integer(N), N >= 0 ->
set_options(St#st{max_objs=N}, Rest);
-set_options(St, [{max_size, N} | Rest]) when is_integer(N), N > 0 ->
+set_options(St, [{max_size, N} | Rest]) when is_integer(N), N >= 0 ->
set_options(St#st{max_size=N}, Rest);
-set_options(St, [{max_lifetime, N} | Rest]) when is_integer(N), N > 0 ->
+set_options(St, [{max_lifetime, N} | Rest]) when is_integer(N), N >= 0 ->
set_options(St#st{max_lifetime=N}, Rest);
set_options(_, [Opt | _]) ->
throw({invalid_option, Opt}).
[couchdb-ets-lru] 13/30: set module version to 1
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jaydoane pushed a commit to branch time-unit-parameterization
in repository https://gitbox.apache.org/repos/asf/couchdb-ets-lru.git
commit 4af7633f9288a89f11ae51b4b32d36fd38565f39
Author: Robert Newson <ro...@cloudant.com>
AuthorDate: Fri Nov 22 16:38:15 2013 +0000
set module version to 1
---
src/ets_lru.erl | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/src/ets_lru.erl b/src/ets_lru.erl
index 7311081..dbf3402 100644
--- a/src/ets_lru.erl
+++ b/src/ets_lru.erl
@@ -11,7 +11,8 @@
% the License.
-module(ets_lru).
--behavior(gen_server).
+-behaviour(gen_server).
+-vsn(1).
-export([
[couchdb-ets-lru] 02/30: Some PropEr tests
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jaydoane pushed a commit to branch time-unit-parameterization
in repository https://gitbox.apache.org/repos/asf/couchdb-ets-lru.git
commit f64b4136dd4d7f551be29bbbbb2b8ddc6d892ede
Author: Paul J. Davis <pa...@gmail.com>
AuthorDate: Tue Dec 18 02:56:03 2012 -0600
Some PropEr tests
These are only semi-thorough but I'm resanobly confident that the LRU
works as advertised. I still need to go through and add tests for lease expirations though.
---
.gitignore | 2 +
Makefile | 35 +++++++
rebar.config | 12 +++
test/ets_lru_behavior_tests.erl | 195 +++++++++++++++++++++++++++++++++++++
test/ets_lru_constraints_tests.erl | 120 +++++++++++++++++++++++
5 files changed, 364 insertions(+)
diff --git a/.gitignore b/.gitignore
index fc83a9a..9287ed2 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1 +1,3 @@
+.eunit/
+deps/
ebin/
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..77f45fd
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,35 @@
+REBAR?=./rebar
+
+
+all: build
+
+
+clean:
+ $(REBAR) clean
+ rm -rf logs
+ rm -rf .eunit
+ rm -f test/*.beam
+
+
+distclean: clean
+ git clean -fxd
+
+
+deps:
+ @if test ! -d ./deps; then \
+ $(REBAR) get-deps; \
+ fi
+
+
+build: deps
+ $(REBAR) compile
+
+
+eunit:
+ $(REBAR) eunit skip_deps=true
+
+
+check: build eunit
+
+
+.PHONY: all clean distclean deps build eunit check
diff --git a/rebar.config b/rebar.config
new file mode 100644
index 0000000..660dc25
--- /dev/null
+++ b/rebar.config
@@ -0,0 +1,12 @@
+% Copyright 2012 Cloudant. All rights reserved.
+
+{deps, [
+ {proper, ".*", {git, "https://github.com/manopapad/proper.git", "master"}}
+]}.
+
+{eunit_opts, [
+ verbose,
+ {report, {
+ eunit_surefire, [{dir,"."}]
+ }}
+]}.
diff --git a/test/ets_lru_behavior_tests.erl b/test/ets_lru_behavior_tests.erl
new file mode 100644
index 0000000..cd65ab2
--- /dev/null
+++ b/test/ets_lru_behavior_tests.erl
@@ -0,0 +1,195 @@
+-module(ets_lru_behavior_tests).
+-behaviour(proper_statem).
+
+
+-include_lib("proper/include/proper.hrl").
+-include_lib("eunit/include/eunit.hrl").
+
+
+-export([
+ initial_state/0,
+ command/1,
+ precondition/2,
+ postcondition/3,
+ next_state/3,
+ random_key/1
+]).
+
+
+-export([
+ kvs_insert/4,
+ kvs_lookup/2,
+ kvs_remove/2,
+ kvs_hit/2
+]).
+
+
+-record(st, {
+ ets_lru,
+ kvs_lru
+}).
+
+
+proper_test_() ->
+ PropErOpts = [
+ {to_file, user},
+ {max_size, 20},
+ {numtests, 1000}
+ ],
+ {timeout, 3600, ?_assertEqual([], proper:module(?MODULE, PropErOpts))}.
+
+
+prop_lru() ->
+ Fmt = "History: ~p~nState: ~p~nRes: ~p~nCmds:~n~p~n",
+ ?FORALL(Cmds, commands(?MODULE),
+ begin
+ {H, S, R} = run_commands(?MODULE, Cmds),
+ cleanup(S),
+ ?WHENFAIL(
+ io:format(standard_error, Fmt, [H, S, R, Cmds]),
+ R =:= ok
+ )
+ end
+ ).
+
+
+initial_state() ->
+ #st{}.
+
+
+command(#st{ets_lru=undefined}=S) ->
+ MaxObjs = 1 + random:uniform(5),
+ Opts = [{max_objects, MaxObjs}],
+ {call, ets_lru, create, [proper_ets_lru_tab, Opts]};
+command(S) ->
+ Key = {call, ?MODULE, random_key, [S]},
+ frequency([
+ % Common operations
+ {50, {call, ets_lru, insert, [S#st.ets_lru, key(), val()]}},
+ {5, {call, ets_lru, lookup, [S#st.ets_lru, Key]}},
+
+ % Make removes less common so we hit limits
+ {3, {call, ets_lru, remove, [S#st.ets_lru, Key]}},
+
+ {1, {call, ets_lru, insert, [S#st.ets_lru, Key, val()]}},
+ {1, {call, ets_lru, lookup, [S#st.ets_lru, key()]}},
+ {1, {call, ets_lru, remove, [S#st.ets_lru, key()]}},
+
+ {1, {call, ets_lru, hit, [S#st.ets_lru, Key]}},
+ {1, {call, ets_lru, clear, [S#st.ets_lru]}}
+ ]).
+
+
+precondition(_, _) ->
+ true.
+
+
+postcondition(_S, {call, _, create, [_, _]}, {ok, _}) ->
+ true;
+postcondition(S, {call, _, insert, [_, _Key, _]}, ok) ->
+ check_constraints(S);
+postcondition(S, {call, _, lookup, [_, Key]}, Val) ->
+ case lists:keysearch(Key, 1, S#st.kvs_lru) of
+ {value, {Key, V}} when {ok, V} == Val ->
+ check_constraints(S);
+ false when Val == not_found ->
+ check_constraints(S);
+ E ->
+ io:format(standard_error, "Bad lookup: ~p ~p~n",
+ [E, Val]),
+ false
+ end;
+postcondition(S, {call, _, remove, [_, _Key]}, ok) ->
+ check_constraints(S);
+postcondition(S, {call, _, hit, [_, _Key]}, ok) ->
+ check_constraints(S);
+postcondition(S, {call, _, clear, [_]}, ok) ->
+ check_constraints(S);
+postcondition(_S, _C, _V) ->
+ io:format(standard_error, "BAD CALL: ~p ~p~n", [_C, _V]),
+ false.
+
+
+check_constraints(S) ->
+ ELRU = S#st.ets_lru,
+ Count = ets:info(element(2, ELRU), size),
+ MaxCount = element(5, ELRU),
+ case Count > MaxCount of
+ true ->
+ io:format(standard_error, "Max count exceeded: ~p ~p~n",
+ [Count, MaxCount]);
+ false ->
+ ok
+ end,
+ Count =< MaxCount.
+
+
+next_state(S, V, {call, _, create, [_, _]}) ->
+ S#st{
+ ets_lru={call, erlang, element, [2, V]},
+ kvs_lru=[]
+ };
+next_state(#st{kvs_lru=KVs}=S, _V, {call, _, insert, [_, Key, Val]}) ->
+ S#st{
+ kvs_lru={call, ?MODULE, kvs_insert, [KVs, Key, Val, S#st.ets_lru]}
+ };
+next_state(#st{kvs_lru=KVs}=S, _V, {call, _, lookup, [_, Key]}) ->
+ S#st{
+ kvs_lru={call, ?MODULE, kvs_lookup, [KVs, Key]}
+ };
+next_state(#st{kvs_lru=KVs}=S, _V, {call, _, remove, [_, Key]}) ->
+ S#st{
+ kvs_lru={call, ?MODULE, kvs_remove, [KVs, Key]}
+ };
+next_state(#st{kvs_lru=KVs}=S, _V, {call, _, hit, [_, Key]}) ->
+ S#st{
+ kvs_lru={call, ?MODULE, kvs_hit, [KVs, Key]}
+ };
+next_state(S, _V, {call, _, clear, [_]}) ->
+ S#st{
+ kvs_lru=[]
+ }.
+
+
+cleanup(#st{ets_lru=undefined}) ->
+ ok;
+cleanup(S) ->
+ ets_lru:destroy(S#st.ets_lru).
+
+
+random_key(#st{kvs_lru=KVs}) ->
+ Keys = [foo] ++ [K || {K, _V, _T} <- KVs],
+ NumKeys = erlang:length(Keys),
+ KeyPos = random:uniform(NumKeys),
+ lists:nth(KeyPos, Keys).
+
+
+% Simple inefficient LRU implementation
+
+kvs_insert(KVs, K, V, ELRU) ->
+ Max = element(5, ELRU),
+ NewKVs = [{K, V} | lists:keydelete(K, 1, KVs)],
+ lists:sublist(NewKVs, Max).
+
+
+kvs_lookup(KVs, K) ->
+ case lists:keysearch(K, 1, KVs) of
+ {value, {K, V}} ->
+ TmpKVs = lists:keydelete(K, 1, KVs),
+ [{K, V} | TmpKVs];
+ false ->
+ KVs
+ end.
+
+
+kvs_remove(KVs, K) ->
+ lists:keydelete(K, 1, KVs).
+
+
+kvs_hit(S, K) ->
+ kvs_lookup(S, K).
+
+
+key() -> any().
+val() -> any().
+
diff --git a/test/ets_lru_constraints_tests.erl b/test/ets_lru_constraints_tests.erl
new file mode 100644
index 0000000..ebd2f37
--- /dev/null
+++ b/test/ets_lru_constraints_tests.erl
@@ -0,0 +1,120 @@
+-module(ets_lru_max_count_tests).
+-behaviour(proper_statem).
+
+
+-include_lib("proper/include/proper.hrl").
+-include_lib("eunit/include/eunit.hrl").
+
+
+-export([
+ initial_state/0,
+ command/1,
+ precondition/2,
+ postcondition/3,
+ next_state/3,
+ random_key/1
+]).
+
+
+-record(st, {lru, keys}).
+
+
+proper_test_() ->
+ PropErOpts = [
+ {to_file, user},
+ {max_size, 25},
+ {numtests, 1000}
+ ],
+ {timeout, 3600, ?_assertEqual([], proper:module(?MODULE, PropErOpts))}.
+
+
+prop_lru() ->
+ Fmt = "History: ~p~nState: ~p~nRes: ~p~nCmds:~n~p~n",
+ ?FORALL(Cmds, commands(?MODULE),
+ begin
+ {H, S, R} = run_commands(?MODULE, Cmds),
+ cleanup(S),
+ ?WHENFAIL(
+ io:format(standard_error, Fmt, [H, S, R, Cmds]),
+ R =:= ok
+ )
+ end
+ ).
+
+
+initial_state() ->
+ #st{keys=[]}.
+
+
+command(#st{lru=undefined}=S) ->
+ MaxObjs = 1 + random:uniform(10),
+ MaxSize = 512 + random:uniform(128),
+ Opts = [{max_objects, MaxObjs}, {max_size, MaxSize}],
+ {call, ets_lru, create, [proper_ets_lru_tab, Opts]};
+command(S) ->
+ Key = {call, ?MODULE, random_key, [S#st.keys]},
+ frequency([
+ {50, {call, ets_lru, insert, [S#st.lru, key(), val()]}},
+ {1, {call, ets_lru, lookup, [S#st.lru, Key]}},
+ {1, {call, ets_lru, remove, [S#st.lru, Key]}},
+ {1, {call, ets_lru, hit, [S#st.lru, Key]}}
+ ]).
+
+
+precondition(_, _) ->
+ true.
+
+
+postcondition(_S, {call, _, create, [_, _]}, {ok, _}) ->
+ true;
+postcondition(S, _C, _V) ->
+ check_constraints(S).
+
+
+check_constraints(S) ->
+ Count = ets:info(element(2, S#st.lru), size),
+ MaxCount = element(5, S#st.lru),
+ case Count > MaxCount of
+ true ->
+ io:format(standard_error, "Max count exceeded: ~p ~p~n",
+ [Count, MaxCount]);
+ false ->
+ ok
+ end,
+ Size = ets:info(element(2, S#st.lru), memory),
+ MaxSize = element(6, S#st.lru),
+ case Size > MaxSize of
+ true ->
+ io:format(standard_error, "Max size exceeded: ~p ~p~n",
+ [Size, MaxSize]);
+ false ->
+ ok
+ end,
+ Count =< MaxCount andalso Size =< MaxSize.
+
+
+next_state(S, V, {call, _, create, [_, _]}) ->
+ S#st{
+ lru={call, erlang, element, [2, V]}
+ };
+next_state(S, _V, {call, _, insert, [_, Key, _Val]}) ->
+ S#st{keys=[Key | S#st.keys]};
+next_state(S, _V, _C) ->
+ S.
+
+
+cleanup(#st{lru=undefined}) ->
+ ok;
+cleanup(S) ->
+ ets_lru:destroy(S#st.lru).
+
+
+random_key(Keys0) ->
+ Keys = [foo] ++ Keys0,
+ NumKeys = erlang:length(Keys),
+ KeyPos = random:uniform(NumKeys),
+ lists:nth(KeyPos, Keys).
+
+
+key() -> any().
+val() -> any().
[couchdb-ets-lru] 17/30: Add Makefile
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jaydoane pushed a commit to branch time-unit-parameterization
in repository https://gitbox.apache.org/repos/asf/couchdb-ets-lru.git
commit 8a50cf5714e861f6fbafa78c424370005f6bd529
Author: Alexander Shorin <kx...@apache.org>
AuthorDate: Fri Jul 24 05:49:21 2015 +0300
Add Makefile
---
Makefile | 41 +++++++++++++++++++++++++++++++++++++++++
1 file changed, 41 insertions(+)
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..058a7ec
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,41 @@
+REBAR?=rebar
+
+
+.PHONY: all
+# target: all - Makes everything
+all: build
+
+
+.PHONY: build
+# target: build - Builds the project
+build:
+ $(REBAR) compile
+
+
+.PHONY: check
+# target: check - Checks if project builds and passes all the tests
+check: build eunit
+
+
+.PHONY: clean
+# target: clean - Removes build artifacts
+clean:
+ $(REBAR) clean
+
+
+.PHONY: distclean
+# target: distclean - Removes all unversioned files
+distclean: clean
+ git clean -fxd
+
+
+.PHONY: eunit
+# target: eunit - Runs eunit test suite
+eunit:
+ $(REBAR) eunit
+
+
+.PHONY: help
+# target: help - Prints this help
+help:
+ @egrep "^# target:" Makefile | sed -e 's/^# target: //g' | sort
[couchdb-ets-lru] 16/30: Migrate the tests from etap to eunit
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jaydoane pushed a commit to branch time-unit-parameterization
in repository https://gitbox.apache.org/repos/asf/couchdb-ets-lru.git
commit fb44bea467f13497d1af8b869f62203ba58a9dcb
Author: Eric Avdey <ei...@eiri.ca>
AuthorDate: Thu Apr 30 09:16:19 2015 -0300
Migrate the tests from etap to eunit
All the etap tests converted to eunit. The tests for the validating
of the correct handeling of the bad options for LRU are re-enabled.
This work is a part of COUCHDB-2590.
---
test/01-basic-behavior.t | 102 --------
test/02-lru-options.t | 72 ------
test/03-limit-max-objects.t | 37 ---
test/04-limit-max-size.t | 37 ---
test/05-limit-lifetime.t | 34 ---
test/06-match.t | 47 ----
test/etap.erl | 612 --------------------------------------------
test/ets_lru_test.erl | 299 ++++++++++++++++++++++
test/tutil.erl | 41 ---
9 files changed, 299 insertions(+), 982 deletions(-)
diff --git a/test/01-basic-behavior.t b/test/01-basic-behavior.t
deleted file mode 100755
index 0015998..0000000
--- a/test/01-basic-behavior.t
+++ /dev/null
@@ -1,102 +0,0 @@
-#! /usr/bin/env escript
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-% http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--define(WITH_LRU(F), tutil:with_lru(fun(LRU) -> F(LRU) end)).
-
-main([]) ->
- code:add_pathz("test"),
- code:add_pathz("ebin"),
-
- tutil:run(16, fun() -> test() end).
-
-
-test() ->
- test_lifecycle(),
- test_table_names(),
- ?WITH_LRU(test_insert_lookup),
- ?WITH_LRU(test_insert_overwrite),
- ?WITH_LRU(test_insert_remove),
- ?WITH_LRU(test_clear),
-
- ok.
-
-
-test_lifecycle() ->
- Resp = ets_lru:start_link(?MODULE, []),
- etap:fun_is(
- fun({ok, LRU}) when is_pid(LRU) -> true; (_) -> false end,
- Resp,
- "ets_lru:start_link/2 returned an LRU"
- ),
- {ok, LRU} = Resp,
- etap:is(ok, ets_lru:stop(LRU), "Destroyed the LRU ok").
-
-
-test_table_names() ->
- {ok, LRU} = ets_lru:start_link(foo, []),
- Exists = fun(Name) -> ets:info(Name, size) == 0 end,
- NExists = fun(Name) -> ets:info(Name, size) == undefined end,
- etap:is(Exists(foo_objects), true, "foo_objects exists"),
- etap:is(Exists(foo_atimes), true, "foo_atimes exists"),
- etap:is(Exists(foo_ctimes), true, "foo_ctimes exists"),
-
- Ref = erlang:monitor(process, LRU),
- ets_lru:stop(LRU),
-
- receive {'DOWN', Ref, process, LRU, Reason} -> ok end,
- etap:is(Reason, normal, "LRU stopped normally"),
-
- etap:is(NExists(foo_objects), true, "foo_objects doesn't exist"),
- etap:is(NExists(foo_atimes), true, "foo_atimes doesn't exist"),
- etap:is(NExists(foo_ctimes), true, "foo_ctimes doesn't exist"),
-
- ok.
-
-
-test_insert_lookup(LRU) ->
- ok = ets_lru:insert(LRU, foo, bar),
- Resp = ets_lru:lookup(LRU, foo),
- etap:is(Resp, {ok, bar}, "Lookup returned the inserted value").
-
-
-test_insert_lookup_d(LRU) ->
- ok = ets_lru:insert(LRU, foo, bar),
- Resp = ets_lru:lookup_d(test_lru, foo),
- etap:is(Resp, {ok, bar}, "Dirty lookup returned the inserted value").
-
-
-test_insert_overwrite(LRU) ->
- ok = ets_lru:insert(LRU, foo, bar),
- Resp1 = ets_lru:lookup(LRU, foo),
- etap:is(Resp1, {ok, bar}, "Lookup returned the inserted value"),
- ok = ets_lru:insert(LRU, foo, bam),
- Resp2 = ets_lru:lookup(LRU, foo),
- etap:is(Resp2, {ok, bam}, "Lookup returned the newly inserted value").
-
-
-test_insert_remove(LRU) ->
- ok = ets_lru:insert(LRU, foo, bar),
- Resp1 = ets_lru:lookup(LRU, foo),
- etap:is(Resp1, {ok, bar}, "Lookup returned the inserted value"),
- ok = ets_lru:remove(LRU, foo),
- Resp2 = ets_lru:lookup(LRU, foo),
- etap:is(Resp2, not_found, "Lookup returned not_found for removed value").
-
-
-test_clear(LRU) ->
- ok = ets_lru:insert(LRU, foo, bar),
- Resp1 = ets_lru:lookup(LRU, foo),
- etap:is(Resp1, {ok, bar}, "Lookup returned the inserted value"),
- ok = ets_lru:clear(LRU),
- Resp2 = ets_lru:lookup(LRU, foo),
- etap:is(Resp2, not_found, "Lookup returned not_found after a clear").
diff --git a/test/02-lru-options.t b/test/02-lru-options.t
deleted file mode 100755
index c9fb721..0000000
--- a/test/02-lru-options.t
+++ /dev/null
@@ -1,72 +0,0 @@
-#! /usr/bin/env escript
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-% http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
-main([]) ->
- code:add_pathz("test"),
- code:add_pathz("ebin"),
-
- tutil:run(9, fun() -> test() end).
-
-
-test() ->
- test_max_objects(),
- test_max_size(),
- test_lifetime(),
- test_bad_option(),
-
- ok.
-
-
-test_max_objects() ->
- % See also: 03-limit-max-objects.t
- test_good([{max_objects, 5}]),
- test_good([{max_objects, 1}]),
- test_good([{max_objects, 923928342098203942}]).
-
-
-test_max_size() ->
- % See also: 04-limit-max-size.t
- test_good([{max_size, 1}]),
- test_good([{max_size, 5}]),
- test_good([{max_size, 2342923423942309423094}]).
-
-
-test_lifetime() ->
- % See also: 05-limit-lifetime.t
- test_good([{max_lifetime, 1}]),
- test_good([{max_lifetime, 5}]),
- test_good([{max_lifetime, 1244209909180928348}]).
-
-
-test_bad_option() ->
- % Figure out a test for these.
- %test_bad([{bingo, bango}]),
- %test_bad([12]),
- %test_bad([true]).
- ok.
-
-
-test_good(Options) ->
- Msg = io_lib:format("LRU created ok with options: ~w", [Options]),
- etap:fun_is(fun
- ({ok, LRU}) when is_pid(LRU) -> ets_lru:stop(LRU), true;
- (_) -> false
- end, ets_lru:start_link(?MODULE, Options), lists:flatten(Msg)).
-
-
-% test_bad(Options) ->
-% etap:fun_is(fun
-% ({invalid_option, _}) -> true;
-% ({ok, LRU}) -> ets_lru:stop(LRU), false;
-% (_) -> false
-% end, catch ets_lru:start_link(?MODULE, Options), "LRU bad options").
diff --git a/test/03-limit-max-objects.t b/test/03-limit-max-objects.t
deleted file mode 100755
index 00a40a8..0000000
--- a/test/03-limit-max-objects.t
+++ /dev/null
@@ -1,37 +0,0 @@
-#! /usr/bin/env escript
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-% http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
-objs() -> 25.
-
-main([]) ->
- code:add_pathz("test"),
- code:add_pathz("ebin"),
-
- tutil:run(1, fun() -> test() end).
-
-
-test() ->
- {ok, LRU} = ets_lru:start_link(lru, [{max_objects, objs()}]),
- etap:is(insert_kvs(LRU, 100 * objs()), ok, "Max object count ok"),
- ok = ets_lru:stop(LRU).
-
-
-insert_kvs(LRU, 0) ->
- ok;
-insert_kvs(LRU, Count) ->
- ets_lru:insert(LRU, Count, bar),
- case ets:info(lru_objects, size) > objs() of
- true -> erlang:error(exceeded_max_objects);
- false -> ok
- end,
- insert_kvs(LRU, Count-1).
diff --git a/test/04-limit-max-size.t b/test/04-limit-max-size.t
deleted file mode 100755
index a54cdf0..0000000
--- a/test/04-limit-max-size.t
+++ /dev/null
@@ -1,37 +0,0 @@
-#! /usr/bin/env escript
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-% http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
-max_size() -> 1024.
-
-main([]) ->
- code:add_pathz("test"),
- code:add_pathz("ebin"),
-
- tutil:run(1, fun() -> test() end).
-
-
-test() ->
- {ok, LRU} = ets_lru:start_link(lru, [{max_size, max_size()}]),
- etap:is(insert_kvs(LRU, 10000), ok, "Max size ok"),
- ok = ets_lru:stop(LRU).
-
-
-insert_kvs(LRU, 0) ->
- ok;
-insert_kvs(LRU, Count) ->
- ets_lru:insert(LRU, Count, 1.5234),
- case ets:info(lru_objects, memory) > max_size() of
- true -> erlang:error(exceeded_max_size);
- false -> ok
- end,
- insert_kvs(LRU, Count-1).
diff --git a/test/05-limit-lifetime.t b/test/05-limit-lifetime.t
deleted file mode 100755
index eb6d54d..0000000
--- a/test/05-limit-lifetime.t
+++ /dev/null
@@ -1,34 +0,0 @@
-#! /usr/bin/env escript
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-% http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
-lifetime() -> 100.
-
-main([]) ->
- code:add_pathz("test"),
- code:add_pathz("ebin"),
-
- tutil:run(2, fun() -> test() end).
-
-
-test() ->
- {ok, LRU} = ets_lru:start_link(lru, [{max_lifetime, lifetime()}]),
- ok = test_single_entry(LRU),
- ok = ets_lru:stop(LRU).
-
-
-test_single_entry(LRU) ->
- ets_lru:insert(LRU, foo, bar),
- etap:is(ets_lru:lookup(LRU, foo), {ok, bar}, "Expire leaves new entries"),
- timer:sleep(round(lifetime() * 1.5)),
- etap:is(ets_lru:lookup(LRU, foo), not_found, "Entry was expired"),
- ok.
diff --git a/test/06-match.t b/test/06-match.t
deleted file mode 100644
index c409e8d..0000000
--- a/test/06-match.t
+++ /dev/null
@@ -1,47 +0,0 @@
-#!/usr/bin/env escript
-
--define(WITH_LRU(F), tutil:with_lru(fun(LRU) -> F(LRU) end)).
-
-main([]) ->
- code:add_pathz("test"),
- code:add_pathz("ebin"),
- tutil:run(7, fun() -> test() end).
-
-test() ->
- ?WITH_LRU(test_match_zero_values),
- ?WITH_LRU(test_match_one_value),
- ?WITH_LRU(test_match_many_values),
- ?WITH_LRU(test_match_zero_objects),
- ?WITH_LRU(test_match_one_object),
- ?WITH_LRU(test_match_many_objects),
- ok.
-
-test_match_zero_values(LRU) ->
- etap:is(ets_lru:match(LRU, a, '$1'), [], "Empty match").
-
-test_match_one_value(LRU) ->
- ets_lru:insert(LRU, b, {x,y}),
- Values = ets_lru:match(LRU, b, {'$1', '$2'}),
- etap:is(Values, [[x,y]], "Single match").
-
-test_match_many_values(LRU) ->
- ets_lru:insert(LRU, boston, {state, "MA"}),
- ets_lru:insert(LRU, new_york, {state, "NY"}),
- Values = ets_lru:match(LRU, '_', {state, '$1'}),
- etap:is(lists:sort(Values), [["MA"],["NY"]], "Multiple match").
-
-test_match_zero_objects(LRU) ->
- etap:is(ets_lru:match_object(LRU, a, '$1'), [], "Empty match_object").
-
-test_match_one_object(LRU) ->
- ets_lru:insert(LRU, ans, 42),
- ViaRegistered = ets_lru:match_object(test_lru, ans, '$1'),
- etap:is(ViaRegistered, [42], "Single match_object (registered)"),
- ViaPid = ets_lru:match_object(LRU, ans, '$1'),
- etap:is(ViaPid, [42], "Single match_object (pid)").
-
-test_match_many_objects(LRU) ->
- ets_lru:insert(LRU, {color, blue}, a),
- ets_lru:insert(LRU, {color, red}, b),
- Values = ets_lru:match_object(LRU, {color, '_'}, '_'),
- etap:is(lists:sort(Values), [a, b], "Multiple match_object").
diff --git a/test/etap.erl b/test/etap.erl
deleted file mode 100644
index 6924d09..0000000
--- a/test/etap.erl
+++ /dev/null
@@ -1,612 +0,0 @@
-%% Copyright (c) 2008-2009 Nick Gerakines <ni...@gerakines.net>
-%%
-%% Permission is hereby granted, free of charge, to any person
-%% obtaining a copy of this software and associated documentation
-%% files (the "Software"), to deal in the Software without
-%% restriction, including without limitation the rights to use,
-%% copy, modify, merge, publish, distribute, sublicense, and/or sell
-%% copies of the Software, and to permit persons to whom the
-%% Software is furnished to do so, subject to the following
-%% conditions:
-%%
-%% The above copyright notice and this permission notice shall be
-%% included in all copies or substantial portions of the Software.
-%%
-%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-%% EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
-%% OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-%% NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
-%% HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
-%% WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-%% FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
-%% OTHER DEALINGS IN THE SOFTWARE.
-%%
-%% @author Nick Gerakines <ni...@gerakines.net> [http://socklabs.com/]
-%% @author Jeremy Wall <je...@marzhillstudios.com>
-%% @version 0.3.4
-%% @copyright 2007-2008 Jeremy Wall, 2008-2009 Nick Gerakines
-%% @reference http://testanything.org/wiki/index.php/Main_Page
-%% @reference http://en.wikipedia.org/wiki/Test_Anything_Protocol
-%% @todo Finish implementing the skip directive.
-%% @todo Document the messages handled by this receive loop.
-%% @todo Explain in documentation why we use a process to handle test input.
-%% @doc etap is a TAP testing module for Erlang components and applications.
-%% This module allows developers to test their software using the TAP method.
-%%
-%% <blockquote cite="http://en.wikipedia.org/wiki/Test_Anything_Protocol"><p>
-%% TAP, the Test Anything Protocol, is a simple text-based interface between
-%% testing modules in a test harness. TAP started life as part of the test
-%% harness for Perl but now has implementations in C/C++, Python, PHP, Perl
-%% and probably others by the time you read this.
-%% </p></blockquote>
-%%
-%% The testing process begins by defining a plan using etap:plan/1, running
-%% a number of etap tests and then calling eta:end_tests/0. Please refer to
-%% the Erlang modules in the t directory of this project for example tests.
--module(etap).
--vsn("0.3.4").
-
--export([
- ensure_test_server/0,
- start_etap_server/0,
- test_server/1,
- msg/1, msg/2,
- diag/1, diag/2,
- expectation_mismatch_message/3,
- plan/1,
- end_tests/0,
- not_ok/2, ok/2, is_ok/2, is/3, isnt/3, any/3, none/3,
- fun_is/3, expect_fun/3, expect_fun/4,
- is_greater/3,
- skip/1, skip/2,
- datetime/1,
- skip/3,
- bail/0, bail/1,
- test_state/0, failure_count/0
-]).
-
--export([
- contains_ok/3,
- is_before/4
-]).
-
--export([
- is_pid/2,
- is_alive/2,
- is_mfa/3
-]).
-
--export([
- loaded_ok/2,
- can_ok/2, can_ok/3,
- has_attrib/2, is_attrib/3,
- is_behaviour/2
-]).
-
--export([
- dies_ok/2,
- lives_ok/2,
- throws_ok/3
-]).
-
-
--record(test_state, {
- planned = 0,
- count = 0,
- pass = 0,
- fail = 0,
- skip = 0,
- skip_reason = ""
-}).
-
-%% @spec plan(N) -> Result
-%% N = unknown | skip | {skip, string()} | integer()
-%% Result = ok
-%% @doc Create a test plan and boot strap the test server.
-plan(unknown) ->
- ensure_test_server(),
- etap_server ! {self(), plan, unknown},
- ok;
-plan(skip) ->
- io:format("1..0 # skip~n");
-plan({skip, Reason}) ->
- io:format("1..0 # skip ~s~n", [Reason]);
-plan(N) when is_integer(N), N > 0 ->
- ensure_test_server(),
- etap_server ! {self(), plan, N},
- ok.
-
-%% @spec end_tests() -> ok
-%% @doc End the current test plan and output test results.
-%% @todo This should probably be done in the test_server process.
-end_tests() ->
- case whereis(etap_server) of
- undefined -> self() ! true;
- _ -> etap_server ! {self(), state}
- end,
- State = receive X -> X end,
- if
- State#test_state.planned == -1 ->
- io:format("1..~p~n", [State#test_state.count]);
- true ->
- ok
- end,
- case whereis(etap_server) of
- undefined -> ok;
- _ -> etap_server ! done, ok
- end.
-
-bail() ->
- bail("").
-
-bail(Reason) ->
- etap_server ! {self(), diag, "Bail out! " ++ Reason},
- etap_server ! done, ok,
- ok.
-
-%% @spec test_state() -> Return
-%% Return = test_state_record() | {error, string()}
-%% @doc Return the current test state
-test_state() ->
- etap_server ! {self(), state},
- receive
- X when is_record(X, test_state) -> X
- after
- 1000 -> {error, "Timed out waiting for etap server reply.~n"}
- end.
-
-%% @spec failure_count() -> Return
-%% Return = integer() | {error, string()}
-%% @doc Return the current failure count
-failure_count() ->
- case test_state() of
- #test_state{fail=FailureCount} -> FailureCount;
- X -> X
- end.
-
-%% @spec msg(S) -> ok
-%% S = string()
-%% @doc Print a message in the test output.
-msg(S) -> etap_server ! {self(), diag, S}, ok.
-
-%% @spec msg(Format, Data) -> ok
-%% Format = atom() | string() | binary()
-%% Data = [term()]
-%% UnicodeList = [Unicode]
-%% Unicode = int()
-%% @doc Print a message in the test output.
-%% Function arguments are passed through io_lib:format/2.
-msg(Format, Data) -> msg(io_lib:format(Format, Data)).
-
-%% @spec diag(S) -> ok
-%% S = string()
-%% @doc Print a debug/status message related to the test suite.
-diag(S) -> msg("# " ++ S).
-
-%% @spec diag(Format, Data) -> ok
-%% Format = atom() | string() | binary()
-%% Data = [term()]
-%% UnicodeList = [Unicode]
-%% Unicode = int()
-%% @doc Print a debug/status message related to the test suite.
-%% Function arguments are passed through io_lib:format/2.
-diag(Format, Data) -> diag(io_lib:format(Format, Data)).
-
-%% @spec expectation_mismatch_message(Got, Expected, Desc) -> ok
-%% Got = any()
-%% Expected = any()
-%% Desc = string()
-%% @doc Print an expectation mismatch message in the test output.
-expectation_mismatch_message(Got, Expected, Desc) ->
- msg(" ---"),
- msg(" description: ~p", [Desc]),
- msg(" found: ~p", [Got]),
- msg(" wanted: ~p", [Expected]),
- msg(" ..."),
- ok.
-
-% @spec evaluate(Pass, Got, Expected, Desc) -> Result
-%% Pass = true | false
-%% Got = any()
-%% Expected = any()
-%% Desc = string()
-%% Result = true | false
-%% @doc Evaluate a test statement, printing an expectation mismatch message
-%% if the test failed.
-evaluate(Pass, Got, Expected, Desc) ->
- case mk_tap(Pass, Desc) of
- false ->
- expectation_mismatch_message(Got, Expected, Desc),
- false;
- true ->
- true
- end.
-
-%% @spec ok(Expr, Desc) -> Result
-%% Expr = true | false
-%% Desc = string()
-%% Result = true | false
-%% @doc Assert that a statement is true.
-ok(Expr, Desc) -> evaluate(Expr == true, Expr, true, Desc).
-
-%% @spec not_ok(Expr, Desc) -> Result
-%% Expr = true | false
-%% Desc = string()
-%% Result = true | false
-%% @doc Assert that a statement is false.
-not_ok(Expr, Desc) -> evaluate(Expr == false, Expr, false, Desc).
-
-%% @spec is_ok(Expr, Desc) -> Result
-%% Expr = any()
-%% Desc = string()
-%% Result = true | false
-%% @doc Assert that two values are the same.
-is_ok(Expr, Desc) -> evaluate(Expr == ok, Expr, ok, Desc).
-
-%% @spec is(Got, Expected, Desc) -> Result
-%% Got = any()
-%% Expected = any()
-%% Desc = string()
-%% Result = true | false
-%% @doc Assert that two values are the same.
-is(Got, Expected, Desc) -> evaluate(Got == Expected, Got, Expected, Desc).
-
-%% @spec isnt(Got, Expected, Desc) -> Result
-%% Got = any()
-%% Expected = any()
-%% Desc = string()
-%% Result = true | false
-%% @doc Assert that two values are not the same.
-isnt(Got, Expected, Desc) -> evaluate(Got /= Expected, Got, Expected, Desc).
-
-%% @spec is_greater(ValueA, ValueB, Desc) -> Result
-%% ValueA = number()
-%% ValueB = number()
-%% Desc = string()
-%% Result = true | false
-%% @doc Assert that an integer is greater than another.
-is_greater(ValueA, ValueB, Desc) when is_integer(ValueA), is_integer(ValueB) ->
- mk_tap(ValueA > ValueB, Desc).
-
-%% @spec any(Got, Items, Desc) -> Result
-%% Got = any()
-%% Items = [any()]
-%% Desc = string()
-%% Result = true | false
-%% @doc Assert that an item is in a list.
-any(Got, Items, Desc) when is_function(Got) ->
- is(lists:any(Got, Items), true, Desc);
-any(Got, Items, Desc) ->
- is(lists:member(Got, Items), true, Desc).
-
-%% @spec none(Got, Items, Desc) -> Result
-%% Got = any()
-%% Items = [any()]
-%% Desc = string()
-%% Result = true | false
-%% @doc Assert that an item is not in a list.
-none(Got, Items, Desc) when is_function(Got) ->
- is(lists:any(Got, Items), false, Desc);
-none(Got, Items, Desc) ->
- is(lists:member(Got, Items), false, Desc).
-
-%% @spec fun_is(Fun, Expected, Desc) -> Result
-%% Fun = function()
-%% Expected = any()
-%% Desc = string()
-%% Result = true | false
-%% @doc Use an anonymous function to assert a pattern match.
-fun_is(Fun, Expected, Desc) when is_function(Fun) ->
- is(Fun(Expected), true, Desc).
-
-%% @spec expect_fun(ExpectFun, Got, Desc) -> Result
-%% ExpectFun = function()
-%% Got = any()
-%% Desc = string()
-%% Result = true | false
-%% @doc Use an anonymous function to assert a pattern match, using actual
-%% value as the argument to the function.
-expect_fun(ExpectFun, Got, Desc) ->
- evaluate(ExpectFun(Got), Got, ExpectFun, Desc).
-
-%% @spec expect_fun(ExpectFun, Got, Desc, ExpectStr) -> Result
-%% ExpectFun = function()
-%% Got = any()
-%% Desc = string()
-%% ExpectStr = string()
-%% Result = true | false
-%% @doc Use an anonymous function to assert a pattern match, using actual
-%% value as the argument to the function.
-expect_fun(ExpectFun, Got, Desc, ExpectStr) ->
- evaluate(ExpectFun(Got), Got, ExpectStr, Desc).
-
-%% @equiv skip(TestFun, "")
-skip(TestFun) when is_function(TestFun) ->
- skip(TestFun, "").
-
-%% @spec skip(TestFun, Reason) -> ok
-%% TestFun = function()
-%% Reason = string()
-%% @doc Skip a test.
-skip(TestFun, Reason) when is_function(TestFun), is_list(Reason) ->
- begin_skip(Reason),
- catch TestFun(),
- end_skip(),
- ok.
-
-%% @spec skip(Q, TestFun, Reason) -> ok
-%% Q = true | false | function()
-%% TestFun = function()
-%% Reason = string()
-%% @doc Skips a test conditionally. The first argument to this function can
-%% either be the 'true' or 'false' atoms or a function that returns 'true' or
-%% 'false'.
-skip(QFun, TestFun, Reason) when is_function(QFun), is_function(TestFun), is_list(Reason) ->
- case QFun() of
- true -> begin_skip(Reason), TestFun(), end_skip();
- _ -> TestFun()
- end,
- ok;
-
-skip(Q, TestFun, Reason) when is_function(TestFun), is_list(Reason), Q == true ->
- begin_skip(Reason),
- TestFun(),
- end_skip(),
- ok;
-
-skip(_, TestFun, Reason) when is_function(TestFun), is_list(Reason) ->
- TestFun(),
- ok.
-
-%% @private
-begin_skip(Reason) ->
- etap_server ! {self(), begin_skip, Reason}.
-
-%% @private
-end_skip() ->
- etap_server ! {self(), end_skip}.
-
-%% @spec contains_ok(string(), string(), string()) -> true | false
-%% @doc Assert that a string is contained in another string.
-contains_ok(Source, String, Desc) ->
- etap:isnt(
- string:str(Source, String),
- 0,
- Desc
- ).
-
-%% @spec is_before(string(), string(), string(), string()) -> true | false
-%% @doc Assert that a string comes before another string within a larger body.
-is_before(Source, StringA, StringB, Desc) ->
- etap:is_greater(
- string:str(Source, StringB),
- string:str(Source, StringA),
- Desc
- ).
-
-%% @doc Assert that a given variable is a pid.
-is_pid(Pid, Desc) when is_pid(Pid) -> etap:ok(true, Desc);
-is_pid(_, Desc) -> etap:ok(false, Desc).
-
-%% @doc Assert that a given process/pid is alive.
-is_alive(Pid, Desc) ->
- etap:ok(erlang:is_process_alive(Pid), Desc).
-
-%% @doc Assert that the current function of a pid is a given {M, F, A} tuple.
-is_mfa(Pid, MFA, Desc) ->
- etap:is({current_function, MFA}, erlang:process_info(Pid, current_function), Desc).
-
-%% @spec loaded_ok(atom(), string()) -> true | false
-%% @doc Assert that a module has been loaded successfully.
-loaded_ok(M, Desc) when is_atom(M) ->
- etap:fun_is(fun({module, _}) -> true; (_) -> false end, code:load_file(M), Desc).
-
-%% @spec can_ok(atom(), atom()) -> true | false
-%% @doc Assert that a module exports a given function.
-can_ok(M, F) when is_atom(M), is_atom(F) ->
- Matches = [X || {X, _} <- M:module_info(exports), X == F],
- etap:ok(Matches > 0, lists:concat([M, " can ", F])).
-
-%% @spec can_ok(atom(), atom(), integer()) -> true | false
-%% @doc Assert that a module exports a given function with a given arity.
-can_ok(M, F, A) when is_atom(M); is_atom(F), is_number(A) ->
- Matches = [X || X <- M:module_info(exports), X == {F, A}],
- etap:ok(Matches > 0, lists:concat([M, " can ", F, "/", A])).
-
-%% @spec has_attrib(M, A) -> true | false
-%% M = atom()
-%% A = atom()
-%% @doc Asserts that a module has a given attribute.
-has_attrib(M, A) when is_atom(M), is_atom(A) ->
- etap:isnt(
- proplists:get_value(A, M:module_info(attributes), 'asdlkjasdlkads'),
- 'asdlkjasdlkads',
- lists:concat([M, " has attribute ", A])
- ).
-
-%% @spec has_attrib(M, A. V) -> true | false
-%% M = atom()
-%% A = atom()
-%% V = any()
-%% @doc Asserts that a module has a given attribute with a given value.
-is_attrib(M, A, V) when is_atom(M) andalso is_atom(A) ->
- etap:is(
- proplists:get_value(A, M:module_info(attributes)),
- [V],
- lists:concat([M, "'s ", A, " is ", V])
- ).
-
-%% @spec is_behavior(M, B) -> true | false
-%% M = atom()
-%% B = atom()
-%% @doc Asserts that a given module has a specific behavior.
-is_behaviour(M, B) when is_atom(M) andalso is_atom(B) ->
- is_attrib(M, behaviour, B).
-
-%% @doc Assert that an exception is raised when running a given function.
-dies_ok(F, Desc) ->
- case (catch F()) of
- {'EXIT', _} -> etap:ok(true, Desc);
- _ -> etap:ok(false, Desc)
- end.
-
-%% @doc Assert that an exception is not raised when running a given function.
-lives_ok(F, Desc) ->
- etap:is(try_this(F), success, Desc).
-
-%% @doc Assert that the exception thrown by a function matches the given exception.
-throws_ok(F, Exception, Desc) ->
- try F() of
- _ -> etap:ok(nok, Desc)
- catch
- _:E ->
- etap:is(E, Exception, Desc)
- end.
-
-%% @private
-%% @doc Run a function and catch any exceptions.
-try_this(F) when is_function(F, 0) ->
- try F() of
- _ -> success
- catch
- throw:E -> {throw, E};
- error:E -> {error, E};
- exit:E -> {exit, E}
- end.
-
-%% @private
-%% @doc Start the etap_server process if it is not running already.
-ensure_test_server() ->
- case whereis(etap_server) of
- undefined ->
- proc_lib:start(?MODULE, start_etap_server,[]);
- _ ->
- diag("The test server is already running.")
- end.
-
-%% @private
-%% @doc Start the etap_server loop and register itself as the etap_server
-%% process.
-start_etap_server() ->
- catch register(etap_server, self()),
- proc_lib:init_ack(ok),
- etap:test_server(#test_state{
- planned = 0,
- count = 0,
- pass = 0,
- fail = 0,
- skip = 0,
- skip_reason = ""
- }).
-
-
-%% @private
-%% @doc The main etap_server receive/run loop. The etap_server receive loop
-%% responds to seven messages apperatining to failure or passing of tests.
-%% It is also used to initiate the testing process with the {_, plan, _}
-%% message that clears the current test state.
-test_server(State) ->
- NewState = receive
- {_From, plan, unknown} ->
- io:format("# Current time local ~s~n", [datetime(erlang:localtime())]),
- io:format("# Using etap version ~p~n", [ proplists:get_value(vsn, proplists:get_value(attributes, etap:module_info())) ]),
- State#test_state{
- planned = -1,
- count = 0,
- pass = 0,
- fail = 0,
- skip = 0,
- skip_reason = ""
- };
- {_From, plan, N} ->
- io:format("# Current time local ~s~n", [datetime(erlang:localtime())]),
- io:format("# Using etap version ~p~n", [ proplists:get_value(vsn, proplists:get_value(attributes, etap:module_info())) ]),
- io:format("1..~p~n", [N]),
- State#test_state{
- planned = N,
- count = 0,
- pass = 0,
- fail = 0,
- skip = 0,
- skip_reason = ""
- };
- {_From, begin_skip, Reason} ->
- State#test_state{
- skip = 1,
- skip_reason = Reason
- };
- {_From, end_skip} ->
- State#test_state{
- skip = 0,
- skip_reason = ""
- };
- {_From, pass, Desc} ->
- FullMessage = skip_diag(
- " - " ++ Desc,
- State#test_state.skip,
- State#test_state.skip_reason
- ),
- io:format("ok ~p ~s~n", [State#test_state.count + 1, FullMessage]),
- State#test_state{
- count = State#test_state.count + 1,
- pass = State#test_state.pass + 1
- };
-
- {_From, fail, Desc} ->
- FullMessage = skip_diag(
- " - " ++ Desc,
- State#test_state.skip,
- State#test_state.skip_reason
- ),
- io:format("not ok ~p ~s~n", [State#test_state.count + 1, FullMessage]),
- State#test_state{
- count = State#test_state.count + 1,
- fail = State#test_state.fail + 1
- };
- {From, state} ->
- From ! State,
- State;
- {_From, diag, Message} ->
- io:format("~s~n", [Message]),
- State;
- {From, count} ->
- From ! State#test_state.count,
- State;
- {From, is_skip} ->
- From ! State#test_state.skip,
- State;
- done ->
- exit(normal)
- end,
- test_server(NewState).
-
-%% @private
-%% @doc Process the result of a test and send it to the etap_server process.
-mk_tap(Result, Desc) ->
- IsSkip = lib:sendw(etap_server, is_skip),
- case [IsSkip, Result] of
- [_, true] ->
- etap_server ! {self(), pass, Desc},
- true;
- [1, _] ->
- etap_server ! {self(), pass, Desc},
- true;
- _ ->
- etap_server ! {self(), fail, Desc},
- false
- end.
-
-%% @private
-%% @doc Format a date/time string.
-datetime(DateTime) ->
- {{Year, Month, Day}, {Hour, Min, Sec}} = DateTime,
- io_lib:format("~4.10.0B-~2.10.0B-~2.10.0B ~2.10.0B:~2.10.0B:~2.10.0B", [Year, Month, Day, Hour, Min, Sec]).
-
-%% @private
-%% @doc Craft an output message taking skip/todo into consideration.
-skip_diag(Message, 0, _) ->
- Message;
-skip_diag(_Message, 1, "") ->
- " # SKIP";
-skip_diag(_Message, 1, Reason) ->
- " # SKIP : " ++ Reason.
diff --git a/test/ets_lru_test.erl b/test/ets_lru_test.erl
new file mode 100644
index 0000000..8cfefcc
--- /dev/null
+++ b/test/ets_lru_test.erl
@@ -0,0 +1,299 @@
+-module(ets_lru_test).
+
+-compile([export_all]).
+
+-include_lib("eunit/include/eunit.hrl").
+
+lifecyle_test_() ->
+ {
+ "Test LRU lifecycle",
+ {setup,
+ fun() -> ets_lru:start_link(?MODULE, []) end,
+ fun({ok, LRU}) -> is_process_alive(LRU) == false end,
+ fun({ok, LRU}) ->
+ [
+ {
+ "ets_lru:start_link/2 returned an LRU",
+ ?_assert(is_pid(LRU))
+ },
+ {
+ "Destroyed the LRU ok",
+ ?_assertEqual(ok, ets_lru:stop(LRU))
+ }
+ ]
+ end
+ }
+ }.
+
+table_names_test_() ->
+ {
+ "Test tables names",
+ {setup,
+ fun() -> ets_lru:start_link(foo, []) end,
+ fun({ok, LRU}) ->
+ [
+ {
+ "foo_objects exists",
+ ?_assertEqual(0, ets:info(foo_objects, size))
+ },
+ {
+ "foo_atimes exists",
+ ?_assertEqual(0, ets:info(foo_atimes, size))
+ },
+ {
+ "foo_ctimes exists",
+ ?_assertEqual(0, ets:info(foo_ctimes, size))
+ },
+ {
+ "LRU stopped normally",
+ ?_test(begin
+ Reason = stop_lru({ok, LRU}),
+ ?assertEqual(normal, Reason)
+ end)
+ },
+ {
+ "foo_objects doesn't exists",
+ ?_assertEqual(undefined, ets:info(foo_objects, size))
+ },
+ {
+ "foo_atimes doesn't exists",
+ ?_assertEqual(undefined, ets:info(foo_atimes, size))
+ },
+ {
+ "foo_ctimes doesn't exists",
+ ?_assertEqual(undefined, ets:info(foo_ctimes, size))
+ }
+ ]
+ end
+ }
+ }.
+
+basic_behavior_test_() ->
+ {
+ "Test basic behavior",
+ {foreach,
+ fun() ->
+ {ok, LRU} = ets_lru:start_link(test_lru, []),
+ ok = ets_lru:insert(LRU, foo, bar),
+ {ok, LRU}
+ end,
+ fun stop_lru/1,
+ [
+ fun({ok, LRU}) ->
+ {
+ "Lookup returned the inserted value",
+ ?_assertEqual({ok, bar}, ets_lru:lookup(LRU, foo))
+ }
+ end,
+ fun({ok, _LRU}) ->
+ {
+ "Dirty lookup returned the inserted value",
+ ?_assertEqual({ok, bar},
+ ets_lru:lookup_d(test_lru, foo))
+ }
+ end,
+ fun({ok, LRU}) ->
+ [{
+ "Lookup returned the inserted value",
+ ?_assertEqual({ok, bar}, ets_lru:lookup(LRU, foo))
+ },
+ {
+ "Insert new value",
+ ?_assertEqual(ok, ets_lru:insert(LRU, foo, bam))
+ },
+ {
+ "Lookup returned the newly inserted value",
+ ?_assertEqual({ok, bam}, ets_lru:lookup(LRU, foo))
+ }]
+ end,
+ fun({ok, LRU}) ->
+ [{
+ "Lookup returned the inserted value",
+ ?_assertEqual({ok, bar}, ets_lru:lookup(LRU, foo))
+ },
+ {
+ "Remove value",
+ ?_assertEqual(ok, ets_lru:remove(LRU, foo))
+ },
+ {
+ "Lookup returned not_found for removed value",
+ ?_assertEqual(not_found, ets_lru:lookup(LRU, foo))
+ }]
+ end,
+ fun({ok, LRU}) ->
+ [{
+ "Lookup returned the inserted value",
+ ?_assertEqual({ok, bar}, ets_lru:lookup(LRU, foo))
+ },
+ {
+ "Clear LRU",
+ ?_assertEqual(ok, ets_lru:clear(LRU))
+ },
+ {
+ "Lookup returned not_found after a clear",
+ ?_assertEqual(not_found, ets_lru:lookup(LRU, foo))
+ }]
+ end
+ ]
+ }
+ }.
+
+lru_options_test_() ->
+ {
+ "Test LRU options",
+ {foreachx,
+ fun(Opts) ->
+ process_flag(trap_exit,true),
+ ets_lru:start_link(?MODULE, Opts)
+ end,
+ fun(_, Cfg) -> stop_lru(Cfg) end,
+ [
+ {[{max_objects, 1}], fun test_good_opts/2},
+ {[{max_objects, 5}], fun test_good_opts/2},
+ {[{max_objects, 923928342098203942}], fun test_good_opts/2},
+ {[{max_size, 1}], fun test_good_opts/2},
+ {[{max_size, 5}], fun test_good_opts/2},
+ {[{max_size, 2342923423942309423094}], fun test_good_opts/2},
+ {[{max_lifetime, 1}], fun test_good_opts/2},
+ {[{max_lifetime, 5}], fun test_good_opts/2},
+ {[{max_lifetime, 1244209909180928348}], fun test_good_opts/2},
+ {[{bingo, bango}], fun test_bad_opts/2},
+ {[12], fun test_bad_opts/2},
+ {[true], fun test_bad_opts/2}
+ ]
+ }
+ }.
+
+lru_limits_test_() ->
+ {
+ "Test LRU limits",
+ {foreachx,
+ fun(Opts) -> ets_lru:start_link(lru, Opts) end,
+ fun(_, Cfg) -> stop_lru(Cfg) end,
+ [
+ {[{max_objects, 25}], fun test_limits/2},
+ {[{max_size, 1024}], fun test_limits/2},
+ {[{max_lifetime, 100}], fun test_limits/2}
+ ]
+ }
+ }.
+
+lru_match_test_() ->
+ {
+ "Test match functions",
+ {foreach,
+ fun() -> ets_lru:start_link(test_lru, []) end,
+ fun stop_lru/1,
+ [
+ fun({ok, LRU}) ->
+ {
+ "Empty match",
+ ?_assertEqual([], ets_lru:match(LRU, a, '$1'))
+ }
+ end,
+ fun({ok, LRU}) ->
+ ets_lru:insert(LRU, b, {x, y}),
+ {
+ "Single match",
+ ?_assertEqual([[x, y]],
+ ets_lru:match(LRU, b, {'$1', '$2'}))
+ }
+ end,
+ fun({ok, LRU}) ->
+ ets_lru:insert(LRU, boston, {state, "MA"}),
+ ets_lru:insert(LRU, new_york, {state, "NY"}),
+ Values = ets_lru:match(LRU, '_', {state, '$1'}),
+ {
+ "Multiple match",
+ ?_assertEqual([["MA"],["NY"]], lists:sort(Values))
+ }
+ end,
+ fun({ok, LRU}) ->
+ {
+ "Empty match_object",
+ ?_assertEqual([], ets_lru:match_object(LRU, a, '$1'))
+ }
+ end,
+ fun({ok, LRU}) ->
+ ets_lru:insert(LRU, ans, 42),
+ [{
+ "Single match_object (registered)",
+ ?_assertEqual([42],
+ ets_lru:match_object(test_lru, ans, '$1'))
+ },
+ {
+ "Single match_object (pid)",
+ ?_assertEqual([42],
+ ets_lru:match_object(LRU, ans, '$1'))
+ }]
+ end,
+ fun({ok, LRU}) ->
+ ets_lru:insert(LRU, {color, blue}, a),
+ ets_lru:insert(LRU, {color, red}, b),
+ Values = ets_lru:match_object(LRU, {color, '_'}, '_'),
+ {
+ "Multiple match_object",
+ ?_assertEqual(lists:sort(Values), [a, b])
+ }
+ end
+ ]
+ }
+ }.
+
+
+test_good_opts(Opts, {ok, LRU}) ->
+ Msg = io_lib:format("LRU created ok with options: ~w", [Opts]),
+ {lists:flatten(Msg), ?_assert(is_pid(LRU))};
+test_good_opts(Opts, ErrorMsg) ->
+ Msg = io_lib:format("LRU created ok with options: ~w", [Opts]),
+ {lists:flatten(Msg), ?_assertEqual(ok, ErrorMsg)}.
+
+test_bad_opts([Opts], {error,{bad_return_value,{invalid_option,Opts2}}}) ->
+ Msg = io_lib:format("LRU failed with bad options: ~w", [Opts]),
+ {lists:flatten(Msg), ?_assertEqual(Opts, Opts2)}.
+
+test_limits([{max_objects, N}], {ok, LRU}) ->
+ {
+ "Max object count ok",
+ ?_assert(insert_kvs(size, LRU, 100 * N, N))
+ };
+test_limits([{max_size, N}], {ok, LRU}) ->
+ {
+ "Max size ok",
+ ?_assert(insert_kvs(memory, LRU, 10 * N, N))
+ };
+test_limits([{max_lifetime, N}], {ok, LRU}) ->
+ [
+ {
+ "Expire leaves new entries",
+ ?_test(begin
+ ets_lru:insert(LRU, foo, bar),
+ ?assertEqual({ok, bar}, ets_lru:lookup(LRU, foo))
+ end)
+ },
+ {
+ "Entry was expired",
+ ?_test(begin
+ timer:sleep(round(N * 1.5)),
+ ?assertEqual(not_found, ets_lru:lookup(LRU, foo))
+ end)
+ }
+ ].
+
+
+insert_kvs(_, _, 0, _) ->
+ true;
+insert_kvs(Info, LRU, Count, Limit) ->
+ ets_lru:insert(LRU, Count, 1.5234),
+ case ets:info(lru_objects, Info) > Limit of
+ true -> erlang:error(exceeded_limit);
+ false -> true
+ end,
+ insert_kvs(Info, LRU, Count - 1, Limit).
+
+stop_lru({ok, LRU}) ->
+ Ref = erlang:monitor(process, LRU),
+ ets_lru:stop(LRU),
+ receive {'DOWN', Ref, process, LRU, Reason} -> Reason end;
+stop_lru({error, _}) ->
+ ok.
diff --git a/test/tutil.erl b/test/tutil.erl
deleted file mode 100644
index 3bf154b..0000000
--- a/test/tutil.erl
+++ /dev/null
@@ -1,41 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-% http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(tutil).
-
--export([
- run/2,
- with_lru/1
-]).
-
-
-run(Plan, Fun) ->
- etap:plan(Plan),
- case (catch Fun()) of
- ok ->
- etap:end_tests();
- Error ->
- Msg = lists:flatten(io_lib:format("Error: ~p", [Error])),
- etap:bail(Msg)
- end.
-
-
-with_lru(Fun) ->
- {ok, LRU} = ets_lru:start_link(test_lru, []),
- Ref = erlang:monitor(process, LRU),
- try
- Fun(LRU)
- after
- ets_lru:stop(LRU),
- receive {'DOWN', Ref, process, LRU, _} -> ok end
- end.
-
[couchdb-ets-lru] 18/30: Integrate with Travis CI
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jaydoane pushed a commit to branch time-unit-parameterization
in repository https://gitbox.apache.org/repos/asf/couchdb-ets-lru.git
commit 09128046ae9fbabfe1d70cb406aca878f6ea1dd5
Author: Alexander Shorin <kx...@apache.org>
AuthorDate: Fri Jul 24 05:49:38 2015 +0300
Integrate with Travis CI
---
.travis.yml | 10 ++++++++++
1 file changed, 10 insertions(+)
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 0000000..99e6cb3
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,10 @@
+language: erlang
+
+otp_release:
+ - 17.5
+ - 17.4
+ - 17.1
+ - 17.0
+ - R16B03-1
+ - R14B04
+ - R14B02
[couchdb-ets-lru] 12/30: Add new match and match_object functions
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jaydoane pushed a commit to branch time-unit-parameterization
in repository https://gitbox.apache.org/repos/asf/couchdb-ets-lru.git
commit 807c21ad4b7236b0c029b0a608ad2bce6a65785d
Author: Brian Mitchell <br...@cloudant.com>
AuthorDate: Tue Oct 15 10:04:09 2013 -0400
Add new match and match_object functions
---
src/ets_lru.erl | 33 +++++++++++++++++++++++++++++++++
test/06-match.t | 44 ++++++++++++++++++++++++++++++++++++++++++++
2 files changed, 77 insertions(+)
diff --git a/src/ets_lru.erl b/src/ets_lru.erl
index dc68fb8..7311081 100644
--- a/src/ets_lru.erl
+++ b/src/ets_lru.erl
@@ -20,6 +20,8 @@
insert/3,
lookup/2,
+ match/3,
+ match_object/3,
remove/2,
clear/1,
@@ -78,6 +80,23 @@ insert(LRU, Key, Val) ->
remove(LRU, Key) ->
gen_server:call(LRU, {remove, Key}).
+%% @doc match/3 provides an efficient way to retrieve parts of the
+%% keys and values without copying or requiring circumvention of the
+%% ets_lru API. The KeySpec and ValueSpec parameters are used as part
+%% of one larger match spec so keep in mind that all capturing
+%% placeholders will be aliased between the key and value parts.
+-spec match(atom() | pid(), term(), term()) -> [[any()]].
+match(LRU, KeySpec, ValueSpec) ->
+ gen_server:call(LRU, {match, KeySpec, ValueSpec}).
+
+%% @doc match_object/3 provides an efficient way to retrieve multiple
+%% values using match conditions. The KeySpec and ValueSpec parameters
+%% are used as part of one larger match spec so keep in mind that all
+%% capturing placeholders will be aliased between the key and value
+%% parts.
+-spec match_object(atom() | pid(), term(), term()) -> [any()].
+match_object(LRU, KeySpec, ValueSpec) ->
+ gen_server:call(LRU, {match_object, KeySpec, ValueSpec}).
clear(LRU) ->
gen_server:call(LRU, clear).
@@ -122,6 +141,20 @@ handle_call({lookup, Key}, _From, St) ->
end,
{reply, Reply, St, 0};
+handle_call({match_object, KeySpec, ValueSpec}, _From, St) ->
+ Pattern = #entry{key=KeySpec, val=ValueSpec, _='_'},
+ Entries = ets:match_object(St#st.objects, Pattern),
+ Values = lists:map(fun(#entry{key=Key,val=Val}) ->
+ accessed(Key, St),
+ Val
+ end, Entries),
+ {reply, Values, St, 0};
+
+handle_call({match, KeySpec, ValueSpec}, _From, St) ->
+ Pattern = #entry{key=KeySpec, val=ValueSpec, _='_'},
+ Values = ets:match(St#st.objects, Pattern),
+ {reply, Values, St, 0};
+
handle_call({insert, Key, Val}, _From, St) ->
NewATime = erlang:now(),
Pattern = #entry{key=Key, atime='$1', _='_'},
diff --git a/test/06-match.t b/test/06-match.t
new file mode 100644
index 0000000..907ae78
--- /dev/null
+++ b/test/06-match.t
@@ -0,0 +1,44 @@
+#!/usr/bin/env escript
+
+-define(WITH_LRU(F), tutil:with_lru(fun(LRU) -> F(LRU) end)).
+
+main([]) ->
+ code:add_pathz("test"),
+ code:add_pathz("ebin"),
+ tutil:run(6, fun() -> test() end).
+
+test() ->
+ ?WITH_LRU(test_match_zero_values),
+ ?WITH_LRU(test_match_one_value),
+ ?WITH_LRU(test_match_many_values),
+ ?WITH_LRU(test_match_zero_objects),
+ ?WITH_LRU(test_match_one_object),
+ ?WITH_LRU(test_match_many_objects),
+ ok.
+
+test_match_zero_values(LRU) ->
+ etap:is(ets_lru:match(LRU, a, '$1'), [], "Empty match").
+
+test_match_one_value(LRU) ->
+ ets_lru:insert(LRU, b, {x,y}),
+ Values = ets_lru:match(LRU, b, {'$1', '$2'}),
+ etap:is(Values, [[x,y]], "Single match").
+
+test_match_many_values(LRU) ->
+ ets_lru:insert(LRU, boston, {state, "MA"}),
+ ets_lru:insert(LRU, new_york, {state, "NY"}),
+ Values = ets_lru:match(LRU, '_', {state, '$1'}),
+ etap:is(lists:sort(Values), [["MA"],["NY"]], "Multiple match").
+
+test_match_zero_objects(LRU) ->
+ etap:is(ets_lru:match_object(LRU, a, '$1'), [], "Empty match_object").
+
+test_match_one_object(LRU) ->
+ ets_lru:insert(LRU, ans, 42),
+ etap:is(ets_lru:match_object(LRU, ans, '$1'), [42], "Single match_object").
+
+test_match_many_objects(LRU) ->
+ ets_lru:insert(LRU, {color, blue}, a),
+ ets_lru:insert(LRU, {color, red}, b),
+ Values = ets_lru:match_object(LRU, {color, '_'}, '_'),
+ etap:is(lists:sort(Values), [a, b], "Multiple match_object").
[couchdb-ets-lru] 04/30: Refactor ets_lru into a gen_server
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jaydoane pushed a commit to branch time-unit-parameterization
in repository https://gitbox.apache.org/repos/asf/couchdb-ets-lru.git
commit 3f2bae1d7aa30c47316e55232050a416d144ac92
Author: Paul J. Davis <pa...@gmail.com>
AuthorDate: Fri Dec 28 02:14:00 2012 -0600
Refactor ets_lru into a gen_server
The max_lifetime eviction made me realize this really does need to be an
active process model. This is written as a gen_server with the intention
that it'll be inserted into the supervision tree appropriately by
applications that use it.
---
.gitignore | 2 +
src/ets_lru.erl | 344 ++++++++++++++++++++++++++++----------------
test/01-basic-behavior.t | 47 ++++--
test/02-lru-options.t | 48 +++----
test/03-limit-max-objects.t | 4 +-
test/04-limit-max-size.t | 4 +-
test/05-limit-lifetime.t | 18 ++-
test/tutil.erl | 9 +-
8 files changed, 300 insertions(+), 176 deletions(-)
diff --git a/.gitignore b/.gitignore
index f218820..90bd4cb 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,5 @@
+erl_crash.dump
+
.eunit/
ebin/
test/*.beam
diff --git a/src/ets_lru.erl b/src/ets_lru.erl
index 73398d9..4aecabf 100644
--- a/src/ets_lru.erl
+++ b/src/ets_lru.erl
@@ -1,201 +1,301 @@
% Copyright 2012 Cloudant. All rights reserved.
-module(ets_lru).
+-behavior(gen_server).
-export([
- create/2,
- destroy/1,
+ start_link/2,
+ stop/1,
insert/3,
lookup/2,
- member/2,
remove/2,
- hit/2,
- expire/1,
- clear/1
+ clear/1,
+
+ % Dirty functions read straight from
+ % the ETS tables which means there are
+ % race conditions with concurrent access.
+ lookup_d/2
+]).
+
+-export([
+ init/1,
+ terminate/2,
+
+ handle_call/3,
+ handle_cast/2,
+ handle_info/2,
+
+ code_change/3
]).
-record(entry, {
key,
val,
- atime
+ atime,
+ ctime
}).
--record(ets_lru, {
+-record(st, {
objects,
atimes,
- named=false,
+ ctimes,
max_objs,
max_size,
-
- lifetime
+ max_lifetime
}).
-create(Name, Options) ->
- LRU = set_options(#ets_lru{}, Options),
- Opts = case LRU#ets_lru.named of
- true -> [named_table];
- false -> []
- end,
- {OName, ATName} = table_names(Name),
- {ok, LRU#ets_lru{
- objects = ets:new(OName,
- [set, protected, {keypos, #entry.key}] ++ Opts),
- atimes = ets:new(ATName,
- [ordered_set, protected] ++ Opts)
- }}.
+start_link(Name, Options) when is_atom(Name) ->
+ gen_server:start_link({local, Name}, ?MODULE, {Name, Options}, []).
-destroy(#ets_lru{objects=Objs, atimes=ATimes}) ->
- true = ets:delete(Objs),
- true = ets:delete(ATimes),
- ok.
+stop(LRU) ->
+ gen_server:cast(LRU, stop).
-insert(#ets_lru{objects=Objs, atimes=ATs}=LRU, Key, Val) ->
- NewATime = erlang:now(),
- Pattern = #entry{key=Key, atime='$1', _='_'},
- case ets:match(Objs, Pattern) of
- [[ATime]] ->
- true = ets:delete(ATs, ATime),
- true = ets:insert(ATs, {NewATime, Key}),
- true = ets:update_element(Objs, Key, {#entry.val, Val});
- [] ->
- true = ets:insert(ATs, {NewATime, Key}),
- true = ets:insert(Objs, #entry{key=Key, val=Val, atime=NewATime})
- end,
- trim(LRU).
+lookup(LRU, Key) ->
+ gen_server:call(LRU, {lookup, Key}).
+
+
+insert(LRU, Key, Val) ->
+ gen_server:call(LRU, {insert, Key, Val}).
-lookup(#ets_lru{objects=Objs}=LRU, Key) ->
- case ets:lookup(Objs, Key) of
+remove(LRU, Key) ->
+ gen_server:call(LRU, {remove, Key}).
+
+
+clear(LRU) ->
+ gen_server:call(LRU, clear).
+
+
+lookup_d(Name, Key) when is_atom(Name) ->
+ case ets:lookup(obj_table(Name), Key) of
[#entry{val=Val}] ->
- hit(LRU, Key),
+ gen_server:cast(Name, {accessed, Key}),
{ok, Val};
[] ->
not_found
end.
-member(#ets_lru{objects=Objs}, Key) ->
- ets:member(Objs, Key).
+init({Name, Options}) ->
+ St = set_options(#st{}, Options),
+ ObjOpts = [set, named_table, protected, {keypos, #entry.key}],
+ TimeOpts = [ordered_set, named_table, protected],
+ {ok, St#st{
+ objects = ets:new(obj_table(Name), ObjOpts),
+ atimes = ets:new(at_table(Name), TimeOpts),
+ ctimes = ets:new(ct_table(Name), TimeOpts)
+ }}.
-remove(#ets_lru{objects=Objs, atimes=ATs}=LRU, Key) ->
- case ets:match(Objs, #entry{key=Key, atime='$1', _='_'}) of
+
+terminate(_Reason, St) ->
+ true = ets:delete(St#st.objects),
+ true = ets:delete(St#st.atimes),
+ true = ets:delete(St#st.ctimes),
+ ok.
+
+
+handle_call({lookup, Key}, _From, St) ->
+ Reply = case ets:lookup(St#st.objects, Key) of
+ [#entry{val=Val}] ->
+ accessed(St, Key),
+ {ok, Val};
+ [] ->
+ not_found
+ end,
+ {reply, Reply, St, 0};
+
+handle_call({insert, Key, Val}, _From, St) ->
+ NewATime = erlang:now(),
+ Pattern = #entry{key=Key, atime='$1', _='_'},
+ case ets:match(St#st.objects, Pattern) of
[[ATime]] ->
- true = ets:delete(ATs, ATime),
- true = ets:delete(Objs, Key),
+ Update = {#entry.val, Val},
+ true = ets:update_element(St#st.objects, Key, Update),
+ true = ets:delete(St#st.atimes, ATime),
+ true = ets:insert(St#st.atimes, {NewATime, Key});
+ [] ->
+ Entry = #entry{key=Key, val=Val, atime=NewATime, ctime=NewATime},
+ true = ets:insert(St#st.objects, Entry),
+ true = ets:insert(St#st.atimes, {NewATime, Key}),
+ true = ets:insert(St#st.ctimes, {NewATime, Key})
+ end,
+ {reply, ok, St, 0};
+
+handle_call({remove, Key}, _From, St) ->
+ Pattern = #entry{key=Key, atime='$1', ctime='$2', _='_'},
+ Reply = case ets:match(St#st.objects, Pattern) of
+ [[ATime, CTime]] ->
+ true = ets:delete(St#st.objects, Key),
+ true = ets:delete(St#st.atimes, ATime),
+ true = ets:delete(St#st.ctimes, CTime),
ok;
[] ->
- ok
+ not_found
end,
- false = member(LRU, Key),
- ok.
+ {reply, Reply, St, 0};
+
+handle_call(clear, _From, St) ->
+ true = ets:delete_all_objects(St#st.objects),
+ true = ets:delete_all_objects(St#st.atimes),
+ true = ets:delete_all_objects(St#st.ctimes),
+ % No need to timeout here and evict cache
+ % entries because its now empty.
+ {reply, ok, St};
+
+
+handle_call(Msg, _From, St) ->
+ {stop, {invalid_call, Msg}, {invalid_call, Msg}, St}.
+
+handle_cast({accessed, Key}, St) ->
+ accessed(Key, St),
+ {noreply, St, 0};
-hit(#ets_lru{objects=Objs, atimes=ATs}, Key) ->
- case ets:match(Objs, #entry{key=Key, atime='$1', _='_'}) of
+handle_cast(stop, St) ->
+ {stop, normal, St};
+
+handle_cast(Msg, St) ->
+ {stop, {invalid_cast, Msg}, St}.
+
+
+handle_info(timeout, St) ->
+ trim(St),
+ {noreply, St, next_timeout(St)};
+
+handle_info(Msg, St) ->
+ {stop, {invalid_info, Msg}, St}.
+
+
+code_change(_OldVsn, St, _Extra) ->
+ {ok, St}.
+
+
+accessed(St, Key) ->
+ Pattern = #entry{key=Key, atime='$1', _='_'},
+ case ets:match(St#st.objects, Pattern) of
[[ATime]] ->
NewATime = erlang:now(),
- true = ets:delete(ATs, ATime),
- true = ets:insert(ATs, {NewATime, Key}),
- true = ets:update_element(Objs, Key, {#entry.atime, NewATime}),
+ Update = {#entry.atime, NewATime},
+ true = ets:update_element(St#st.objects, Key, Update),
+ true = ets:delete(St#st.atimes, ATime),
+ true = ets:insert(St#st.atimes, {NewATime, Key}),
ok;
[] ->
ok
end.
-expire(#ets_lru{lifetime=undefined}) ->
- ok;
-expire(#ets_lru{objects=Objs, atimes=ATs, lifetime=LT}=LRU) ->
- Now = os:timestamp(),
- LTMicro = LT * 1000,
- case ets:first(ATs) of
- '$end_of_table' ->
- ok;
- ATime ->
- case timer:now_diff(Now, ATime) > LTMicro of
- true ->
- [{ATime, Key}] = ets:lookup(ATs, ATime),
- true = ets:delete(ATs, ATime),
- true = ets:delete(Objs, Key),
- expire(LRU);
- false ->
- ok
- end
- end.
-
-
-clear(#ets_lru{objects=Objs, atimes=ATs}) ->
- true = ets:delete_all_objects(Objs),
- true = ets:delete_all_objects(ATs),
- ok.
+trim(St) ->
+ trim_count(St),
+ trim_size(St),
+ trim_lifetime(St).
-trim(#ets_lru{}=LRU) ->
- case trim_count(LRU) of
- trimmed -> trim(LRU);
- _ -> ok
- end,
- case trim_size(LRU) of
- trimmed -> trim(LRU);
- _ -> ok
+trim_count(#st{max_objs=undefined}) ->
+ ok;
+trim_count(#st{max_objs=Max}=St) ->
+ case ets:info(St#st.objects, size) > Max of
+ true ->
+ drop_lru(St, fun trim_count/1);
+ false ->
+ ok
end.
-trim_count(#ets_lru{max_objs=undefined}) ->
+trim_size(#st{max_size=undefined}) ->
ok;
-trim_count(#ets_lru{objects=Objs, max_objs=MO}=LRU) ->
- case ets:info(Objs, size) > MO of
- true -> drop_entry(LRU);
- false -> ok
+trim_size(#st{max_size=Max}=St) ->
+ case ets:info(St#st.objects, memory) > Max of
+ true ->
+ drop_lru(St, fun trim_size/1);
+ false ->
+ ok
end.
-trim_size(#ets_lru{max_size=undefined}) ->
+trim_lifetime(#st{max_lifetime=undefined}) ->
ok;
-trim_size(#ets_lru{objects=Objs, max_size=MS}=LRU) ->
- case ets:info(Objs, memory) > MS of
- true -> drop_entry(LRU);
- false -> ok
+trim_lifetime(#st{max_lifetime=Max}=St) ->
+ Now = os:timestamp(),
+ case ets:first(St#st.ctimes) of
+ '$end_of_table' ->
+ ok;
+ CTime ->
+ DiffInMilli = timer:now_diff(Now, CTime) div 1000,
+ case DiffInMilli > Max of
+ true ->
+ [{CTime, Key}] = ets:lookup(St#st.ctimes, CTime),
+ Pattern = #entry{key=Key, atime='$1', _='_'},
+ [[ATime]] = ets:match(St#st.objects, Pattern),
+ true = ets:delete(St#st.objects, Key),
+ true = ets:delete(St#st.atimes, ATime),
+ true = ets:delete(St#st.ctimes, CTime),
+ trim_lifetime(St);
+ false ->
+ ok
+ end
end.
-drop_entry(#ets_lru{objects=Objs, atimes=ATs}) ->
- case ets:first(ATs) of
+drop_lru(St, Continue) ->
+ case ets:first(St#st.atimes) of
'$end_of_table' ->
empty;
ATime ->
- [{ATime, Key}] = ets:lookup(ATs, ATime),
- true = ets:delete(ATs, ATime),
- true = ets:delete(Objs, Key),
- trimmed
+ [{ATime, Key}] = ets:lookup(St#st.atimes, ATime),
+ Pattern = #entry{key=Key, ctime='$1', _='_'},
+ [[CTime]] = ets:match(St#st.objects, Pattern),
+ true = ets:delete(St#st.objects, Key),
+ true = ets:delete(St#st.atimes, ATime),
+ true = ets:delete(St#st.ctimes, CTime),
+ Continue(St)
+ end.
+
+
+next_timeout(#st{max_lifetime=undefined}) ->
+ infinity;
+next_timeout(St) ->
+ case ets:first(St#st.ctimes) of
+ '$end_of_table' ->
+ infinity;
+ CTime ->
+ Now = os:timestamp(),
+ DiffInMilli = timer:now_diff(Now, CTime) div 1000,
+ erlang:max(St#st.max_lifetime - DiffInMilli, 0)
end.
-set_options(LRU, []) ->
- LRU;
-set_options(LRU, [named_tables | Rest]) ->
- set_options(LRU#ets_lru{named=true}, Rest);
-set_options(LRU, [{max_objects, N} | Rest]) when is_integer(N), N > 0 ->
- set_options(LRU#ets_lru{max_objs=N}, Rest);
-set_options(LRU, [{max_size, N} | Rest]) when is_integer(N), N > 0 ->
- set_options(LRU#ets_lru{max_size=N}, Rest);
-set_options(LRU, [{lifetime, N} | Rest]) when is_integer(N), N > 0 ->
- set_options(LRU#ets_lru{lifetime=N}, Rest);
+set_options(St, []) ->
+ St;
+set_options(St, [{max_objects, N} | Rest]) when is_integer(N), N > 0 ->
+ set_options(St#st{max_objs=N}, Rest);
+set_options(St, [{max_size, N} | Rest]) when is_integer(N), N > 0 ->
+ set_options(St#st{max_size=N}, Rest);
+set_options(St, [{max_lifetime, N} | Rest]) when is_integer(N), N > 0 ->
+ set_options(St#st{max_lifetime=N}, Rest);
set_options(_, [Opt | _]) ->
throw({invalid_option, Opt}).
-table_names(Base) when is_atom(Base) ->
- BList = atom_to_list(Base),
- OName = list_to_atom(BList ++ "_objects"),
- ATName = list_to_atom(BList ++ "_atimes"),
- {OName, ATName}.
+obj_table(Name) ->
+ table_name(Name, "_objects").
+
+
+at_table(Name) ->
+ table_name(Name, "_atimes").
+
+
+ct_table(Name) ->
+ table_name(Name, "_ctimes").
+
+table_name(Name, Ext) ->
+ list_to_atom(atom_to_list(Name) ++ Ext).
diff --git a/test/01-basic-behavior.t b/test/01-basic-behavior.t
index a35a944..7e87a5d 100755
--- a/test/01-basic-behavior.t
+++ b/test/01-basic-behavior.t
@@ -6,29 +6,50 @@ main([]) ->
code:add_pathz("test"),
code:add_pathz("ebin"),
- tutil:run(12, fun() -> test() end).
+ tutil:run(16, fun() -> test() end).
test() ->
test_lifecycle(),
+ test_table_names(),
?WITH_LRU(test_insert_lookup),
?WITH_LRU(test_insert_overwrite),
?WITH_LRU(test_insert_remove),
- ?WITH_LRU(test_member),
?WITH_LRU(test_clear),
ok.
test_lifecycle() ->
- Resp = ets_lru:create(?MODULE, []),
+ Resp = ets_lru:start_link(?MODULE, []),
etap:fun_is(
- fun({ok, _LRU}) -> true; (_) -> false end,
+ fun({ok, LRU}) when is_pid(LRU) -> true; (_) -> false end,
Resp,
- "ets_lru:create/2 returned an LRU"
+ "ets_lru:start_link/2 returned an LRU"
),
{ok, LRU} = Resp,
- etap:is(ok, ets_lru:destroy(LRU), "Destroyed the LRU ok").
+ etap:is(ok, ets_lru:stop(LRU), "Destroyed the LRU ok").
+
+
+test_table_names() ->
+ {ok, LRU} = ets_lru:start_link(foo, []),
+ Exists = fun(Name) -> ets:info(Name, size) == 0 end,
+ NExists = fun(Name) -> ets:info(Name, size) == undefined end,
+ etap:is(Exists(foo_objects), true, "foo_objects exists"),
+ etap:is(Exists(foo_atimes), true, "foo_atimes exists"),
+ etap:is(Exists(foo_ctimes), true, "foo_ctimes exists"),
+
+ Ref = erlang:monitor(process, LRU),
+ ets_lru:stop(LRU),
+
+ receive {'DOWN', Ref, process, LRU, Reason} -> ok end,
+ etap:is(Reason, normal, "LRU stopped normally"),
+
+ etap:is(NExists(foo_objects), true, "foo_objects doesn't exist"),
+ etap:is(NExists(foo_atimes), true, "foo_atimes doesn't exist"),
+ etap:is(NExists(foo_ctimes), true, "foo_ctimes doesn't exist"),
+
+ ok.
test_insert_lookup(LRU) ->
@@ -37,6 +58,12 @@ test_insert_lookup(LRU) ->
etap:is(Resp, {ok, bar}, "Lookup returned the inserted value").
+test_insert_lookup_d(LRU) ->
+ ok = ets_lru:insert(LRU, foo, bar),
+ Resp = ets_lru:lookup_d(test_lru, foo),
+ etap:is(Resp, {ok, bar}, "Dirty lookup returned the inserted value").
+
+
test_insert_overwrite(LRU) ->
ok = ets_lru:insert(LRU, foo, bar),
Resp1 = ets_lru:lookup(LRU, foo),
@@ -55,14 +82,6 @@ test_insert_remove(LRU) ->
etap:is(Resp2, not_found, "Lookup returned not_found for removed value").
-test_member(LRU) ->
- etap:is(false, ets_lru:member(LRU, foo), "Not yet a member: foo"),
- ok = ets_lru:insert(LRU, foo, bar),
- etap:is(true, ets_lru:member(LRU, foo), "Now a member: foo"),
- ok = ets_lru:remove(LRU, foo),
- etap:is(false, ets_lru:member(LRU, foo), "No longer a member: foo").
-
-
test_clear(LRU) ->
ok = ets_lru:insert(LRU, foo, bar),
Resp1 = ets_lru:lookup(LRU, foo),
diff --git a/test/02-lru-options.t b/test/02-lru-options.t
index 7dbec8f..59d0ba1 100755
--- a/test/02-lru-options.t
+++ b/test/02-lru-options.t
@@ -4,26 +4,15 @@ main([]) ->
code:add_pathz("test"),
code:add_pathz("ebin"),
- tutil:run(unknown, fun() -> test() end).
+ tutil:run(9, fun() -> test() end).
test() ->
- test_named_tables(),
test_max_objects(),
test_max_size(),
test_lifetime(),
test_bad_option(),
-
- ok.
-
-test_named_tables() ->
- {ok, LRU} = ets_lru:create(foo, [named_tables]),
- etap:is(ets:info(foo_objects, size), 0, "foo_objects table exists"),
- etap:is(ets:info(foo_atimes, size), 0, "foo_atimes table exists"),
- ok = ets_lru:destroy(LRU),
- etap:isnt(catch ets:info(foo_objects, size), 0, "foo_objects is gone"),
- etap:isnt(catch ets:info(foo_atimes, size), 0, "foo_atimes is gone"),
ok.
@@ -38,32 +27,35 @@ test_max_size() ->
% See also: 04-limit-max-size.t
test_good([{max_size, 1}]),
test_good([{max_size, 5}]),
- test_good([{max_size, 23423409090923423942309423094}]).
+ test_good([{max_size, 2342923423942309423094}]).
test_lifetime() ->
% See also: 05-limit-lifetime.t
- test_good([{lifetime, 1}]),
- test_good([{lifetime, 5}]),
- test_good([{lifetime, 1244209909182409328409283409238}]).
+ test_good([{max_lifetime, 1}]),
+ test_good([{max_lifetime, 5}]),
+ test_good([{max_lifetime, 1244209909180928348}]).
test_bad_option() ->
- test_bad([{bingo, bango}]),
- test_bad([12]),
- test_bad([true]).
-
+ % Figure out a test for these.
+ %test_bad([{bingo, bango}]),
+ %test_bad([12]),
+ %test_bad([true]).
+ ok.
+
test_good(Options) ->
+ Msg = io_lib:format("LRU created ok with options: ~w", [Options]),
etap:fun_is(fun
- ({ok, LRU}) -> ets_lru:destroy(LRU), true;
+ ({ok, LRU}) when is_pid(LRU) -> ets_lru:stop(LRU), true;
(_) -> false
- end, ets_lru:create(?MODULE, Options), "LRU created ok with options").
+ end, ets_lru:start_link(?MODULE, Options), lists:flatten(Msg)).
-test_bad(Options) ->
- etap:fun_is(fun
- ({invalid_option, _}) -> true;
- ({ok, LRU}) -> ets_lru:destroy(LRU), false;
- (_) -> false
- end, catch ets_lru:create(?MODULE, Options), "LRU error with options").
\ No newline at end of file
+% test_bad(Options) ->
+% etap:fun_is(fun
+% ({invalid_option, _}) -> true;
+% ({ok, LRU}) -> ets_lru:stop(LRU), false;
+% (_) -> false
+% end, catch ets_lru:start_link(?MODULE, Options), "LRU bad options").
diff --git a/test/03-limit-max-objects.t b/test/03-limit-max-objects.t
index ccf9e7d..bd4e793 100755
--- a/test/03-limit-max-objects.t
+++ b/test/03-limit-max-objects.t
@@ -10,9 +10,9 @@ main([]) ->
test() ->
- {ok, LRU} = ets_lru:create(lru, [named_tables, {max_objects, objs()}]),
+ {ok, LRU} = ets_lru:start_link(lru, [{max_objects, objs()}]),
etap:is(insert_kvs(LRU, 100 * objs()), ok, "Max object count ok"),
- ok = ets_lru:destroy(LRU).
+ ok = ets_lru:stop(LRU).
insert_kvs(LRU, 0) ->
diff --git a/test/04-limit-max-size.t b/test/04-limit-max-size.t
index b318e27..5cdf0ce 100755
--- a/test/04-limit-max-size.t
+++ b/test/04-limit-max-size.t
@@ -10,9 +10,9 @@ main([]) ->
test() ->
- {ok, LRU} = ets_lru:create(lru, [named_tables, {max_size, max_size()}]),
+ {ok, LRU} = ets_lru:start_link(lru, [{max_size, max_size()}]),
etap:is(insert_kvs(LRU, 10000), ok, "Max size ok"),
- ok = ets_lru:destroy(LRU).
+ ok = ets_lru:stop(LRU).
insert_kvs(LRU, 0) ->
diff --git a/test/05-limit-lifetime.t b/test/05-limit-lifetime.t
index 2421579..95effb2 100755
--- a/test/05-limit-lifetime.t
+++ b/test/05-limit-lifetime.t
@@ -1,15 +1,23 @@
#! /usr/bin/env escript
-lifetime() -> 1024.
+lifetime() -> 100.
main([]) ->
code:add_pathz("test"),
code:add_pathz("ebin"),
- tutil:run(unknown, fun() -> test() end).
+ tutil:run(2, fun() -> test() end).
test() ->
- {ok, LRU} = ets_lru:create(lru, [named_tables, {lifetime, lifetime()}]),
- % Figure out how to test this.
- ok = ets_lru:destroy(LRU).
+ {ok, LRU} = ets_lru:start_link(lru, [{max_lifetime, lifetime()}]),
+ ok = test_single_entry(LRU),
+ ok = ets_lru:stop(LRU).
+
+
+test_single_entry(LRU) ->
+ ets_lru:insert(LRU, foo, bar),
+ etap:is(ets_lru:lookup(LRU, foo), {ok, bar}, "Expire leaves new entries"),
+ timer:sleep(round(lifetime() * 1.5)),
+ etap:is(ets_lru:lookup(LRU, foo), not_found, "Entry was expired"),
+ ok.
diff --git a/test/tutil.erl b/test/tutil.erl
index ac258e6..3e4bd68 100644
--- a/test/tutil.erl
+++ b/test/tutil.erl
@@ -18,9 +18,12 @@ run(Plan, Fun) ->
with_lru(Fun) ->
- {ok, LRU} = ets_lru:create(?MODULE, []),
+ {ok, LRU} = ets_lru:start_link(test_lru, []),
+ Ref = erlang:monitor(process, LRU),
try
Fun(LRU)
after
- ets_lru:destroy(LRU)
- end.
\ No newline at end of file
+ ets_lru:stop(LRU),
+ receive {'DOWN', Ref, process, LRU, _} -> ok end
+ end.
+