diff options
| author | Paul J. Davis <paul.joseph.davis@gmail.com> | 2017-12-15 11:52:36 -0600 |
|---|---|---|
| committer | Russell Branca <chewbranca@apache.org> | 2018-06-22 22:12:35 +0000 |
| commit | 0b48df67520a023c95d6f229534378664601c241 (patch) | |
| tree | 134665a52c27dc0462270a48e05f31a844585b06 /test/elixir | |
| parent | 0097ac565517c460fa25eb40f1ad4e3750266eca (diff) | |
| download | couchdb-0b48df67520a023c95d6f229534378664601c241.tar.gz | |
Move elixir_suite to test/elixir
Diffstat (limited to 'test/elixir')
| -rw-r--r-- | test/elixir/.gitignore | 2 | ||||
| -rw-r--r-- | test/elixir/Makefile | 2 | ||||
| -rw-r--r-- | test/elixir/README.md | 12 | ||||
| -rw-r--r-- | test/elixir/config/config.exs | 30 | ||||
| -rw-r--r-- | test/elixir/config/test.exs | 3 | ||||
| -rw-r--r-- | test/elixir/lib/couch.ex | 73 | ||||
| -rw-r--r-- | test/elixir/mix.exs | 30 | ||||
| -rw-r--r-- | test/elixir/mix.lock | 3 | ||||
| -rw-r--r-- | test/elixir/test/all_docs_test.exs | 132 | ||||
| -rw-r--r-- | test/elixir/test/basics_test.exs | 277 | ||||
| -rw-r--r-- | test/elixir/test/config_test.exs | 149 | ||||
| -rw-r--r-- | test/elixir/test/reduce_test.exs | 416 | ||||
| -rw-r--r-- | test/elixir/test/rewrite_test.exs | 339 | ||||
| -rw-r--r-- | test/elixir/test/test_helper.exs | 135 | ||||
| -rw-r--r-- | test/elixir/test/uuids_test.exs | 94 | ||||
| -rw-r--r-- | test/elixir/test/view_collation_test.exs | 133 |
16 files changed, 1830 insertions, 0 deletions
diff --git a/test/elixir/.gitignore b/test/elixir/.gitignore new file mode 100644 index 000000000..2e39defe6 --- /dev/null +++ b/test/elixir/.gitignore @@ -0,0 +1,2 @@ +_build/ +deps/ diff --git a/test/elixir/Makefile b/test/elixir/Makefile new file mode 100644 index 000000000..bfcf017d5 --- /dev/null +++ b/test/elixir/Makefile @@ -0,0 +1,2 @@ +all: + mix test --trace diff --git a/test/elixir/README.md b/test/elixir/README.md new file mode 100644 index 000000000..a7aedd37b --- /dev/null +++ b/test/elixir/README.md @@ -0,0 +1,12 @@ +# Elixir Test Suite + +Proof of concept porting the JS test suite to Elixir. + +Currently the basics.js suite has been partially ported over. + +To run the suite: + +``` +mix deps.get +mix test --trace +``` diff --git a/test/elixir/config/config.exs b/test/elixir/config/config.exs new file mode 100644 index 000000000..966ae83bb --- /dev/null +++ b/test/elixir/config/config.exs @@ -0,0 +1,30 @@ +# This file is responsible for configuring your application +# and its dependencies with the aid of the Mix.Config module. +use Mix.Config + +# This configuration is loaded before any dependency and is restricted +# to this project. If another project depends on this project, this +# file won't be loaded nor affect the parent project. For this reason, +# if you want to provide default values for your application for +# 3rd-party users, it should be done in your "mix.exs" file. + +# You can configure your application as: +# +# config :foo, key: :value +# +# and access this configuration in your application as: +# +# Application.get_env(:foo, :key) +# +# You can also configure a 3rd-party app: +# +# config :logger, level: :info +# + +# It is also possible to import configuration files, relative to this +# directory. For example, you can emulate configuration per environment +# by uncommenting the line below and defining dev.exs, test.exs and such. +# Configuration from the imported file will override the ones defined +# here (which is why it is important to import them last). +# +# import_config "#{Mix.env}.exs" diff --git a/test/elixir/config/test.exs b/test/elixir/config/test.exs new file mode 100644 index 000000000..4b28ea99b --- /dev/null +++ b/test/elixir/config/test.exs @@ -0,0 +1,3 @@ +config :logger, + backends: [:console], + compile_time_purge_level: :debug diff --git a/test/elixir/lib/couch.ex b/test/elixir/lib/couch.ex new file mode 100644 index 000000000..511901107 --- /dev/null +++ b/test/elixir/lib/couch.ex @@ -0,0 +1,73 @@ +defmodule Couch do + use HTTPotion.Base + + @moduledoc """ + CouchDB library to power test suite. + """ + + def process_url(url) do + "http://localhost:15984" <> url + end + + def process_request_headers(headers) do + headers + |> Dict.put(:"User-Agent", "couch-potion") + |> Dict.put(:"Content-Type", "application/json") + end + + def process_options(options) do + Dict.put options, :basic_auth, {"adm", "pass"} + end + + def process_request_body(body) do + if is_map(body) do + :jiffy.encode(body) + else + body + end + end + + def process_response_body(headers, body) do + case headers[:'content-type'] do + "application/json" -> + body |> IO.iodata_to_binary |> :jiffy.decode([:return_maps]) + _ -> + process_response_body(body) + end + end + + def login(user, pass) do + resp = Couch.post("/_session", body: %{:username => user, :password => pass}) + true = resp.body["ok"] + resp.body + end + + # HACK: this is here until this commit lands in a release + # https://github.com/myfreeweb/httpotion/commit/f3fa2f0bc3b9b400573942b3ba4628b48bc3c614 + def handle_response(response) do + case response do + { :ok, status_code, headers, body, _ } -> + processed_headers = process_response_headers(headers) + %HTTPotion.Response{ + status_code: process_status_code(status_code), + headers: processed_headers, + body: process_response_body(processed_headers, body) + } + { :ok, status_code, headers, body } -> + processed_headers = process_response_headers(headers) + %HTTPotion.Response{ + status_code: process_status_code(status_code), + headers: processed_headers, + body: process_response_body(processed_headers, body) + } + { :ibrowse_req_id, id } -> + %HTTPotion.AsyncResponse{ id: id } + { :error, { :conn_failed, { :error, reason }}} -> + %HTTPotion.ErrorResponse{ message: error_to_string(reason)} + { :error, :conn_failed } -> + %HTTPotion.ErrorResponse{ message: "conn_failed"} + { :error, reason } -> + %HTTPotion.ErrorResponse{ message: error_to_string(reason)} + end + end +end diff --git a/test/elixir/mix.exs b/test/elixir/mix.exs new file mode 100644 index 000000000..9b0f642dd --- /dev/null +++ b/test/elixir/mix.exs @@ -0,0 +1,30 @@ +defmodule Foo.Mixfile do + use Mix.Project + + def project do + [ + app: :foo, + version: "0.1.0", + elixir: "~> 1.5", + start_permanent: Mix.env == :prod, + deps: deps() + ] + end + + # Run "mix help compile.app" to learn about applications. + def application do + [ + extra_applications: [:logger] + ] + end + + # Run "mix help deps" to learn about dependencies. + defp deps do + [ + # {:dep_from_hexpm, "~> 0.3.0"}, + {:httpotion, "~> 3.0"}, + {:jiffy, "~> 0.14.11"} + # {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}, + ] + end +end diff --git a/test/elixir/mix.lock b/test/elixir/mix.lock new file mode 100644 index 000000000..0723e9474 --- /dev/null +++ b/test/elixir/mix.lock @@ -0,0 +1,3 @@ +%{"httpotion": {:hex, :httpotion, "3.0.3", "17096ea1a7c0b2df74509e9c15a82b670d66fc4d66e6ef584189f63a9759428d", [], [{:ibrowse, "~> 4.4", [hex: :ibrowse, repo: "hexpm", optional: false]}], "hexpm"}, + "ibrowse": {:hex, :ibrowse, "4.4.0", "2d923325efe0d2cb09b9c6a047b2835a5eda69d8a47ed6ff8bc03628b764e991", [], [], "hexpm"}, + "jiffy": {:hex, :jiffy, "0.14.11", "919a87d491c5a6b5e3bbc27fafedc3a0761ca0b4c405394f121f582fd4e3f0e5", [], [], "hexpm"}} diff --git a/test/elixir/test/all_docs_test.exs b/test/elixir/test/all_docs_test.exs new file mode 100644 index 000000000..2fd608dc6 --- /dev/null +++ b/test/elixir/test/all_docs_test.exs @@ -0,0 +1,132 @@ +defmodule AllDocsTest do + use CouchTestCase + + @moduletag :all_docs + + @moduledoc """ + Test CouchDB _all_docs + This is a port of the all_docs.js suite + """ + + # TODO: do we need to bring this in? + # var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"}, {w: 3}); + + @tag :with_db + test "All Docs tests", context do + db_name = context[:db_name] + resp1 = Couch.post("/#{db_name}", [body: %{:_id => "0", :a => 1, :b => 1}]).body + resp2 = Couch.post("/#{db_name}", [body: %{:_id => "3", :a => 4, :b => 16}]).body + resp3 = Couch.post("/#{db_name}", [body: %{:_id => "1", :a => 2, :b => 4}]).body + resp4 = Couch.post("/#{db_name}", [body: %{:_id => "2", :a => 3, :b => 9}]).body + + assert resp1["ok"] + assert resp2["ok"] + assert resp3["ok"] + assert resp4["ok"] + + revs = [resp1["rev"], resp2["rev"], resp3["rev"], resp4["rev"]] + + # Check _all_docs + resp = Couch.get("/#{db_name}/_all_docs").body + rows = resp["rows"] + assert resp["total_rows"] == length(rows) + Enum.each(rows, fn row -> + assert row["id"] >= "0" && row["id"] <= "4" + end) + + # Check _all_docs with descending=true + resp = Couch.get("/#{db_name}/_all_docs", query: %{:descending => true}).body + rows = resp["rows"] + assert resp["total_rows"] == length(rows) + + # Check _all_docs offset + resp = Couch.get("/#{db_name}/_all_docs", query: %{:startkey => "\"2\""}).body + assert resp["offset"] == 2 + + # Confirm that queries may assume raw collation + resp = Couch.get("/#{db_name}/_all_docs", query: %{ + :startkey => "\"org.couchdb.user:\"", + :endkey => "\"org.couchdb.user;\"" + }) + assert length(resp.body["rows"]) == 0 + + # Check that all docs show up in the changes feed; order can vary + resp = Couch.get("/#{db_name}/_changes").body + Enum.each(resp["results"], fn row -> + assert Enum.member?(revs, hd(row["changes"])["rev"]), "doc #{row["id"]} should be in changes" + end) + + # Check that deletions also show up right + doc1 = Couch.get("/#{db_name}/1").body + assert Couch.delete("/#{db_name}/1", query: %{:rev => doc1["_rev"]}).body["ok"] + changes = Couch.get("/#{db_name}/_changes").body["results"] + assert length(changes) == 4 + deleted = Enum.filter(changes, fn row -> row["deleted"] end) + assert length(deleted) == 1 + assert hd(deleted)["id"] == "1" + + # (remember old seq) + orig_doc = Enum.find(changes, fn row -> row["id"] == "3" end) + # Perform an update + doc3 = Couch.get("/#{db_name}/3").body + doc3 = Map.put(doc3, :updated, "totally") + assert Couch.put("/#{db_name}/3", body: doc3).body["ok"] + + # The update should make doc id 3 have another seq num (not nec. higher or the last though) + changes = Couch.get("/#{db_name}/_changes").body["results"] + assert length(changes) == 4 + updated_doc = Enum.find(changes, fn row -> row["id"] == "3" end) + assert orig_doc["seq"] != updated_doc["seq"], "seq num should be different" + + # Ok, now let's see what happens with include docs + changes = Couch.get("/#{db_name}/_changes", query: %{:include_docs => true}).body["results"] + assert length(changes) == 4 + updated_doc = Enum.find(changes, fn row -> row["id"] == doc3["_id"] end) + assert updated_doc["doc"]["updated"] == "totally" + + deleted_doc = Enum.find(changes, fn row -> row["deleted"] end) + assert deleted_doc["doc"]["_deleted"] + + # Test _all_docs with keys + rows = Couch.post("/#{db_name}/_all_docs", query: %{:include_docs => true}, body: %{:keys => ["1"]}).body["rows"] + row = hd(rows) + assert length(rows) == 1 + assert row["key"] == "1" + assert row["id"] == "1" + assert row["value"]["deleted"] + assert row["doc"] == :null + + # Add conflicts + conflicted_doc1 = %{:_id => "3", :_rev => "2-aa01552213fafa022e6167113ed01087", :value => "X"} + conflicted_doc2 = %{:_id => "3", :_rev => "2-ff01552213fafa022e6167113ed01087", :value => "Z"} + assert Couch.put("/#{db_name}/3", query: %{:new_edits => false}, body: conflicted_doc1).body["ok"] + assert Couch.put("/#{db_name}/3", query: %{:new_edits => false}, body: conflicted_doc2).body["ok"] + + win_rev = Couch.get("/#{db_name}/3").body + changes = Couch.get("/#{db_name}/_changes", query: %{:include_docs => true, :conflicts => true, :style => "all_docs"}).body["results"] + + doc3 = Enum.find(changes, fn row -> row["id"] == "3" end) + assert doc3["id"] == "3" + assert length(doc3["changes"]) == 3 + assert win_rev["_rev"] == hd(doc3["changes"])["rev"] + assert is_list(doc3["doc"]["_conflicts"]) + assert length(doc3["doc"]["_conflicts"]) == 2 + + rows = Couch.get("/#{db_name}/_all_docs", query: %{:include_docs => true, :conflicts => true}).body["rows"] + assert length(rows) == 3 + change = hd(tl(tl(rows))) + assert change["key"] == "3" + assert change["id"] == "3" + assert change["value"]["rev"] == win_rev["_rev"] + assert change["doc"]["_rev"] == win_rev["_rev"] + assert change["doc"]["_id"] == "3" + assert is_list(change["doc"]["_conflicts"]) + assert length(change["doc"]["_conflicts"]) == 2 + + # Test that _all_docs collates sanely + assert Couch.post("/#{db_name}", body: %{:_id => "Z", :foo => "Z"}).body["ok"] + assert Couch.post("/#{db_name}", body: %{:_id => "a", :foo => "a"}).body["ok"] + rows = Couch.get("/#{db_name}/_all_docs", query: %{:startkey => "\"Z\"", :endkey => "\"Z\""}).body["rows"] + assert length(rows) == 1 + end +end diff --git a/test/elixir/test/basics_test.exs b/test/elixir/test/basics_test.exs new file mode 100644 index 000000000..40ad4bda1 --- /dev/null +++ b/test/elixir/test/basics_test.exs @@ -0,0 +1,277 @@ +defmodule BasicsTest do + use CouchTestCase + + @moduletag :basics + + @moduledoc """ + Test CouchDB basics. + This is a port of the basics.js suite + """ + + test "Session contains adm context" do + userCtx = Couch.get("/_session").body["userCtx"] + assert userCtx["name"] == "adm", "Should have adm user context" + assert userCtx["roles"] == ["_admin"], "Should have _admin role" + end + + test "Welcome endpoint" do + assert Couch.get("/").body["couchdb"] == "Welcome", "Should say welcome" + end + + @tag :with_db + test "PUT on existing DB should return 412 instead of 500", context do + db_name = context[:db_name] + resp = Couch.put("/#{db_name}") + assert resp.status_code == 412 + refute resp.body["ok"] + end + + @tag :with_db_name + test "Creating a new DB should return location header", context do + db_name = context[:db_name] + {:ok, resp} = create_db(db_name) + msg = "Should return Location header for new db" + assert String.ends_with?(resp.headers["location"], db_name), msg + {:ok, _} = delete_db(db_name) + end + + @tag :with_db_name + test "Creating a new DB with slashes should return Location header (COUCHDB-411)", context do + db_name = context[:db_name] <> "%2Fwith_slashes" + {:ok, resp} = create_db(db_name) + msg = "Should return Location header for new db" + assert String.ends_with?(resp.headers["location"], db_name), msg + {:ok, _} = delete_db(db_name) + end + + @tag :with_db + test "Created database has appropriate db info name", context do + db_name = context[:db_name] + assert Couch.get("/#{db_name}").body["db_name"] == db_name, "Get correct database name" + end + + @tag :with_db + test "Database should be in _all_dbs", context do + assert context[:db_name] in Couch.get("/_all_dbs").body, "Db name in _all_dbs" + end + + @tag :with_db + test "Empty database should have zero docs", context do + assert Couch.get("/#{context[:db_name]}").body["doc_count"] == 0, "Empty doc count in empty db" + end + + @tag :with_db + test "Create a document and save it to the database", context do + resp = Couch.post("/#{context[:db_name]}", [body: %{:_id => "0", :a => 1, :b => 1}]) + assert resp.status_code == 201, "Should be 201 created" + assert resp.body["id"], "Id should be present" + assert resp.body["rev"], "Rev should be present" + + resp2 = Couch.get("/#{context[:db_name]}/#{resp.body["id"]}") + assert resp2.body["_id"] == resp.body["id"], "Ids should match" + assert resp2.body["_rev"] == resp.body["rev"], "Revs should match" + end + + @tag :with_db + test "Revs info status is good", context do + db_name = context[:db_name] + {:ok, _} = create_doc(db_name, sample_doc_foo()) + resp = Couch.get("/#{db_name}/foo", [query: %{:revs_info => true}]) + assert hd(resp.body["_revs_info"])["status"] == "available", "Revs info is available" + end + + @tag :with_db + test "Make sure you can do a seq=true option", context do + db_name = context[:db_name] + {:ok, _} = create_doc(db_name, sample_doc_foo()) + resp = Couch.get("/#{db_name}/foo", [query: %{:local_seq => true}]) + assert resp.body["_local_seq"] == 1, "Local seq value == 1" + end + + @tag :with_db + test "Can create several documents", context do + db_name = context[:db_name] + assert Couch.post("/#{db_name}", [body: %{:_id => "1", :a => 2, :b => 4}]).body["ok"] + assert Couch.post("/#{db_name}", [body: %{:_id => "2", :a => 3, :b => 9}]).body["ok"] + assert Couch.post("/#{db_name}", [body: %{:_id => "3", :a => 4, :b => 16}]).body["ok"] + assert Couch.get("/#{db_name}").body["doc_count"] == 3 + end + + @tag :pending + @tag :with_db + test "Regression test for COUCHDB-954", context do + db_name = context[:db_name] + doc = %{:_id => "COUCHDB-954", :a => 1} + + resp1 = Couch.post("/#{db_name}", [body: doc]) + assert resp1.body["ok"] + old_rev = resp1.body["rev"] + + doc = Map.put(doc, :_rev, old_rev) + resp2 = Couch.post("/#{db_name}", [body: doc]) + assert resp2.body["ok"] + new_rev = resp2.body["rev"] + + # TODO: enable chunked encoding + #resp3 = Couch.get("/#{db_name}/COUCHDB-954", [query: %{:open_revs => "[#{old_rev}, #{new_rev}]"}]) + #assert length(resp3.body) == 2, "Should get two revisions back" + #resp3 = Couch.get("/#{db_name}/COUCHDB-954", [query: %{:open_revs => "[#{old_rev}]", :latest => true}]) + #assert resp3.body["_rev"] == new_rev + end + + @tag :with_db + test "Simple map functions", context do + db_name = context[:db_name] + map_fun = "function(doc) { if (doc.a==4) { emit(null, doc.b); } }" + red_fun = "function(keys, values) { return sum(values); }" + map_doc = %{:views => %{:baz => %{:map => map_fun}}} + red_doc = %{:views => %{:baz => %{:map => map_fun, :reduce => red_fun}}} + + # Bootstrap database and ddoc + assert Couch.post("/#{db_name}", [body: %{:_id => "0", :a => 1, :b => 1}]).body["ok"] + assert Couch.post("/#{db_name}", [body: %{:_id => "1", :a => 2, :b => 4}]).body["ok"] + assert Couch.post("/#{db_name}", [body: %{:_id => "2", :a => 3, :b => 9}]).body["ok"] + assert Couch.post("/#{db_name}", [body: %{:_id => "3", :a => 4, :b => 16}]).body["ok"] + assert Couch.put("/#{db_name}/_design/foo", [body: map_doc]).body["ok"] + assert Couch.put("/#{db_name}/_design/bar", [body: red_doc]).body["ok"] + assert Couch.get("/#{db_name}").body["doc_count"] == 6 + + # Initial view query test + resp = Couch.get("/#{db_name}/_design/foo/_view/baz") + assert resp.body["total_rows"] == 1 + assert hd(resp.body["rows"])["value"] == 16 + + # Modified doc and test for updated view results + doc0 = Couch.get("/#{db_name}/0").body + doc0 = Map.put(doc0, :a, 4) + assert Couch.put("/#{db_name}/0", [body: doc0]).body["ok"] + resp = Couch.get("/#{db_name}/_design/foo/_view/baz") + assert resp.body["total_rows"] == 2 + + # Write 2 more docs and test for updated view results + assert Couch.post("/#{db_name}", [body: %{:a => 3, :b => 9}]).body["ok"] + assert Couch.post("/#{db_name}", [body: %{:a => 4, :b => 16}]).body["ok"] + resp = Couch.get("/#{db_name}/_design/foo/_view/baz") + assert resp.body["total_rows"] == 3 + assert Couch.get("/#{db_name}").body["doc_count"] == 8 + + # Test reduce function + resp = Couch.get("/#{db_name}/_design/bar/_view/baz") + assert hd(resp.body["rows"])["value"] == 33 + + # Delete doc and test for updated view results + doc0 = Couch.get("/#{db_name}/0").body + assert Couch.delete("/#{db_name}/0?rev=#{doc0["_rev"]}").body["ok"] + resp = Couch.get("/#{db_name}/_design/foo/_view/baz") + assert resp.body["total_rows"] == 2 + assert Couch.get("/#{db_name}").body["doc_count"] == 7 + assert Couch.get("/#{db_name}/0").status_code == 404 + refute Couch.get("/#{db_name}/0?rev=#{doc0["_rev"]}").status_code == 404 + end + + @tag :with_db + test "POST doc response has a Location header", context do + db_name = context[:db_name] + resp = Couch.post("/#{db_name}", [body: %{:foo => :bar}]) + assert resp.body["ok"] + loc = resp.headers["Location"] + assert loc, "should have a Location header" + locs = Enum.reverse(String.split(loc, "/")) + assert hd(locs) == resp.body["id"] + assert hd(tl(locs)) == db_name + end + + @tag :with_db + test "POST doc with an _id field isn't overwritten by uuid", context do + db_name = context[:db_name] + resp = Couch.post("/#{db_name}", [body: %{:_id => "oppossum", :yar => "matey"}]) + assert resp.body["ok"] + assert resp.body["id"] == "oppossum" + assert Couch.get("/#{db_name}/oppossum").body["yar"] == "matey" + end + + @tag :pending + @tag :with_db + test "PUT doc has a Location header", context do + db_name = context[:db_name] + resp = Couch.put("/#{db_name}/newdoc", [body: %{:a => 1}]) + assert String.ends_with?(resp.headers["location"], "/#{db_name}/newdoc") + # TODO: make protocol check use defined protocol value + assert String.starts_with?(resp.headers["location"], "http") + end + + @tag :with_db + test "DELETE'ing a non-existent doc should 404", context do + db_name = context[:db_name] + assert Couch.delete("/#{db_name}/doc-does-not-exist").status_code == 404 + end + + @tag :with_db + test "Check for invalid document members", context do + db_name = context[:db_name] + bad_docs = [ + {:goldfish, %{:_zing => 4}}, + {:zebrafish, %{:_zoom => "hello"}}, + {:mudfish, %{:zane => "goldfish", :_fan => "something smells delicious"}}, + {:tastyfish, %{:_bing => %{"wha?" => "soda can"}}} + ] + + Enum.each(bad_docs, fn {id, doc} -> + resp = Couch.put("/#{db_name}/#{id}", [body: doc]) + assert resp.status_code == 400 + assert resp.body["error"] == "doc_validation" + + resp = Couch.post("/#{db_name}", [body: doc]) + assert resp.status_code == 400 + assert resp.body["error"] == "doc_validation" + end) + end + + @tag :with_db + test "PUT error when body not an object", context do + db_name = context[:db_name] + resp = Couch.put("/#{db_name}/bar", [body: "[]"]) + assert resp.status_code == 400 + assert resp.body["error"] == "bad_request" + assert resp.body["reason"] == "Document must be a JSON object" + end + + @tag :with_db + test "_bulk_docs POST error when body not an object", context do + db_name = context[:db_name] + resp = Couch.post("/#{db_name}/_bulk_docs", [body: "[]"]) + assert resp.status_code == 400 + assert resp.body["error"] == "bad_request" + assert resp.body["reason"] == "Request body must be a JSON object" + end + + @tag :with_db + test "_all_docs POST error when multi-get is not a {'key': [...]} structure", context do + db_name = context[:db_name] + resp = Couch.post("/#{db_name}/_all_docs", [body: "[]"]) + assert resp.status_code == 400 + assert resp.body["error"] == "bad_request" + assert resp.body["reason"] == "Request body must be a JSON object" + + resp = Couch.post("/#{db_name}/_all_docs", [body: %{:keys => 1}]) + assert resp.status_code == 400 + assert resp.body["error"] == "bad_request" + assert resp.body["reason"] == "`keys` body member must be an array." + end + + @tag :with_db + test "oops, the doc id got lost in code nirwana", context do + db_name = context[:db_name] + resp = Couch.delete("/#{db_name}/?rev=foobarbaz") + assert resp.status_code == 400, "should return a bad request" + assert resp.body["error"] == "bad_request" + assert resp.body["reason"] == "You tried to DELETE a database with a ?=rev parameter. Did you mean to DELETE a document instead?" + end + + @tag :pending + @tag :with_db + test "On restart, a request for creating an already existing db can not override", context do + # TODO + assert true + end +end diff --git a/test/elixir/test/config_test.exs b/test/elixir/test/config_test.exs new file mode 100644 index 000000000..f83f5a669 --- /dev/null +++ b/test/elixir/test/config_test.exs @@ -0,0 +1,149 @@ +defmodule ConfigTest do + use CouchTestCase + + @moduletag :config + + @moduledoc """ + Test CouchDB config API + This is a port of the config.js suite + """ + + setup do + # TODO: switch this to _local when that's landed + config_url = "/_node/node1@127.0.0.1/_config" + resp = Couch.get(config_url) + assert resp.status_code == 200 + {:ok, config: resp.body, config_url: config_url} + end + + def set_config(context, section, key, val) do + set_config(context, section, key, val, 200) + end + + def set_config(context, section, key, val, status_assert) do + url = "#{context[:config_url]}/#{section}/#{key}" + headers = ["X-Couch-Persist": "false"] + resp = Couch.put(url, headers: headers, body: :jiffy.encode(val)) + if status_assert do + assert resp.status_code == status_assert + end + resp.body + end + + def get_config(context, section) do + get_config(context, section, nil, 200) + end + + def get_config(context, section, key) do + get_config(context, section, key, 200) + end + + def get_config(context, section, key, status_assert) do + url = if key do + "#{context[:config_url]}/#{section}/#{key}" + else + "#{context[:config_url]}/#{section}" + end + resp = Couch.get(url) + if status_assert do + assert resp.status_code == status_assert + end + resp.body + end + + def delete_config(context, section, key) do + delete_config(context, section, key, 200) + end + + def delete_config(context, section, key, status_assert) do + url = "#{context[:config_url]}/#{section}/#{key}" + resp = Couch.delete(url) + if status_assert do + assert resp.status_code == status_assert + end + end + + # TODO: port sever_port tests from config.js + @tag :pending + test "CouchDB respects configured protocols" + + test "Standard config options are present", context do + assert context[:config]["couchdb"]["database_dir"] + assert context[:config]["daemons"]["httpd"] + assert context[:config]["httpd_global_handlers"]["_config"] + assert context[:config]["log"]["level"] + assert context[:config]["query_servers"]["javascript"] + end + + test "Settings can be altered with undefined whitelist allowing any change", context do + refute context["config"]["httpd"]["config_whitelist"], "Default whitelist is empty" + set_config(context, "test", "foo", "bar") + assert get_config(context, "test")["foo"] == "bar" + assert get_config(context, "test", "foo") == "bar" + end + + test "Server-side password hashing, and raw updates disabling that", context do + plain_pass = "s3cret" + set_config(context, "admins", "administrator", plain_pass) + assert Couch.login("administrator", plain_pass)["ok"] + hash_pass = get_config(context, "admins", "administrator") + assert Regex.match?(~r/^-pbkdf2-/, hash_pass) or Regex.match?(~r/^-hashed-/, hash_pass) + delete_config(context, "admins", "administrator") + assert Couch.delete("/_session").body["ok"] + end + + @tag :pending + test "PORT `BUGGED` ?raw tests from config.js" + + test "Non-term whitelist values allow further modification of the whitelist", context do + val = "!This is an invalid Erlang term!" + set_config(context, "httpd", "config_whitelist", val) + assert val == get_config(context, "httpd", "config_whitelist") + delete_config(context, "httpd", "config_whitelist") + end + + test "Non-list whitelist values allow further modification of the whitelist", context do + val = "{[yes, a_valid_erlang_term, but_unfortunately, not_a_list]}" + set_config(context, "httpd", "config_whitelist", val) + assert val == get_config(context, "httpd", "config_whitelist") + delete_config(context, "httpd", "config_whitelist") + end + + test "Keys not in the whitelist may not be modified", context do + val = "[{httpd,config_whitelist}, {test,foo}]" + set_config(context, "httpd", "config_whitelist", val) + assert val == get_config(context, "httpd", "config_whitelist") + set_config(context, "test", "foo", "PUT to whitelisted config variable") + delete_config(context, "test", "foo") + end + + test "Non-2-tuples in the whitelist are ignored", context do + val = "[{httpd,config_whitelist}, these, {are}, {nOt, 2, tuples}, [so], [they, will], [all, become, noops], {test,foo}]" + set_config(context, "httpd", "config_whitelist", val) + assert val == get_config(context, "httpd", "config_whitelist") + set_config(context, "test", "foo", "PUT to whitelisted config variable") + delete_config(context, "test", "foo") + end + + test "Atoms, binaries, and strings suffice as whitelist sections and keys.", context do + vals = ["{test,foo}", "{\"test\",\"foo\"}", "{<<\"test\">>,<<\"foo\">>}"] + Enum.each(vals, fn pair -> + set_config(context, "httpd", "config_whitelist", "[{httpd,config_whitelist}, #{pair}") + pair_format = case String.at(pair, 1) do + "t" -> "tuple" + "\"" -> "string" + "<" -> "binary" + end + set_config(context, "test", "foo", "PUT with #{pair_format}") + delete_config(context, "test", "foo") + end) + delete_config(context, "httpd", "config_whitelist") + end + + test "Blacklist is functional", context do + sections = ["daemons", "external", "httpd_design_handlers", "httpd_db_handlers", "native_query_servers", "os_daemons", "query_servers"] + Enum.each(sections, fn section -> + set_config(context, section, "wohali", "rules", 403) + end) + end +end diff --git a/test/elixir/test/reduce_test.exs b/test/elixir/test/reduce_test.exs new file mode 100644 index 000000000..5c56165ed --- /dev/null +++ b/test/elixir/test/reduce_test.exs @@ -0,0 +1,416 @@ +defmodule ReduceTest do + use CouchTestCase + + @moduletag :views + + @moduledoc """ + Test CouchDB view reduces + This is a port of the reduce.js suite + """ + + def summate(n) do + (n + 1) * n / 2 + end + + @tag :with_db + test "Basic reduce functions", context do + db_name = context[:db_name] + view_url = "/#{db_name}/_design/foo/_view/bar" + num_docs = 500 + map = ~s""" +function (doc) { + emit(doc.integer, doc.integer); + emit(doc.integer, doc.integer); +}; + """ + reduce = "function (keys, values) { return sum(values); };" + red_doc = %{:views => %{:bar => %{:map => map, :reduce => reduce}}} + + assert Couch.put("/#{db_name}/_design/foo", [body: red_doc]).body["ok"] + docs = make_docs(1, num_docs) + assert Couch.post("/#{db_name}/_bulk_docs", [body: %{:docs => docs}, query: %{w: 3}]).status_code == 201 + + rows = Couch.get(view_url).body["rows"] + assert hd(rows)["value"] == 2 * summate(num_docs) + + query = %{:startkey => 4, :endkey => 4} + rows = Couch.get(view_url, query: query).body["rows"] + assert hd(rows)["value"] == 8 + + query = %{:startkey => 4, :endkey => 5} + rows = Couch.get(view_url, query: query).body["rows"] + assert hd(rows)["value"] == 18 + + query = %{:startkey => 4, :endkey => 6} + rows = Couch.get(view_url, query: query).body["rows"] + assert hd(rows)["value"] == 30 + + query = %{:group => true, :limit => 3} + rows = Couch.get(view_url, query: query).body["rows"] + assert Enum.at(rows, 0)["value"] == 2 + assert Enum.at(rows, 1)["value"] == 4 + assert Enum.at(rows, 2)["value"] == 6 + + half_num_docs = Integer.floor_div(num_docs, 2) + max = Integer.floor_div(num_docs, 30) + 1 + for i <- 1..max, i * 30 + 1 < half_num_docs do + i = i * 30 + 1 + query = %{:startkey => i, :endkey => num_docs - i} + rows = Couch.get(view_url, query: query).body["rows"] + assert hd(rows)["value"] == 2 * (summate(num_docs - i) - summate(i - 1)) + end + end + + @tag :with_db + test "More complex array key view row testing", context do + db_name = context[:db_name] + view_url = "/#{db_name}/_design/foo/_view/bar" + map = "function (doc) { emit(doc.keys, 1); };" + reduce = "function (keys, values) { return sum(values); };" + red_doc = %{:views => %{bar: %{map: map, reduce: reduce}}} + + assert Couch.put("/#{db_name}/_design/foo", [body: red_doc]).body["ok"] + for i <- 1..5 do + for j <- 0..9 do + docs = [ + %{keys: ["a"]}, + %{keys: ["a"]}, + %{keys: ["a", "b"]}, + %{keys: ["a", "b"]}, + %{keys: ["a", "b", "c"]}, + %{keys: ["a", "b", "d"]}, + %{keys: ["a", "c", "d"]}, + %{keys: ["d"]}, + %{keys: ["d", "a"]}, + %{keys: ["d", "b"]}, + %{keys: ["d", "c"]} + ] + assert Couch.post("/#{db_name}/_bulk_docs", [body: %{docs: docs}, query: %{w: 3}]).status_code == 201 + total_docs = 1 + ((i - 1) * 10 * 11) + ((j + 1) * 11); + assert Couch.get("/#{db_name}").body["doc_count"] == total_docs + end + + # test group by exact key match + query = %{group: true} + rows = Couch.get(view_url, query: query).body["rows"] + assert Enum.at(rows, 0) == %{"key" => ["a"], "value" => 20 * i} + assert Enum.at(rows, 0) == %{"key" => ["a"], "value" => 20 * i} + assert Enum.at(rows, 0) == %{"key" => ["a"], "value" => 20 * i} + assert Enum.at(rows, 1) == %{"key" => ["a", "b"], "value" => 20 * i} + assert Enum.at(rows, 2) == %{"key" => ["a", "b", "c"], "value" => 10 * i} + assert Enum.at(rows, 3) == %{"key" => ["a", "b", "d"], "value" => 10 * i} + + # test group reduce and limit params provide valid json + query = %{group: true, limit: 2} + rows = Couch.get(view_url, query: query).body["rows"] + assert Enum.at(rows, 0) == %{"key" => ["a"], "value" => 20 * i} + assert length(rows) == 2 + + # test group by the first element in the key array + query = %{group_level: 2} + rows = Couch.get(view_url, query: query).body["rows"] + assert Enum.at(rows, 0) == %{"key" => ["a"], "value" => 20*i} + assert Enum.at(rows, 1) == %{"key" => ["a","b"], "value" => 40*i} + assert Enum.at(rows, 2) == %{"key" => ["a","c"], "value" => 10*i} + assert Enum.at(rows, 3) == %{"key" => ["d"], "value" => 10*i} + assert Enum.at(rows, 4) == %{"key" => ["d","a"], "value" => 10*i} + assert Enum.at(rows, 5) == %{"key" => ["d","b"], "value" => 10*i} + assert Enum.at(rows, 6) == %{"key" => ["d","c"], "value" => 10*i} + + # test endkey with inclusive_end=true + query = %{group_level: 2, endkey: ~s(["d"]), inclusive_end: true} + rows = Couch.get(view_url, query: query).body["rows"] + assert Enum.at(rows, 0) == %{"key" => ["a"], "value" => 20*i} + assert Enum.at(rows, 1) == %{"key" => ["a","b"], "value" => 40*i} + assert Enum.at(rows, 2) == %{"key" => ["a","c"], "value" => 10*i} + assert Enum.at(rows, 3) == %{"key" => ["d"], "value" => 10*i} + assert length(rows) == 4 + + # test endkey with inclusive_end=false + query = %{group_level: 2, endkey: ~s(["d"]), inclusive_end: false} + rows = Couch.get(view_url, query: query).body["rows"] + assert Enum.at(rows, 0) == %{"key" => ["a"], "value" => 20*i} + assert Enum.at(rows, 1) == %{"key" => ["a","b"], "value" => 40*i} + assert Enum.at(rows, 2) == %{"key" => ["a","c"], "value" => 10*i} + assert length(rows) == 3 + end + end + + @tag :with_db + test "More complex reductions that need to use the combine option", context do + db_name = context[:db_name] + view_url = "/#{db_name}/_design/foo/_view/bar" + map = "function (doc) { emit(doc.val, doc.val); };" + reduce = ~s""" +function (keys, values, rereduce) { + // This computes the standard deviation of the mapped results + var stdDeviation=0.0; + var count=0; + var total=0.0; + var sqrTotal=0.0; + + if (!rereduce) { + // This is the reduce phase, we are reducing over emitted values from + // the map functions. + for(var i in values) { + total = total + values[i]; + sqrTotal = sqrTotal + (values[i] * values[i]); + } + count = values.length; + } + else { + // This is the rereduce phase, we are re-reducing previosuly + // reduced values. + for(var i in values) { + count = count + values[i].count; + total = total + values[i].total; + sqrTotal = sqrTotal + values[i].sqrTotal; + } + } + + var variance = (sqrTotal - ((total * total)/count)) / count; + stdDeviation = Math.sqrt(variance); + + // the reduce result. It contains enough information to be rereduced + // with other reduce results. + return {"stdDeviation":stdDeviation,"count":count, + "total":total,"sqrTotal":sqrTotal}; +} + """ + + red_doc = %{:views => %{:bar => %{:map => map, :reduce => reduce}}} + assert Couch.put("/#{db_name}/_design/foo", [body: red_doc]).body["ok"] + + Enum.each(1..10, fn _ -> + docs = for i <- 1..10, do: %{val: i * 10} + assert Couch.post("/#{db_name}/_bulk_docs", [body: %{:docs => docs}, query: %{w: 3}]).status_code == 201 + end) + + rows = Couch.get(view_url).body["rows"] + assert_in_delta hd(rows)["value"]["stdDeviation"], 28.722813232690143, 0.0000000001 + end + + @tag :with_db + test "Reduce pagination", context do + db_name = context[:db_name] + view_url = "/#{db_name}/_design/foo/_view/bar" + ddoc = %{ + _id: "_design/foo", + language: "javascript", + views: %{ + bar: %{ + reduce: "_count", + map: ~s""" + function(doc) { + emit(doc.int, doc._id); + emit(doc.int + 1, doc._id); + emit(doc.int + 2, doc._id); + } + """ + } + } + } + + assert Couch.put("/#{db_name}/_design/foo", [body: ddoc]).body["ok"] + docs = for i <- 0..1122, do: %{_id: Integer.to_string(i), int: i} + assert Couch.post("/#{db_name}/_bulk_docs", [body: %{:docs => docs}, query: %{w: 3}]).status_code == 201 + + rand_val = fn -> :rand.uniform(100000000) end + + # ?group=false tests + query = %{startkey: 400, endkey: 402, foobar: rand_val.()} + rows = Couch.get(view_url, query: query).body["rows"] + assert hd(rows)["value"] == 9 + query = %{startkey: 402, endkey: 400, foobar: rand_val.(), descending: true} + rows = Couch.get(view_url, query: query).body["rows"] + assert hd(rows)["value"] == 9 + + query = %{startkey: 400, endkey: 402, foobar: rand_val.(), inclusive_end: false} + rows = Couch.get(view_url, query: query).body["rows"] + assert hd(rows)["value"] == 6 + query = %{startkey: 402, endkey: 400, foobar: rand_val.(), inclusive_end: false, descending: true} + rows = Couch.get(view_url, query: query).body["rows"] + assert hd(rows)["value"] == 6 + + query = %{startkey: 400, endkey: 402, foobar: rand_val.(), endkey_docid: "400"} + rows = Couch.get(view_url, query: query).body["rows"] + assert hd(rows)["value"] == 7 + query = %{startkey: 400, endkey: 402, foobar: rand_val.(), endkey_docid: "400", inclusive_end: false} + rows = Couch.get(view_url, query: query).body["rows"] + assert hd(rows)["value"] == 6 + + query = %{startkey: 400, endkey: 402, foobar: rand_val.(), endkey_docid: "401"} + rows = Couch.get(view_url, query: query).body["rows"] + assert hd(rows)["value"] == 8 + query = %{startkey: 400, endkey: 402, foobar: rand_val.(), endkey_docid: "401", inclusive_end: false} + rows = Couch.get(view_url, query: query).body["rows"] + assert hd(rows)["value"] == 7 + + query = %{startkey: 400, endkey: 402, foobar: rand_val.(), endkey_docid: "402"} + rows = Couch.get(view_url, query: query).body["rows"] + assert hd(rows)["value"] == 9 + query = %{startkey: 400, endkey: 402, foobar: rand_val.(), endkey_docid: "402", inclusive_end: false} + rows = Couch.get(view_url, query: query).body["rows"] + assert hd(rows)["value"] == 8 + + query = %{startkey: 402, endkey: 400, foobar: rand_val.(), endkey_docid: "398", descending: true} + rows = Couch.get(view_url, query: query).body["rows"] + assert hd(rows)["value"] == 9 + query = %{startkey: 402, endkey: 400, foobar: rand_val.(), endkey_docid: "398", descending: true, inclusive_end: false} + rows = Couch.get(view_url, query: query).body["rows"] + assert hd(rows)["value"] == 8 + + query = %{startkey: 402, endkey: 400, foobar: rand_val.(), endkey_docid: "399", descending: true} + rows = Couch.get(view_url, query: query).body["rows"] + assert hd(rows)["value"] == 8 + query = %{startkey: 402, endkey: 400, foobar: rand_val.(), endkey_docid: "399", descending: true, inclusive_end: false} + rows = Couch.get(view_url, query: query).body["rows"] + assert hd(rows)["value"] == 7 + + query = %{startkey: 402, endkey: 400, foobar: rand_val.(), endkey_docid: "400", descending: true} + rows = Couch.get(view_url, query: query).body["rows"] + assert hd(rows)["value"] == 7 + query = %{startkey: 402, endkey: 400, foobar: rand_val.(), endkey_docid: "400", descending: true, inclusive_end: false} + rows = Couch.get(view_url, query: query).body["rows"] + assert hd(rows)["value"] == 6 + + query = %{startkey: 402, endkey: 400, foobar: rand_val.(), startkey_docid: "400", descending: true} + rows = Couch.get(view_url, query: query).body["rows"] + assert hd(rows)["value"] == 7 + + query = %{startkey: 402, endkey: 400, foobar: rand_val.(), startkey_docid: "401", descending: true, inclusive_end: false} + rows = Couch.get(view_url, query: query).body["rows"] + assert hd(rows)["value"] == 5 + + # ?group=true tests + query = %{:group => true, startkey: 400, endkey: 402, foobar: rand_val.()} + rows = Couch.get(view_url, query: query).body["rows"] + assert length(rows) == 3 + assert Enum.at(rows, 0)["key"] == 400 + assert Enum.at(rows, 0)["value"] == 3 + assert Enum.at(rows, 1)["key"] == 401 + assert Enum.at(rows, 1)["value"] == 3 + assert Enum.at(rows, 2)["key"] == 402 + assert Enum.at(rows, 2)["value"] == 3 + + query = %{:group => true, startkey: 402, endkey: 400, foobar: rand_val.(), descending: true} + rows = Couch.get(view_url, query: query).body["rows"] + assert length(rows) == 3 + assert Enum.at(rows, 0)["key"] == 402 + assert Enum.at(rows, 0)["value"] == 3 + assert Enum.at(rows, 1)["key"] == 401 + assert Enum.at(rows, 1)["value"] == 3 + assert Enum.at(rows, 2)["key"] == 400 + assert Enum.at(rows, 2)["value"] == 3 + + query = %{:group => true, startkey: 400, endkey: 402, foobar: rand_val.(), inclusive_end: false} + rows = Couch.get(view_url, query: query).body["rows"] + assert length(rows) == 2 + assert Enum.at(rows, 0)["key"] == 400 + assert Enum.at(rows, 0)["value"] == 3 + assert Enum.at(rows, 1)["key"] == 401 + assert Enum.at(rows, 1)["value"] == 3 + + query = %{:group => true, startkey: 402, endkey: 400, foobar: rand_val.(), inclusive_end: false, descending: true} + rows = Couch.get(view_url, query: query).body["rows"] + assert length(rows) == 2 + assert Enum.at(rows, 0)["key"] == 402 + assert Enum.at(rows, 0)["value"] == 3 + assert Enum.at(rows, 1)["key"] == 401 + assert Enum.at(rows, 1)["value"] == 3 + + query = %{:group => true, startkey: 400, endkey: 402, foobar: rand_val.(), endkey_docid: "401"} + rows = Couch.get(view_url, query: query).body["rows"] + assert length(rows) == 3 + assert Enum.at(rows, 0)["key"] == 400 + assert Enum.at(rows, 0)["value"] == 3 + assert Enum.at(rows, 1)["key"] == 401 + assert Enum.at(rows, 1)["value"] == 3 + assert Enum.at(rows, 2)["key"] == 402 + assert Enum.at(rows, 2)["value"] == 2 + + query = %{:group => true, startkey: 400, endkey: 402, foobar: rand_val.(), endkey_docid: "400"} + rows = Couch.get(view_url, query: query).body["rows"] + assert length(rows) == 3 + assert Enum.at(rows, 0)["key"] == 400 + assert Enum.at(rows, 0)["value"] == 3 + assert Enum.at(rows, 1)["key"] == 401 + assert Enum.at(rows, 1)["value"] == 3 + assert Enum.at(rows, 2)["key"] == 402 + assert Enum.at(rows, 2)["value"] == 1 + + query = %{:group => true, startkey: 402, endkey: 400, foobar: rand_val.(), startkey_docid: "401", descending: true} + rows = Couch.get(view_url, query: query).body["rows"] + assert length(rows) == 3 + assert Enum.at(rows, 0)["key"] == 402 + assert Enum.at(rows, 0)["value"] == 2 + assert Enum.at(rows, 1)["key"] == 401 + assert Enum.at(rows, 1)["value"] == 3 + assert Enum.at(rows, 2)["key"] == 400 + assert Enum.at(rows, 2)["value"] == 3 + + query = %{:group => true, startkey: 402, endkey: 400, foobar: rand_val.(), startkey_docid: "400", descending: true} + rows = Couch.get(view_url, query: query).body["rows"] + assert length(rows) == 3 + assert Enum.at(rows, 0)["key"] == 402 + assert Enum.at(rows, 0)["value"] == 1 + assert Enum.at(rows, 1)["key"] == 401 + assert Enum.at(rows, 1)["value"] == 3 + assert Enum.at(rows, 2)["key"] == 400 + assert Enum.at(rows, 2)["value"] == 3 + + query = %{:group => true, startkey: 402, endkey: 400, foobar: rand_val.(), startkey_docid: "401", descending: true, inclusive_end: false} + rows = Couch.get(view_url, query: query).body["rows"] + assert length(rows) == 2 + assert Enum.at(rows, 0)["key"] == 402 + assert Enum.at(rows, 0)["value"] == 2 + assert Enum.at(rows, 1)["key"] == 401 + assert Enum.at(rows, 1)["value"] == 3 + + query = %{:group => true, startkey: 402, endkey: 400, foobar: rand_val.(), startkey_docid: "400", descending: true, inclusive_end: false} + rows = Couch.get(view_url, query: query).body["rows"] + assert length(rows) == 2 + assert Enum.at(rows, 0)["key"] == 402 + assert Enum.at(rows, 0)["value"] == 1 + assert Enum.at(rows, 1)["key"] == 401 + assert Enum.at(rows, 1)["value"] == 3 + + query = %{:group => true, startkey: 402, endkey: 400, foobar: rand_val.(), endkey_docid: "398", descending: true, inclusive_end: true} + rows = Couch.get(view_url, query: query).body["rows"] + assert length(rows) == 3 + assert Enum.at(rows, 0)["key"] == 402 + assert Enum.at(rows, 0)["value"] == 3 + assert Enum.at(rows, 1)["key"] == 401 + assert Enum.at(rows, 1)["value"] == 3 + assert Enum.at(rows, 2)["key"] == 400 + assert Enum.at(rows, 2)["value"] == 3 + + query = %{:group => true, startkey: 402, endkey: 400, foobar: rand_val.(), endkey_docid: "399", descending: true, inclusive_end: true} + rows = Couch.get(view_url, query: query).body["rows"] + assert length(rows) == 3 + assert Enum.at(rows, 0)["key"] == 402 + assert Enum.at(rows, 0)["value"] == 3 + assert Enum.at(rows, 1)["key"] == 401 + assert Enum.at(rows, 1)["value"] == 3 + assert Enum.at(rows, 2)["key"] == 400 + assert Enum.at(rows, 2)["value"] == 2 + + query = %{:group => true, startkey: 402, endkey: 400, foobar: rand_val.(), endkey_docid: "399", descending: true, inclusive_end: false} + rows = Couch.get(view_url, query: query).body["rows"] + assert length(rows) == 3 + assert Enum.at(rows, 0)["key"] == 402 + assert Enum.at(rows, 0)["value"] == 3 + assert Enum.at(rows, 1)["key"] == 401 + assert Enum.at(rows, 1)["value"] == 3 + assert Enum.at(rows, 2)["key"] == 400 + assert Enum.at(rows, 2)["value"] == 1 + + query = %{:group => true, startkey: 402, endkey: 400, foobar: rand_val.(), endkey_docid: "400", descending: true, inclusive_end: false} + rows = Couch.get(view_url, query: query).body["rows"] + assert length(rows) == 2 + assert Enum.at(rows, 0)["key"] == 402 + assert Enum.at(rows, 0)["value"] == 3 + assert Enum.at(rows, 1)["key"] == 401 + assert Enum.at(rows, 1)["value"] == 3 + end +end diff --git a/test/elixir/test/rewrite_test.exs b/test/elixir/test/rewrite_test.exs new file mode 100644 index 000000000..54ff80a64 --- /dev/null +++ b/test/elixir/test/rewrite_test.exs @@ -0,0 +1,339 @@ +defmodule RewriteTest do + use CouchTestCase + + @moduletag :js_engine + + @moduledoc """ + Test CouchDB rewrites + This is a port of the rewrite.js suite + """ + + Enum.each(["test_rewrite_suite_db", "test_rewrite_suite_db%2Fwith_slashes"], fn db_name -> + @tag with_random_db: db_name + @tag config: [ + {"httpd", "authentication_handlers", "{couch_httpd_auth, special_test_authentication_handler}"}, + {"httpd", "WWW-Authenticate", "X-Couch-Test-Auth"} + ] + test "Test basic rewrites on #{db_name}", context do + db_name = context[:db_name] + ddoc = ~S""" +{ + "_id": "_design/test", + "language": "javascript", + "_attachments": { + "foo.txt": { + "content_type":"text/plain", + "data": "VGhpcyBpcyBhIGJhc2U2NCBlbmNvZGVkIHRleHQ=" + } + }, + "rewrites": [ + { + "from": "foo", + "to": "foo.txt" + }, + { + "from": "foo2", + "to": "foo.txt", + "method": "GET" + }, + { + "from": "hello/:id", + "to": "_update/hello/:id", + "method": "PUT" + }, + { + "from": "/welcome", + "to": "_show/welcome" + }, + { + "from": "/welcome/:name", + "to": "_show/welcome", + "query": { + "name": ":name" + } + }, + { + "from": "/welcome2", + "to": "_show/welcome", + "query": { + "name": "user" + } + }, + { + "from": "/welcome3/:name", + "to": "_update/welcome2/:name", + "method": "PUT" + }, + { + "from": "/welcome3/:name", + "to": "_show/welcome2/:name", + "method": "GET" + }, + { + "from": "/welcome4/*", + "to" : "_show/welcome3", + "query": { + "name": "*" + } + }, + { + "from": "/welcome5/*", + "to" : "_show/*", + "query": { + "name": "*" + } + }, + { + "from": "basicView", + "to": "_view/basicView" + }, + { + "from": "simpleForm/basicView", + "to": "_list/simpleForm/basicView" + }, + { + "from": "simpleForm/basicViewFixed", + "to": "_list/simpleForm/basicView", + "query": { + "startkey": 3, + "endkey": 8 + } + }, + { + "from": "simpleForm/basicViewPath/:start/:end", + "to": "_list/simpleForm/basicView", + "query": { + "startkey": ":start", + "endkey": ":end" + }, + "formats": { + "start": "int", + "end": "int" + } + }, + { + "from": "simpleForm/complexView", + "to": "_list/simpleForm/complexView", + "query": { + "key": [1, 2] + } + }, + { + "from": "simpleForm/complexView2", + "to": "_list/simpleForm/complexView", + "query": { + "key": ["test", {}] + } + }, + { + "from": "simpleForm/complexView3", + "to": "_list/simpleForm/complexView", + "query": { + "key": ["test", ["test", "essai"]] + } + }, + { + "from": "simpleForm/complexView4", + "to": "_list/simpleForm/complexView2", + "query": { + "key": {"c": 1} + } + }, + { + "from": "simpleForm/complexView5/:a/:b", + "to": "_list/simpleForm/complexView3", + "query": { + "key": [":a", ":b"] + } + }, + { + "from": "simpleForm/complexView6", + "to": "_list/simpleForm/complexView3", + "query": { + "key": [":a", ":b"] + } + }, + { + "from": "simpleForm/complexView7/:a/:b", + "to": "_view/complexView3", + "query": { + "key": [":a", ":b"], + "include_docs": ":doc" + }, + "format": { + "doc": "bool" + } + + }, + { + "from": "/", + "to": "_view/basicView" + }, + { + "from": "/db/*", + "to": "../../*" + } + ], + "lists": { + "simpleForm": "function(head, req) { + log(\"simpleForm\"); + send(\"<ul>\"); + var row, row_number = 0, prevKey, firstKey = null; + while (row = getRow()) { + row_number += 1; + if (!firstKey) firstKey = row.key; + prevKey = row.key; + send(\"\\n<li>Key: \"+row.key + +\" Value: \"+row.value + +\" LineNo: \"+row_number+\"</li>\"); + } + return \"</ul><p>FirstKey: \"+ firstKey + \" LastKey: \"+ prevKey+\"</p>\"; + }" + }, + "shows": { + "welcome": "(function(doc,req) { + return \"Welcome \" + req.query[\"name\"]; + })", + "welcome2": "(function(doc, req) { + return \"Welcome \" + doc.name; + })", + "welcome3": "(function(doc,req) { + return \"Welcome \" + req.query[\"name\"]; + })" + }, + "updates": { + "hello" : "(function(doc, req) { + if (!doc) { + if (req.id) { + return [{ + _id : req.id + }, \"New World\"] + } + return [null, \"Empty World\"]; + } + doc.world = \"hello\"; + doc.edited_by = req.userCtx; + return [doc, \"hello doc\"]; + })", + "welcome2": "(function(doc, req) { + if (!doc) { + if (req.id) { + return [{ + _id: req.id, + name: req.id + }, \"New World\"] + } + return [null, \"Empty World\"]; + } + return [doc, \"hello doc\"]; + })" + }, + "views" : { + "basicView" : { + "map" : "(function(doc) { + if (doc.integer) { + emit(doc.integer, doc.string); + } + + })" + }, + "complexView": { + "map": "(function(doc) { + if (doc.type == \"complex\") { + emit([doc.a, doc.b], doc.string); + } + })" + }, + "complexView2": { + "map": "(function(doc) { + if (doc.type == \"complex\") { + emit(doc.a, doc.string); + } + })" + }, + "complexView3": { + "map": "(function(doc) { + if (doc.type == \"complex\") { + emit(doc.b, doc.string); + } + })" + } + } +} + """ + ddoc = String.replace(ddoc, ~r/[\r\n]+/, "") + + docs1 = make_docs(0, 9) + docs2 = [ + %{"a" => 1, "b" => 1, "string" => "doc 1", "type" => "complex"}, + %{"a" => 1, "b" => 2, "string" => "doc 2", "type" => "complex"}, + %{"a" => "test", "b" => %{}, "string" => "doc 3", "type" => "complex"}, + %{"a" => "test", "b" => ["test", "essai"], "string" => "doc 4", "type" => "complex"}, + %{"a" => %{"c" => 1}, "b" => "", "string" => "doc 5", "type" => "complex"} + ] + + assert Couch.put("/#{db_name}/_design/test", [body: ddoc]).body["ok"] + assert Couch.post("/#{db_name}/_bulk_docs", [body: %{:docs => docs1}, query: %{w: 3}]).status_code == 201 + assert Couch.post("/#{db_name}/_bulk_docs", [body: %{:docs => docs2}, query: %{w: 3}]).status_code == 201 + + # Test simple rewriting + resp = Couch.get("/#{db_name}/_design/test/_rewrite/foo") + assert resp.body == "This is a base64 encoded text" + assert resp.headers["Content-Type"] == "text/plain" + + resp = Couch.get("/#{db_name}/_design/test/_rewrite/foo2") + assert resp.body == "This is a base64 encoded text" + assert resp.headers["Content-Type"] == "text/plain" + + # Test POST, hello update world + resp = Couch.post("/#{db_name}", [body: %{"word" => "plankton", "name" => "Rusty"}]).body + assert resp["ok"] + doc_id = resp["id"] + assert doc_id + + resp = Couch.put("/#{db_name}/_design/test/_rewrite/hello/#{doc_id}") + assert resp.status_code == 201 + assert resp.body == "hello doc" + assert String.match?(resp.headers["Content-Type"], ~r/charset=utf-8/) + + assert Couch.get("/#{db_name}/#{doc_id}").body["world"] == "hello" + + resp = Couch.get("/#{db_name}/_design/test/_rewrite/welcome?name=user") + assert resp.body == "Welcome user" + + resp = Couch.get("/#{db_name}/_design/test/_rewrite/welcome/user") + assert resp.body == "Welcome user" + + resp = Couch.get("/#{db_name}/_design/test/_rewrite/welcome2") + assert resp.body == "Welcome user" + + resp = Couch.put("/#{db_name}/_design/test/_rewrite/welcome3/test") + assert resp.status_code == 201 + assert resp.body == "New World" + assert String.match?(resp.headers["Content-Type"], ~r/charset=utf-8/) + + resp = Couch.get("/#{db_name}/_design/test/_rewrite/welcome3/test") + assert resp.body == "Welcome test" + + # TODO: port the two "bugged" tests from rewrite.js + + resp = Couch.get("/#{db_name}/_design/test/_rewrite/basicView") + assert resp.status_code == 200 + assert resp.body["total_rows"] == 9 + + resp = Couch.get("/#{db_name}/_design/test/_rewrite") + assert resp.status_code == 200 + assert resp.body["total_rows"] == 9 + + # TODO: port _list function tests and everything below in rewrite.js + # This is currently broken because _list funcitons default to application/json + # response bodies and my attempts to change the content-type from within the + # _list function have not yet succeeded. + # + # Test GET with query params + # resp = Couch.get("/#{db_name}/_design/test/_rewrite/simpleForm/basicView", query: %{startkey: 3, endkey: 8}) + # Logger.error("GOT RESP: #{inspect resp.body}") + # assert resp.status_code == 200 + end + end) +end diff --git a/test/elixir/test/test_helper.exs b/test/elixir/test/test_helper.exs new file mode 100644 index 000000000..cb01fc286 --- /dev/null +++ b/test/elixir/test/test_helper.exs @@ -0,0 +1,135 @@ +ExUnit.configure(exclude: [pending: true]) +ExUnit.start() + +defmodule CouchTestCase do + use ExUnit.Case + + defmacro __using__(_opts) do + quote do + require Logger + use ExUnit.Case + + setup context do + setup_funs = [ + &set_db_context/1, + &set_config_context/1 + ] + context = Enum.reduce(setup_funs, context, fn setup_fun, acc -> + setup_fun.(acc) + end) + {:ok, context} + end + + def set_db_context(context) do + context = case context do + %{:with_db_name => true} -> + Map.put(context, :db_name, random_db_name()) + %{:with_db_name => db_name} when is_binary(db_name) -> + Map.put(context, :db_name, db_name) + %{:with_random_db => db_name} when is_binary(db_name) -> + context + |> Map.put(:db_name, random_db_name(db_name)) + |> Map.put(:with_db, true) + %{:with_db => true} -> + Map.put(context, :db_name, random_db_name()) + %{:with_db => db_name} when is_binary(db_name) -> + Map.put(context, :db_name, db_name) + _ -> + context + end + + if Map.has_key? context, :with_db do + {:ok, _} = create_db(context[:db_name]) + on_exit(fn -> delete_db(context[:db_name]) end) + end + + context + end + + def set_config_context(context) do + if is_list(context[:config]) do + Enum.each(context[:config], fn cfg -> + set_config(cfg) + end) + end + context + end + + def random_db_name do + random_db_name("random-test-db") + end + + def random_db_name(prefix) do + time = :erlang.monotonic_time() + umi = :erlang.unique_integer([:monotonic]) + "#{prefix}-#{time}-#{umi}" + end + + def set_config({section, key, value}) do + resp = Couch.get("/_membership") + existing = Enum.map(resp.body["all_nodes"], fn node -> + url = "/_node/#{node}/_config/#{section}/#{key}" + headers = ["X-Couch-Persist": "false"] + body = :jiffy.encode(value) + resp = Couch.put(url, headers: headers, body: body) + assert resp.status_code == 200 + {node, resp.body} + end) + on_exit(fn -> + Enum.each(existing, fn {node, prev_value} -> + if prev_value != "" do + url = "/_node/#{node}/_config/#{section}/#{key}" + headers = ["X-Couch-Persist": "false"] + body = :jiffy.encode(prev_value) + resp = Couch.put(url, headers: headers, body: body) + assert resp.status_code == 200 + else + url = "/_node/#{node}/_config/#{section}/#{key}" + headers = ["X-Couch-Persist": "false"] + resp = Couch.delete(url, headers: headers) + assert resp.status_code == 200 + end + end) + end) + end + + def create_db(db_name) do + resp = Couch.put("/#{db_name}") + assert resp.status_code == 201 + assert resp.body == %{"ok" => true} + {:ok, resp} + end + + def delete_db(db_name) do + resp = Couch.delete("/#{db_name}") + assert resp.status_code == 200 + assert resp.body == %{"ok" => true} + {:ok, resp} + end + + def create_doc(db_name, body) do + resp = Couch.post("/#{db_name}", [body: body]) + assert resp.status_code == 201 + assert resp.body["ok"] + {:ok, resp} + end + + def sample_doc_foo do + %{ + "_id": "foo", + "bar": "baz" + } + end + + def make_docs(id, count) do + for i <- id..count do + %{ + :_id => Integer.to_string(i), + :integer => i, + :string => Integer.to_string(i) + } + end + end + end + end +end diff --git a/test/elixir/test/uuids_test.exs b/test/elixir/test/uuids_test.exs new file mode 100644 index 000000000..3eda45824 --- /dev/null +++ b/test/elixir/test/uuids_test.exs @@ -0,0 +1,94 @@ +defmodule UUIDsTest do + use CouchTestCase + + @moduledoc """ + Test CouchDB UUIDs API + This is a port of the uuids.js suite + """ + + test "cache busting headers are set" do + resp = Couch.get("/_uuids") + assert resp.status_code == 200 + assert Regex.match?(~r/no-cache/, resp.headers["Cache-Control"]) + assert resp.headers["Pragma"] == "no-cache" + assert String.length(resp.headers["ETag"]) > 0 + end + + test "can return single uuid" do + resp = Couch.get("/_uuids") + assert resp.status_code == 200 + [uuid1] = resp.body["uuids"] + + resp = Couch.get("/_uuids", query: %{:count => 1}) + assert resp.status_code == 200 + [uuid2] = resp.body["uuids"] + + assert uuid1 != uuid2 + end + + test "no duplicates in 1,000 UUIDs" do + resp = Couch.get("/_uuids", query: %{:count => 1000}) + assert resp.status_code == 200 + uuids = resp.body["uuids"] + + assert length(Enum.uniq(uuids)) == length(uuids) + end + + test "Method Not Allowed error on POST" do + resp = Couch.post("/_uuids", query: %{:count => 1000}) + assert resp.status_code == 405 + end + + test "Bad Request error when exceeding max UUID count" do + resp = Couch.get("/_uuids", query: %{:count => 1001}) + assert resp.status_code == 400 + end + + @tag config: [ + {"uuids", "algorithm", "sequential"} + ] + test "sequential uuids are sequential" do + resp = Couch.get("/_uuids", query: %{:count => 1000}) + assert resp.status_code == 200 + Enum.reduce(resp.body["uuids"], fn curr, acc -> + assert String.length(curr) == 32 + assert acc < curr + curr + end) + end + + @tag config: [ + {"uuids", "algorithm", "utc_random"} + ] + test "utc_random uuids are roughly random" do + resp = Couch.get("/_uuids", query: %{:count => 1000}) + assert resp.status_code == 200 + uuids = resp.body["uuids"] + + assert String.length(Enum.at(uuids, 1)) == 32 + + # Assert no collisions + assert length(Enum.uniq(uuids)) == length(uuids) + + # Assert rough ordering of UUIDs + u1 = String.slice(Enum.at(uuids, 1), 0..13) + u2 = String.slice(Enum.at(uuids, -1), 0..13) + assert u1 < u2 + end + + @utc_id_suffix "frog" + @tag config: [ + {"uuids", "algorithm", "utc_id"}, + {"uuids", "utc_id_suffix", @utc_id_suffix} + ] + test "utc_id uuids are correct" do + resp = Couch.get("/_uuids", query: %{:count => 10}) + assert resp.status_code == 200 + Enum.reduce(resp.body["uuids"], fn curr, acc -> + assert String.length(curr) == 14 + String.length(@utc_id_suffix) + assert String.slice(curr, 14..-1) == @utc_id_suffix + assert curr > acc + curr + end) + end +end diff --git a/test/elixir/test/view_collation_test.exs b/test/elixir/test/view_collation_test.exs new file mode 100644 index 000000000..10aec2f22 --- /dev/null +++ b/test/elixir/test/view_collation_test.exs @@ -0,0 +1,133 @@ +defmodule ViewCollationTest do + use CouchTestCase + + @moduledoc """ + Test CouchDB View Collation Behavior + This is a port of the view_collation.js suite + """ + + @values [ + # Special values sort before all other types + :null, + :false, + :true, + + # Then numbers + 1, + 2, + 3.0, + 4, + + # Then text, case sensitive + "a", + "A", + "aa", + "b", + "B", + "ba", + "bb", + + # Then arrays, compared element by element until different. + # Longer arrays sort after their prefixes + ["a"], + ["b"], + ["b", "c"], + ["b", "c", "a"], + ["b", "d"], + ["b", "d", "e"], + + # Then objects, compared each key value in the list until different. + # Larger objects sort after their subset objects + {[a: 1]}, + {[a: 2]}, + {[b: 1]}, + {[b: 2]}, + # Member order does matter for collation + {[b: 2, a: 1]}, + {[b: 2, c: 2]} + ] + + setup_all do + db_name = random_db_name() + {:ok, _} = create_db(db_name) + on_exit(fn -> delete_db(db_name) end) + + {docs, _} = Enum.flat_map_reduce(@values, 1, fn value, idx -> + doc = %{:_id => Integer.to_string(idx), :foo => value} + {[doc], idx + 1} + end) + resp = Couch.post("/#{db_name}/_bulk_docs", body: %{:docs => docs}) + Enum.each(resp.body, &(assert &1["ok"])) + + map_fun = "function(doc) { emit(doc.foo, null); }" + map_doc = %{:views => %{:foo => %{:map => map_fun}}} + resp = Couch.put("/#{db_name}/_design/foo", body: map_doc) + assert resp.body["ok"] + + {:ok, [db_name: db_name]} + end + + test "ascending collation order", context do + resp = Couch.get(url(context)) + pairs = Enum.zip(resp.body["rows"], @values) + Enum.each(pairs, fn {row, value} -> + assert row["key"] == convert(value) + end) + end + + test "descending collation order", context do + resp = Couch.get(url(context), query: %{"descending" => "true"}) + pairs = Enum.zip(resp.body["rows"], Enum.reverse(@values)) + Enum.each(pairs, fn {row, value} -> + assert row["key"] == convert(value) + end) + end + + test "key query option", context do + Enum.each(@values, fn value -> + resp = Couch.get(url(context), query: %{:key => :jiffy.encode(value)}) + assert length(resp.body["rows"]) == 1 + assert Enum.at(resp.body["rows"], 0)["key"] == convert(value) + end) + end + + test "inclusive_end=true", context do + query = %{:endkey => :jiffy.encode("b"), :inclusive_end => true} + resp = Couch.get(url(context), query: query) + assert Enum.at(resp.body["rows"], -1)["key"] == "b" + + query = Map.put(query, :descending, true) + resp = Couch.get(url(context), query: query) + assert Enum.at(resp.body["rows"], -1)["key"] == "b" + end + + test "inclusive_end=false", context do + query = %{:endkey => :jiffy.encode("b"), :inclusive_end => false} + resp = Couch.get(url(context), query: query) + assert Enum.at(resp.body["rows"], -1)["key"] == "aa" + + query = Map.put(query, :descending, true) + resp = Couch.get(url(context), query: query) + assert Enum.at(resp.body["rows"], -1)["key"] == "B" + + query = %{ + :endkey => :jiffy.encode("b"), + :endkey_docid => 11, + :inclusive_end => false + } + resp = Couch.get(url(context), query: query) + assert Enum.at(resp.body["rows"], -1)["key"] == "aa" + + query = Map.put(query, :endkey_docid, 12) + resp = Couch.get(url(context), query: query) + assert Enum.at(resp.body["rows"], -1)["key"] == "b" + end + + def url(context) do + "/#{context[:db_name]}/_design/foo/_view/foo" + end + + def convert(value) do + :jiffy.decode(:jiffy.encode(value), [:return_maps]) + end +end
\ No newline at end of file |
