R20 compat for 1.x.x (#952)

* enable R20 builds

* s/crypto:rand_bytes/crypto:strong_rand_bytes/

* R20 compat

* add couch_rand to build chain

* add R20 to travis tests

* add couch_rand module, nicked from #860

* support R15 and R16

* fix attachment tests for r20, backport of #874

* drop R14 from travis

* update to latest erlang versions
diff --git a/.travis.yml b/.travis.yml
index 18f9e00..8760975 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -11,13 +11,12 @@
    - make distcheck
 language: erlang
 otp_release:
-   - 19.0
+   - 20.1
+   - 19.3
    - 18.3
-   - 17.0
+   - 17.5
    - R16B03-1
    - R15B03
-   - R14B04
 matrix:
   allow_failures:
-    - otp_release: R14B04
     - otp_release: R15B03
diff --git a/configure.ac b/configure.ac
index 27ac813..cf165ad 100644
--- a/configure.ac
+++ b/configure.ac
@@ -415,7 +415,7 @@
 
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking Erlang version compatibility" >&5
 $as_echo_n "checking Erlang version compatibility... " >&6; }
-erlang_version_error="The installed Erlang version must be >= R14B (erts-5.8.1) and =< 19 (erts-8.0)"
+erlang_version_error="The installed Erlang version must be >= R14B (erts-5.8.1) and =< 20 (erts-9)"
 
 version="`${ERL} -version 2>&1 | ${SED} 's/[[^0-9]]/ /g'` 0 0 0"
 major_version=`echo $version | ${AWK} "{print \\$1}"`
@@ -423,11 +423,11 @@
 patch_version=`echo $version | ${AWK} "{print \\$3}"`
 echo -n "detected Erlang version: $major_version.$minor_version.$patch_version..."
 
-if test $major_version -lt 5 -o $major_version -gt 8; then
+if test $major_version -lt 5 -o $major_version -gt 9; then
     as_fn_error $? "$erlang_version_error major_version does not match" "$LINENO" 5
 fi
 
-if test $major_version -eq 5 -a $minor_version -lt 8; then
+if test $major_version -eq 5 -a $minor_version -lt 9; then
     as_fn_error $? "$erlang_version_error minor_version does not match" "$LINENO" 5
 fi
 
@@ -442,9 +442,9 @@
 AC_SUBST(otp_release)
 
 AM_CONDITIONAL([USE_OTP_NIFS],
-    [can_use_nifs=$(echo $otp_release | grep -E "^(R14B|R15|R16|17|18|19)")])
+    [can_use_nifs=$(echo $otp_release | grep -E "^(R14B|R15|R16|17|18|19|20)")])
 AM_CONDITIONAL([USE_EJSON_COMPARE_NIF],
-    [can_use_ejson=$(echo $otp_release | grep -E "^(R14B03|R15|R16|17|18|19)")])
+    [can_use_ejson=$(echo $otp_release | grep -E "^(R14B03|R15|R16|17|18|19|20)")])
 
 has_crypto=`\
     ${ERL} -eval "\
@@ -453,7 +453,7 @@
 
 if test -n "$has_crypto"; then
     AC_MSG_ERROR([Could not find the Erlang crypto library.
-    
+
 Has Erlang been compiled with OpenSSL support?])
 fi
 
@@ -461,7 +461,7 @@
 
 if test x${ERLC} = x; then
     AC_MSG_ERROR([Could not find the `erlc' executable.
-    
+
 Is Erlang installed?])
 fi
 
@@ -574,7 +574,7 @@
 if test x${HAS_PDFLATEX} = x; then
     if test x${strictness_enabled} = xyes; then
         AC_MSG_ERROR([Could not find the `pdflatex' executable.
-    
+
 Is LaTeX installed?])
     else
         AC_MSG_WARN([You will be unable to regenerate PDF documentation.])
@@ -586,7 +586,7 @@
 if test x${HAS_MAKEINFO} = x; then
     if test x${strictness_enabled} = xyes; then
         AC_MSG_ERROR([Could not find the `makeinfo' executable.
-    
+
 Is GNU Texinfo installed?])
     else
         AC_MSG_WARN([You will be unable to regenerate info documentation.])
@@ -598,7 +598,7 @@
 if test x${HAS_INSTALLINFO} = x; then
     if test x${strictness_enabled} = xyes; then
         AC_MSG_ERROR([Could not find the `install-info' executable.
-    
+
 Is GNU Texinfo installed?])
     else
         AC_MSG_WARN([You will be unable to install info documentation.])
diff --git a/src/couch_plugins/src/couch_plugins.erl b/src/couch_plugins/src/couch_plugins.erl
index a4950be..b0e0f6f 100644
--- a/src/couch_plugins/src/couch_plugins.erl
+++ b/src/couch_plugins/src/couch_plugins.erl
@@ -228,7 +228,7 @@
   ?LOG_DEBUG("Checking Filename: ~s", [Filename]),
   case file:read_file(Filename) of
   {ok, Data} ->
-    ComputedChecksum = binary_to_list(base64:encode(crypto:sha(Data))),
+    ComputedChecksum = binary_to_list(base64:encode(crypto:hash(sha, Data))),
     case ComputedChecksum of
     Checksum -> ok;
     _Else ->
diff --git a/src/couch_replicator/test/couch_replicator_large_atts_tests.erl b/src/couch_replicator/test/couch_replicator_large_atts_tests.erl
index 7c4e334..f810370 100644
--- a/src/couch_replicator/test/couch_replicator_large_atts_tests.erl
+++ b/src/couch_replicator/test/couch_replicator_large_atts_tests.erl
@@ -176,7 +176,7 @@
         name = Name,
         type = Type,
         att_len = Size,
-        data = fun(Count) -> crypto:rand_bytes(Count) end
+        data = fun(Count) -> crypto:strong_rand_bytes(Count) end
     }.
 
 find_att([], _Name) ->
diff --git a/src/couch_replicator/test/couch_replicator_many_leaves_tests.erl b/src/couch_replicator/test/couch_replicator_many_leaves_tests.erl
index 27d51db..eae003e 100644
--- a/src/couch_replicator/test/couch_replicator_many_leaves_tests.erl
+++ b/src/couch_replicator/test/couch_replicator_many_leaves_tests.erl
@@ -193,7 +193,7 @@
     NewDocs = lists:foldl(
         fun(#doc{atts = Atts, revs = {Pos, [Rev | _]}} = Doc, Acc) ->
             NewAtts = lists:foldl(fun(I, AttAcc) ->
-                AttData = crypto:rand_bytes(100),
+                AttData = crypto:strong_rand_bytes(100),
                 NewAtt = #att{
                     name = ?io2b(["att_", ?i2l(I), "_",
                                   couch_doc:rev_to_str({Pos, Rev})]),
diff --git a/src/couch_replicator/test/couch_replicator_missing_stubs_tests.erl b/src/couch_replicator/test/couch_replicator_missing_stubs_tests.erl
index 8c64929..6e23ba9 100644
--- a/src/couch_replicator/test/couch_replicator_missing_stubs_tests.erl
+++ b/src/couch_replicator/test/couch_replicator_missing_stubs_tests.erl
@@ -121,7 +121,7 @@
 
 populate_db(DbName) ->
     {ok, Db} = couch_db:open_int(DbName, []),
-    AttData = crypto:rand_bytes(6000),
+    AttData = crypto:strong_rand_bytes(6000),
     Doc = #doc{
         id = <<"doc1">>,
         atts = [
@@ -153,7 +153,7 @@
             {ok, Db2} = couch_db:reopen(Db),
             NewDocVersion = Doc#doc{
                 revs = {Pos, [RevId]},
-                body = {[{<<"value">>, base64:encode(crypto:rand_bytes(100))}]}
+                body = {[{<<"value">>, base64:encode(crypto:strong_rand_bytes(100))}]}
             },
             {ok, NewRev} = couch_db:update_doc(Db2, NewDocVersion, []),
             NewRev
diff --git a/src/couchdb/Makefile.am b/src/couchdb/Makefile.am
index 9fe19bc..f069479 100644
--- a/src/couchdb/Makefile.am
+++ b/src/couchdb/Makefile.am
@@ -65,6 +65,7 @@
     couch_passwords.erl \
     couch_primary_sup.erl \
     couch_query_servers.erl \
+    couch_rand.erl \
     couch_ref_counter.erl \
     couch_secondary_sup.erl \
     couch_server.erl \
@@ -122,6 +123,7 @@
     couch_passwords.beam \
     couch_primary_sup.beam \
     couch_query_servers.beam \
+    couch_rand.beam \
     couch_ref_counter.beam \
     couch_secondary_sup.beam \
     couch_server.beam \
@@ -195,4 +197,3 @@
 
 %.beam: %.erl couch_db.hrl couch_js_functions.hrl
 	$(ERLC) $(ERLC_FLAGS) ${TEST} $<;
-
diff --git a/src/couchdb/couch_httpd_auth.erl b/src/couchdb/couch_httpd_auth.erl
index df5e0f5..f7bbb13 100644
--- a/src/couchdb/couch_httpd_auth.erl
+++ b/src/couchdb/couch_httpd_auth.erl
@@ -123,7 +123,7 @@
 %% @deprecated
 proxy_authentification_handler(Req) ->
     proxy_authentication_handler(Req).
-    
+
 proxy_auth_user(Req) ->
     XHeaderUserName = couch_config:get("couch_httpd_auth", "x_auth_username",
                                 "X-Auth-CouchDB-UserName"),
@@ -145,7 +145,7 @@
                         nil ->
                             Req#httpd{user_ctx=#user_ctx{name=?l2b(UserName), roles=Roles}};
                         Secret ->
-                            ExpectedToken = couch_util:to_hex(crypto:sha_mac(Secret, UserName)),
+                            ExpectedToken = couch_util:to_hex(crypto:hmac(sha, Secret, UserName)),
                             case header_value(Req, XHeaderToken) of
                                 Token when Token == ExpectedToken ->
                                     Req#httpd{user_ctx=#user_ctx{name=?l2b(UserName),
@@ -186,7 +186,7 @@
             UserProps ->
                 UserSalt = couch_util:get_value(<<"salt">>, UserProps, <<"">>),
                 FullSecret = <<Secret/binary, UserSalt/binary>>,
-                ExpectedHash = crypto:sha_mac(FullSecret, User ++ ":" ++ TimeStr),
+                ExpectedHash = crypto:hmac(sha, FullSecret, User ++ ":" ++ TimeStr),
                 Hash = ?l2b(HashStr),
                 Timeout = list_to_integer(
                     couch_config:get("couch_httpd_auth", "timeout", "600")),
@@ -233,7 +233,7 @@
 
 cookie_auth_cookie(Req, User, Secret, TimeStamp) ->
     SessionData = User ++ ":" ++ erlang:integer_to_list(TimeStamp, 16),
-    Hash = crypto:sha_mac(Secret, SessionData),
+    Hash = crypto:hmac(sha, Secret, SessionData),
     mochiweb_cookies:cookie("AuthSession",
         couch_util:encodeBase64Url(SessionData ++ ":" ++ ?b2l(Hash)),
         [{path, "/"}] ++ cookie_scheme(Req) ++ max_age()).
diff --git a/src/couchdb/couch_passwords.erl b/src/couchdb/couch_passwords.erl
index 9abf31b..321f89f 100644
--- a/src/couchdb/couch_passwords.erl
+++ b/src/couchdb/couch_passwords.erl
@@ -23,7 +23,7 @@
 %% legacy scheme, not used for new passwords.
 -spec simple(binary(), binary()) -> binary().
 simple(Password, Salt) when is_binary(Password), is_binary(Salt) ->
-    ?l2b(couch_util:to_hex(crypto:sha(<<Password/binary, Salt/binary>>))).
+    ?l2b(couch_util:to_hex(crypto:hash(sha, <<Password/binary, Salt/binary>>))).
 
 %% CouchDB utility functions
 -spec hash_admin_password(binary() | list()) -> binary().
@@ -89,12 +89,12 @@
     when Iteration > Iterations ->
     Acc;
 pbkdf2(Password, Salt, Iterations, BlockIndex, 1, _Prev, _Acc) ->
-    InitialBlock = crypto:sha_mac(Password,
+    InitialBlock = crypto:hmac(sha, Password,
         <<Salt/binary,BlockIndex:32/integer>>),
     pbkdf2(Password, Salt, Iterations, BlockIndex, 2,
         InitialBlock, InitialBlock);
 pbkdf2(Password, Salt, Iterations, BlockIndex, Iteration, Prev, Acc) ->
-    Next = crypto:sha_mac(Password, Prev),
+    Next = crypto:hmac(sha, Password, Prev),
     pbkdf2(Password, Salt, Iterations, BlockIndex, Iteration + 1,
                    Next, crypto:exor(Next, Acc)).
 
diff --git a/src/couchdb/couch_rand.erl b/src/couchdb/couch_rand.erl
new file mode 100644
index 0000000..a57c0d6
--- /dev/null
+++ b/src/couchdb/couch_rand.erl
@@ -0,0 +1,73 @@
+% 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(couch_rand).
+
+
+-export([
+    uniform/0,
+    uniform/1
+]).
+
+
+-define(MIN_OTP_VERSION_WITH_RAND_MODULE, 18).
+
+
+has_rand_module() ->
+    OtpRelease = case erlang:system_info(otp_release) of
+        % < R15 is excluded by ./configure already
+        "R15" ++ _OtpVsn -> 15;
+        "R16" ++ _OtpVsn -> 16;
+        Release -> list_to_integer(Release)
+    end,
+    OtpRelease >= ?MIN_OTP_VERSION_WITH_RAND_MODULE.
+
+
+uniform() ->
+    case has_rand_module() of
+        true -> rand_uniform();
+        _False -> norand_uniform()
+    end.
+
+uniform(N) ->
+    case has_rand_module() of
+        true -> rand_uniform(N);
+        _False -> norand_uniform(N)
+    end.
+
+
+norand_uniform() ->
+    maybe_set_random_seed(),
+    random:uniform().
+
+
+norand_uniform(N) ->
+    maybe_set_random_seed(),
+    random:uniform(N).
+
+
+maybe_set_random_seed() ->
+    case get(random_seed) of
+        undefined ->
+            {_, Sec, USec} = os:timestamp(),
+            Seed = {erlang:phash2(self()), Sec, USec},
+            random:seed(Seed);
+        _ ->
+            ok
+    end.
+
+rand_uniform() ->
+    rand:uniform().
+
+
+rand_uniform(N) ->
+    rand:uniform(N).
diff --git a/src/couchdb/couch_server.erl b/src/couchdb/couch_server.erl
index 7cee0f5..3da4ecf 100644
--- a/src/couchdb/couch_server.erl
+++ b/src/couchdb/couch_server.erl
@@ -128,7 +128,7 @@
     case couch_config:get("admins", User) of
     "-hashed-" ++ HashedPwdAndSalt ->
         [HashedPwd, Salt] = string:tokens(HashedPwdAndSalt, ","),
-        couch_util:to_hex(crypto:sha(ClearPwd ++ Salt)) == HashedPwd;
+        couch_util:to_hex(crypto:hash(sha, ClearPwd ++ Salt)) == HashedPwd;
     _Else ->
         false
     end.
diff --git a/src/couchdb/couch_util.erl b/src/couchdb/couch_util.erl
index 0053084..e2f103f 100644
--- a/src/couchdb/couch_util.erl
+++ b/src/couchdb/couch_util.erl
@@ -209,7 +209,7 @@
 
 % returns a random integer
 rand32() ->
-    crypto:rand_uniform(0, 16#100000000).
+    crypto:strong_rand_bytes(4).
 
 % given a pathname "../foo/bar/" it gives back the fully qualified
 % absolute pathname.
@@ -415,20 +415,20 @@
 
 -spec md5(Data::(iolist() | binary())) -> Digest::binary().
 md5(Data) ->
-    try crypto:md5(Data) catch error:_ -> erlang:md5(Data) end.
+    try crypto:hash(md5, Data) catch error:_ -> erlang:md5(Data) end.
 
 -spec md5_init() -> Context::binary().
 md5_init() ->
-    try crypto:md5_init() catch error:_ -> erlang:md5_init() end.
+    try crypto:hash_init(md5) catch error:_ -> erlang:md5_init() end.
 
 -spec md5_update(Context::binary(), Data::(iolist() | binary())) ->
     NewContext::binary().
 md5_update(Ctx, D) ->
-    try crypto:md5_update(Ctx,D) catch error:_ -> erlang:md5_update(Ctx,D) end.
+    try crypto:hash_update(Ctx,D) catch error:_ -> erlang:md5_update(Ctx,D) end.
 
 -spec md5_final(Context::binary()) -> Digest::binary().
 md5_final(Ctx) ->
-    try crypto:md5_final(Ctx) catch error:_ -> erlang:md5_final(Ctx) end.
+    try crypto:hash_final(Ctx) catch error:_ -> erlang:md5_final(Ctx) end.
 
 % linear search is faster for small lists, length() is 0.5 ms for 100k list
 reorder_results(Keys, SortedResults) when length(Keys) < 100 ->
diff --git a/src/couchdb/couch_uuids.erl b/src/couchdb/couch_uuids.erl
index 6ed75a1..581aba9 100644
--- a/src/couchdb/couch_uuids.erl
+++ b/src/couchdb/couch_uuids.erl
@@ -30,10 +30,10 @@
     gen_server:call(?MODULE, create).
 
 random() ->
-    list_to_binary(couch_util:to_hex(crypto:rand_bytes(16))).
+    list_to_binary(couch_util:to_hex(crypto:strong_rand_bytes(16))).
 
 utc_random() ->
-    utc_suffix(couch_util:to_hex(crypto:rand_bytes(9))).
+    utc_suffix(couch_util:to_hex(crypto:strong_rand_bytes(9))).
 
 utc_suffix(Suffix) ->
     Now = {_, _, Micro} = now(),
@@ -81,7 +81,7 @@
     {ok, State}.
 
 new_prefix() ->
-    couch_util:to_hex((crypto:rand_bytes(13))).
+    couch_util:to_hex((crypto:strong_rand_bytes(13))).
 
 inc() ->
     crypto:rand_uniform(1, 16#ffe).
diff --git a/src/erlang-oauth/oauth.erl b/src/erlang-oauth/oauth.erl
index e75d5fd..d37f715 100644
--- a/src/erlang-oauth/oauth.erl
+++ b/src/erlang-oauth/oauth.erl
@@ -77,7 +77,7 @@
 
 signature_params(Consumer, Params) ->
   Timestamp = unix_timestamp(),
-  Nonce = base64:encode_to_string(crypto:rand_bytes(32)), % cf. ruby-oauth
+  Nonce = base64:encode_to_string(crypto:strong_rand_bytes(32)), % cf. ruby-oauth
   [ {"oauth_version", "1.0"}
   , {"oauth_nonce", Nonce}
   , {"oauth_timestamp", integer_to_list(Timestamp)}
@@ -128,7 +128,7 @@
 
 hmac_sha1_signature(BaseString, Consumer, TokenSecret) ->
   Key = uri_join([consumer_secret(Consumer), TokenSecret]),
-  base64:encode_to_string(crypto:sha_mac(Key, BaseString)).
+  base64:encode_to_string(crypto:hmac(sha, Key, BaseString)).
 
 hmac_sha1_verify(Signature, HttpMethod, URL, Params, Consumer, TokenSecret) ->
   verify_in_constant_time(Signature, hmac_sha1_signature(HttpMethod, URL, Params, Consumer, TokenSecret)).
diff --git a/src/mochiweb/mochiweb.erl b/src/mochiweb/mochiweb.erl
index 250beb5..a157f46 100644
--- a/src/mochiweb/mochiweb.erl
+++ b/src/mochiweb/mochiweb.erl
@@ -187,7 +187,7 @@
                 end,
     TestReqs = [begin
                     Path = "/stuff/" ++ integer_to_list(N),
-                    Body = crypto:rand_bytes(Size),
+                    Body = crypto:strong_rand_bytes(Size),
                     #treq{path=Path, body=Body, xreply=Body}
                 end || N <- lists:seq(1, Times)],
     ClientFun = new_client_fun('POST', TestReqs),
diff --git a/src/mochiweb/mochiweb_multipart.erl b/src/mochiweb/mochiweb_multipart.erl
index a83a88c..85dc613 100644
--- a/src/mochiweb/mochiweb_multipart.erl
+++ b/src/mochiweb/mochiweb_multipart.erl
@@ -38,7 +38,7 @@
     {HeaderList, Body};
 parts_to_body(BodyList, ContentType, Size) when is_list(BodyList) ->
     parts_to_multipart_body(BodyList, ContentType, Size,
-                            mochihex:to_hex(crypto:rand_bytes(8))).
+                            mochihex:to_hex(crypto:strong_rand_bytes(8))).
 
 %% @spec parts_to_multipart_body([bodypart()], ContentType::string(),
 %%                               Size::integer(), Boundary::string()) ->
diff --git a/src/my-first-couchdb-plugin/Makefile b/src/my-first-couchdb-plugin/Makefile
index 7806bd7..6c0e1e6 100644
--- a/src/my-first-couchdb-plugin/Makefile
+++ b/src/my-first-couchdb-plugin/Makefile
@@ -35,4 +35,4 @@
 	@mkdir -p $(PLUGIN_DIST)
 	@cp -r $(PLUGIN_DIRS) $(PLUGIN_DIST)
 	@tar czf $(PLUGIN_VERSION_SLUG).tar.gz $(PLUGIN_DIST)
-	@$(ERL) -eval 'File = "$(PLUGIN_VERSION_SLUG).tar.gz", {ok, Data} = file:read_file(File),io:format("~s: ~s~n", [File, base64:encode(crypto:sha(Data))]),halt()' -noshell
+	@$(ERL) -eval 'File = "$(PLUGIN_VERSION_SLUG).tar.gz", {ok, Data} = file:read_file(File),io:format("~s: ~s~n", [File, base64:encode(crypto:hash(sha, Data))]),halt()' -noshell
diff --git a/test/couchdb/couch_auth_cache_tests.erl b/test/couchdb/couch_auth_cache_tests.erl
index 3b2321c..df00bfc 100644
--- a/test/couchdb/couch_auth_cache_tests.erl
+++ b/test/couchdb/couch_auth_cache_tests.erl
@@ -189,7 +189,7 @@
     {ok, couch_doc:rev_to_str(NewRev)}.
 
 hash_password(Password) ->
-    ?l2b(couch_util:to_hex(crypto:sha(iolist_to_binary([Password, ?SALT])))).
+    ?l2b(couch_util:to_hex(crypto:hash(sha, iolist_to_binary([Password, ?SALT])))).
 
 shutdown_db(DbName) ->
     {ok, AuthDb} = couch_db:open_int(DbName, [?ADMIN_USER]),
diff --git a/test/couchdb/couch_btree_tests.erl b/test/couchdb/couch_btree_tests.erl
index 911640f..6a94d41 100644
--- a/test/couchdb/couch_btree_tests.erl
+++ b/test/couchdb/couch_btree_tests.erl
@@ -82,7 +82,7 @@
 
 sorted_kvs_test_() ->
     Funs = kvs_test_funs(),
-    Sorted = [{Seq, random:uniform()} || Seq <- lists:seq(1, ?ROWS)],
+    Sorted = [{Seq, couch_rand:uniform()} || Seq <- lists:seq(1, ?ROWS)],
     {
         "BTree with sorted keys",
         {
@@ -93,7 +93,7 @@
     }.
 
 rsorted_kvs_test_() ->
-    Sorted = [{Seq, random:uniform()} || Seq <- lists:seq(1, ?ROWS)],
+    Sorted = [{Seq, couch_rand:uniform()} || Seq <- lists:seq(1, ?ROWS)],
     Funs = kvs_test_funs(),
     Reversed = Sorted,
     {
@@ -107,7 +107,7 @@
 
 shuffled_kvs_test_() ->
     Funs = kvs_test_funs(),
-    Sorted = [{Seq, random:uniform()} || Seq <- lists:seq(1, ?ROWS)],
+    Sorted = [{Seq, couch_rand:uniform()} || Seq <- lists:seq(1, ?ROWS)],
     Shuffled = shuffle(Sorted),
     {
         "BTree with shuffled keys",
@@ -463,7 +463,7 @@
         end, randomize(List), lists:seq(1, (T - 1))).
 
 randomize(List) ->
-    D = lists:map(fun(A) -> {random:uniform(), A} end, List),
+    D = lists:map(fun(A) -> {couch_rand:uniform(), A} end, List),
     {_, D1} = lists:unzip(lists:keysort(1, D)),
     D1.
 
diff --git a/test/couchdb/couch_file_tests.erl b/test/couchdb/couch_file_tests.erl
index ad13383..5ef13c9 100644
--- a/test/couchdb/couch_file_tests.erl
+++ b/test/couchdb/couch_file_tests.erl
@@ -253,13 +253,13 @@
     ok.
 
 write_random_data(Fd) ->
-    write_random_data(Fd, 100 + random:uniform(1000)).
+    write_random_data(Fd, 100 + couch_rand:uniform(1000)).
 
 write_random_data(Fd, 0) ->
     {ok, Bytes} = couch_file:bytes(Fd),
     {ok, (1 + Bytes div ?BLOCK_SIZE) * ?BLOCK_SIZE};
 write_random_data(Fd, N) ->
     Choices = [foo, bar, <<"bizzingle">>, "bank", ["rough", stuff]],
-    Term = lists:nth(random:uniform(4) + 1, Choices),
+    Term = lists:nth(couch_rand:uniform(4) + 1, Choices),
     {ok, _, _} = couch_file:append_term(Fd, Term),
     write_random_data(Fd, N - 1).
diff --git a/test/couchdb/couch_work_queue_tests.erl b/test/couchdb/couch_work_queue_tests.erl
index 8a463b5..427be76 100644
--- a/test/couchdb/couch_work_queue_tests.erl
+++ b/test/couchdb/couch_work_queue_tests.erl
@@ -340,7 +340,7 @@
             Parent ! {pong, Ref},
             producer_loop(Parent, Q);
         {produce, Ref, Size} ->
-            Item = crypto:rand_bytes(Size),
+            Item = crypto:strong_rand_bytes(Size),
             Parent ! {item, Ref, Item},
             ok = couch_work_queue:queue(Q, Item),
             producer_loop(Parent, Q)
diff --git a/test/couchdb/couchdb_attachments_tests.erl b/test/couchdb/couchdb_attachments_tests.erl
index cf59785..24416e5 100644
--- a/test/couchdb/couchdb_attachments_tests.erl
+++ b/test/couchdb/couchdb_attachments_tests.erl
@@ -631,8 +631,8 @@
 gzip(Data) ->
     Z = zlib:open(),
     ok = zlib:deflateInit(Z, ?COMPRESSION_LEVEL, deflated, 16 + 15, 8, default),
-    zlib:deflate(Z, Data),
+    Chunk = zlib:deflate(Z, Data),
     Last = zlib:deflate(Z, [], finish),
     ok = zlib:deflateEnd(Z),
     ok = zlib:close(Z),
-    Last.
+    [Chunk | Last].
diff --git a/test/couchdb/couchdb_views_tests.erl b/test/couchdb/couchdb_views_tests.erl
index 6904f00..316029b 100644
--- a/test/couchdb/couchdb_views_tests.erl
+++ b/test/couchdb/couchdb_views_tests.erl
@@ -429,7 +429,7 @@
         fun(_) ->
             couch_doc:from_json_obj({[
                 {<<"_id">>, couch_uuids:new()},
-                {<<"value">>, base64:encode(crypto:rand_bytes(1000))}
+                {<<"value">>, base64:encode(crypto:strong_rand_bytes(1000))}
             ]})
         end,
         lists:seq(1, BatchSize)),