You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@couchdb.apache.org by wo...@apache.org on 2020/10/06 18:42:43 UTC
[couchdb] 01/01: Remove JS tests + support for harness
This is an automated email from the ASF dual-hosted git repository.
wohali pushed a commit to branch remove-js-harness
in repository https://gitbox.apache.org/repos/asf/couchdb.git
commit e955a49daa3732afb4eb63737b940c464bbcc1ca
Author: Joan Touzet <jo...@atypical.net>
AuthorDate: Tue Oct 6 14:35:33 2020 -0400
Remove JS tests + support for harness
---
INSTALL.Unix.md | 27 +-
INSTALL.Windows.md | 4 +-
Makefile.win | 2 +-
build-aux/Jenkinsfile.full | 8 +-
build-aux/Jenkinsfile.pr | 4 +-
configure | 12 +-
configure.ps1 | 4 -
src/couch/priv/couch_js/1.8.5/help.h | 7 -
src/couch/priv/couch_js/1.8.5/http.c | 701 ------------------
src/couch/priv/couch_js/1.8.5/http.h | 27 -
src/couch/priv/couch_js/1.8.5/main.c | 182 -----
src/couch/priv/couch_js/1.8.5/util.c | 2 -
src/couch/priv/couch_js/1.8.5/util.h | 2 -
src/couch/priv/couch_js/60/help.h | 7 -
src/couch/priv/couch_js/60/http.cpp | 649 ----------------
src/couch/priv/couch_js/60/http.h | 27 -
src/couch/priv/couch_js/60/main.cpp | 193 -----
src/couch/priv/couch_js/60/util.cpp | 10 -
src/couch/priv/couch_js/60/util.h | 4 -
src/couch/priv/couch_js/68/help.h | 5 -
src/couch/priv/couch_js/68/http.cpp | 650 -----------------
src/couch/priv/couch_js/68/http.h | 27 -
src/couch/priv/couch_js/68/main.cpp | 198 -----
src/couch/priv/couch_js/68/util.cpp | 10 -
src/couch/rebar.config.script | 31 +-
test/javascript/cli_runner.js | 63 --
test/javascript/couch.js | 557 --------------
test/javascript/couch_http.js | 73 --
test/javascript/couch_test_runner.js | 489 -------------
test/javascript/couchdb.uri | 1 -
test/javascript/json2.js | 482 ------------
test/javascript/replicator_db_inc.js | 97 ---
test/javascript/run | 284 -------
test/javascript/sha1.js | 202 -----
test/javascript/test_setup.js | 127 ----
.../tests-cluster/with-quorum/attachments.js | 37 -
.../with-quorum/attachments_delete.js | 33 -
.../attachments_delete_overridden_quorum.js | 38 -
.../with-quorum/attachments_overridden_quorum.js | 42 --
.../tests-cluster/with-quorum/db_creation.js | 28 -
.../with-quorum/db_creation_overridden_quorum.js | 30 -
.../tests-cluster/with-quorum/db_deletion.js | 31 -
.../with-quorum/db_deletion_overridden_quorum.js | 24 -
.../tests-cluster/with-quorum/doc_bulk.js | 26 -
.../with-quorum/doc_bulk_overridden_quorum.js | 26 -
.../tests-cluster/with-quorum/doc_copy.js | 28 -
.../with-quorum/doc_copy_overridden_quorum.js | 32 -
.../tests-cluster/with-quorum/doc_crud.js | 32 -
.../with-quorum/doc_crud_overridden_quorum.js | 32 -
.../tests-cluster/without-quorum/attachments.js | 40 -
.../without-quorum/attachments_delete.js | 39 -
.../attachments_delete_overridden_quorum.js | 38 -
.../attachments_overridden_quorum.js | 43 --
.../tests-cluster/without-quorum/db_creation.js | 28 -
.../db_creation_overridden_quorum.js | 32 -
.../tests-cluster/without-quorum/db_deletion.js | 31 -
.../db_deletion_overridden_quorum.js | 26 -
.../tests-cluster/without-quorum/doc_bulk.js | 29 -
.../without-quorum/doc_bulk_overridden_quorum.js | 29 -
.../tests-cluster/without-quorum/doc_copy.js | 31 -
.../without-quorum/doc_copy_overridden_quorum.js | 35 -
.../tests-cluster/without-quorum/doc_crud.js | 36 -
.../without-quorum/doc_crud_overridden_quorum.js | 35 -
test/javascript/tests/all_docs.js | 167 -----
test/javascript/tests/attachment_names.js | 99 ---
test/javascript/tests/attachment_paths.js | 156 ----
test/javascript/tests/attachment_ranges.js | 164 -----
test/javascript/tests/attachment_views.js | 145 ----
test/javascript/tests/attachments.js | 358 ---------
test/javascript/tests/attachments_multipart.js | 426 -----------
test/javascript/tests/auth_cache.js | 274 -------
test/javascript/tests/basics.js | 302 --------
test/javascript/tests/batch_save.js | 52 --
test/javascript/tests/bulk_docs.js | 153 ----
test/javascript/tests/changes.js | 812 ---------------------
test/javascript/tests/coffee.js | 72 --
test/javascript/tests/compact.js | 71 --
test/javascript/tests/config.js | 222 ------
test/javascript/tests/conflicts.js | 123 ----
test/javascript/tests/cookie_auth.js | 303 --------
test/javascript/tests/copy_doc.js | 70 --
test/javascript/tests/design_docs.js | 447 ------------
test/javascript/tests/design_docs_query.js | 156 ----
test/javascript/tests/design_options.js | 78 --
test/javascript/tests/design_paths.js | 74 --
test/javascript/tests/erlang_views.js | 137 ----
test/javascript/tests/etags_head.js | 87 ---
test/javascript/tests/etags_views.js | 224 ------
test/javascript/tests/form_submit.js | 31 -
test/javascript/tests/http.js | 82 ---
test/javascript/tests/invalid_docids.js | 82 ---
test/javascript/tests/jsonp.js | 87 ---
test/javascript/tests/large_docs.js | 38 -
test/javascript/tests/list_views.js | 502 -------------
test/javascript/tests/lorem.txt | 103 ---
test/javascript/tests/lorem_b64.txt | 1 -
test/javascript/tests/lots_of_docs.js | 60 --
test/javascript/tests/method_override.js | 45 --
test/javascript/tests/multiple_rows.js | 85 ---
test/javascript/tests/proxyauth.js | 136 ----
test/javascript/tests/purge.js | 140 ----
test/javascript/tests/reader_acl.js | 222 ------
test/javascript/tests/recreate_doc.js | 157 ----
test/javascript/tests/reduce.js | 423 -----------
test/javascript/tests/reduce_builtin.js | 206 ------
test/javascript/tests/reduce_false.js | 50 --
test/javascript/tests/reduce_false_temp.js | 41 --
test/javascript/tests/replicator_db_bad_rep_id.js | 104 ---
test/javascript/tests/replicator_db_by_doc_id.js | 129 ----
.../tests/replicator_db_compact_rep_db.js | 119 ---
test/javascript/tests/replicator_db_continuous.js | 137 ----
.../tests/replicator_db_credential_delegation.js | 149 ----
.../tests/replicator_db_field_validation.js | 178 -----
test/javascript/tests/replicator_db_filtered.js | 105 ---
test/javascript/tests/replicator_db_identical.js | 87 ---
.../tests/replicator_db_identical_continuous.js | 139 ----
.../tests/replicator_db_invalid_filter.js | 119 ---
test/javascript/tests/replicator_db_security.js | 371 ----------
test/javascript/tests/replicator_db_simple.js | 114 ---
test/javascript/tests/replicator_db_successive.js | 127 ----
test/javascript/tests/replicator_db_survives.js | 126 ----
test/javascript/tests/replicator_db_swap_rep_db.js | 170 -----
.../tests/replicator_db_update_security.js | 92 ---
test/javascript/tests/replicator_db_user_ctx.js | 272 -------
test/javascript/tests/replicator_db_write_auth.js | 102 ---
test/javascript/tests/rev_stemming.js | 124 ----
test/javascript/tests/rewrite.js | 513 -------------
test/javascript/tests/rewrite_js.js | 351 ---------
test/javascript/tests/security_validation.js | 330 ---------
test/javascript/tests/show_documents.js | 376 ----------
test/javascript/tests/stats.js | 358 ---------
test/javascript/tests/update_documents.js | 236 ------
test/javascript/tests/users_db.js | 222 ------
test/javascript/tests/users_db_security.js | 418 -----------
test/javascript/tests/utf8.js | 46 --
test/javascript/tests/uuids.js | 148 ----
test/javascript/tests/view_collation.js | 121 ---
test/javascript/tests/view_collation_raw.js | 134 ----
test/javascript/tests/view_compaction.js | 112 ---
test/javascript/tests/view_conflicts.js | 57 --
test/javascript/tests/view_errors.js | 211 ------
test/javascript/tests/view_include_docs.js | 196 -----
test/javascript/tests/view_multi_key_all_docs.js | 99 ---
test/javascript/tests/view_multi_key_design.js | 235 ------
test/javascript/tests/view_multi_key_temp.js | 44 --
test/javascript/tests/view_offsets.js | 118 ---
test/javascript/tests/view_pagination.js | 151 ----
test/javascript/tests/view_sandboxing.js | 169 -----
test/javascript/tests/view_update_seq.js | 119 ---
149 files changed, 26 insertions(+), 21244 deletions(-)
diff --git a/INSTALL.Unix.md b/INSTALL.Unix.md
index cb45e9a..0c82628 100644
--- a/INSTALL.Unix.md
+++ b/INSTALL.Unix.md
@@ -45,8 +45,6 @@ You should have the following installed:
* https://archive.mozilla.org/pub/firefox/releases/60.9.0esr/source/ (src/js)
* GNU Make (http://www.gnu.org/software/make/)
* GNU Compiler Collection (http://gcc.gnu.org/)
- * libcurl (http://curl.haxx.se/libcurl/)
- * help2man (http://www.gnu.org/s/help2man/)
* Python (>=2.7) (http://python.org/)
To build Fauxton, you should have the following installed:
@@ -56,12 +54,10 @@ To build Fauxton, you should have the following installed:
To build the documentation, you should have the following installed:
* Python Sphinx (>=1.5) (http://pypi.python.org/pypi/Sphinx)
-It is recommended that you install Erlang OTP R16B03-1 or above where
-possible. You will only need libcurl if you plan to run the
-JavaScript test suite. And help2man is only need if you plan on
-installing the CouchDB man pages. Python and Sphinx are only required
-for building the online documentation. Documentation build can be disabled
-by adding the `--disable-docs` flag to the `configure` script.
+It is recommended that you install Erlang OTP R16B03-1 or above where possible.
+Python and Sphinx are only required for building the online documentation.
+Documentation build can be disabled by adding the `--disable-docs` flag to the
+`configure` script.
### Debian-based Systems
@@ -69,7 +65,9 @@ You can install the dependencies by running:
sudo apt-get --no-install-recommends -y install \
build-essential pkg-config erlang erlang-reltool \
- libicu-dev libmozjs185-dev libcurl4-openssl-dev
+ libicu-dev libmozjs-60-dev
+
+Your distribution may have libmozjs-68-dev instead of 60. Both are supported.
You can install the Node.JS dependencies via [NodeSource](https://github.com/nodesource/distributions#installation-instructions).
@@ -89,9 +87,8 @@ packages.
You can install the dependencies by running:
sudo yum install autoconf autoconf-archive automake \
- curl-devel erlang-asn1 erlang-erts erlang-eunit \
- erlang-xmerl help2man \
- js-devel-1.8.5 libicu-devel libtool perl-Test-Harness
+ erlang-asn1 erlang-erts erlang-eunit erlang-xmerl \
+ libmozjs-60-dev libicu-devel libtool perl-Test-Harness
You can install the Node.JS dependencies via [NodeSource](https://github.com/nodesource/distributions#rpminstall).
@@ -111,7 +108,7 @@ the Command Line Tools:
You can then install the other dependencies by running:
brew install autoconf autoconf-archive automake libtool \
- erlang icu4c spidermonkey curl pkg-config
+ erlang icu4c spidermonkey pkg-config
You can install the Node.JS dependencies via the
[official Macintosh installer](https://nodejs.org/en/download/).
@@ -143,8 +140,8 @@ You can install this by running:
You can install the remaining dependencies by running:
- pkg install help2man openssl icu curl git bash \
- autoconf automake libtool node spidermonkey185 \
+ pkg install openssl icu git bash \
+ autoconf automake libtool node spidermonkey60 \
erlang node8 npm-node8 lang/python py27-sphinx py27-pip
pip install --upgrade sphinx_rtd_theme nose requests hypothesis
diff --git a/INSTALL.Windows.md b/INSTALL.Windows.md
index 9ba84b7..6cf148c 100644
--- a/INSTALL.Windows.md
+++ b/INSTALL.Windows.md
@@ -13,9 +13,9 @@ Build & Test
Once all dependencies are built and installed per the documentation in
couchdb-glazier, these commands will configure and build CouchDB:
- powershell -ExecutionPolicy Bypass .\configure.ps1 -WithCurl
+ powershell -ExecutionPolicy Bypass .\configure.ps1
make -f Makefile.win check
This will build couchdb, as well as run the eunit and javascript tests.
-As of CouchDB 2.0 RC1, all eunit and javascript tests should pass.
+As of CouchDB 2.0 RC1, all tests should pass.
diff --git a/Makefile.win b/Makefile.win
index edfc1bf..5278722 100644
--- a/Makefile.win
+++ b/Makefile.win
@@ -428,7 +428,7 @@ devclean:
config.erl:
@echo Apache CouchDB has not been configured.
@echo Try "powershell -ExecutionPolicy Bypass .\configure.ps1 -?" for help.
- @echo You probably want "powershell -ExecutionPolicy Bypass .\configure.ps1 -WithCurl".
+ @echo You probably want "powershell -ExecutionPolicy Bypass .\configure.ps1".
@echo.
@false
diff --git a/build-aux/Jenkinsfile.full b/build-aux/Jenkinsfile.full
index d7a7657..5f99da6 100644
--- a/build-aux/Jenkinsfile.full
+++ b/build-aux/Jenkinsfile.full
@@ -21,7 +21,7 @@ mkdir build
cd build
tar -xf ${WORKSPACE}/apache-couchdb-*.tar.gz
cd apache-couchdb-*
-./configure --with-curl --spidermonkey-version ${sm_ver}
+./configure --spidermonkey-version ${sm_ver}
make check || (make build-report && false)
'''
@@ -93,7 +93,7 @@ pipeline {
sh '''
set
rm -rf apache-couchdb-*
- ./configure --with-curl
+ ./configure
make dist
chmod -R a+w * .
'''
@@ -140,7 +140,7 @@ pipeline {
cd build
tar -xf $WORKSPACE/apache-couchdb-*.tar.gz
cd apache-couchdb-*
- ./configure --with-curl
+ ./configure
gmake check || (build-aux/logfile-uploader.py && false)
# No package build for FreeBSD at this time
@@ -177,7 +177,7 @@ pipeline {
cd build
tar -xzf $WORKSPACE/apache-couchdb-*.tar.gz
cd apache-couchdb-*
- ./configure --with-curl --spidermonkey-version 60
+ ./configure --spidermonkey-version 60
make check || (build-aux/logfile-uploader.py && false)
# No package build for macOS at this time
diff --git a/build-aux/Jenkinsfile.pr b/build-aux/Jenkinsfile.pr
index ca548ff..114dfd8 100644
--- a/build-aux/Jenkinsfile.pr
+++ b/build-aux/Jenkinsfile.pr
@@ -21,7 +21,7 @@ cd build
tar -xf ${WORKSPACE}/apache-couchdb-*.tar.gz
cd apache-couchdb-*
. /usr/local/kerl/${KERL_VER}/activate
-./configure --with-curl
+./configure
make check || (make build-report && false)
'''
@@ -80,7 +80,7 @@ pipeline {
set
rm -rf apache-couchdb-*
. /usr/local/kerl/${LOW_ERLANG_VER}/activate
- ./configure --with-curl
+ ./configure
make dist
chmod -R a+w * .
'''
diff --git a/configure b/configure
index b91b18d..0793d68 100755
--- a/configure
+++ b/configure
@@ -22,7 +22,6 @@ basename=`basename $0`
PACKAGE_AUTHOR_NAME="The Apache Software Foundation"
# TEST=0
-WITH_CURL="false"
WITH_PROPER="true"
WITH_FAUXTON=1
WITH_DOCS=1
@@ -47,11 +46,10 @@ Options:
-h | --help display a short help message and exit
-u | --user USER set the username to run as (defaults to $COUCHDB_USER)
- -c | --with-curl request that couchjs is linked to cURL (default false)
--disable-fauxton do not build Fauxton
--disable-docs do not build any documentation or manpages
--erlang-md5 use erlang for md5 hash operations
- --dev alias for --with-curl --disable-docs --disable-fauxton
+ --dev alias for --disable-docs --disable-fauxton
--spidermonkey-version VSN specify the version of SpiderMonkey to use (defaults to $SM_VSN)
--skip-deps do not update erlang dependencies
--rebar=PATH use rebar by specified path (version >=2.6.0 && <3.0 required)
@@ -66,12 +64,6 @@ parse_opts() {
exit
;;
- --with-curl|-c)
- WITH_CURL="true"
- shift
- continue
- ;;
-
--without-proper)
WITH_PROPER="false"
shift
@@ -117,7 +109,6 @@ parse_opts() {
--dev)
WITH_DOCS=0
WITH_FAUXTON=0
- WITH_CURL="true"
shift
continue
;;
@@ -256,7 +247,6 @@ spidermonkey_version = $SM_VSN
EOF
cat > $rootdir/config.erl << EOF
-{with_curl, $WITH_CURL}.
{with_proper, $WITH_PROPER}.
{erlang_md5, $ERLANG_MD5}.
{aegis_key_manager, "$AEGIS_KEY_MANAGER"}.
diff --git a/configure.ps1 b/configure.ps1
index 65f8517..8935c3c 100644
--- a/configure.ps1
+++ b/configure.ps1
@@ -5,7 +5,6 @@
This command is responsible for generating the build
system for Apache CouchDB.
- -WithCurl request that couchjs is linked to cURL (default false)
-DisableFauxton request build process skip building Fauxton (default false)
-DisableDocs request build process skip building documentation (default false)
-SkipDeps do not update Erlang dependencies (default false)
@@ -42,7 +41,6 @@
Param(
[switch]$Test = $false,
- [switch]$WithCurl = $false, # request that couchjs is linked to cURL (default false)
[switch]$DisableFauxton = $false, # do not build Fauxton
[switch]$DisableDocs = $false, # do not build any documentation or manpages
[switch]$SkipDeps = $false, # do not update erlang dependencies
@@ -183,9 +181,7 @@ spidermonkey_version = $SpiderMonkeyVersion
"@
$InstallMk | Out-File "$rootdir\install.mk" -encoding ascii
-$lowercurl = "$WithCurl".ToLower()
$ConfigERL = @"
-{with_curl, $lowercurl}.
{spidermonkey_version, "$SpiderMonkeyVersion"}.
"@
$ConfigERL | Out-File "$rootdir\config.erl" -encoding ascii
diff --git a/src/couch/priv/couch_js/1.8.5/help.h b/src/couch/priv/couch_js/1.8.5/help.h
index 335935e..3a19901 100644
--- a/src/couch/priv/couch_js/1.8.5/help.h
+++ b/src/couch/priv/couch_js/1.8.5/help.h
@@ -46,15 +46,9 @@ static const char USAGE_TEMPLATE[] =
"\n"
" -h display a short help message and exit\n"
" -V display version information and exit\n"
- " -H enable %s cURL bindings (only avaiable\n"
- " if package was built with cURL available)\n"
- " -T enable test suite specific functions (these\n"
- " should not be enabled for production systems)\n"
" -S SIZE specify that the runtime should allow at\n"
" most SIZE bytes of memory to be allocated\n"
" default is 64 MiB\n"
- " -u FILE path to a .uri file containing the address\n"
- " (or addresses) of one or more servers\n"
" --eval Enable runtime code evaluation (dangerous!)\n"
"\n"
"Report bugs at <%s>.\n";
@@ -78,7 +72,6 @@ static const char USAGE_TEMPLATE[] =
basename, \
basename, \
PACKAGE_NAME, \
- basename, \
PACKAGE_BUGREPORT)
#define DISPLAY_USAGE couch_usage(BASENAME)
diff --git a/src/couch/priv/couch_js/1.8.5/http.c b/src/couch/priv/couch_js/1.8.5/http.c
deleted file mode 100644
index c4b3896..0000000
--- a/src/couch/priv/couch_js/1.8.5/http.c
+++ /dev/null
@@ -1,701 +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.
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <jsapi.h>
-#include "config.h"
-#include "utf8.h"
-#include "util.h"
-
-// Soft dependency on cURL bindings because they're
-// only used when running the JS tests from the
-// command line which is rare.
-#ifndef HAVE_CURL
-
-void
-http_check_enabled()
-{
- fprintf(stderr, "HTTP API was disabled at compile time.\n");
- exit(3);
-}
-
-
-JSBool
-http_ctor(JSContext* cx, JSObject* req)
-{
- return JS_FALSE;
-}
-
-
-JSBool
-http_dtor(JSContext* cx, JSObject* req)
-{
- return JS_FALSE;
-}
-
-
-JSBool
-http_open(JSContext* cx, JSObject* req, jsval mth, jsval url, jsval snc)
-{
- return JS_FALSE;
-}
-
-
-JSBool
-http_set_hdr(JSContext* cx, JSObject* req, jsval name, jsval val)
-{
- return JS_FALSE;
-}
-
-
-JSBool
-http_send(JSContext* cx, JSObject* req, jsval body)
-{
- return JS_FALSE;
-}
-
-
-int
-http_status(JSContext* cx, JSObject* req, jsval body)
-{
- return -1;
-}
-
-JSBool
-http_uri(JSContext* cx, JSObject* req, couch_args* args, jsval* uri_val)
-{
- return JS_FALSE;
-}
-
-
-#else
-#include <curl/curl.h>
-#ifndef XP_WIN
-#include <unistd.h>
-#endif
-
-
-void
-http_check_enabled()
-{
- return;
-}
-
-
-// Map some of the string function names to things which exist on Windows
-#ifdef XP_WIN
-#define strcasecmp _strcmpi
-#define strncasecmp _strnicmp
-#define snprintf _snprintf
-#endif
-
-
-typedef struct curl_slist CurlHeaders;
-
-
-typedef struct {
- int method;
- char* url;
- CurlHeaders* req_headers;
- jsint last_status;
-} HTTPData;
-
-
-char* METHODS[] = {"GET", "HEAD", "POST", "PUT", "DELETE", "COPY", "OPTIONS", NULL};
-
-
-#define GET 0
-#define HEAD 1
-#define POST 2
-#define PUT 3
-#define DELETE 4
-#define COPY 5
-#define OPTIONS 6
-
-
-static JSBool
-go(JSContext* cx, JSObject* obj, HTTPData* http, char* body, size_t blen);
-
-
-static JSString*
-str_from_binary(JSContext* cx, char* data, size_t length);
-
-
-JSBool
-http_ctor(JSContext* cx, JSObject* req)
-{
- HTTPData* http = NULL;
- JSBool ret = JS_FALSE;
-
- http = (HTTPData*) malloc(sizeof(HTTPData));
- if(!http)
- {
- JS_ReportError(cx, "Failed to create CouchHTTP instance.");
- goto error;
- }
-
- http->method = -1;
- http->url = NULL;
- http->req_headers = NULL;
- http->last_status = -1;
-
- if(!JS_SetPrivate(cx, req, http))
- {
- JS_ReportError(cx, "Failed to set private CouchHTTP data.");
- goto error;
- }
-
- ret = JS_TRUE;
- goto success;
-
-error:
- if(http) free(http);
-
-success:
- return ret;
-}
-
-
-void
-http_dtor(JSContext* cx, JSObject* obj)
-{
- HTTPData* http = (HTTPData*) JS_GetPrivate(cx, obj);
- if(http) {
- if(http->url) free(http->url);
- if(http->req_headers) curl_slist_free_all(http->req_headers);
- free(http);
- }
-}
-
-
-JSBool
-http_open(JSContext* cx, JSObject* req, jsval mth, jsval url, jsval snc)
-{
- HTTPData* http = (HTTPData*) JS_GetPrivate(cx, req);
- char* method = NULL;
- int methid;
- JSBool ret = JS_FALSE;
-
- if(!http) {
- JS_ReportError(cx, "Invalid CouchHTTP instance.");
- goto done;
- }
-
- if(JSVAL_IS_VOID(mth)) {
- JS_ReportError(cx, "You must specify a method.");
- goto done;
- }
-
- method = enc_string(cx, mth, NULL);
- if(!method) {
- JS_ReportError(cx, "Failed to encode method.");
- goto done;
- }
-
- for(methid = 0; METHODS[methid] != NULL; methid++) {
- if(strcasecmp(METHODS[methid], method) == 0) break;
- }
-
- if(methid > OPTIONS) {
- JS_ReportError(cx, "Invalid method specified.");
- goto done;
- }
-
- http->method = methid;
-
- if(JSVAL_IS_VOID(url)) {
- JS_ReportError(cx, "You must specify a URL.");
- goto done;
- }
-
- if(http->url != NULL) {
- free(http->url);
- http->url = NULL;
- }
-
- http->url = enc_string(cx, url, NULL);
- if(http->url == NULL) {
- JS_ReportError(cx, "Failed to encode URL.");
- goto done;
- }
-
- if(JSVAL_IS_BOOLEAN(snc) && JSVAL_TO_BOOLEAN(snc)) {
- JS_ReportError(cx, "Synchronous flag must be false.");
- goto done;
- }
-
- if(http->req_headers) {
- curl_slist_free_all(http->req_headers);
- http->req_headers = NULL;
- }
-
- // Disable Expect: 100-continue
- http->req_headers = curl_slist_append(http->req_headers, "Expect:");
-
- ret = JS_TRUE;
-
-done:
- if(method) free(method);
- return ret;
-}
-
-
-JSBool
-http_set_hdr(JSContext* cx, JSObject* req, jsval name, jsval val)
-{
- HTTPData* http = (HTTPData*) JS_GetPrivate(cx, req);
- char* keystr = NULL;
- char* valstr = NULL;
- char* hdrbuf = NULL;
- size_t hdrlen = -1;
- JSBool ret = JS_FALSE;
-
- if(!http) {
- JS_ReportError(cx, "Invalid CouchHTTP instance.");
- goto done;
- }
-
- if(JSVAL_IS_VOID(name))
- {
- JS_ReportError(cx, "You must speciy a header name.");
- goto done;
- }
-
- keystr = enc_string(cx, name, NULL);
- if(!keystr)
- {
- JS_ReportError(cx, "Failed to encode header name.");
- goto done;
- }
-
- if(JSVAL_IS_VOID(val))
- {
- JS_ReportError(cx, "You must specify a header value.");
- goto done;
- }
-
- valstr = enc_string(cx, val, NULL);
- if(!valstr)
- {
- JS_ReportError(cx, "Failed to encode header value.");
- goto done;
- }
-
- hdrlen = strlen(keystr) + strlen(valstr) + 3;
- hdrbuf = (char*) malloc(hdrlen * sizeof(char));
- if(!hdrbuf) {
- JS_ReportError(cx, "Failed to allocate header buffer.");
- goto done;
- }
-
- snprintf(hdrbuf, hdrlen, "%s: %s", keystr, valstr);
- http->req_headers = curl_slist_append(http->req_headers, hdrbuf);
-
- ret = JS_TRUE;
-
-done:
- if(keystr) free(keystr);
- if(valstr) free(valstr);
- if(hdrbuf) free(hdrbuf);
- return ret;
-}
-
-JSBool
-http_send(JSContext* cx, JSObject* req, jsval body)
-{
- HTTPData* http = (HTTPData*) JS_GetPrivate(cx, req);
- char* bodystr = NULL;
- size_t bodylen = 0;
- JSBool ret = JS_FALSE;
-
- if(!http) {
- JS_ReportError(cx, "Invalid CouchHTTP instance.");
- goto done;
- }
-
- if(!JSVAL_IS_VOID(body)) {
- bodystr = enc_string(cx, body, &bodylen);
- if(!bodystr) {
- JS_ReportError(cx, "Failed to encode body.");
- goto done;
- }
- }
-
- ret = go(cx, req, http, bodystr, bodylen);
-
-done:
- if(bodystr) free(bodystr);
- return ret;
-}
-
-int
-http_status(JSContext* cx, JSObject* req)
-{
- HTTPData* http = (HTTPData*) JS_GetPrivate(cx, req);
-
- if(!http) {
- JS_ReportError(cx, "Invalid CouchHTTP instance.");
- return JS_FALSE;
- }
-
- return http->last_status;
-}
-
-JSBool
-http_uri(JSContext* cx, JSObject* req, couch_args* args, jsval* uri_val)
-{
- FILE* uri_fp = NULL;
- JSString* uri_str;
-
- // Default is http://localhost:15986/ when no uri file is specified
- if (!args->uri_file) {
- uri_str = JS_InternString(cx, "http://localhost:15986/");
- *uri_val = STRING_TO_JSVAL(uri_str);
- JS_SetReservedSlot(cx, req, 0, *uri_val);
- return JS_TRUE;
- }
-
- // Else check to see if the base url is cached in a reserved slot
- if (JS_GetReservedSlot(cx, req, 0, uri_val) && !JSVAL_IS_VOID(*uri_val)) {
- return JS_TRUE;
- }
-
- // Read the first line of the couch.uri file.
- if(!((uri_fp = fopen(args->uri_file, "r")) &&
- (uri_str = couch_readline(cx, uri_fp)))) {
- JS_ReportError(cx, "Failed to read couch.uri file.");
- goto error;
- }
-
- fclose(uri_fp);
- *uri_val = STRING_TO_JSVAL(uri_str);
- JS_SetReservedSlot(cx, req, 0, *uri_val);
- return JS_TRUE;
-
-error:
- if(uri_fp) fclose(uri_fp);
- return JS_FALSE;
-}
-
-
-// Curl Helpers
-
-typedef struct {
- HTTPData* http;
- JSContext* cx;
- JSObject* resp_headers;
- char* sendbuf;
- size_t sendlen;
- size_t sent;
- int sent_once;
- char* recvbuf;
- size_t recvlen;
- size_t read;
-} CurlState;
-
-/*
- * I really hate doing this but this doesn't have to be
- * uber awesome, it just has to work.
- */
-CURL* HTTP_HANDLE = NULL;
-char ERRBUF[CURL_ERROR_SIZE];
-
-static size_t send_body(void *ptr, size_t size, size_t nmem, void *data);
-static int seek_body(void *ptr, curl_off_t offset, int origin);
-static size_t recv_body(void *ptr, size_t size, size_t nmem, void *data);
-static size_t recv_header(void *ptr, size_t size, size_t nmem, void *data);
-
-static JSBool
-go(JSContext* cx, JSObject* obj, HTTPData* http, char* body, size_t bodylen)
-{
- CurlState state;
- char* referer;
- JSString* jsbody;
- JSBool ret = JS_FALSE;
- jsval tmp;
-
- state.cx = cx;
- state.http = http;
-
- state.sendbuf = body;
- state.sendlen = bodylen;
- state.sent = 0;
- state.sent_once = 0;
-
- state.recvbuf = NULL;
- state.recvlen = 0;
- state.read = 0;
-
- if(HTTP_HANDLE == NULL) {
- HTTP_HANDLE = curl_easy_init();
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_READFUNCTION, send_body);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_SEEKFUNCTION,
- (curl_seek_callback) seek_body);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_HEADERFUNCTION, recv_header);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_WRITEFUNCTION, recv_body);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_NOPROGRESS, 1);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_ERRORBUFFER, ERRBUF);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_COOKIEFILE, "");
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_USERAGENT,
- "CouchHTTP Client - Relax");
- }
-
- if(!HTTP_HANDLE) {
- JS_ReportError(cx, "Failed to initialize cURL handle.");
- goto done;
- }
-
- if(!JS_GetReservedSlot(cx, obj, 0, &tmp)) {
- JS_ReportError(cx, "Failed to readreserved slot.");
- goto done;
- }
-
- if(!(referer = enc_string(cx, tmp, NULL))) {
- JS_ReportError(cx, "Failed to encode referer.");
- goto done;
- }
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_REFERER, referer);
- free(referer);
-
- if(http->method < 0 || http->method > OPTIONS) {
- JS_ReportError(cx, "INTERNAL: Unknown method.");
- goto done;
- }
-
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_CUSTOMREQUEST, METHODS[http->method]);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_NOBODY, 0);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_FOLLOWLOCATION, 1);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_UPLOAD, 0);
-
- if(http->method == HEAD) {
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_NOBODY, 1);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_FOLLOWLOCATION, 0);
- } else if(http->method == POST || http->method == PUT) {
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_UPLOAD, 1);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_FOLLOWLOCATION, 0);
- }
-
- if(body && bodylen) {
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_INFILESIZE, bodylen);
- } else {
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_INFILESIZE, 0);
- }
-
- // curl_easy_setopt(HTTP_HANDLE, CURLOPT_VERBOSE, 1);
-
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_URL, http->url);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_HTTPHEADER, http->req_headers);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_READDATA, &state);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_SEEKDATA, &state);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_WRITEHEADER, &state);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_WRITEDATA, &state);
-
- if(curl_easy_perform(HTTP_HANDLE) != 0) {
- JS_ReportError(cx, "Failed to execute HTTP request: %s", ERRBUF);
- goto done;
- }
-
- if(!state.resp_headers) {
- JS_ReportError(cx, "Failed to recieve HTTP headers.");
- goto done;
- }
-
- tmp = OBJECT_TO_JSVAL(state.resp_headers);
- if(!JS_DefineProperty(
- cx, obj,
- "_headers",
- tmp,
- NULL, NULL,
- JSPROP_READONLY
- )) {
- JS_ReportError(cx, "INTERNAL: Failed to set response headers.");
- goto done;
- }
-
- if(state.recvbuf) {
- state.recvbuf[state.read] = '\0';
- jsbody = dec_string(cx, state.recvbuf, state.read+1);
- if(!jsbody) {
- // If we can't decode the body as UTF-8 we forcefully
- // convert it to a string by just forcing each byte
- // to a jschar.
- jsbody = str_from_binary(cx, state.recvbuf, state.read);
- if(!jsbody) {
- if(!JS_IsExceptionPending(cx)) {
- JS_ReportError(cx, "INTERNAL: Failed to decode body.");
- }
- goto done;
- }
- }
- tmp = STRING_TO_JSVAL(jsbody);
- } else {
- tmp = JS_GetEmptyStringValue(cx);
- }
-
- if(!JS_DefineProperty(
- cx, obj,
- "responseText",
- tmp,
- NULL, NULL,
- JSPROP_READONLY
- )) {
- JS_ReportError(cx, "INTERNAL: Failed to set responseText.");
- goto done;
- }
-
- ret = JS_TRUE;
-
-done:
- if(state.recvbuf) JS_free(cx, state.recvbuf);
- return ret;
-}
-
-static size_t
-send_body(void *ptr, size_t size, size_t nmem, void *data)
-{
- CurlState* state = (CurlState*) data;
- size_t length = size * nmem;
- size_t towrite = state->sendlen - state->sent;
-
- // Assume this is cURL trying to resend a request that
- // failed.
- if(towrite == 0 && state->sent_once == 0) {
- state->sent_once = 1;
- return 0;
- } else if(towrite == 0) {
- state->sent = 0;
- state->sent_once = 0;
- towrite = state->sendlen;
- }
-
- if(length < towrite) towrite = length;
-
- memcpy(ptr, state->sendbuf + state->sent, towrite);
- state->sent += towrite;
-
- return towrite;
-}
-
-static int
-seek_body(void* ptr, curl_off_t offset, int origin)
-{
- CurlState* state = (CurlState*) ptr;
- if(origin != SEEK_SET) return -1;
-
- state->sent = (size_t) offset;
- return (int) state->sent;
-}
-
-static size_t
-recv_header(void *ptr, size_t size, size_t nmem, void *data)
-{
- CurlState* state = (CurlState*) data;
- char code[4];
- char* header = (char*) ptr;
- size_t length = size * nmem;
- JSString* hdr = NULL;
- jsuint hdrlen;
- jsval hdrval;
-
- if(length > 7 && strncasecmp(header, "HTTP/1.", 7) == 0) {
- if(length < 12) {
- return CURLE_WRITE_ERROR;
- }
-
- memcpy(code, header+9, 3*sizeof(char));
- code[3] = '\0';
- state->http->last_status = atoi(code);
-
- state->resp_headers = JS_NewArrayObject(state->cx, 0, NULL);
- if(!state->resp_headers) {
- return CURLE_WRITE_ERROR;
- }
-
- return length;
- }
-
- // We get a notice at the \r\n\r\n after headers.
- if(length <= 2) {
- return length;
- }
-
- // Append the new header to our array.
- hdr = dec_string(state->cx, header, length);
- if(!hdr) {
- return CURLE_WRITE_ERROR;
- }
-
- if(!JS_GetArrayLength(state->cx, state->resp_headers, &hdrlen)) {
- return CURLE_WRITE_ERROR;
- }
-
- hdrval = STRING_TO_JSVAL(hdr);
- if(!JS_SetElement(state->cx, state->resp_headers, hdrlen, &hdrval)) {
- return CURLE_WRITE_ERROR;
- }
-
- return length;
-}
-
-static size_t
-recv_body(void *ptr, size_t size, size_t nmem, void *data)
-{
- CurlState* state = (CurlState*) data;
- size_t length = size * nmem;
- char* tmp = NULL;
-
- if(!state->recvbuf) {
- state->recvlen = 4096;
- state->read = 0;
- state->recvbuf = JS_malloc(state->cx, state->recvlen);
- }
-
- if(!state->recvbuf) {
- return CURLE_WRITE_ERROR;
- }
-
- // +1 so we can add '\0' back up in the go function.
- while(length+1 > state->recvlen - state->read) state->recvlen *= 2;
- tmp = JS_realloc(state->cx, state->recvbuf, state->recvlen);
- if(!tmp) return CURLE_WRITE_ERROR;
- state->recvbuf = tmp;
-
- memcpy(state->recvbuf + state->read, ptr, length);
- state->read += length;
- return length;
-}
-
-JSString*
-str_from_binary(JSContext* cx, char* data, size_t length)
-{
- jschar* conv = (jschar*) JS_malloc(cx, length * sizeof(jschar));
- JSString* ret = NULL;
- size_t i;
-
- if(!conv) return NULL;
-
- for(i = 0; i < length; i++) {
- conv[i] = (jschar) data[i];
- }
-
- ret = JS_NewUCString(cx, conv, length);
- if(!ret) JS_free(cx, conv);
-
- return ret;
-}
-
-#endif /* HAVE_CURL */
diff --git a/src/couch/priv/couch_js/1.8.5/http.h b/src/couch/priv/couch_js/1.8.5/http.h
deleted file mode 100644
index 63d45bd..0000000
--- a/src/couch/priv/couch_js/1.8.5/http.h
+++ /dev/null
@@ -1,27 +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.
-
-#ifndef COUCH_JS_HTTP_H
-#define COUCH_JS_HTTP_H
-
-#include "util.h"
-
-void http_check_enabled();
-JSBool http_ctor(JSContext* cx, JSObject* req);
-void http_dtor(JSContext* cx, JSObject* req);
-JSBool http_open(JSContext* cx, JSObject* req, jsval mth, jsval url, jsval snc);
-JSBool http_set_hdr(JSContext* cx, JSObject* req, jsval name, jsval val);
-JSBool http_send(JSContext* cx, JSObject* req, jsval body);
-int http_status(JSContext* cx, JSObject* req);
-JSBool http_uri(JSContext* cx, JSObject *req, couch_args* args, jsval* uri);
-
-#endif
diff --git a/src/couch/priv/couch_js/1.8.5/main.c b/src/couch/priv/couch_js/1.8.5/main.c
index 986791c..c8e385c 100644
--- a/src/couch/priv/couch_js/1.8.5/main.c
+++ b/src/couch/priv/couch_js/1.8.5/main.c
@@ -22,7 +22,6 @@
#include <jsapi.h>
#include "config.h"
-#include "http.h"
#include "utf8.h"
#include "util.h"
@@ -49,105 +48,6 @@ static JSClass global_class = {
JSCLASS_NO_OPTIONAL_MEMBERS
};
-
-static JSBool
-req_ctor(JSContext* cx, uintN argc, jsval* vp)
-{
- JSBool ret;
- JSObject* obj = JS_NewObjectForConstructor(cx, vp);
- if(!obj) {
- JS_ReportError(cx, "Failed to create CouchHTTP instance.\n");
- return JS_FALSE;
- }
- ret = http_ctor(cx, obj);
- JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(obj));
- return ret;
-}
-
-
-static void
-req_dtor(JSContext* cx, JSObject* obj)
-{
- http_dtor(cx, obj);
-}
-
-
-static JSBool
-req_open(JSContext* cx, uintN argc, jsval* vp)
-{
- JSObject* obj = JS_THIS_OBJECT(cx, vp);
- jsval* argv = JS_ARGV(cx, vp);
- JSBool ret = JS_FALSE;
-
- if(argc == 2) {
- ret = http_open(cx, obj, argv[0], argv[1], JSVAL_FALSE);
- } else if(argc == 3) {
- ret = http_open(cx, obj, argv[0], argv[1], argv[2]);
- } else {
- JS_ReportError(cx, "Invalid call to CouchHTTP.open");
- }
-
- JS_SET_RVAL(cx, vp, JSVAL_VOID);
- return ret;
-}
-
-
-static JSBool
-req_set_hdr(JSContext* cx, uintN argc, jsval* vp)
-{
- JSObject* obj = JS_THIS_OBJECT(cx, vp);
- jsval* argv = JS_ARGV(cx, vp);
- JSBool ret = JS_FALSE;
-
- if(argc == 2) {
- ret = http_set_hdr(cx, obj, argv[0], argv[1]);
- } else {
- JS_ReportError(cx, "Invalid call to CouchHTTP.set_header");
- }
-
- JS_SET_RVAL(cx, vp, JSVAL_VOID);
- return ret;
-}
-
-
-static JSBool
-req_send(JSContext* cx, uintN argc, jsval* vp)
-{
- JSObject* obj = JS_THIS_OBJECT(cx, vp);
- jsval* argv = JS_ARGV(cx, vp);
- JSBool ret = JS_FALSE;
-
- if(argc == 1) {
- ret = http_send(cx, obj, argv[0]);
- } else {
- JS_ReportError(cx, "Invalid call to CouchHTTP.send");
- }
-
- JS_SET_RVAL(cx, vp, JSVAL_VOID);
- return ret;
-}
-
-
-static JSBool
-req_status(JSContext* cx, JSObject* obj, jsid pid, jsval* vp)
-{
- int status = http_status(cx, obj);
- if(status < 0)
- return JS_FALSE;
-
- JS_SET_RVAL(cx, vp, INT_TO_JSVAL(status));
- return JS_TRUE;
-}
-
-
-static JSBool
-base_url(JSContext *cx, JSObject* obj, jsid pid, jsval* vp)
-{
- couch_args *args = (couch_args*)JS_GetContextPrivate(cx);
- return http_uri(cx, obj, args, &JS_RVAL(cx, vp));
-}
-
-
static JSBool
evalcx(JSContext *cx, uintN argc, jsval* vp)
{
@@ -281,63 +181,6 @@ seal(JSContext* cx, uintN argc, jsval* vp)
}
-static JSBool
-js_sleep(JSContext* cx, uintN argc, jsval* vp)
-{
- jsval* argv = JS_ARGV(cx, vp);
- int duration = 0;
- if(!JS_ConvertArguments(cx, argc, argv, "/i", &duration)) {
- return JS_FALSE;
- }
-
-#ifdef XP_WIN
- Sleep(duration);
-#else
- usleep(duration * 1000);
-#endif
-
- return JS_TRUE;
-}
-
-
-JSClass CouchHTTPClass = {
- "CouchHTTP",
- JSCLASS_HAS_PRIVATE
- | JSCLASS_CONSTRUCT_PROTOTYPE
- | JSCLASS_HAS_RESERVED_SLOTS(2),
- JS_PropertyStub,
- JS_PropertyStub,
- JS_PropertyStub,
- JS_StrictPropertyStub,
- JS_EnumerateStub,
- JS_ResolveStub,
- JS_ConvertStub,
- req_dtor,
- JSCLASS_NO_OPTIONAL_MEMBERS
-};
-
-
-JSPropertySpec CouchHTTPProperties[] = {
- {"status", 0, JSPROP_READONLY, req_status, NULL},
- {"base_url", 0, JSPROP_READONLY | JSPROP_SHARED, base_url, NULL},
- {0, 0, 0, 0, 0}
-};
-
-
-JSFunctionSpec CouchHTTPFunctions[] = {
- JS_FS("_open", req_open, 3, 0),
- JS_FS("_setRequestHeader", req_set_hdr, 2, 0),
- JS_FS("_send", req_send, 1, 0),
- JS_FS_END
-};
-
-
-JSFunctionSpec TestSuiteFunctions[] = {
- JS_FS("sleep", js_sleep, 1, 0),
- JS_FS_END
-};
-
-
static JSFunctionSpec global_functions[] = {
JS_FS("evalcx", evalcx, 0, 0),
JS_FS("gc", gc, 0, 0),
@@ -376,7 +219,6 @@ main(int argc, const char* argv[])
JSContext* cx = NULL;
JSObject* global = NULL;
JSCrossCompartmentCall *call = NULL;
- JSObject* klass = NULL;
JSSCRIPT_TYPE script;
JSString* scriptsrc;
const jschar* schars;
@@ -420,30 +262,6 @@ main(int argc, const char* argv[])
if(couch_load_funcs(cx, global, global_functions) != JS_TRUE)
return 1;
- if(args->use_http) {
- http_check_enabled();
-
- klass = JS_InitClass(
- cx, global,
- NULL,
- &CouchHTTPClass, req_ctor,
- 0,
- CouchHTTPProperties, CouchHTTPFunctions,
- NULL, NULL
- );
-
- if(!klass)
- {
- fprintf(stderr, "Failed to initialize CouchHTTP class.\n");
- exit(2);
- }
- }
-
- if(args->use_test_funs) {
- if(couch_load_funcs(cx, global, TestSuiteFunctions) != JS_TRUE)
- return 1;
- }
-
for(i = 0 ; args->scripts[i] ; i++) {
// Convert script source to jschars.
scriptsrc = couch_readfile(cx, args->scripts[i]);
diff --git a/src/couch/priv/couch_js/1.8.5/util.c b/src/couch/priv/couch_js/1.8.5/util.c
index cf676ea..5cf94b6 100644
--- a/src/couch/priv/couch_js/1.8.5/util.c
+++ b/src/couch/priv/couch_js/1.8.5/util.c
@@ -96,8 +96,6 @@ couch_parse_args(int argc, const char* argv[])
fprintf(stderr, "Invalid stack size.\n");
exit(2);
}
- } else if(strcmp("-u", argv[i]) == 0) {
- args->uri_file = argv[++i];
} else if(strcmp("--eval", argv[i]) == 0) {
args->eval = 1;
} else if(strcmp("--", argv[i]) == 0) {
diff --git a/src/couch/priv/couch_js/1.8.5/util.h b/src/couch/priv/couch_js/1.8.5/util.h
index b24d7f7..9dd290a 100644
--- a/src/couch/priv/couch_js/1.8.5/util.h
+++ b/src/couch/priv/couch_js/1.8.5/util.h
@@ -21,8 +21,6 @@ typedef struct {
int use_test_funs;
int stack_size;
const char** scripts;
- const char* uri_file;
- JSString* uri;
} couch_args;
couch_args* couch_parse_args(int argc, const char* argv[]);
diff --git a/src/couch/priv/couch_js/60/help.h b/src/couch/priv/couch_js/60/help.h
index ffb6eb4..826babb 100644
--- a/src/couch/priv/couch_js/60/help.h
+++ b/src/couch/priv/couch_js/60/help.h
@@ -46,15 +46,9 @@ static const char USAGE_TEMPLATE[] =
"\n"
" -h display a short help message and exit\n"
" -V display version information and exit\n"
- " -H enable %s cURL bindings (only avaiable\n"
- " if package was built with cURL available)\n"
- " -T enable test suite specific functions (these\n"
- " should not be enabled for production systems)\n"
" -S SIZE specify that the runtime should allow at\n"
" most SIZE bytes of memory to be allocated\n"
" default is 64 MiB\n"
- " -u FILE path to a .uri file containing the address\n"
- " (or addresses) of one or more servers\n"
" --eval Enable runtime code evaluation (dangerous!)\n"
"\n"
"Report bugs at <%s>.\n";
@@ -78,7 +72,6 @@ static const char USAGE_TEMPLATE[] =
basename, \
basename, \
PACKAGE_NAME, \
- basename, \
PACKAGE_BUGREPORT)
#define DISPLAY_USAGE couch_usage(BASENAME)
diff --git a/src/couch/priv/couch_js/60/http.cpp b/src/couch/priv/couch_js/60/http.cpp
deleted file mode 100644
index e1e44d6..0000000
--- a/src/couch/priv/couch_js/60/http.cpp
+++ /dev/null
@@ -1,649 +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.
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <jsapi.h>
-#include <js/Initialization.h>
-#include "config.h"
-#include "util.h"
-
-// Soft dependency on cURL bindings because they're
-// only used when running the JS tests from the
-// command line which is rare.
-#ifndef HAVE_CURL
-
-void
-http_check_enabled()
-{
- fprintf(stderr, "HTTP API was disabled at compile time.\n");
- exit(3);
-}
-
-
-bool
-http_ctor(JSContext* cx, JSObject* req)
-{
- return false;
-}
-
-
-void
-http_dtor(JSFreeOp* fop, JSObject* req)
-{
- return;
-}
-
-
-bool
-http_open(JSContext* cx, JSObject* req, JS::Value mth, JS::Value url, JS::Value snc)
-{
- return false;
-}
-
-
-bool
-http_set_hdr(JSContext* cx, JSObject* req, JS::Value name, JS::Value val)
-{
- return false;
-}
-
-
-bool
-http_send(JSContext* cx, JSObject* req, JS::Value body)
-{
- return false;
-}
-
-
-int
-http_status(JSContext* cx, JSObject* req)
-{
- return -1;
-}
-
-bool
-http_uri(JSContext* cx, JSObject* req, couch_args* args, JS::Value* uri_val)
-{
- return false;
-}
-
-
-#else
-#include <curl/curl.h>
-#ifndef XP_WIN
-#include <unistd.h>
-#endif
-
-
-void
-http_check_enabled()
-{
- return;
-}
-
-
-// Map some of the string function names to things which exist on Windows
-#ifdef XP_WIN
-#define strcasecmp _strcmpi
-#define strncasecmp _strnicmp
-#endif
-
-
-typedef struct curl_slist CurlHeaders;
-
-
-typedef struct {
- int method;
- std::string url;
- CurlHeaders* req_headers;
- int16_t last_status;
-} HTTPData;
-
-
-const char* METHODS[] = {"GET", "HEAD", "POST", "PUT", "DELETE", "COPY", "OPTIONS", NULL};
-
-
-#define GET 0
-#define HEAD 1
-#define POST 2
-#define PUT 3
-#define DELETE 4
-#define COPY 5
-#define OPTIONS 6
-
-
-static bool go(JSContext* cx, JSObject* obj, HTTPData* http, std::string& body);
-
-
-bool
-http_ctor(JSContext* cx, JSObject* req)
-{
- HTTPData* http = new HTTPData();
- bool ret = false;
-
- if(!http)
- {
- JS_ReportErrorUTF8(cx, "Failed to create CouchHTTP instance.");
- goto error;
- }
-
- http->method = -1;
- http->req_headers = NULL;
- http->last_status = -1;
-
- JS_SetPrivate(req, http);
-
- ret = true;
- goto success;
-
-error:
- if(http) delete http;
-
-success:
- return ret;
-}
-
-
-void
-http_dtor(JSFreeOp* fop, JSObject* obj)
-{
- HTTPData* http = (HTTPData*) JS_GetPrivate(obj);
- if(http) {
- if(http->req_headers) curl_slist_free_all(http->req_headers);
- delete http;
- }
-}
-
-
-bool
-http_open(JSContext* cx, JSObject* req, JS::Value mth, JS::Value url, JS::Value snc)
-{
- HTTPData* http = (HTTPData*) JS_GetPrivate(req);
- int methid;
-
- if(!http) {
- JS_ReportErrorUTF8(cx, "Invalid CouchHTTP instance.");
- return false;
- }
-
- if(!mth.isString()) {
- JS_ReportErrorUTF8(cx, "Method must be a string.");
- return false;
- }
-
- std::string method;
- if(!js_to_string(cx, JS::RootedValue(cx, mth), method)) {
- JS_ReportErrorUTF8(cx, "Failed to encode method.");
- return false;
- }
-
- for(methid = 0; METHODS[methid] != NULL; methid++) {
- if(strcasecmp(METHODS[methid], method.c_str()) == 0) break;
- }
-
- if(methid > OPTIONS) {
- JS_ReportErrorUTF8(cx, "Invalid method specified.");
- return false;
- }
-
- http->method = methid;
-
- if(!url.isString()) {
- JS_ReportErrorUTF8(cx, "URL must be a string");
- return false;
- }
-
- std::string urlstr;
- if(!js_to_string(cx, JS::RootedValue(cx, url), urlstr)) {
- JS_ReportErrorUTF8(cx, "Failed to encode URL.");
- return false;
- }
- http->url = urlstr;
-
- if(snc.isBoolean() && snc.isTrue()) {
- JS_ReportErrorUTF8(cx, "Synchronous flag must be false.");
- return false;
- }
-
- if(http->req_headers) {
- curl_slist_free_all(http->req_headers);
- http->req_headers = NULL;
- }
-
- // Disable Expect: 100-continue
- http->req_headers = curl_slist_append(http->req_headers, "Expect:");
-
- return true;
-}
-
-
-bool
-http_set_hdr(JSContext* cx, JSObject* req, JS::Value name, JS::Value val)
-{
- HTTPData* http = (HTTPData*) JS_GetPrivate(req);
-
- if(!http) {
- JS_ReportErrorUTF8(cx, "Invalid CouchHTTP instance.");
- return false;
- }
-
- if(!name.isString())
- {
- JS_ReportErrorUTF8(cx, "Header names must be strings.");
- return false;
- }
-
- std::string keystr;
- if(!js_to_string(cx, JS::RootedValue(cx, name), keystr))
- {
- JS_ReportErrorUTF8(cx, "Failed to encode header name.");
- return false;
- }
-
- if(!val.isString())
- {
- JS_ReportErrorUTF8(cx, "Header values must be strings.");
- return false;
- }
-
- std::string valstr;
- if(!js_to_string(cx, JS::RootedValue(cx, val), valstr)) {
- JS_ReportErrorUTF8(cx, "Failed to encode header value.");
- return false;
- }
-
- std::string header = keystr + ": " + valstr;
- http->req_headers = curl_slist_append(http->req_headers, header.c_str());
-
- return true;
-}
-
-bool
-http_send(JSContext* cx, JSObject* req, JS::Value body)
-{
- HTTPData* http = (HTTPData*) JS_GetPrivate(req);
-
- if(!http) {
- JS_ReportErrorUTF8(cx, "Invalid CouchHTTP instance.");
- return false;
- }
-
- std::string bodystr;
- if(!js_to_string(cx, JS::RootedValue(cx, body), bodystr)) {
- JS_ReportErrorUTF8(cx, "Failed to encode body.");
- return false;
- }
-
- return go(cx, req, http, bodystr);
-}
-
-int
-http_status(JSContext* cx, JSObject* req)
-{
- HTTPData* http = (HTTPData*) JS_GetPrivate(req);
-
- if(!http) {
- JS_ReportErrorUTF8(cx, "Invalid CouchHTTP instance.");
- return false;
- }
-
- return http->last_status;
-}
-
-bool
-http_uri(JSContext* cx, JSObject* req, couch_args* args, JS::Value* uri_val)
-{
- FILE* uri_fp = NULL;
- JSString* uri_str;
-
- // Default is http://localhost:15986/ when no uri file is specified
- if (!args->uri_file) {
- uri_str = JS_NewStringCopyZ(cx, "http://localhost:15986/");
- *uri_val = JS::StringValue(uri_str);
- JS_SetReservedSlot(req, 0, *uri_val);
- return true;
- }
-
- // Else check to see if the base url is cached in a reserved slot
- *uri_val = JS_GetReservedSlot(req, 0);
- if (!(*uri_val).isUndefined()) {
- return true;
- }
-
- // Read the first line of the couch.uri file.
- if(!((uri_fp = fopen(args->uri_file, "r")) &&
- (uri_str = couch_readline(cx, uri_fp)))) {
- JS_ReportErrorUTF8(cx, "Failed to read couch.uri file.");
- goto error;
- }
-
- fclose(uri_fp);
- *uri_val = JS::StringValue(uri_str);
- JS_SetReservedSlot(req, 0, *uri_val);
- return true;
-
-error:
- if(uri_fp) fclose(uri_fp);
- return false;
-}
-
-
-// Curl Helpers
-
-typedef struct {
- HTTPData* http;
- JSContext* cx;
- JSObject* resp_headers;
- const char* sendbuf;
- size_t sendlen;
- size_t sent;
- int sent_once;
- char* recvbuf;
- size_t recvlen;
- size_t read;
-} CurlState;
-
-/*
- * I really hate doing this but this doesn't have to be
- * uber awesome, it just has to work.
- */
-CURL* HTTP_HANDLE = NULL;
-char ERRBUF[CURL_ERROR_SIZE];
-
-static size_t send_body(void *ptr, size_t size, size_t nmem, void *data);
-static int seek_body(void *ptr, curl_off_t offset, int origin);
-static size_t recv_body(void *ptr, size_t size, size_t nmem, void *data);
-static size_t recv_header(void *ptr, size_t size, size_t nmem, void *data);
-
-static bool
-go(JSContext* cx, JSObject* obj, HTTPData* http, std::string& body)
-{
- CurlState state;
- JSString* jsbody;
- bool ret = false;
- JS::Value tmp;
- JS::RootedObject robj(cx, obj);
- JS::RootedValue vobj(cx);
-
-
- state.cx = cx;
- state.http = http;
-
- state.sendbuf = body.c_str();
- state.sendlen = body.size();
- state.sent = 0;
- state.sent_once = 0;
-
- state.recvbuf = NULL;
- state.recvlen = 0;
- state.read = 0;
-
- if(HTTP_HANDLE == NULL) {
- HTTP_HANDLE = curl_easy_init();
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_READFUNCTION, send_body);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_SEEKFUNCTION,
- (curl_seek_callback) seek_body);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_HEADERFUNCTION, recv_header);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_WRITEFUNCTION, recv_body);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_NOPROGRESS, 1);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_ERRORBUFFER, ERRBUF);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_COOKIEFILE, "");
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_USERAGENT,
- "CouchHTTP Client - Relax");
- }
-
- if(!HTTP_HANDLE) {
- JS_ReportErrorUTF8(cx, "Failed to initialize cURL handle.");
- if(state.recvbuf) JS_free(cx, state.recvbuf);
- return ret;
- }
-
- tmp = JS_GetReservedSlot(obj, 0);
-
- std::string referer;
- if(!js_to_string(cx, JS::RootedValue(cx, tmp), referer)) {
- JS_ReportErrorUTF8(cx, "Failed to encode referer.");
- if(state.recvbuf) JS_free(cx, state.recvbuf);
- return ret;
- }
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_REFERER, referer.c_str());
-
- if(http->method < 0 || http->method > OPTIONS) {
- JS_ReportErrorUTF8(cx, "INTERNAL: Unknown method.");
- if(state.recvbuf) JS_free(cx, state.recvbuf);
- return ret;
- }
-
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_CUSTOMREQUEST, METHODS[http->method]);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_NOBODY, 0);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_FOLLOWLOCATION, 1);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_UPLOAD, 0);
-
- if(http->method == HEAD) {
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_NOBODY, 1);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_FOLLOWLOCATION, 0);
- } else if(http->method == POST || http->method == PUT) {
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_UPLOAD, 1);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_FOLLOWLOCATION, 0);
- }
-
- if(body.size() > 0) {
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_INFILESIZE, body.size());
- } else {
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_INFILESIZE, 0);
- }
-
- // curl_easy_setopt(HTTP_HANDLE, CURLOPT_VERBOSE, 1);
-
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_URL, http->url.c_str());
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_HTTPHEADER, http->req_headers);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_READDATA, &state);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_SEEKDATA, &state);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_WRITEHEADER, &state);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_WRITEDATA, &state);
-
- if(curl_easy_perform(HTTP_HANDLE) != 0) {
- JS_ReportErrorUTF8(cx, "Failed to execute HTTP request: %s", ERRBUF);
- if(state.recvbuf) JS_free(cx, state.recvbuf);
- return ret;
- }
-
- if(!state.resp_headers) {
- JS_ReportErrorUTF8(cx, "Failed to recieve HTTP headers.");
- if(state.recvbuf) JS_free(cx, state.recvbuf);
- return ret;
- }
- tmp = JS::ObjectValue(*state.resp_headers);
- JS::RootedValue rtmp(cx, tmp);
-
- if(!JS_DefineProperty(
- cx, robj,
- "_headers",
- rtmp,
- JSPROP_READONLY
- )) {
- JS_ReportErrorUTF8(cx, "INTERNAL: Failed to set response headers.");
- if(state.recvbuf) JS_free(cx, state.recvbuf);
- return ret;;
- }
-
- if(state.recvbuf) {
- state.recvbuf[state.read] = '\0';
- std::string bodystr(state.recvbuf, state.read);
- jsbody = string_to_js(cx, bodystr);
- if(!jsbody) {
- // If we can't decode the body as UTF-8 we forcefully
- // convert it to a string by just forcing each byte
- // to a char16_t.
- jsbody = JS_NewStringCopyN(cx, state.recvbuf, state.read);
- if(!jsbody) {
- if(!JS_IsExceptionPending(cx)) {
- JS_ReportErrorUTF8(cx, "INTERNAL: Failed to decode body.");
- }
- if(state.recvbuf) JS_free(cx, state.recvbuf);
- return ret;
- }
- }
- tmp = JS::StringValue(jsbody);
- } else {
- tmp = JS_GetEmptyStringValue(cx);
- }
-
- JS::RootedValue rtmp2(cx, tmp);
-
- if(!JS_DefineProperty(
- cx, robj,
- "responseText",
- rtmp2,
- JSPROP_READONLY
- )) {
- JS_ReportErrorUTF8(cx, "INTERNAL: Failed to set responseText.");
- if(state.recvbuf) JS_free(cx, state.recvbuf);
- return ret;
- }
-
- ret = true;
- if(state.recvbuf) JS_free(cx, state.recvbuf);
- return ret;
-}
-
-static size_t
-send_body(void *ptr, size_t size, size_t nmem, void *data)
-{
- CurlState* state = static_cast<CurlState*>(data);
- size_t length = size * nmem;
- size_t towrite = state->sendlen - state->sent;
-
- // Assume this is cURL trying to resend a request that
- // failed.
- if(towrite == 0 && state->sent_once == 0) {
- state->sent_once = 1;
- return 0;
- } else if(towrite == 0) {
- state->sent = 0;
- state->sent_once = 0;
- towrite = state->sendlen;
- }
-
- if(length < towrite) towrite = length;
-
- memcpy(ptr, state->sendbuf + state->sent, towrite);
- state->sent += towrite;
-
- return towrite;
-}
-
-static int
-seek_body(void* ptr, curl_off_t offset, int origin)
-{
- CurlState* state = static_cast<CurlState*>(ptr);
- if(origin != SEEK_SET) return -1;
-
- state->sent = static_cast<size_t>(offset);
- return static_cast<int>(state->sent);
-}
-
-static size_t
-recv_header(void *ptr, size_t size, size_t nmem, void *data)
-{
- CurlState* state = static_cast<CurlState*>(data);
- char code[4];
- char* header = static_cast<char*>(ptr);
- size_t length = size * nmem;
- JSString* hdr = NULL;
- uint32_t hdrlen;
-
- if(length > 7 && strncasecmp(header, "HTTP/1.", 7) == 0) {
- if(length < 12) {
- return CURLE_WRITE_ERROR;
- }
-
- memcpy(code, header+9, 3*sizeof(char));
- code[3] = '\0';
- state->http->last_status = atoi(code);
-
- state->resp_headers = JS_NewArrayObject(state->cx, 0);
- if(!state->resp_headers) {
- return CURLE_WRITE_ERROR;
- }
-
- return length;
- }
-
- // We get a notice at the \r\n\r\n after headers.
- if(length <= 2) {
- return length;
- }
-
- // Append the new header to our array.
- std::string hdrstr(header, length);
- hdr = string_to_js(state->cx, hdrstr);
- if(!hdr) {
- return CURLE_WRITE_ERROR;
- }
-
- JS::RootedObject obj(state->cx, state->resp_headers);
- if(!JS_GetArrayLength(state->cx, obj, &hdrlen)) {
- return CURLE_WRITE_ERROR;
- }
-
- JS::RootedString hdrval(state->cx, hdr);
- if(!JS_SetElement(state->cx, obj, hdrlen, hdrval)) {
- return CURLE_WRITE_ERROR;
- }
-
- return length;
-}
-
-static size_t
-recv_body(void *ptr, size_t size, size_t nmem, void *data)
-{
- CurlState* state = static_cast<CurlState*>(data);
- size_t length = size * nmem;
- char* tmp = NULL;
-
- if(!state->recvbuf) {
- state->recvlen = 4096;
- state->read = 0;
- state->recvbuf = static_cast<char*>(JS_malloc(
- state->cx,
- state->recvlen
- ));
- }
-
- if(!state->recvbuf) {
- return CURLE_WRITE_ERROR;
- }
-
- // +1 so we can add '\0' back up in the go function.
- size_t oldlen = state->recvlen;
- while(length+1 > state->recvlen - state->read) state->recvlen *= 2;
- tmp = static_cast<char*>(JS_realloc(
- state->cx,
- state->recvbuf,
- oldlen,
- state->recvlen
- ));
- if(!tmp) return CURLE_WRITE_ERROR;
- state->recvbuf = tmp;
-
- memcpy(state->recvbuf + state->read, ptr, length);
- state->read += length;
- return length;
-}
-
-#endif /* HAVE_CURL */
diff --git a/src/couch/priv/couch_js/60/http.h b/src/couch/priv/couch_js/60/http.h
deleted file mode 100644
index 797b3c0..0000000
--- a/src/couch/priv/couch_js/60/http.h
+++ /dev/null
@@ -1,27 +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.
-
-#ifndef COUCH_JS_HTTP_H
-#define COUCH_JS_HTTP_H
-
-#include "util.h"
-
-void http_check_enabled();
-bool http_ctor(JSContext* cx, JSObject* req);
-void http_dtor(JSFreeOp* fop, JSObject* req);
-bool http_open(JSContext* cx, JSObject* req, JS::Value mth, JS::Value url, JS::Value snc);
-bool http_set_hdr(JSContext* cx, JSObject* req, JS::Value name, JS::Value val);
-bool http_send(JSContext* cx, JSObject* req, JS::Value body);
-int http_status(JSContext* cx, JSObject* req);
-bool http_uri(JSContext* cx, JSObject *req, couch_args* args, JS::Value* uri);
-
-#endif
diff --git a/src/couch/priv/couch_js/60/main.cpp b/src/couch/priv/couch_js/60/main.cpp
index 828b9da..5169b05 100644
--- a/src/couch/priv/couch_js/60/main.cpp
+++ b/src/couch/priv/couch_js/60/main.cpp
@@ -27,7 +27,6 @@
#include <js/Wrapper.h>
#include "config.h"
-#include "http.h"
#include "util.h"
static bool enableSharedMemory = true;
@@ -53,136 +52,6 @@ static JSClass global_class = {
&global_ops
};
-
-static void
-req_dtor(JSFreeOp* fop, JSObject* obj)
-{
- http_dtor(fop, obj);
-}
-
-// With JSClass.construct.
-static const JSClassOps clsOps = {
- nullptr,
- nullptr,
- nullptr,
- nullptr,
- nullptr,
- nullptr,
- req_dtor,
- nullptr,
- nullptr,
- nullptr
-};
-
-static const JSClass CouchHTTPClass = {
- "CouchHTTP", /* name */
- JSCLASS_HAS_PRIVATE | JSCLASS_HAS_RESERVED_SLOTS(2), /* flags */
- &clsOps
-};
-
-static bool
-req_ctor(JSContext* cx, unsigned int argc, JS::Value* vp)
-{
- bool ret;
- JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
- JSObject* obj = JS_NewObjectForConstructor(cx, &CouchHTTPClass, args);
- if(!obj) {
- JS_ReportErrorUTF8(cx, "Failed to create CouchHTTP instance");
- return false;
- }
- ret = http_ctor(cx, obj);
- args.rval().setObject(*obj);
- return ret;
-}
-
-static bool
-req_open(JSContext* cx, unsigned int argc, JS::Value* vp)
-{
- JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
- JS::Value vobj = args.computeThis(cx);
- JSObject* obj = vobj.toObjectOrNull();
- bool ret = false;
-
- if(argc == 2) {
- ret = http_open(cx, obj, args[0], args[1], JS::BooleanValue(false));
- } else if(argc == 3) {
- ret = http_open(cx, obj, args[0], args[1], args[2]);
- } else {
- JS_ReportErrorUTF8(cx, "Invalid call to CouchHTTP.open");
- }
-
- args.rval().setUndefined();
- return ret;
-}
-
-
-static bool
-req_set_hdr(JSContext* cx, unsigned int argc, JS::Value* vp)
-{
- JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
- JS::Value vobj = args.computeThis(cx);
- JSObject* obj = vobj.toObjectOrNull();
- bool ret = false;
-
- if(argc == 2) {
- ret = http_set_hdr(cx, obj, args[0], args[1]);
- } else {
- JS_ReportErrorUTF8(cx, "Invalid call to CouchHTTP.set_header");
- }
-
- args.rval().setUndefined();
- return ret;
-}
-
-
-static bool
-req_send(JSContext* cx, unsigned int argc, JS::Value* vp)
-{
- JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
- JS::Value vobj = args.computeThis(cx);
- JSObject* obj = vobj.toObjectOrNull();
- bool ret = false;
-
- if(argc == 1) {
- ret = http_send(cx, obj, args[0]);
- } else {
- JS_ReportErrorUTF8(cx, "Invalid call to CouchHTTP.send");
- }
-
- args.rval().setUndefined();
- return ret;
-}
-
-static bool
-req_status(JSContext* cx, unsigned int argc, JS::Value* vp)
-{
- JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
- JS::Value vobj = args.computeThis(cx);
- JSObject* obj = vobj.toObjectOrNull();
-
- int status = http_status(cx, obj);
-
- if(status < 0)
- return false;
-
- args.rval().set(JS::Int32Value(status));
- return true;
-}
-
-static bool
-base_url(JSContext *cx, unsigned int argc, JS::Value* vp)
-{
- JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
- JS::Value vobj = args.computeThis(cx);
- JSObject* obj = vobj.toObjectOrNull();
-
- couch_args *cargs = static_cast<couch_args*>(JS_GetContextPrivate(cx));
- JS::Value uri_val;
- bool rc = http_uri(cx, obj, cargs, &uri_val);
- args.rval().set(uri_val);
- return rc;
-}
-
static void
SetStandardCompartmentOptions(JS::CompartmentOptions& options)
{
@@ -353,43 +222,6 @@ seal(JSContext* cx, unsigned int argc, JS::Value* vp)
}
-static bool
-js_sleep(JSContext* cx, unsigned int argc, JS::Value* vp)
-{
- JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
-
- int duration = args[0].toInt32();
-
-#ifdef XP_WIN
- Sleep(duration);
-#else
- usleep(duration * 1000);
-#endif
-
- return true;
-}
-
-JSPropertySpec CouchHTTPProperties[] = {
- JS_PSG("status", req_status, 0),
- JS_PSG("base_url", base_url, 0),
- JS_PS_END
-};
-
-
-JSFunctionSpec CouchHTTPFunctions[] = {
- JS_FN("_open", req_open, 3, 0),
- JS_FN("_setRequestHeader", req_set_hdr, 2, 0),
- JS_FN("_send", req_send, 1, 0),
- JS_FS_END
-};
-
-
-JSFunctionSpec TestSuiteFunctions[] = {
- JS_FN("sleep", js_sleep, 1, 0),
- JS_FS_END
-};
-
-
static JSFunctionSpec global_functions[] = {
JS_FN("evalcx", evalcx, 0, 0),
JS_FN("gc", gc, 0, 0),
@@ -423,7 +255,6 @@ int
main(int argc, const char* argv[])
{
JSContext* cx = NULL;
- JSObject* klass = NULL;
char* scriptsrc;
size_t slen;
int i;
@@ -461,30 +292,6 @@ main(int argc, const char* argv[])
if(couch_load_funcs(cx, global, global_functions) != true)
return 1;
- if(args->use_http) {
- http_check_enabled();
-
- klass = JS_InitClass(
- cx, global,
- NULL,
- &CouchHTTPClass, req_ctor,
- 0,
- CouchHTTPProperties, CouchHTTPFunctions,
- NULL, NULL
- );
-
- if(!klass)
- {
- fprintf(stderr, "Failed to initialize CouchHTTP class.\n");
- exit(2);
- }
- }
-
- if(args->use_test_funs) {
- if(couch_load_funcs(cx, global, TestSuiteFunctions) != true)
- return 1;
- }
-
for(i = 0 ; args->scripts[i] ; i++) {
slen = couch_readfile(args->scripts[i], &scriptsrc);
diff --git a/src/couch/priv/couch_js/60/util.cpp b/src/couch/priv/couch_js/60/util.cpp
index c37c41f..3bc58a9 100644
--- a/src/couch/priv/couch_js/60/util.cpp
+++ b/src/couch/priv/couch_js/60/util.cpp
@@ -142,12 +142,8 @@ couch_parse_args(int argc, const char* argv[])
return NULL;
args->eval = 0;
- args->use_http = 0;
- args->use_test_funs = 0;
args->stack_size = 64L * 1024L * 1024L;
args->scripts = nullptr;
- args->uri_file = nullptr;
- args->uri = nullptr;
while(i < argc) {
if(strcmp("-h", argv[i]) == 0) {
@@ -156,18 +152,12 @@ couch_parse_args(int argc, const char* argv[])
} else if(strcmp("-V", argv[i]) == 0) {
DISPLAY_VERSION;
exit(0);
- } else if(strcmp("-H", argv[i]) == 0) {
- args->use_http = 1;
- } else if(strcmp("-T", argv[i]) == 0) {
- args->use_test_funs = 1;
} else if(strcmp("-S", argv[i]) == 0) {
args->stack_size = atoi(argv[++i]);
if(args->stack_size <= 0) {
fprintf(stderr, "Invalid stack size.\n");
exit(2);
}
- } else if(strcmp("-u", argv[i]) == 0) {
- args->uri_file = argv[++i];
} else if(strcmp("--eval", argv[i]) == 0) {
args->eval = 1;
} else if(strcmp("--", argv[i]) == 0) {
diff --git a/src/couch/priv/couch_js/60/util.h b/src/couch/priv/couch_js/60/util.h
index 4c27f0f..35882a6 100644
--- a/src/couch/priv/couch_js/60/util.h
+++ b/src/couch/priv/couch_js/60/util.h
@@ -17,12 +17,8 @@
typedef struct {
int eval;
- int use_http;
- int use_test_funs;
int stack_size;
const char** scripts;
- const char* uri_file;
- JSString* uri;
} couch_args;
std::string js_to_string(JSContext* cx, JS::HandleValue val);
diff --git a/src/couch/priv/couch_js/68/help.h b/src/couch/priv/couch_js/68/help.h
index c5cb832..c01c9b8 100644
--- a/src/couch/priv/couch_js/68/help.h
+++ b/src/couch/priv/couch_js/68/help.h
@@ -46,10 +46,6 @@ static const char USAGE_TEMPLATE[] =
"\n"
" -h display a short help message and exit\n"
" -V display version information and exit\n"
- " -H enable %s cURL bindings (only avaiable\n"
- " if package was built with cURL available)\n"
- " -T enable test suite specific functions (these\n"
- " should not be enabled for production systems)\n"
" -S SIZE specify that the runtime should allow at\n"
" most SIZE bytes of memory to be allocated\n"
" default is 64 MiB\n"
@@ -78,7 +74,6 @@ static const char USAGE_TEMPLATE[] =
basename, \
basename, \
PACKAGE_NAME, \
- basename, \
PACKAGE_BUGREPORT)
#define DISPLAY_USAGE couch_usage(BASENAME)
diff --git a/src/couch/priv/couch_js/68/http.cpp b/src/couch/priv/couch_js/68/http.cpp
deleted file mode 100644
index 20a6097..0000000
--- a/src/couch/priv/couch_js/68/http.cpp
+++ /dev/null
@@ -1,650 +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.
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <jsapi.h>
-#include <js/Initialization.h>
-#include <js/MemoryFunctions.h>
-#include "config.h"
-#include "util.h"
-
-// Soft dependency on cURL bindings because they're
-// only used when running the JS tests from the
-// command line which is rare.
-#ifndef HAVE_CURL
-
-void
-http_check_enabled()
-{
- fprintf(stderr, "HTTP API was disabled at compile time.\n");
- exit(3);
-}
-
-
-bool
-http_ctor(JSContext* cx, JSObject* req)
-{
- return false;
-}
-
-
-void
-http_dtor(JSFreeOp* fop, JSObject* req)
-{
- return;
-}
-
-
-bool
-http_open(JSContext* cx, JSObject* req, JS::Value mth, JS::Value url, JS::Value snc)
-{
- return false;
-}
-
-
-bool
-http_set_hdr(JSContext* cx, JSObject* req, JS::Value name, JS::Value val)
-{
- return false;
-}
-
-
-bool
-http_send(JSContext* cx, JSObject* req, JS::Value body)
-{
- return false;
-}
-
-
-int
-http_status(JSContext* cx, JSObject* req)
-{
- return -1;
-}
-
-bool
-http_uri(JSContext* cx, JSObject* req, couch_args* args, JS::Value* uri_val)
-{
- return false;
-}
-
-
-#else
-#include <curl/curl.h>
-#ifndef XP_WIN
-#include <unistd.h>
-#endif
-
-
-void
-http_check_enabled()
-{
- return;
-}
-
-
-// Map some of the string function names to things which exist on Windows
-#ifdef XP_WIN
-#define strcasecmp _strcmpi
-#define strncasecmp _strnicmp
-#endif
-
-
-typedef struct curl_slist CurlHeaders;
-
-
-typedef struct {
- int method;
- std::string url;
- CurlHeaders* req_headers;
- int16_t last_status;
-} HTTPData;
-
-
-const char* METHODS[] = {"GET", "HEAD", "POST", "PUT", "DELETE", "COPY", "OPTIONS", NULL};
-
-
-#define GET 0
-#define HEAD 1
-#define POST 2
-#define PUT 3
-#define DELETE 4
-#define COPY 5
-#define OPTIONS 6
-
-
-static bool go(JSContext* cx, JSObject* obj, HTTPData* http, std::string& body);
-
-
-bool
-http_ctor(JSContext* cx, JSObject* req)
-{
- HTTPData* http = new HTTPData();
- bool ret = false;
-
- if(!http)
- {
- JS_ReportErrorUTF8(cx, "Failed to create CouchHTTP instance.");
- goto error;
- }
-
- http->method = -1;
- http->req_headers = NULL;
- http->last_status = -1;
-
- JS_SetPrivate(req, http);
-
- ret = true;
- goto success;
-
-error:
- if(http) delete http;
-
-success:
- return ret;
-}
-
-
-void
-http_dtor(JSFreeOp* fop, JSObject* obj)
-{
- HTTPData* http = (HTTPData*) JS_GetPrivate(obj);
- if(http) {
- if(http->req_headers) curl_slist_free_all(http->req_headers);
- delete http;
- }
-}
-
-
-bool
-http_open(JSContext* cx, JSObject* req, JS::Value mth, JS::Value url, JS::Value snc)
-{
- HTTPData* http = (HTTPData*) JS_GetPrivate(req);
- int methid;
-
- if(!http) {
- JS_ReportErrorUTF8(cx, "Invalid CouchHTTP instance.");
- return false;
- }
-
- if(!mth.isString()) {
- JS_ReportErrorUTF8(cx, "Method must be a string.");
- return false;
- }
-
- std::string method;
- if(!js_to_string(cx, JS::RootedValue(cx, mth), method)) {
- JS_ReportErrorUTF8(cx, "Failed to encode method.");
- return false;
- }
-
- for(methid = 0; METHODS[methid] != NULL; methid++) {
- if(strcasecmp(METHODS[methid], method.c_str()) == 0) break;
- }
-
- if(methid > OPTIONS) {
- JS_ReportErrorUTF8(cx, "Invalid method specified.");
- return false;
- }
-
- http->method = methid;
-
- if(!url.isString()) {
- JS_ReportErrorUTF8(cx, "URL must be a string");
- return false;
- }
-
- std::string urlstr;
- if(!js_to_string(cx, JS::RootedValue(cx, url), urlstr)) {
- JS_ReportErrorUTF8(cx, "Failed to encode URL.");
- return false;
- }
- http->url = urlstr;
-
- if(snc.isBoolean() && snc.isTrue()) {
- JS_ReportErrorUTF8(cx, "Synchronous flag must be false.");
- return false;
- }
-
- if(http->req_headers) {
- curl_slist_free_all(http->req_headers);
- http->req_headers = NULL;
- }
-
- // Disable Expect: 100-continue
- http->req_headers = curl_slist_append(http->req_headers, "Expect:");
-
- return true;
-}
-
-
-bool
-http_set_hdr(JSContext* cx, JSObject* req, JS::Value name, JS::Value val)
-{
- HTTPData* http = (HTTPData*) JS_GetPrivate(req);
-
- if(!http) {
- JS_ReportErrorUTF8(cx, "Invalid CouchHTTP instance.");
- return false;
- }
-
- if(!name.isString())
- {
- JS_ReportErrorUTF8(cx, "Header names must be strings.");
- return false;
- }
-
- std::string keystr;
- if(!js_to_string(cx, JS::RootedValue(cx, name), keystr))
- {
- JS_ReportErrorUTF8(cx, "Failed to encode header name.");
- return false;
- }
-
- if(!val.isString())
- {
- JS_ReportErrorUTF8(cx, "Header values must be strings.");
- return false;
- }
-
- std::string valstr;
- if(!js_to_string(cx, JS::RootedValue(cx, val), valstr)) {
- JS_ReportErrorUTF8(cx, "Failed to encode header value.");
- return false;
- }
-
- std::string header = keystr + ": " + valstr;
- http->req_headers = curl_slist_append(http->req_headers, header.c_str());
-
- return true;
-}
-
-bool
-http_send(JSContext* cx, JSObject* req, JS::Value body)
-{
- HTTPData* http = (HTTPData*) JS_GetPrivate(req);
-
- if(!http) {
- JS_ReportErrorUTF8(cx, "Invalid CouchHTTP instance.");
- return false;
- }
-
- std::string bodystr;
- if(!js_to_string(cx, JS::RootedValue(cx, body), bodystr)) {
- JS_ReportErrorUTF8(cx, "Failed to encode body.");
- return false;
- }
-
- return go(cx, req, http, bodystr);
-}
-
-int
-http_status(JSContext* cx, JSObject* req)
-{
- HTTPData* http = (HTTPData*) JS_GetPrivate(req);
-
- if(!http) {
- JS_ReportErrorUTF8(cx, "Invalid CouchHTTP instance.");
- return false;
- }
-
- return http->last_status;
-}
-
-bool
-http_uri(JSContext* cx, JSObject* req, couch_args* args, JS::Value* uri_val)
-{
- FILE* uri_fp = NULL;
- JSString* uri_str;
-
- // Default is http://localhost:15986/ when no uri file is specified
- if (!args->uri_file) {
- uri_str = JS_NewStringCopyZ(cx, "http://localhost:15986/");
- *uri_val = JS::StringValue(uri_str);
- JS_SetReservedSlot(req, 0, *uri_val);
- return true;
- }
-
- // Else check to see if the base url is cached in a reserved slot
- *uri_val = JS_GetReservedSlot(req, 0);
- if (!(*uri_val).isUndefined()) {
- return true;
- }
-
- // Read the first line of the couch.uri file.
- if(!((uri_fp = fopen(args->uri_file, "r")) &&
- (uri_str = couch_readline(cx, uri_fp)))) {
- JS_ReportErrorUTF8(cx, "Failed to read couch.uri file.");
- goto error;
- }
-
- fclose(uri_fp);
- *uri_val = JS::StringValue(uri_str);
- JS_SetReservedSlot(req, 0, *uri_val);
- return true;
-
-error:
- if(uri_fp) fclose(uri_fp);
- return false;
-}
-
-
-// Curl Helpers
-
-typedef struct {
- HTTPData* http;
- JSContext* cx;
- JSObject* resp_headers;
- const char* sendbuf;
- size_t sendlen;
- size_t sent;
- int sent_once;
- char* recvbuf;
- size_t recvlen;
- size_t read;
-} CurlState;
-
-/*
- * I really hate doing this but this doesn't have to be
- * uber awesome, it just has to work.
- */
-CURL* HTTP_HANDLE = NULL;
-char ERRBUF[CURL_ERROR_SIZE];
-
-static size_t send_body(void *ptr, size_t size, size_t nmem, void *data);
-static int seek_body(void *ptr, curl_off_t offset, int origin);
-static size_t recv_body(void *ptr, size_t size, size_t nmem, void *data);
-static size_t recv_header(void *ptr, size_t size, size_t nmem, void *data);
-
-static bool
-go(JSContext* cx, JSObject* obj, HTTPData* http, std::string& body)
-{
- CurlState state;
- JSString* jsbody;
- bool ret = false;
- JS::Value tmp;
- JS::RootedObject robj(cx, obj);
- JS::RootedValue vobj(cx);
-
-
- state.cx = cx;
- state.http = http;
-
- state.sendbuf = body.c_str();;
- state.sendlen = body.size();
- state.sent = 0;
- state.sent_once = 0;
-
- state.recvbuf = NULL;
- state.recvlen = 0;
- state.read = 0;
-
- if(HTTP_HANDLE == NULL) {
- HTTP_HANDLE = curl_easy_init();
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_READFUNCTION, send_body);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_SEEKFUNCTION,
- (curl_seek_callback) seek_body);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_HEADERFUNCTION, recv_header);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_WRITEFUNCTION, recv_body);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_NOPROGRESS, 1);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_ERRORBUFFER, ERRBUF);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_COOKIEFILE, "");
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_USERAGENT,
- "CouchHTTP Client - Relax");
- }
-
- if(!HTTP_HANDLE) {
- JS_ReportErrorUTF8(cx, "Failed to initialize cURL handle.");
- if(state.recvbuf) JS_free(cx, state.recvbuf);
- return ret;
- }
-
- tmp = JS_GetReservedSlot(obj, 0);
-
- std::string referer;
- if(!js_to_string(cx, JS::RootedValue(cx, tmp), referer)) {
- JS_ReportErrorUTF8(cx, "Failed to encode referer.");
- if(state.recvbuf) JS_free(cx, state.recvbuf);
- return ret;
- }
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_REFERER, referer.c_str());
-
- if(http->method < 0 || http->method > OPTIONS) {
- JS_ReportErrorUTF8(cx, "INTERNAL: Unknown method.");
- if(state.recvbuf) JS_free(cx, state.recvbuf);
- return ret;
- }
-
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_CUSTOMREQUEST, METHODS[http->method]);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_NOBODY, 0);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_FOLLOWLOCATION, 1);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_UPLOAD, 0);
-
- if(http->method == HEAD) {
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_NOBODY, 1);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_FOLLOWLOCATION, 0);
- } else if(http->method == POST || http->method == PUT) {
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_UPLOAD, 1);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_FOLLOWLOCATION, 0);
- }
-
- if(body.size() > 0) {
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_INFILESIZE, body.size());
- } else {
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_INFILESIZE, 0);
- }
-
- // curl_easy_setopt(HTTP_HANDLE, CURLOPT_VERBOSE, 1);
-
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_URL, http->url.c_str());
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_HTTPHEADER, http->req_headers);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_READDATA, &state);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_SEEKDATA, &state);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_WRITEHEADER, &state);
- curl_easy_setopt(HTTP_HANDLE, CURLOPT_WRITEDATA, &state);
-
- if(curl_easy_perform(HTTP_HANDLE) != 0) {
- JS_ReportErrorUTF8(cx, "Failed to execute HTTP request: %s", ERRBUF);
- if(state.recvbuf) JS_free(cx, state.recvbuf);
- return ret;
- }
-
- if(!state.resp_headers) {
- JS_ReportErrorUTF8(cx, "Failed to recieve HTTP headers.");
- if(state.recvbuf) JS_free(cx, state.recvbuf);
- return ret;
- }
- tmp = JS::ObjectValue(*state.resp_headers);
- JS::RootedValue rtmp(cx, tmp);
-
- if(!JS_DefineProperty(
- cx, robj,
- "_headers",
- rtmp,
- JSPROP_READONLY
- )) {
- JS_ReportErrorUTF8(cx, "INTERNAL: Failed to set response headers.");
- if(state.recvbuf) JS_free(cx, state.recvbuf);
- return ret;;
- }
-
- if(state.recvbuf) {
- state.recvbuf[state.read] = '\0';
- std::string bodystr(state.recvbuf, state.read);
- jsbody = string_to_js(cx, bodystr);
- if(!jsbody) {
- // If we can't decode the body as UTF-8 we forcefully
- // convert it to a string by just forcing each byte
- // to a char16_t.
- jsbody = JS_NewStringCopyN(cx, state.recvbuf, state.read);
- if(!jsbody) {
- if(!JS_IsExceptionPending(cx)) {
- JS_ReportErrorUTF8(cx, "INTERNAL: Failed to decode body.");
- }
- if(state.recvbuf) JS_free(cx, state.recvbuf);
- return ret;
- }
- }
- tmp = JS::StringValue(jsbody);
- } else {
- tmp = JS_GetEmptyStringValue(cx);
- }
-
- JS::RootedValue rtmp2(cx, tmp);
-
- if(!JS_DefineProperty(
- cx, robj,
- "responseText",
- rtmp2,
- JSPROP_READONLY
- )) {
- JS_ReportErrorUTF8(cx, "INTERNAL: Failed to set responseText.");
- if(state.recvbuf) JS_free(cx, state.recvbuf);
- return ret;
- }
-
- ret = true;
- if(state.recvbuf) JS_free(cx, state.recvbuf);
- return ret;
-}
-
-static size_t
-send_body(void *ptr, size_t size, size_t nmem, void *data)
-{
- CurlState* state = static_cast<CurlState*>(data);
- size_t length = size * nmem;
- size_t towrite = state->sendlen - state->sent;
-
- // Assume this is cURL trying to resend a request that
- // failed.
- if(towrite == 0 && state->sent_once == 0) {
- state->sent_once = 1;
- return 0;
- } else if(towrite == 0) {
- state->sent = 0;
- state->sent_once = 0;
- towrite = state->sendlen;
- }
-
- if(length < towrite) towrite = length;
-
- memcpy(ptr, state->sendbuf + state->sent, towrite);
- state->sent += towrite;
-
- return towrite;
-}
-
-static int
-seek_body(void* ptr, curl_off_t offset, int origin)
-{
- CurlState* state = static_cast<CurlState*>(ptr);
- if(origin != SEEK_SET) return -1;
-
- state->sent = static_cast<size_t>(offset);
- return static_cast<int>(state->sent);
-}
-
-static size_t
-recv_header(void *ptr, size_t size, size_t nmem, void *data)
-{
- CurlState* state = static_cast<CurlState*>(data);
- char code[4];
- char* header = static_cast<char*>(ptr);
- size_t length = size * nmem;
- JSString* hdr = NULL;
- uint32_t hdrlen;
-
- if(length > 7 && strncasecmp(header, "HTTP/1.", 7) == 0) {
- if(length < 12) {
- return CURLE_WRITE_ERROR;
- }
-
- memcpy(code, header+9, 3*sizeof(char));
- code[3] = '\0';
- state->http->last_status = atoi(code);
-
- state->resp_headers = JS_NewArrayObject(state->cx, 0);
- if(!state->resp_headers) {
- return CURLE_WRITE_ERROR;
- }
-
- return length;
- }
-
- // We get a notice at the \r\n\r\n after headers.
- if(length <= 2) {
- return length;
- }
-
- // Append the new header to our array.
- std::string hdrstr(header, length);
- hdr = string_to_js(state->cx, hdrstr);
- if(!hdr) {
- return CURLE_WRITE_ERROR;
- }
-
- JS::RootedObject obj(state->cx, state->resp_headers);
- if(!JS_GetArrayLength(state->cx, obj, &hdrlen)) {
- return CURLE_WRITE_ERROR;
- }
-
- JS::RootedString hdrval(state->cx, hdr);
- if(!JS_SetElement(state->cx, obj, hdrlen, hdrval)) {
- return CURLE_WRITE_ERROR;
- }
-
- return length;
-}
-
-static size_t
-recv_body(void *ptr, size_t size, size_t nmem, void *data)
-{
- CurlState* state = static_cast<CurlState*>(data);
- size_t length = size * nmem;
- char* tmp = NULL;
-
- if(!state->recvbuf) {
- state->recvlen = 4096;
- state->read = 0;
- state->recvbuf = static_cast<char*>(JS_malloc(
- state->cx,
- state->recvlen
- ));
- }
-
- if(!state->recvbuf) {
- return CURLE_WRITE_ERROR;
- }
-
- // +1 so we can add '\0' back up in the go function.
- size_t oldlen = state->recvlen;
- while(length+1 > state->recvlen - state->read) state->recvlen *= 2;
- tmp = static_cast<char*>(JS_realloc(
- state->cx,
- state->recvbuf,
- oldlen,
- state->recvlen
- ));
- if(!tmp) return CURLE_WRITE_ERROR;
- state->recvbuf = tmp;
-
- memcpy(state->recvbuf + state->read, ptr, length);
- state->read += length;
- return length;
-}
-
-#endif /* HAVE_CURL */
diff --git a/src/couch/priv/couch_js/68/http.h b/src/couch/priv/couch_js/68/http.h
deleted file mode 100644
index 797b3c0..0000000
--- a/src/couch/priv/couch_js/68/http.h
+++ /dev/null
@@ -1,27 +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.
-
-#ifndef COUCH_JS_HTTP_H
-#define COUCH_JS_HTTP_H
-
-#include "util.h"
-
-void http_check_enabled();
-bool http_ctor(JSContext* cx, JSObject* req);
-void http_dtor(JSFreeOp* fop, JSObject* req);
-bool http_open(JSContext* cx, JSObject* req, JS::Value mth, JS::Value url, JS::Value snc);
-bool http_set_hdr(JSContext* cx, JSObject* req, JS::Value name, JS::Value val);
-bool http_send(JSContext* cx, JSObject* req, JS::Value body);
-int http_status(JSContext* cx, JSObject* req);
-bool http_uri(JSContext* cx, JSObject *req, couch_args* args, JS::Value* uri);
-
-#endif
diff --git a/src/couch/priv/couch_js/68/main.cpp b/src/couch/priv/couch_js/68/main.cpp
index 2c95f61..bb62d16 100644
--- a/src/couch/priv/couch_js/68/main.cpp
+++ b/src/couch/priv/couch_js/68/main.cpp
@@ -30,7 +30,6 @@
#include <js/Wrapper.h>
#include "config.h"
-#include "http.h"
#include "util.h"
static bool enableSharedMemory = true;
@@ -56,141 +55,6 @@ static JSClass global_class = {
&global_ops
};
-
-static void
-req_dtor(JSFreeOp* fop, JSObject* obj)
-{
- http_dtor(fop, obj);
-}
-
-// With JSClass.construct.
-static const JSClassOps clsOps = {
- nullptr,
- nullptr,
- nullptr,
- nullptr,
- nullptr,
- nullptr,
- req_dtor,
- nullptr,
- nullptr,
- nullptr
-};
-
-static const JSClass CouchHTTPClass = {
- "CouchHTTP", /* name */
- JSCLASS_HAS_PRIVATE | JSCLASS_HAS_RESERVED_SLOTS(2), /* flags */
- &clsOps
-};
-
-static bool
-req_ctor(JSContext* cx, unsigned int argc, JS::Value* vp)
-{
- bool ret;
- JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
- JSObject* obj = JS_NewObjectForConstructor(cx, &CouchHTTPClass, args);
- if(!obj) {
- JS_ReportErrorUTF8(cx, "Failed to create CouchHTTP instance");
- return false;
- }
- ret = http_ctor(cx, obj);
- args.rval().setObject(*obj);
- return ret;
-}
-
-static bool
-req_open(JSContext* cx, unsigned int argc, JS::Value* vp)
-{
- JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
- JS::RootedObject obj(cx);
- if (!args.computeThis(cx, &obj))
- return false;
- bool ret = false;
-
- if(argc == 2) {
- ret = http_open(cx, obj, args[0], args[1], JS::BooleanValue(false));
- } else if(argc == 3) {
- ret = http_open(cx, obj, args[0], args[1], args[2]);
- } else {
- JS_ReportErrorUTF8(cx, "Invalid call to CouchHTTP.open");
- }
-
- args.rval().setUndefined();
- return ret;
-}
-
-
-static bool
-req_set_hdr(JSContext* cx, unsigned int argc, JS::Value* vp)
-{
- JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
- JS::RootedObject obj(cx);
- if (!args.computeThis(cx, &obj))
- return false;
- bool ret = false;
-
- if(argc == 2) {
- ret = http_set_hdr(cx, obj, args[0], args[1]);
- } else {
- JS_ReportErrorUTF8(cx, "Invalid call to CouchHTTP.set_header");
- }
-
- args.rval().setUndefined();
- return ret;
-}
-
-
-static bool
-req_send(JSContext* cx, unsigned int argc, JS::Value* vp)
-{
- JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
- JS::RootedObject obj(cx);
- if (!args.computeThis(cx, &obj))
- return false;
- bool ret = false;
-
- if(argc == 1) {
- ret = http_send(cx, obj, args[0]);
- } else {
- JS_ReportErrorUTF8(cx, "Invalid call to CouchHTTP.send");
- }
-
- args.rval().setUndefined();
- return ret;
-}
-
-static bool
-req_status(JSContext* cx, unsigned int argc, JS::Value* vp)
-{
- JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
- JS::RootedObject obj(cx);
- if (!args.computeThis(cx, &obj))
- return false;
-
- int status = http_status(cx, obj);
-
- if(status < 0)
- return false;
-
- args.rval().set(JS::Int32Value(status));
- return true;
-}
-
-static bool
-base_url(JSContext *cx, unsigned int argc, JS::Value* vp)
-{
- JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
- JS::RootedObject obj(cx);
- if (!args.computeThis(cx, &obj))
- return false;
-
- couch_args *cargs = static_cast<couch_args*>(JS_GetContextPrivate(cx));
- JS::Value uri_val;
- bool rc = http_uri(cx, obj, cargs, &uri_val);
- args.rval().set(uri_val);
- return rc;
-}
-
static JSObject*
NewSandbox(JSContext* cx, bool lazy)
{
@@ -358,43 +222,6 @@ seal(JSContext* cx, unsigned int argc, JS::Value* vp)
}
-static bool
-js_sleep(JSContext* cx, unsigned int argc, JS::Value* vp)
-{
- JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
-
- int duration = args[0].toInt32();
-
-#ifdef XP_WIN
- Sleep(duration);
-#else
- usleep(duration * 1000);
-#endif
-
- return true;
-}
-
-JSPropertySpec CouchHTTPProperties[] = {
- JS_PSG("status", req_status, 0),
- JS_PSG("base_url", base_url, 0),
- JS_PS_END
-};
-
-
-JSFunctionSpec CouchHTTPFunctions[] = {
- JS_FN("_open", req_open, 3, 0),
- JS_FN("_setRequestHeader", req_set_hdr, 2, 0),
- JS_FN("_send", req_send, 1, 0),
- JS_FS_END
-};
-
-
-JSFunctionSpec TestSuiteFunctions[] = {
- JS_FN("sleep", js_sleep, 1, 0),
- JS_FS_END
-};
-
-
static JSFunctionSpec global_functions[] = {
JS_FN("evalcx", evalcx, 0, 0),
JS_FN("gc", gc, 0, 0),
@@ -428,7 +255,6 @@ int
main(int argc, const char* argv[])
{
JSContext* cx = NULL;
- JSObject* klass = NULL;
int i;
couch_args* args = couch_parse_args(argc, argv);
@@ -463,30 +289,6 @@ main(int argc, const char* argv[])
if(couch_load_funcs(cx, global, global_functions) != true)
return 1;
- if(args->use_http) {
- http_check_enabled();
-
- klass = JS_InitClass(
- cx, global,
- NULL,
- &CouchHTTPClass, req_ctor,
- 0,
- CouchHTTPProperties, CouchHTTPFunctions,
- NULL, NULL
- );
-
- if(!klass)
- {
- fprintf(stderr, "Failed to initialize CouchHTTP class.\n");
- exit(2);
- }
- }
-
- if(args->use_test_funs) {
- if(couch_load_funcs(cx, global, TestSuiteFunctions) != true)
- return 1;
- }
-
for(i = 0 ; args->scripts[i] ; i++) {
const char* filename = args->scripts[i];
diff --git a/src/couch/priv/couch_js/68/util.cpp b/src/couch/priv/couch_js/68/util.cpp
index 7717f11..6e6105d 100644
--- a/src/couch/priv/couch_js/68/util.cpp
+++ b/src/couch/priv/couch_js/68/util.cpp
@@ -135,12 +135,8 @@ couch_parse_args(int argc, const char* argv[])
return NULL;
args->eval = 0;
- args->use_http = 0;
- args->use_test_funs = 0;
args->stack_size = 64L * 1024L * 1024L;
args->scripts = nullptr;
- args->uri_file = nullptr;
- args->uri = nullptr;
while(i < argc) {
if(strcmp("-h", argv[i]) == 0) {
@@ -149,18 +145,12 @@ couch_parse_args(int argc, const char* argv[])
} else if(strcmp("-V", argv[i]) == 0) {
DISPLAY_VERSION;
exit(0);
- } else if(strcmp("-H", argv[i]) == 0) {
- args->use_http = 1;
- } else if(strcmp("-T", argv[i]) == 0) {
- args->use_test_funs = 1;
} else if(strcmp("-S", argv[i]) == 0) {
args->stack_size = atoi(argv[++i]);
if(args->stack_size <= 0) {
fprintf(stderr, "Invalid stack size.\n");
exit(2);
}
- } else if(strcmp("-u", argv[i]) == 0) {
- args->uri_file = argv[++i];
} else if(strcmp("--eval", argv[i]) == 0) {
args->eval = 1;
} else if(strcmp("--", argv[i]) == 0) {
diff --git a/src/couch/rebar.config.script b/src/couch/rebar.config.script
index ed5420f..59bd40f 100644
--- a/src/couch/rebar.config.script
+++ b/src/couch/rebar.config.script
@@ -132,29 +132,6 @@ end.
}
end.
-{CURL_CFLAGS, CURL_LDFLAGS} = case lists:keyfind(with_curl, 1, CouchConfig) of
- {with_curl, true} ->
- case os:type() of
- {win32, _} ->
- {
- "/DHAVE_CURL",
- "/DHAVE_CURL libcurl.lib"
- };
- {unix, freebsd} ->
- {
- "-DHAVE_CURL -I/usr/local/include",
- "-DHAVE_CURL -lcurl"
- };
- _ ->
- {
- "-DHAVE_CURL",
- "-DHAVE_CURL -lcurl"
- }
- end;
- _ ->
- {"", ""}
-end.
-
CouchJSSrc = case SMVsn of
"1.8.5" -> ["priv/couch_js/1.8.5/*.c"];
"60" -> ["priv/couch_js/60/*.cpp"];
@@ -164,13 +141,13 @@ end.
CouchJSEnv = case SMVsn of
"1.8.5" ->
[
- {"CFLAGS", JS_CFLAGS ++ " " ++ CURL_CFLAGS},
- {"LDFLAGS", JS_LDFLAGS ++ " " ++ CURL_LDFLAGS}
+ {"CFLAGS", JS_CFLAGS},
+ {"LDFLAGS", JS_LDFLAGS}
];
_ ->
[
- {"CXXFLAGS", JS_CFLAGS ++ " " ++ CURL_CFLAGS},
- {"LDFLAGS", JS_LDFLAGS ++ " " ++ CURL_LDFLAGS}
+ {"CXXFLAGS", JS_CFLAGS},
+ {"LDFLAGS", JS_LDFLAGS}
]
end.
diff --git a/test/javascript/cli_runner.js b/test/javascript/cli_runner.js
deleted file mode 100644
index a35348f..0000000
--- a/test/javascript/cli_runner.js
+++ /dev/null
@@ -1,63 +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.
-//
-
-/*
- * Quit current test execution if it is tagged as skipped or ported to elixir
- */
-function quitIfSkippedOrPorted() {
- if(couchTests.skip) {
- quit(2);
- }
-
- if(couchTests.elixir) {
- quit(3);
- }
-}
-
-/*
- * Futon test suite was designed to be able to run all tests populated into
- * couchTests. Here we should only be loading one test, so we'll pop the first
- * test off the list and run the test. If more than one item is loaded in the
- * test object, return an error.
- */
-function runTest() {
- CouchDB.reloadConfig();
- var count = 0;
- var start = new Date().getTime();
-
- for(var name in couchTests) {
- count++;
- }
-
- if (count !== 1) {
- console.log('Only one test per file is allowed.');
- quit(1);
- }
-
- try {
- // Add artificial wait for each test of 1 sec
- while (new Date().getTime() < start + 1200);
- couchTests[name]();
- quit(0);
- } catch(e) {
- console.log("\nError: " + e.message);
- fmtStack(e.stack);
- quit(1)
- }
-}
-
-quitIfSkippedOrPorted();
-
-waitForSuccess(CouchDB.isRunning, 'isRunning');
-
-runTest();
diff --git a/test/javascript/couch.js b/test/javascript/couch.js
deleted file mode 100644
index c325d68..0000000
--- a/test/javascript/couch.js
+++ /dev/null
@@ -1,557 +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.
-
-// A simple class to represent a database. Uses XMLHttpRequest to interface with
-// the CouchDB server.
-
-function CouchDB(name, httpHeaders, globalRequestOptions) {
- this.globalRequestOptions = globalRequestOptions || {}
- this.name = name;
- this.uri = "/" + encodeURIComponent(name) + "/";
-
- // The XMLHttpRequest object from the most recent request. Callers can
- // use this to check result http status and headers.
- this.last_req = null;
-
- this.request = function(method, uri, requestOptions) {
- requestOptions = requestOptions || {};
- requestOptions.headers = combine(requestOptions.headers, httpHeaders);
- requestOptions.url = globalRequestOptions;
- return CouchDB.request(method, uri, requestOptions);
- };
-
- // Creates the database on the server
- this.createDb = function() {
- this.last_req = this.request("PUT", this.uri);
- CouchDB.maybeThrowError(this.last_req);
- return JSON.parse(this.last_req.responseText);
- };
-
- // Deletes the database on the server
- this.deleteDb = function() {
- this.last_req = this.request("DELETE", this.uri + "?sync=true");
- if (this.last_req.status == 404) {
- return false;
- }
- CouchDB.maybeThrowError(this.last_req);
- return JSON.parse(this.last_req.responseText);
- };
-
- // Save a document to the database
- this.save = function(doc, options, http_headers) {
- if (doc._id == undefined) {
- doc._id = CouchDB.newUuids(1)[0];
- }
- http_headers = http_headers || {};
- this.last_req = this.request("PUT", this.uri +
- encodeURIComponent(doc._id) + encodeOptions(options),
- {body: JSON.stringify(doc), headers: http_headers});
- CouchDB.maybeThrowError(this.last_req);
- var result = JSON.parse(this.last_req.responseText);
- doc._rev = result.rev;
- return result;
- };
-
- // Open a document from the database
- this.open = function(docId, url_params, http_headers) {
- this.last_req = this.request("GET", this.uri + encodeURIComponent(docId)
- + encodeOptions(url_params), {headers:http_headers});
- if (this.last_req.status == 404) {
- return null;
- }
- CouchDB.maybeThrowError(this.last_req);
- return JSON.parse(this.last_req.responseText);
- };
-
- // Deletes a document from the database
- this.deleteDoc = function(doc) {
- this.last_req = this.request("DELETE", this.uri + encodeURIComponent(doc._id)
- + "?rev=" + doc._rev);
- CouchDB.maybeThrowError(this.last_req);
- var result = JSON.parse(this.last_req.responseText);
- doc._rev = result.rev; //record rev in input document
- doc._deleted = true;
- return result;
- };
-
- // Deletes an attachment from a document
- this.deleteDocAttachment = function(doc, attachment_name) {
- this.last_req = this.request("DELETE", this.uri + encodeURIComponent(doc._id)
- + "/" + attachment_name + "?rev=" + doc._rev);
- CouchDB.maybeThrowError(this.last_req);
- var result = JSON.parse(this.last_req.responseText);
- doc._rev = result.rev; //record rev in input document
- return result;
- };
-
- this.bulkSave = function(docs, options) {
- // first prepoulate the UUIDs for new documents
- var newCount = 0;
- for (var i=0; i<docs.length; i++) {
- if (docs[i]._id == undefined) {
- newCount++;
- }
- }
- var newUuids = CouchDB.newUuids(newCount);
- var newCount = 0;
- for (var i=0; i<docs.length; i++) {
- if (docs[i]._id == undefined) {
- docs[i]._id = newUuids.pop();
- }
- }
- var json = {"docs": docs};
- // put any options in the json
- for (var option in options) {
- json[option] = options[option];
- }
- this.last_req = this.request("POST", this.uri + "_bulk_docs", {
- body: JSON.stringify(json)
- });
- if (this.last_req.status == 417) {
- return {errors: JSON.parse(this.last_req.responseText)};
- }
- else {
- CouchDB.maybeThrowError(this.last_req);
- var results = JSON.parse(this.last_req.responseText);
- for (var i = 0; i < docs.length; i++) {
- if(results[i] && results[i].rev && results[i].ok) {
- docs[i]._rev = results[i].rev;
- }
- }
- return results;
- }
- };
-
- this.ensureFullCommit = function() {
- this.last_req = this.request("POST", this.uri + "_ensure_full_commit");
- CouchDB.maybeThrowError(this.last_req);
- return JSON.parse(this.last_req.responseText);
- };
-
- // Applies the map function to the contents of database and returns the results.
- this.query = function(mapFun, reduceFun, options, keys, language) {
- //var body = {language: language || "javascript"};
- var body = {}
- if(keys) {
- options.keys = keys ;
- }
- if (typeof(mapFun) != "string") {
- mapFun = mapFun.toSource ? mapFun.toSource() : "(" + mapFun.toString() + ")";
- }
- if ((!language) || language.toLowerCase() == "javascript") {
- mapFun = mapFun + "/" + "* avoid race cond " + (new Date().getTime()) + " *" + "/";
- }
- body.map = mapFun;
- if (reduceFun != null) {
- if (typeof(reduceFun) != "string") {
- reduceFun = reduceFun.toSource ?
- reduceFun.toSource() : "(" + reduceFun.toString() + ")";
- }
- body.reduce = reduceFun;
- }
- if (options && options.options != undefined) {
- body.options = options.options;
- delete options.options;
- }
- var ddoc = {
- language: language || "javascript",
- views: {
- view: body
- }
- };
- var ddoc_name = "_design/temp_" + get_random_string();
- this.last_req = this.request("PUT", this.uri + ddoc_name, {
- headers: {"Content-Type": "application/json"},
- body: JSON.stringify(ddoc)
- });
- CouchDB.maybeThrowError(this.last_req);
- var ddoc_result = JSON.parse(this.last_req.responseText)
- this.last_req = this.request("GET", this.uri + ddoc_name + "/_view/view"
- + encodeOptions(options));
- CouchDB.maybeThrowError(this.last_req);
- var query_result = JSON.parse(this.last_req.responseText);
- var res = this.request("DELETE", this.uri + ddoc_name + '?rev=' + ddoc_result.rev);
-
- return query_result;
- };
-
- this.view = function(viewname, options, keys) {
- var viewParts = viewname.split('/');
- var viewPath = this.uri + "_design/" + viewParts[0] + "/_view/"
- + viewParts[1] + encodeOptions(options);
- if(!keys) {
- this.last_req = this.request("GET", viewPath);
- } else {
- this.last_req = this.request("POST", viewPath, {
- headers: {"Content-Type": "application/json"},
- body: JSON.stringify({keys:keys})
- });
- }
- if (this.last_req.status == 404) {
- return null;
- }
- CouchDB.maybeThrowError(this.last_req);
- return JSON.parse(this.last_req.responseText);
- };
-
- // gets information about the database
- this.info = function() {
- this.last_req = this.request("GET", this.uri);
- CouchDB.maybeThrowError(this.last_req);
- return JSON.parse(this.last_req.responseText);
- };
-
- // gets information about a design doc
- this.designInfo = function(docid) {
- this.last_req = this.request("GET", this.uri + docid + "/_info");
- CouchDB.maybeThrowError(this.last_req);
- return JSON.parse(this.last_req.responseText);
- };
-
- this.allDocs = function(options,keys) {
- if(!keys) {
- this.last_req = this.request("GET", this.uri + "_all_docs"
- + encodeOptions(options));
- } else {
- this.last_req = this.request("POST", this.uri + "_all_docs"
- + encodeOptions(options), {
- headers: {"Content-Type": "application/json"},
- body: JSON.stringify({keys:keys})
- });
- }
- CouchDB.maybeThrowError(this.last_req);
- return JSON.parse(this.last_req.responseText);
- };
-
- this.designDocs = function() {
- return this.allDocs({startkey:"_design", endkey:"_design0"});
- };
-
- this.changes = function(options) {
- this.last_req = this.request("GET", this.uri + "_changes"
- + encodeOptions(options));
- CouchDB.maybeThrowError(this.last_req);
- return JSON.parse(this.last_req.responseText);
- };
-
- this.compact = function() {
- this.last_req = this.request("POST", this.uri + "_compact");
- CouchDB.maybeThrowError(this.last_req);
- return JSON.parse(this.last_req.responseText);
- };
-
- this.viewCleanup = function() {
- this.last_req = this.request("POST", this.uri + "_view_cleanup");
- CouchDB.maybeThrowError(this.last_req);
- return JSON.parse(this.last_req.responseText);
- };
-
- this.setDbProperty = function(propId, propValue) {
- this.last_req = this.request("PUT", this.uri + propId,{
- body:JSON.stringify(propValue)
- });
- CouchDB.maybeThrowError(this.last_req);
- return JSON.parse(this.last_req.responseText);
- };
-
- this.getDbProperty = function(propId) {
- this.last_req = this.request("GET", this.uri + propId);
- CouchDB.maybeThrowError(this.last_req);
- return JSON.parse(this.last_req.responseText);
- };
-
- this.setSecObj = function(secObj) {
- this.last_req = this.request("PUT", this.uri + "_security",{
- body:JSON.stringify(secObj)
- });
- CouchDB.maybeThrowError(this.last_req);
- return JSON.parse(this.last_req.responseText);
- };
-
- this.getSecObj = function() {
- this.last_req = this.request("GET", this.uri + "_security");
- CouchDB.maybeThrowError(this.last_req);
- return JSON.parse(this.last_req.responseText);
- };
-
- // Convert a options object to an url query string.
- // ex: {key:'value',key2:'value2'} becomes '?key="value"&key2="value2"'
- function encodeOptions(options) {
- var buf = [];
- if (typeof(options) == "object" && options !== null) {
- for (var name in options) {
- if (!options.hasOwnProperty(name)) { continue; };
- var value = options[name];
- if (name == "key" || name == "keys" || name == "startkey" || name == "endkey" || (name == "open_revs" && value !== "all")) {
- value = toJSON(value);
- }
- buf.push(encodeURIComponent(name) + "=" + encodeURIComponent(value));
- }
- }
- if (!buf.length) {
- return "";
- }
- return "?" + buf.join("&");
- }
-
- function toJSON(obj) {
- return obj !== null ? JSON.stringify(obj) : null;
- }
-
- function combine(object1, object2) {
- if (!object2) {
- return object1;
- }
- if (!object1) {
- return object2;
- }
-
- for (var name in object2) {
- object1[name] = object2[name];
- }
- return object1;
- }
-
-}
-
-// this is the XMLHttpRequest object from last request made by the following
-// CouchDB.* functions (except for calls to request itself).
-// Use this from callers to check HTTP status or header values of requests.
-CouchDB.last_req = null;
-CouchDB.urlPrefix = '';
-
-CouchDB.login = function(name, password) {
- CouchDB.last_req = CouchDB.request("POST", "/_session", {
- headers: {"Content-Type": "application/x-www-form-urlencoded",
- "X-CouchDB-WWW-Authenticate": "Cookie"},
- body: "name=" + encodeURIComponent(name) + "&password="
- + encodeURIComponent(password)
- });
- return JSON.parse(CouchDB.last_req.responseText);
-}
-
-CouchDB.logout = function() {
- CouchDB.last_req = CouchDB.request("DELETE", "/_session", {
- headers: {"Content-Type": "application/x-www-form-urlencoded",
- "X-CouchDB-WWW-Authenticate": "Cookie"}
- });
- return JSON.parse(CouchDB.last_req.responseText);
-};
-
-CouchDB.session = function(options) {
- options = options || {};
- CouchDB.last_req = CouchDB.request("GET", "/_session", options);
- CouchDB.maybeThrowError(CouchDB.last_req);
- return JSON.parse(CouchDB.last_req.responseText);
-};
-
-CouchDB.allDbs = function() {
- CouchDB.last_req = CouchDB.request("GET", "/_all_dbs");
- CouchDB.maybeThrowError(CouchDB.last_req);
- return JSON.parse(CouchDB.last_req.responseText);
-};
-
-CouchDB.allDesignDocs = function() {
- var ddocs = {}, dbs = CouchDB.allDbs();
- for (var i=0; i < dbs.length; i++) {
- var db = new CouchDB(dbs[i]);
- ddocs[dbs[i]] = db.designDocs();
- };
- return ddocs;
-};
-
-CouchDB.getVersion = function() {
- CouchDB.last_req = CouchDB.request("GET", "/");
- CouchDB.maybeThrowError(CouchDB.last_req);
- return JSON.parse(CouchDB.last_req.responseText).version;
-};
-
-CouchDB.reloadConfig = function() {
- // diabled until cluser port gets /_config
- return {};
- CouchDB.last_req = CouchDB.request("POST", "/_config/_reload");
- CouchDB.maybeThrowError(CouchDB.last_req);
- return JSON.parse(CouchDB.last_req.responseText);
-};
-
-CouchDB.replicate = function(source, target, rep_options) {
- rep_options = rep_options || {};
- var headers = rep_options.headers || {};
- var body = rep_options.body || {};
- body.source = source;
- body.target = target;
- CouchDB.last_req = CouchDB.request("POST", "/_replicate", {
- headers: headers,
- body: JSON.stringify(body)
- });
- CouchDB.maybeThrowError(CouchDB.last_req);
- return JSON.parse(CouchDB.last_req.responseText);
-};
-
-CouchDB.newXhr = function() {
- if (typeof(XMLHttpRequest) != "undefined") {
- return new XMLHttpRequest();
- } else if (typeof(ActiveXObject) != "undefined") {
- return new ActiveXObject("Microsoft.XMLHTTP");
- } else {
- throw new Error("No XMLHTTPRequest support detected");
- }
-};
-
-CouchDB.xhrbody = function(xhr) {
- if (xhr.responseText) {
- return xhr.responseText;
- } else if (xhr.body) {
- return xhr.body
- } else {
- throw new Error("No XMLHTTPRequest support detected");
- }
-}
-
-CouchDB.xhrheader = function(xhr, header) {
- if(xhr.getResponseHeader) {
- return xhr.getResponseHeader(header);
- } else if(xhr.headers) {
- return xhr.headers[header] || null;
- } else {
- throw new Error("No XMLHTTPRequest support detected");
- }
-}
-
-CouchDB.proxyUrl = function(uri) {
- if(uri.substr(0, CouchDB.protocol.length) != CouchDB.protocol) {
- uri = CouchDB.urlPrefix + uri;
- }
- return uri;
-}
-
-CouchDB.request = function(method, uri, options) {
- options = typeof(options) == 'object' ? options : {};
- options.headers = typeof(options.headers) == 'object' ? options.headers : {};
- options.headers["Content-Type"] = options.headers["Content-Type"] || options.headers["content-type"] || "application/json";
- options.headers["Accept"] = options.headers["Accept"] || options.headers["accept"] || "application/json";
- var req = CouchDB.newXhr();
- uri = CouchDB.proxyUrl(uri);
-
- if (options.url) {
- var params = '';
- for (var key in options.url) {
- var value = options.url[key]
- params += key + '=' + value + '&'
- }
- // if uri already has a ? append with &
- if (uri.indexOf('?') === -1) {
- uri += '?' + params;
- } else {
- uri += '&' + params;
- }
- }
- // console.log(uri);
- // console.log(JSON.stringify(options, null, 2));
- req.open(method, uri, false);
- if (options.headers) {
- var headers = options.headers;
- for (var headerName in headers) {
- if (!headers.hasOwnProperty(headerName)) { continue; }
- req.setRequestHeader(headerName, headers[headerName]);
- }
- }
- req.send(options.body || "");
- return req;
-};
-
-CouchDB.requestStats = function(path, test) {
- var query_arg = "";
- if(test !== null) {
- query_arg = "?flush=true";
- }
-
- var url = "/_node/_local/_stats/" + path.join("/") + query_arg;
- var stat = CouchDB.request("GET", url).responseText;
- return JSON.parse(stat);
-};
-
-CouchDB.uuids_cache = [];
-
-CouchDB.newUuids = function(n, buf) {
- buf = buf || 100;
- if (CouchDB.uuids_cache.length >= n) {
- var uuids = CouchDB.uuids_cache.slice(CouchDB.uuids_cache.length - n);
- if(CouchDB.uuids_cache.length - n == 0) {
- CouchDB.uuids_cache = [];
- } else {
- CouchDB.uuids_cache =
- CouchDB.uuids_cache.slice(0, CouchDB.uuids_cache.length - n);
- }
- return uuids;
- } else {
- CouchDB.last_req = CouchDB.request("GET", "/_uuids?count=" + (buf + n));
- CouchDB.maybeThrowError(CouchDB.last_req);
- var result = JSON.parse(CouchDB.last_req.responseText);
- CouchDB.uuids_cache =
- CouchDB.uuids_cache.concat(result.uuids.slice(0, buf));
- return result.uuids.slice(buf);
- }
-};
-
-CouchDB.maybeThrowError = function(req) {
- if (req.status >= 400) {
- try {
- var result = JSON.parse(req.responseText);
- } catch (ParseError) {
- var result = {error:"unknown", reason:req.responseText};
- }
-
- throw (new CouchError(result));
- }
-}
-
-CouchDB.params = function(options) {
- options = options || {};
- var returnArray = [];
- for(var key in options) {
- var value = options[key];
- returnArray.push(key + "=" + value);
- }
- return returnArray.join("&");
-};
-// Used by replication test
-if (typeof window == 'undefined' || !window) {
- var hostRE = RegExp("https?://([^\/]+)");
- var getter = function () {
- return (new CouchHTTP).base_url.match(hostRE)[1];
- };
- if(Object.defineProperty) {
- Object.defineProperty(CouchDB, "host", {
- get : getter,
- enumerable : true
- });
- } else {
- CouchDB.__defineGetter__("host", getter);
- }
- CouchDB.protocol = "http://";
- CouchDB.inBrowser = false;
-} else {
- CouchDB.host = window.location.host;
- CouchDB.inBrowser = true;
- CouchDB.protocol = window.location.protocol + "//";
-}
-
-// Turns an {error: ..., reason: ...} response into an Error instance
-function CouchError(error) {
- var inst = new Error(error.reason);
- inst.name = 'CouchError';
- inst.error = error.error;
- inst.reason = error.reason;
- return inst;
-}
-CouchError.prototype.constructor = CouchError;
diff --git a/test/javascript/couch_http.js b/test/javascript/couch_http.js
deleted file mode 100644
index c44ce28..0000000
--- a/test/javascript/couch_http.js
+++ /dev/null
@@ -1,73 +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.
-
-(function() {
- if(typeof(CouchHTTP) != "undefined") {
- CouchHTTP.prototype.open = function(method, url, async) {
- if(!/^\s*http:\/\//.test(url)) {
- if(/^\//.test(url)) {
- // The couch.uri file (base_url) has a trailing slash
- url = this.base_url + url.slice(1);
- } else {
- url = this.base_url + url;
- }
- }
-
- return this._open(method, url, async);
- };
-
- CouchHTTP.prototype.setRequestHeader = function(name, value) {
- // Drop content-length headers because cURL will set it for us
- // based on body length
- if(name.toLowerCase().replace(/^\s+|\s+$/g, '') != "content-length") {
- this._setRequestHeader(name, value);
- }
- }
-
- CouchHTTP.prototype.send = function(body) {
- this._send(body || "");
- var headers = {};
- this._headers.forEach(function(hdr) {
- var pair = hdr.split(":");
- var name = pair.shift();
- headers[name] = pair.join(":").replace(/^\s+|\s+$/g, "");
- });
- this.headers = headers;
- };
-
- CouchHTTP.prototype.getResponseHeader = function(name) {
- for(var hdr in this.headers) {
- if(hdr.toLowerCase() == name.toLowerCase()) {
- return this.headers[hdr];
- }
- }
- return null;
- };
- }
-})();
-
-CouchDB.urlPrefix = "";
-CouchDB.newXhr = function() {
- return new CouchHTTP();
-};
-
-CouchDB.xhrheader = function(xhr, header) {
- if(typeof(xhr) == "CouchHTTP") {
- return xhr.getResponseHeader(header);
- } else {
- return xhr.headers[header];
- }
-}
-
-CouchDB.xhrbody = function(xhr) {
- return xhr.responseText || xhr.body;
-}
diff --git a/test/javascript/couch_test_runner.js b/test/javascript/couch_test_runner.js
deleted file mode 100644
index 7fe8ed3..0000000
--- a/test/javascript/couch_test_runner.js
+++ /dev/null
@@ -1,489 +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.
-
-// *********************** Test Framework of Sorts ************************* //
-
-
-function loadScript(url) {
- // disallow loading remote URLs
- var re = /^[a-z0-9_]+(\/[a-z0-9_]+)*\.js#?$/;
- if (!re.test(url)) {
- throw "Not loading remote test scripts";
- }
- if (typeof document != "undefined") document.write('<script src="'+url+'"></script>');
-};
-
-function patchTest(fun) {
- var source = fun.toString();
- var output = "";
- var i = 0;
- var testMarker = "T(";
- while (i < source.length) {
- var testStart = source.indexOf(testMarker, i);
- if (testStart == -1) {
- output = output + source.substring(i, source.length);
- break;
- }
- var testEnd = source.indexOf(");", testStart);
- var testCode = source.substring(testStart + testMarker.length, testEnd);
- output += source.substring(i, testStart) + "T(" + testCode + "," + JSON.stringify(testCode);
- i = testEnd;
- }
- try {
- return eval("(" + output + ")");
- } catch (e) {
- return null;
- }
-}
-
-function runAllTests() {
- var rows = $("#tests tbody.content tr");
- $("td", rows).text("");
- $("td.status", rows).removeClass("error").removeClass("failure").removeClass("success").text("not run");
- var offset = 0;
- function runNext() {
- if (offset < rows.length) {
- var row = rows.get(offset);
- runTest($("th button", row).get(0), function() {
- offset += 1;
- setTimeout(runNext, 100);
- }, false, true);
- } else {
- saveTestReport();
- }
- }
- runNext();
-}
-
-var numFailures = 0;
-var currentRow = null;
-
-function runTest(button, callback, debug, noSave) {
-
- // offer to save admins
- if (currentRow != null) {
- alert("Can not run multiple tests simultaneously.");
- return;
- }
- var row = currentRow = $(button).parents("tr").get(0);
- $("td.status", row).removeClass("error").removeClass("failure").removeClass("success");
- $("td", row).text("");
- $("#toolbar li.current").text("Running: "+row.id);
- var testFun = couchTests[row.id];
- function run() {
- numFailures = 0;
- var start = new Date().getTime();
- try {
- if (debug == undefined || !debug) {
- testFun = patchTest(testFun) || testFun;
- }
- testFun(debug);
- var status = numFailures > 0 ? "failure" : "success";
- } catch (e) {
- var status = "error";
- if ($("td.details ol", row).length == 0) {
- $("<ol></ol>").appendTo($("td.details", row));
- }
- $("<li><b>Exception raised:</b> <code class='error'></code></li>")
- .find("code").text(JSON.stringify(e)).end()
- .appendTo($("td.details ol", row));
- if (debug) {
- currentRow = null;
- throw e;
- }
- }
- if ($("td.details ol", row).length) {
- $("<a href='#'>Run with debugger</a>").click(function() {
- runTest(this, undefined, true);
- }).prependTo($("td.details ol", row));
- }
- var duration = new Date().getTime() - start;
- $("td.status", row).removeClass("running").addClass(status).text(status);
- $("td.duration", row).text(duration + "ms");
- $("#toolbar li.current").text("Finished: "+row.id);
- updateTestsFooter();
- currentRow = null;
- if (callback) callback();
- if (!noSave) saveTestReport();
- }
- $("td.status", row).addClass("running").text("running…");
- setTimeout(run, 100);
-}
-
-function showSource(cell) {
- var name = $(cell).text();
- var win = window.open("", name, "width=700,height=500,resizable=yes,scrollbars=yes");
- win.document.location = "script/test/" + name + ".js";
-}
-
-var readyToRun;
-function setupAdminParty(fun) {
- if (readyToRun) {
- fun();
- } else {
- function removeAdmins(confs, doneFun) {
- // iterate through the config and remove current user last
- // current user is at front of list
- var remove = confs.pop();
- if (remove) {
- $.couch.config({
- success : function() {
- removeAdmins(confs, doneFun);
- }
- }, "admins", remove[0], null);
- } else {
- doneFun();
- }
- };
- $.couch.session({
- success : function(resp) {
- var userCtx = resp.userCtx;
- if (userCtx.name && userCtx.roles.indexOf("_admin") != -1) {
- // admin but not admin party. dialog offering to make admin party
- $.showDialog("dialog/_admin_party.html", {
- submit: function(data, callback) {
- $.couch.config({
- success : function(conf) {
- var meAdmin, adminConfs = [];
- for (var name in conf) {
- if (name == userCtx.name) {
- meAdmin = [name, conf[name]];
- } else {
- adminConfs.push([name, conf[name]]);
- }
- }
- adminConfs.unshift(meAdmin);
- removeAdmins(adminConfs, function() {
- callback();
- $.futon.session.sidebar();
- readyToRun = true;
- setTimeout(fun, 500);
- });
- }
- }, "admins");
- }
- });
- } else if (userCtx.roles.indexOf("_admin") != -1) {
- // admin party!
- readyToRun = true;
- fun();
- } else {
- // not an admin
- alert("Error: You need to be an admin to run the tests.");
- };
- }
- });
- }
-};
-
-function updateTestsListing() {
- for (var name in couchTests) {
- var testFunction = couchTests[name];
- var row = $("<tr><th></th><td></td><td></td><td></td></tr>")
- .find("th").text(name).attr("title", "Show source").click(function() {
- showSource(this);
- }).end()
- .find("td:nth(0)").addClass("status").text("not run").end()
- .find("td:nth(1)").addClass("duration").end()
- .find("td:nth(2)").addClass("details").end();
- $("<button type='button' class='run' title='Run test'></button>").click(function() {
- this.blur();
- var self = this;
- // check for admin party
- setupAdminParty(function() {
- runTest(self);
- });
- return false;
- }).prependTo(row.find("th"));
- row.attr("id", name).appendTo("#tests tbody.content");
- }
- $("#tests tr").removeClass("odd").filter(":odd").addClass("odd");
- updateTestsFooter();
-}
-
-function updateTestsFooter() {
- var tests = $("#tests tbody.content tr td.status");
- var testsRun = tests.filter(".success, .error, .failure");
- var testsFailed = testsRun.not(".success");
- var totalDuration = 0;
- $("#tests tbody.content tr td.duration:contains('ms')").each(function() {
- var text = $(this).text();
- totalDuration += parseInt(text.substr(0, text.length - 2), 10);
- });
- $("#tests tbody.footer td").html("<span>"+testsRun.length + " of " + tests.length +
- " test(s) run, " + testsFailed.length + " failures (" +
- totalDuration + " ms)</span> ");
-}
-
-// make report and save to local db
-// display how many reports need replicating to the mothership
-// have button to replicate them
-
-function saveTestReport(report) {
- var report = makeTestReport();
- if (report) {
- var db = $.couch.db("test_suite_reports");
- var saveReport = function(db_info) {
- report.db = db_info;
- $.couch.info({success : function(node_info) {
- report.node = node_info;
- db.saveDoc(report);
- }});
- };
- var createDb = function() {
- db.create({success: function() {
- db.info({success:saveReport});
- }});
- };
- db.info({error: createDb, success:saveReport});
- }
-};
-
-function makeTestReport() {
- var report = {};
- report.summary = $("#tests tbody.footer td").text();
- report.platform = testPlatform();
- var date = new Date();
- report.timestamp = date.getTime();
- report.timezone = date.getTimezoneOffset();
- report.tests = [];
- $("#tests tbody.content tr").each(function() {
- var status = $("td.status", this).text();
- if (status != "not run") {
- var test = {};
- test.name = this.id;
- test.status = status;
- test.duration = parseInt($("td.duration", this).text());
- test.details = [];
- $("td.details li", this).each(function() {
- test.details.push($(this).text());
- });
- if (test.details.length == 0) {
- delete test.details;
- }
- report.tests.push(test);
- }
- });
- if (report.tests.length > 0) return report;
-};
-
-function testPlatform() {
- var b = $.browser;
- var bs = ["mozilla", "msie", "opera", "safari"];
- for (var i=0; i < bs.length; i++) {
- if (b[bs[i]]) {
- return {"browser" : bs[i], "version" : b.version};
- }
- };
- return {"browser" : "undetected"};
-}
-
-
-function reportTests() {
- // replicate the database to couchdb.couchdb.org
-}
-
-// Use T to perform a test that returns false on failure and if the test fails,
-// display the line that failed.
-// Example:
-// T(MyValue==1);
-function T(arg1, arg2, testName) {
- if (!arg1) {
- if (currentRow) {
- if ($("td.details ol", currentRow).length == 0) {
- $("<ol></ol>").appendTo($("td.details", currentRow));
- }
- var message = (arg2 != null ? arg2 : arg1).toString();
- $("<li><b>Assertion " + (testName ? "'" + testName + "'" : "") + " failed:</b> <code class='failure'></code></li>")
- .find("code").text(message).end()
- .appendTo($("td.details ol", currentRow));
- }
- numFailures += 1;
- }
-}
-
-function TIsnull(actual, testName) {
- T(actual === null, "expected 'null', got '"
- + repr(actual) + "'", testName);
-}
-
-function TEquals(expected, actual, testName) {
- T(equals(expected, actual), "expected '" + repr(expected) +
- "', got '" + repr(actual) + "'", testName);
-}
-
-function TNotEquals(expected, actual, testName) {
- T(notEquals(expected, actual), "expected != '" + repr(expected) +
- "', got '" + repr(actual) + "'", testName);
-}
-
-function TEqualsIgnoreCase(expected, actual, testName) {
- T(equals(expected.toUpperCase(), actual.toUpperCase()), "expected '" + repr(expected) +
- "', got '" + repr(actual) + "'", testName);
-}
-
-function equals(a,b) {
- if (a === b) return true;
- try {
- return repr(a) === repr(b);
- } catch (e) {
- return false;
- }
-}
-
-function notEquals(a,b) {
- if (a != b) return true;
- return false;
-}
-
-function repr(val) {
- if (val === undefined) {
- return null;
- } else if (val === null) {
- return "null";
- } else {
- return JSON.stringify(val);
- }
-}
-
-function makeDocs(start, end, templateDoc) {
- var templateDocSrc = templateDoc ? JSON.stringify(templateDoc) : "{}";
- if (end === undefined) {
- end = start;
- start = 0;
- }
- var docs = [];
- for (var i = start; i < end; i++) {
- var newDoc = eval("(" + templateDocSrc + ")");
- newDoc._id = (i).toString();
- newDoc.integer = i;
- newDoc.string = (i).toString();
- docs.push(newDoc);
- }
- return docs;
-}
-
-function run_on_modified_server(settings, fun) {
- var xhr = CouchDB.request("GET", "/_membership");
- var nodes = JSON.parse(xhr.responseText).all_nodes;
- try {
- // set the settings
- for(var i=0; i < settings.length; i++) {
- var s = settings[i];
- for (var n in nodes) {
- xhr = CouchDB.request("PUT", "/_node/" + nodes[n] + "/_config/" + s.section + "/" + s.key, {
- body: JSON.stringify(s.value),
- headers: {"X-Couch-Persist": "false"}
- });
- CouchDB.maybeThrowError(xhr);
- if (typeof s[nodes[n]] === 'undefined') {
- s[nodes[n]] = {};
- }
- s[nodes[n]] = xhr.responseText;
- }
- }
- // run the thing
- fun();
- } finally {
- // unset the settings
- for(var j=0; j < i; j++) {
- for (var n in nodes) {
- var s = settings[j];
- if(s[nodes[n]] == "\"\"\n") { // unset value
- CouchDB.request("DELETE", "/_node/" + nodes[n] + "/_config/" + s.section + "/" + s.key, {
- headers: {"X-Couch-Persist": "false"}
- });
- } else {
- CouchDB.request("PUT", "/_node/" + nodes[n] + "/_config/" + s.section + "/" + s.key, {
- body: s[nodes[n]],
- headers: {"X-Couch-Persist": "false"}
- });
- }
- }
- }
- }
-}
-
-function stringFun(fun) {
- var string = fun.toSource ? fun.toSource() : "(" + fun.toString() + ")";
- return string;
-}
-
-function waitForSuccess(fun, tag) {
- var start = new Date();
- while(true) {
- if (new Date() - start > 5000) {
- throw("timeout: "+tag);
- } else {
- try {
- fun();
- break;
- } catch (e) {
- log(e)
- }
- // sync http req allow async req to happen
- try {
- CouchDB.request("GET", "/test_suite_db/?tag="+encodeURIComponent(tag));
- } catch (e) {}
- }
- }
-}
-
-// legacy functions for CouchDB < 1.2.0
-// we keep them to make sure we keep BC
-CouchDB.user_prefix = "org.couchdb.user:";
-
-CouchDB.prepareUserDoc = function(user_doc, new_password) {
- user_doc._id = user_doc._id || CouchDB.user_prefix + user_doc.name;
- if (new_password) {
- user_doc.password = new_password;
- }
- user_doc.type = "user";
- if (!user_doc.roles) {
- user_doc.roles = [];
- }
- return user_doc;
-};
-
-function get_random_string() {
- return Math.random()
- .toString(36)
- .replace(/[^a-z]+/g, '')
- .substr(0, 8);
-}
-
-function get_random_db_name() {
- return "test_suite_db_" + get_random_string()
-}
-
-// for Heisenbug-prone spots: retry n times (e.g. quora not met immediately)
-// if the problem still persists afterwards, we need sth else (similar to e.g. webdriver)
-function retry_part(fct, n, duration) {
- n = n || 3;
- duration = (duration == undefined ? 100 : duration);
- for(var i=1; i<=n; i++){
- try {
- return fct();
- }catch(e){
- if(i<n){
- // wait
- sleep(duration);
- }else{
- throw e;
- }
- }
- }
-}
-
-function wait(ms) {
- sleep(ms);
-}
diff --git a/test/javascript/couchdb.uri b/test/javascript/couchdb.uri
deleted file mode 100644
index 99c8819..0000000
--- a/test/javascript/couchdb.uri
+++ /dev/null
@@ -1 +0,0 @@
-http://127.0.0.1:15984/
diff --git a/test/javascript/json2.js b/test/javascript/json2.js
deleted file mode 100644
index a1a3b17..0000000
--- a/test/javascript/json2.js
+++ /dev/null
@@ -1,482 +0,0 @@
-/*
- http://www.JSON.org/json2.js
- 2010-03-20
-
- Public Domain.
-
- NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
-
- See http://www.JSON.org/js.html
-
-
- This code should be minified before deployment.
- See http://javascript.crockford.com/jsmin.html
-
- USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
- NOT CONTROL.
-
-
- This file creates a global JSON object containing two methods: stringify
- and parse.
-
- JSON.stringify(value, replacer, space)
- value any JavaScript value, usually an object or array.
-
- replacer an optional parameter that determines how object
- values are stringified for objects. It can be a
- function or an array of strings.
-
- space an optional parameter that specifies the indentation
- of nested structures. If it is omitted, the text will
- be packed without extra whitespace. If it is a number,
- it will specify the number of spaces to indent at each
- level. If it is a string (such as '\t' or ' '),
- it contains the characters used to indent at each level.
-
- This method produces a JSON text from a JavaScript value.
-
- When an object value is found, if the object contains a toJSON
- method, its toJSON method will be called and the result will be
- stringified. A toJSON method does not serialize: it returns the
- value represented by the name/value pair that should be serialized,
- or undefined if nothing should be serialized. The toJSON method
- will be passed the key associated with the value, and this will be
- bound to the value
-
- For example, this would serialize Dates as ISO strings.
-
- Date.prototype.toJSON = function (key) {
- function f(n) {
- // Format integers to have at least two digits.
- return n < 10 ? '0' + n : n;
- }
-
- return this.getUTCFullYear() + '-' +
- f(this.getUTCMonth() + 1) + '-' +
- f(this.getUTCDate()) + 'T' +
- f(this.getUTCHours()) + ':' +
- f(this.getUTCMinutes()) + ':' +
- f(this.getUTCSeconds()) + 'Z';
- };
-
- You can provide an optional replacer method. It will be passed the
- key and value of each member, with this bound to the containing
- object. The value that is returned from your method will be
- serialized. If your method returns undefined, then the member will
- be excluded from the serialization.
-
- If the replacer parameter is an array of strings, then it will be
- used to select the members to be serialized. It filters the results
- such that only members with keys listed in the replacer array are
- stringified.
-
- Values that do not have JSON representations, such as undefined or
- functions, will not be serialized. Such values in objects will be
- dropped; in arrays they will be replaced with null. You can use
- a replacer function to replace those with JSON values.
- JSON.stringify(undefined) returns undefined.
-
- The optional space parameter produces a stringification of the
- value that is filled with line breaks and indentation to make it
- easier to read.
-
- If the space parameter is a non-empty string, then that string will
- be used for indentation. If the space parameter is a number, then
- the indentation will be that many spaces.
-
- Example:
-
- text = JSON.stringify(['e', {pluribus: 'unum'}]);
- // text is '["e",{"pluribus":"unum"}]'
-
-
- text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
- // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
-
- text = JSON.stringify([new Date()], function (key, value) {
- return this[key] instanceof Date ?
- 'Date(' + this[key] + ')' : value;
- });
- // text is '["Date(---current time---)"]'
-
-
- JSON.parse(text, reviver)
- This method parses a JSON text to produce an object or array.
- It can throw a SyntaxError exception.
-
- The optional reviver parameter is a function that can filter and
- transform the results. It receives each of the keys and values,
- and its return value is used instead of the original value.
- If it returns what it received, then the structure is not modified.
- If it returns undefined then the member is deleted.
-
- Example:
-
- // Parse the text. Values that look like ISO date strings will
- // be converted to Date objects.
-
- myData = JSON.parse(text, function (key, value) {
- var a;
- if (typeof value === 'string') {
- a =
-/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
- if (a) {
- return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
- +a[5], +a[6]));
- }
- }
- return value;
- });
-
- myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
- var d;
- if (typeof value === 'string' &&
- value.slice(0, 5) === 'Date(' &&
- value.slice(-1) === ')') {
- d = new Date(value.slice(5, -1));
- if (d) {
- return d;
- }
- }
- return value;
- });
-
-
- This is a reference implementation. You are free to copy, modify, or
- redistribute.
-*/
-
-/*jslint evil: true, strict: false */
-
-/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
- call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
- getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
- lastIndex, length, parse, prototype, push, replace, slice, stringify,
- test, toJSON, toString, valueOf
-*/
-
-
-// Create a JSON object only if one does not already exist. We create the
-// methods in a closure to avoid creating global variables.
-
-if (!this.JSON) {
- this.JSON = {};
-}
-
-(function () {
-
- function f(n) {
- // Format integers to have at least two digits.
- return n < 10 ? '0' + n : n;
- }
-
- if (typeof Date.prototype.toJSON !== 'function') {
-
- Date.prototype.toJSON = function (key) {
-
- return isFinite(this.valueOf()) ?
- this.getUTCFullYear() + '-' +
- f(this.getUTCMonth() + 1) + '-' +
- f(this.getUTCDate()) + 'T' +
- f(this.getUTCHours()) + ':' +
- f(this.getUTCMinutes()) + ':' +
- f(this.getUTCSeconds()) + 'Z' : null;
- };
-
- String.prototype.toJSON =
- Number.prototype.toJSON =
- Boolean.prototype.toJSON = function (key) {
- return this.valueOf();
- };
- }
-
- var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
- escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
- gap,
- indent,
- meta = { // table of character substitutions
- '\b': '\\b',
- '\t': '\\t',
- '\n': '\\n',
- '\f': '\\f',
- '\r': '\\r',
- '"' : '\\"',
- '\\': '\\\\'
- },
- rep;
-
-
- function quote(string) {
-
-// If the string contains no control characters, no quote characters, and no
-// backslash characters, then we can safely slap some quotes around it.
-// Otherwise we must also replace the offending characters with safe escape
-// sequences.
-
- escapable.lastIndex = 0;
- return escapable.test(string) ?
- '"' + string.replace(escapable, function (a) {
- var c = meta[a];
- return typeof c === 'string' ? c :
- '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
- }) + '"' :
- '"' + string + '"';
- }
-
-
- function str(key, holder) {
-
-// Produce a string from holder[key].
-
- var i, // The loop counter.
- k, // The member key.
- v, // The member value.
- length,
- mind = gap,
- partial,
- value = holder[key];
-
-// If the value has a toJSON method, call it to obtain a replacement value.
-
- if (value && typeof value === 'object' &&
- typeof value.toJSON === 'function') {
- value = value.toJSON(key);
- }
-
-// If we were called with a replacer function, then call the replacer to
-// obtain a replacement value.
-
- if (typeof rep === 'function') {
- value = rep.call(holder, key, value);
- }
-
-// What happens next depends on the value's type.
-
- switch (typeof value) {
- case 'string':
- return quote(value);
-
- case 'number':
-
-// JSON numbers must be finite. Encode non-finite numbers as null.
-
- return isFinite(value) ? String(value) : 'null';
-
- case 'boolean':
- case 'null':
-
-// If the value is a boolean or null, convert it to a string. Note:
-// typeof null does not produce 'null'. The case is included here in
-// the remote chance that this gets fixed someday.
-
- return String(value);
-
-// If the type is 'object', we might be dealing with an object or an array or
-// null.
-
- case 'object':
-
-// Due to a specification blunder in ECMAScript, typeof null is 'object',
-// so watch out for that case.
-
- if (!value) {
- return 'null';
- }
-
-// Make an array to hold the partial results of stringifying this object value.
-
- gap += indent;
- partial = [];
-
-// Is the value an array?
-
- if (Object.prototype.toString.apply(value) === '[object Array]') {
-
-// The value is an array. Stringify every element. Use null as a placeholder
-// for non-JSON values.
-
- length = value.length;
- for (i = 0; i < length; i += 1) {
- partial[i] = str(i, value) || 'null';
- }
-
-// Join all of the elements together, separated with commas, and wrap them in
-// brackets.
-
- v = partial.length === 0 ? '[]' :
- gap ? '[\n' + gap +
- partial.join(',\n' + gap) + '\n' +
- mind + ']' :
- '[' + partial.join(',') + ']';
- gap = mind;
- return v;
- }
-
-// If the replacer is an array, use it to select the members to be stringified.
-
- if (rep && typeof rep === 'object') {
- length = rep.length;
- for (i = 0; i < length; i += 1) {
- k = rep[i];
- if (typeof k === 'string') {
- v = str(k, value);
- if (v) {
- partial.push(quote(k) + (gap ? ': ' : ':') + v);
- }
- }
- }
- } else {
-
-// Otherwise, iterate through all of the keys in the object.
-
- for (k in value) {
- if (Object.hasOwnProperty.call(value, k)) {
- v = str(k, value);
- if (v) {
- partial.push(quote(k) + (gap ? ': ' : ':') + v);
- }
- }
- }
- }
-
-// Join all of the member texts together, separated with commas,
-// and wrap them in braces.
-
- v = partial.length === 0 ? '{}' :
- gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
- mind + '}' : '{' + partial.join(',') + '}';
- gap = mind;
- return v;
- }
- }
-
-// If the JSON object does not yet have a stringify method, give it one.
-
- if (typeof JSON.stringify !== 'function') {
- JSON.stringify = function (value, replacer, space) {
-
-// The stringify method takes a value and an optional replacer, and an optional
-// space parameter, and returns a JSON text. The replacer can be a function
-// that can replace values, or an array of strings that will select the keys.
-// A default replacer method can be provided. Use of the space parameter can
-// produce text that is more easily readable.
-
- var i;
- gap = '';
- indent = '';
-
-// If the space parameter is a number, make an indent string containing that
-// many spaces.
-
- if (typeof space === 'number') {
- for (i = 0; i < space; i += 1) {
- indent += ' ';
- }
-
-// If the space parameter is a string, it will be used as the indent string.
-
- } else if (typeof space === 'string') {
- indent = space;
- }
-
-// If there is a replacer, it must be a function or an array.
-// Otherwise, throw an error.
-
- rep = replacer;
- if (replacer && typeof replacer !== 'function' &&
- (typeof replacer !== 'object' ||
- typeof replacer.length !== 'number')) {
- throw new Error('JSON.stringify');
- }
-
-// Make a fake root object containing our value under the key of ''.
-// Return the result of stringifying the value.
-
- return str('', {'': value});
- };
- }
-
-
-// If the JSON object does not yet have a parse method, give it one.
-
- if (typeof JSON.parse !== 'function') {
- JSON.parse = function (text, reviver) {
-
-// The parse method takes a text and an optional reviver function, and returns
-// a JavaScript value if the text is a valid JSON text.
-
- var j;
-
- function walk(holder, key) {
-
-// The walk method is used to recursively walk the resulting structure so
-// that modifications can be made.
-
- var k, v, value = holder[key];
- if (value && typeof value === 'object') {
- for (k in value) {
- if (Object.hasOwnProperty.call(value, k)) {
- v = walk(value, k);
- if (v !== undefined) {
- value[k] = v;
- } else {
- delete value[k];
- }
- }
- }
- }
- return reviver.call(holder, key, value);
- }
-
-
-// Parsing happens in four stages. In the first stage, we replace certain
-// Unicode characters with escape sequences. JavaScript handles many characters
-// incorrectly, either silently deleting them, or treating them as line endings.
-
- text = String(text);
- cx.lastIndex = 0;
- if (cx.test(text)) {
- text = text.replace(cx, function (a) {
- return '\\u' +
- ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
- });
- }
-
-// In the second stage, we run the text against regular expressions that look
-// for non-JSON patterns. We are especially concerned with '()' and 'new'
-// because they can cause invocation, and '=' because it can cause mutation.
-// But just to be safe, we want to reject all unexpected forms.
-
-// We split the second stage into 4 regexp operations in order to work around
-// crippling inefficiencies in IE's and Safari's regexp engines. First we
-// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
-// replace all simple value tokens with ']' characters. Third, we delete all
-// open brackets that follow a colon or comma or that begin the text. Finally,
-// we look to see that the remaining characters are only whitespace or ']' or
-// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
-
- if (/^[\],:{}\s]*$/.
-test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
-replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
-replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
-
-// In the third stage we use the eval function to compile the text into a
-// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
-// in JavaScript: it can begin a block or an object literal. We wrap the text
-// in parens to eliminate the ambiguity.
-
- j = eval('(' + text + ')');
-
-// In the optional fourth stage, we recursively walk the new structure, passing
-// each name/value pair to a reviver function for possible transformation.
-
- return typeof reviver === 'function' ?
- walk({'': j}, '') : j;
- }
-
-// If the text is not JSON parseable, then a SyntaxError is thrown.
-
- throw new SyntaxError('JSON.parse');
- };
- }
-}());
diff --git a/test/javascript/replicator_db_inc.js b/test/javascript/replicator_db_inc.js
deleted file mode 100644
index 46dcdd7..0000000
--- a/test/javascript/replicator_db_inc.js
+++ /dev/null
@@ -1,97 +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.
-
-var replicator_db = {};
-replicator_db.wait_rep_doc = 500; // number of millisecs to wait after saving a Rep Doc
-replicator_db.dbA = new CouchDB("test_suite_rep_db_a", {"X-Couch-Full-Commit":"false"});
-replicator_db.dbB = new CouchDB("test_suite_rep_db_b", {"X-Couch-Full-Commit":"false"});
-replicator_db.repDb = new CouchDB("test_suite_rep_db", {"X-Couch-Full-Commit":"false"});
-replicator_db.usersDb = new CouchDB("test_suite_auth", {"X-Couch-Full-Commit":"false"});
-
-replicator_db.docs1 = [
- {
- _id: "foo1",
- value: 11
- },
- {
- _id: "foo2",
- value: 22
- },
- {
- _id: "foo3",
- value: 33
- }
-];
-
-replicator_db.waitForRep = function waitForSeq(repDb, repDoc, state, errorState) {
- var newRep,
- t0 = new Date(),
- t1,
- ms = 3000;
-
- do {
- newRep = repDb.open(repDoc._id);
- t1 = new Date();
- } while (((t1 - t0) <= ms) && newRep._replication_state !== state && (!errorState || newRep._replication_state !== errorState));
- return newRep ? newRep._replication_state : null;
-}
-
-replicator_db.waitForSeq = function waitForSeq(sourceDb, targetDb) {
- var targetSeq,
- sourceSeq = sourceDb.info().update_seq,
- t0 = new Date(),
- t1,
- ms = 3000;
-
- do {
- targetSeq = targetDb.info().update_seq;
- t1 = new Date();
- } while (((t1 - t0) <= ms) && targetSeq < sourceSeq);
-}
-
-replicator_db.waitForDocPos = function waitForDocPos(db, docId, pos) {
- var doc, curPos, t0, t1,
- maxWait = 3000;
-
- doc = db.open(docId);
- curPos = Number(doc._rev.split("-", 1));
- t0 = t1 = new Date();
-
- while ((curPos < pos) && ((t1 - t0) <= maxWait)) {
- doc = db.open(docId);
- curPos = Number(doc._rev.split("-", 1));
- t1 = new Date();
- }
-
- return doc;
-}
-
-replicator_db.wait = function wait(ms) {
- var t0 = new Date(), t1;
- do {
- CouchDB.request("GET", "/");
- t1 = new Date();
- } while ((t1 - t0) <= ms);
-}
-
-
-replicator_db.populate_db = function populate_db(db, docs) {
- if (db.name !== replicator_db.usersDb.name) {
- db.deleteDb();
- db.createDb();
- }
- for (var i = 0; i < docs.length; i++) {
- var d = docs[i];
- delete d._rev;
- T(db.save(d).ok);
- }
-}
diff --git a/test/javascript/run b/test/javascript/run
deleted file mode 100755
index d60179e..0000000
--- a/test/javascript/run
+++ /dev/null
@@ -1,284 +0,0 @@
-#!/usr/bin/env python3
-#
-# 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.
-
-import glob
-import optparse as op
-import os
-import subprocess as sp
-import sys
-import time
-import re
-import xml.dom.minidom as md
-
-
-USAGE = "%prog [options] [command to run...]"
-TEST_PATH = os.path.dirname(os.path.abspath(__file__))
-ROOT_PATH = os.path.dirname(os.path.dirname(TEST_PATH))
-N = 3
-
-COUCHJS = "src/couch/priv/couchjs"
-
-SCRIPTS = """
- test/javascript/json2.js
- test/javascript/sha1.js
- test/javascript/couch.js
- test/javascript/replicator_db_inc.js
- test/javascript/couch_test_runner.js
- test/javascript/couch_http.js
- test/javascript/test_setup.js
- share/server/util.js
-""".split()
-
-RUNNER = "test/javascript/cli_runner.js"
-
-
-def mkformatter(tests):
- longest = max([len(x) for x in tests])
- green = "\033[32m"
- orange = "\033[33m"
- red = "\033[31m"
- clear = "\033[0m"
- if not sys.stderr.isatty():
- green, orange, red, clear = "", "", "", ""
-
- def _colorized(rval):
- if rval == 0:
- return green + "pass" + clear
- elif rval == 2:
- return orange + "skipped" + clear
- elif rval == 3:
- return green + "ported to elixir" + clear
- else:
- return red + ("fail: %d" % rval) + clear
-
- def _fmt(test):
- if isinstance(test, str):
- padding = (longest - len(test)) * " "
- sys.stderr.write(test + " " + padding)
- sys.stderr.flush()
- elif isinstance(test, int):
- if test:
- sys.stderr.write(_colorized(test) + os.linesep)
- else:
- sys.stderr.write(_colorized(test) + os.linesep)
- sys.stderr.flush()
-
- return _fmt
-
-
-def run_couchjs(test, fmt):
- fmt(test)
- cmd = (
- [COUCHJS, "--eval", "-H", "-T"]
- + ["-u", "test/javascript/couchdb.uri"]
- + SCRIPTS
- + [test, RUNNER]
- )
- p = sp.Popen(cmd, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.STDOUT)
- output = []
- while True:
- line = p.stdout.readline()
- if not line:
- break
- line = line.decode()
- output.append(line)
- sys.stderr.write(line)
- p.wait()
- fmt(p.returncode)
- return (p.returncode, "".join(output))
-
-
-def write_junit(filename, total_time, results):
- failures = 0
- skipped = 0
- for (_, rc, _, _) in results:
- if rc == 2 or rc == 3:
- skipped += 1
- else:
- failures += 1
-
- doc = md.Document()
- root = doc.createElement("testsuite")
- root.setAttribute("name", "JavaScript tests")
- root.setAttribute("time", "%0.3f" % total_time)
- root.setAttribute("tests", str(len(results)))
- root.setAttribute("failures", str(failures))
- root.setAttribute("errors", "0")
- root.setAttribute("skipped", str(skipped))
- doc.appendChild(root)
-
- for (path, rc, output, test_time) in results:
- name = os.path.split(path)[-1]
- tc = doc.createElement("testcase")
- tc.setAttribute("name", name)
- tc.setAttribute("time", "%0.3f" % test_time)
- if rc == 0:
- pass
- elif rc == 2:
- skipped = doc.createElement("skipped")
- skipped.setAttribute("message", "disabled")
- tc.appendChild(skipped)
- elif rc == 3:
- skipped = doc.createElement("skipped")
- skipped.setAttribute("message", "ported to elixir")
- tc.appendChild(skipped)
- else:
- failure = doc.createElement("failure")
- failure.setAttribute("message", "failed: %d" % rc)
- failure_text = "Exit Code: %d" % rc + "\n\n" + output
- message = doc.createTextNode(failure_text)
- failure.appendChild(message)
- tc.appendChild(failure)
- root.appendChild(tc)
-
- with open(filename, "w") as handle:
- doc.writexml(handle, addindent=" ", newl=os.linesep)
-
-
-def options():
- return [
- op.make_option(
- "-s",
- "--start",
- metavar="FILENAME",
- default=None,
- help="Start from the given filename if multiple files are passed",
- ),
- op.make_option(
- "-a",
- "--all",
- action="store_true",
- dest="all",
- help="Run all tests, even if one or more fail",
- ),
- op.make_option(
- "-i",
- "--ignore",
- type="string",
- action="callback",
- default=None,
- callback=get_delimited_list,
- dest="ignore",
- help="Ignore test suites",
- ),
- op.make_option(
- "-u",
- "--suites",
- type="string",
- action="callback",
- default=None,
- callback=get_delimited_list,
- dest="suites",
- help="Run specific suites",
- ),
- op.make_option(
- "-p",
- "--path",
- type="string",
- default="test/javascript/tests",
- dest="test_path",
- help="Path where the tests are located",
- ),
- op.make_option(
- "-j",
- "--junit-report",
- type="string",
- default="test/javascript/junit.xml",
- dest="junit_report",
- help="Write a JUnit compatible test report",
- ),
- ]
-
-
-def main():
- parser = op.OptionParser(usage=USAGE, option_list=options())
- opts, args = parser.parse_args()
-
- run_list = []
- ignore_list = []
- tests = []
- run_list = [opts.test_path] if not opts.suites else opts.suites
- run_list = build_test_case_paths(opts.test_path, run_list)
- ignore_list = build_test_case_paths(opts.test_path, opts.ignore)
- # sort is needed because certain tests fail if executed out of order
- tests = sorted(list(set(run_list) - set(ignore_list)))
-
- if opts.start is not None:
- tmp = []
- for name in tests:
- if name >= opts.start:
- tmp.append(name)
- tests = tmp
-
- results = []
- begin = time.time()
- passed = 0
- failed = 0
- if len(tests) > 0:
- fmt = mkformatter(tests)
- for test in tests:
- tbefore = time.time()
- (result, output) = run_couchjs(test, fmt)
- results.append((test, result, output, time.time() - tbefore))
- if result == 0 or result == 2 or result == 3:
- passed += 1
- else:
- failed += 1
- if not opts.all:
- break
-
- total_time = time.time() - begin
- if opts.junit_report:
- write_junit(opts.junit_report, total_time, results)
-
- sys.stderr.write(
- "=======================================================" + os.linesep
- )
- sys.stderr.write("JavaScript tests complete." + os.linesep)
- sys.stderr.write(
- " Failed: {0}. Skipped or passed: {1}.".format(failed, passed) + os.linesep
- )
- exit(failed > 0)
-
-
-def build_test_case_paths(path, args=None):
- tests = []
- if args is None:
- args = []
- for name in args:
- if os.path.isdir(name):
- tests.extend(sorted(glob.glob(os.path.join(name, "*.js"))))
- elif os.path.isfile(name):
- check = tests.append(name)
- else:
- pname = os.path.join(path, name)
- if os.path.isfile(pname):
- tests.append(pname)
- elif os.path.isfile(pname + ".js"):
- tests.append(pname + ".js")
- else:
- sys.stderr.write("Waring - Unknown test: " + name + os.linesep)
- return tests
-
-
-def get_delimited_list(option, opt, value, parser):
- delimited = [i for i in re.split(r",|\s", value.strip()) if i]
- setattr(parser.values, option.dest, delimited)
-
-
-if __name__ == "__main__":
- try:
- main()
- except KeyboardInterrupt:
- pass
diff --git a/test/javascript/sha1.js b/test/javascript/sha1.js
deleted file mode 100644
index ee73a63..0000000
--- a/test/javascript/sha1.js
+++ /dev/null
@@ -1,202 +0,0 @@
-/*
- * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
- * in FIPS PUB 180-1
- * Version 2.1a Copyright Paul Johnston 2000 - 2002.
- * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
- * Distributed under the BSD License
- * See http://pajhome.org.uk/crypt/md5 for details.
- */
-
-/*
- * Configurable variables. You may need to tweak these to be compatible with
- * the server-side, but the defaults work in most cases.
- */
-var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */
-var b64pad = "="; /* base-64 pad character. "=" for strict RFC compliance */
-var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */
-
-/*
- * These are the functions you'll usually want to call
- * They take string arguments and return either hex or base-64 encoded strings
- */
-function hex_sha1(s){return binb2hex(core_sha1(str2binb(s),s.length * chrsz));}
-function b64_sha1(s){return binb2b64(core_sha1(str2binb(s),s.length * chrsz));}
-function str_sha1(s){return binb2str(core_sha1(str2binb(s),s.length * chrsz));}
-function hex_hmac_sha1(key, data){ return binb2hex(core_hmac_sha1(key, data));}
-function b64_hmac_sha1(key, data){ return binb2b64(core_hmac_sha1(key, data));}
-function str_hmac_sha1(key, data){ return binb2str(core_hmac_sha1(key, data));}
-
-/*
- * Perform a simple self-test to see if the VM is working
- */
-function sha1_vm_test()
-{
- return hex_sha1("abc") == "a9993e364706816aba3e25717850c26c9cd0d89d";
-}
-
-/*
- * Calculate the SHA-1 of an array of big-endian words, and a bit length
- */
-function core_sha1(x, len)
-{
- /* append padding */
- x[len >> 5] |= 0x80 << (24 - len % 32);
- x[((len + 64 >> 9) << 4) + 15] = len;
-
- var w = Array(80);
- var a = 1732584193;
- var b = -271733879;
- var c = -1732584194;
- var d = 271733878;
- var e = -1009589776;
-
- for(var i = 0; i < x.length; i += 16)
- {
- var olda = a;
- var oldb = b;
- var oldc = c;
- var oldd = d;
- var olde = e;
-
- for(var j = 0; j < 80; j++)
- {
- if(j < 16) w[j] = x[i + j];
- else w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);
- var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)),
- safe_add(safe_add(e, w[j]), sha1_kt(j)));
- e = d;
- d = c;
- c = rol(b, 30);
- b = a;
- a = t;
- }
-
- a = safe_add(a, olda);
- b = safe_add(b, oldb);
- c = safe_add(c, oldc);
- d = safe_add(d, oldd);
- e = safe_add(e, olde);
- }
- return Array(a, b, c, d, e);
-
-}
-
-/*
- * Perform the appropriate triplet combination function for the current
- * iteration
- */
-function sha1_ft(t, b, c, d)
-{
- if(t < 20) return (b & c) | ((~b) & d);
- if(t < 40) return b ^ c ^ d;
- if(t < 60) return (b & c) | (b & d) | (c & d);
- return b ^ c ^ d;
-}
-
-/*
- * Determine the appropriate additive constant for the current iteration
- */
-function sha1_kt(t)
-{
- return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 :
- (t < 60) ? -1894007588 : -899497514;
-}
-
-/*
- * Calculate the HMAC-SHA1 of a key and some data
- */
-function core_hmac_sha1(key, data)
-{
- var bkey = str2binb(key);
- if(bkey.length > 16) bkey = core_sha1(bkey, key.length * chrsz);
-
- var ipad = Array(16), opad = Array(16);
- for(var i = 0; i < 16; i++)
- {
- ipad[i] = bkey[i] ^ 0x36363636;
- opad[i] = bkey[i] ^ 0x5C5C5C5C;
- }
-
- var hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * chrsz);
- return core_sha1(opad.concat(hash), 512 + 160);
-}
-
-/*
- * Add integers, wrapping at 2^32. This uses 16-bit operations internally
- * to work around bugs in some JS interpreters.
- */
-function safe_add(x, y)
-{
- var lsw = (x & 0xFFFF) + (y & 0xFFFF);
- var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
- return (msw << 16) | (lsw & 0xFFFF);
-}
-
-/*
- * Bitwise rotate a 32-bit number to the left.
- */
-function rol(num, cnt)
-{
- return (num << cnt) | (num >>> (32 - cnt));
-}
-
-/*
- * Convert an 8-bit or 16-bit string to an array of big-endian words
- * In 8-bit function, characters >255 have their hi-byte silently ignored.
- */
-function str2binb(str)
-{
- var bin = Array();
- var mask = (1 << chrsz) - 1;
- for(var i = 0; i < str.length * chrsz; i += chrsz)
- bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (32 - chrsz - i%32);
- return bin;
-}
-
-/*
- * Convert an array of big-endian words to a string
- */
-function binb2str(bin)
-{
- var str = "";
- var mask = (1 << chrsz) - 1;
- for(var i = 0; i < bin.length * 32; i += chrsz)
- str += String.fromCharCode((bin[i>>5] >>> (32 - chrsz - i%32)) & mask);
- return str;
-}
-
-/*
- * Convert an array of big-endian words to a hex string.
- */
-function binb2hex(binarray)
-{
- var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
- var str = "";
- for(var i = 0; i < binarray.length * 4; i++)
- {
- str += hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8+4)) & 0xF) +
- hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8 )) & 0xF);
- }
- return str;
-}
-
-/*
- * Convert an array of big-endian words to a base-64 string
- */
-function binb2b64(binarray)
-{
- var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
- var str = "";
- for(var i = 0; i < binarray.length * 4; i += 3)
- {
- var triplet = (((binarray[i >> 2] >> 8 * (3 - i %4)) & 0xFF) << 16)
- | (((binarray[i+1 >> 2] >> 8 * (3 - (i+1)%4)) & 0xFF) << 8 )
- | ((binarray[i+2 >> 2] >> 8 * (3 - (i+2)%4)) & 0xFF);
- for(var j = 0; j < 4; j++)
- {
- if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
- else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
- }
- }
- return str;
-}
diff --git a/test/javascript/test_setup.js b/test/javascript/test_setup.js
deleted file mode 100644
index 6140c0e..0000000
--- a/test/javascript/test_setup.js
+++ /dev/null
@@ -1,127 +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.
-
-/*
- * Add global couchTests object required for existing tests.
- */
-var couchTests = {};
-
-var console = {
- log: function(arg) {
- var msg = (arg.toString()).replace(/\n/g, "\n ");
- print(msg, true);
- }
-};
-
-var fmtStack = function(stack) {
- if(!stack) {
- console.log("No stack information");
- return;
- }
- console.log("Trace back (most recent call first):\n");
- var re = new RegExp("(.*?)@([^:]*):(.*)$");
- var lines = stack.split("\n");
- for(var i = 0; i < lines.length; i++) {
- var line = lines[i];
- if(!line.length) continue;
- var match = re.exec(line);
- if(!match) continue
- var match = re.exec(line);
- if(!match) continue
- var source = match[1].substr(0, 70);
- var file = match[2];
- var lnum = match[3];
- while(lnum.length < 3) lnum = " " + lnum;
- console.log(" " + lnum + ": " + file);
- console.log(" " + source);
- }
-}
-
-function T(arg1, arg2) {
- if(!arg1) {
- var result = (arg2 ? arg2 : arg1);
- throw((result instanceof Error ? result : Error(result)));
- }
-}
-
-function waitForSuccess(fun, tag) {
- var start = new Date().getTime();
- var complete = false;
-
- while (!complete) {
- var now = new Date().getTime();
- if (now > start + 10000) {
- complete = true;
- throw(Error('\nFAIL ' + tag));
- }
- try {
- while (new Date().getTime() < now + 500);
- complete = fun();
- } catch (e) {}
- }
-}
-
-function getUptime() {
- var url = "/_node/node1@127.0.0.1/_system"
- var stats = JSON.parse(CouchDB.request("GET", url).responseText);
- return stats['uptime'];
-}
-
-function restartNodeRequest(node) {
- var url = "/_node/" + node +"/_restart"
- var result = JSON.parse(CouchDB.request("POST", url).responseText);
- if (result.ok != true) {
- throw(Error('FAILED to restart: ' + node));
- }
-}
-
-function restartServer() {
- var olduptime = getUptime();
- if (olduptime < 15) {
- // handle quick-restarts, though this slows things down
- sleep(15000);
- olduptime = getUptime();
- }
-
- restartNodeRequest('node1@127.0.0.1');
-
- /* Wait up to 15s for server to restart */
- var start = new Date().getTime();
- var complete = false;
- while (1) {
- sleep(500);
- try {
- if (getUptime() < olduptime) {
- return;
- }
- } catch (e) {}
-
- var now = new Date().getTime();
- if (now > start + 30000) {
- try {
- uptime = getUptime();
- throw(Error('FAILED to restart: ' + uptime + ' not < ' + olduptime));
- } catch (e) {
- throw(Error('FAILED to restart: server is unresponsive, waited 30s'));
- }
- }
- }
-}
-
-/*
- * If last_req is an object, we got something back. This might be an error, but
- * CouchDB is up and running!
- */
-CouchDB.isRunning = function() {
- CouchDB.last_req = CouchDB.request("GET", "/");
- return typeof CouchDB.last_req == 'object';
-};
diff --git a/test/javascript/tests-cluster/with-quorum/attachments.js b/test/javascript/tests-cluster/with-quorum/attachments.js
deleted file mode 100644
index 8186d75..0000000
--- a/test/javascript/tests-cluster/with-quorum/attachments.js
+++ /dev/null
@@ -1,37 +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.
-
-couchTests.attachments= function(debug) {
- return console.log('done in test/elixir/test/cluster_with_quorum_test.exs');
- var db_name = get_random_db_name();
- var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"});
- db.createDb();
- if (debug) debugger;
-
- var doc = db.save({_id:"dummy"});
- T(doc.ok);
-
- var xhr = CouchDB.request("PUT", "/" + db_name + "/dummy/foo.txt?rev=" + doc.rev, {
- body:"This is no base64 encoded text",
- headers:{"Content-Type": "text/plain;charset=utf-8"}
- });
- T(xhr.status == 201,"Should return 201");
- var rev = JSON.parse(xhr.responseText).rev;
-
- xhr = CouchDB.request("PUT", "/" + db_name + "/dummy/foo.txt?rev=" + rev, {
- body:"This is no base64 encoded text-2",
- headers:{"Content-Type": "text/plain;charset=utf-8"}
- });
- T(xhr.status == 201,"Should return 201");
-
- db.deleteDb();
-}
diff --git a/test/javascript/tests-cluster/with-quorum/attachments_delete.js b/test/javascript/tests-cluster/with-quorum/attachments_delete.js
deleted file mode 100644
index 1980c11..0000000
--- a/test/javascript/tests-cluster/with-quorum/attachments_delete.js
+++ /dev/null
@@ -1,33 +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.
-
-couchTests.attachments_delete= function(debug) {
- return console.log('done in test/elixir/test/cluster_with_quorum_test.exs');
- var db_name = get_random_db_name();
- var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"});
- db.createDb();
- if (debug) debugger;
-
- var doc = db.save({_id:"dummy"});
- T(doc.ok);
- var xhr = CouchDB.request("PUT", "/" + db_name + "/dummy/foo.txt?rev=" + doc.rev, {
- body:"This is no base64 encoded text",
- headers:{"Content-Type": "text/plain;charset=utf-8"}
- });
- T(xhr.status == 201,"Should return 201 Accepted");
- var rev = JSON.parse(xhr.responseText).rev;
-
- xhr = CouchDB.request("DELETE", "/" + db_name + "/dummy/foo.txt?rev=" + rev);
- T(xhr.status == 200,"Should return 200 Ok but returns "+xhr.status);
-
- db.deleteDb();
-}
diff --git a/test/javascript/tests-cluster/with-quorum/attachments_delete_overridden_quorum.js b/test/javascript/tests-cluster/with-quorum/attachments_delete_overridden_quorum.js
deleted file mode 100644
index 48c1f34..0000000
--- a/test/javascript/tests-cluster/with-quorum/attachments_delete_overridden_quorum.js
+++ /dev/null
@@ -1,38 +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.
-
-couchTests.skip = true;
-couchTests.attachments_delete_overridden_quorum= function(debug) {
- return console.log('done in test/elixir/test/cluster_with_quorum_test.exs');
- var db_name = get_random_db_name();
- var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"},{"w":3});
- db.createDb();
- if (debug) debugger;
-
- var doc = db.save({_id:"dummy"});
- T(doc.ok);
- var xhr = CouchDB.request("PUT", "/" + db_name + "/dummy/foo.txt?rev=" + doc.rev, {
- body:"This is no base64 encoded text",
- headers:{"Content-Type": "text/plain;charset=utf-8"}
- });
- var rev = JSON.parse(xhr.responseText).rev;
-
- xhr = CouchDB.request("DELETE", "/" + db_name + "/dummy/foo.txt?rev=" + rev);
- console.log("TODO: Clarify correct behaviour. Is not considering overridden quorum. 202->"+xhr.status);
- // TODO: Define correct behaviour
- //T(xhr.status == 202,"Should return 202 but returns "+xhr.status);
-
- //db.deleteDb();
- // cleanup
- // TODO DB deletions fails if the quorum is not met.
- xhr = CouchDB.request("DELETE", "/" + db_name + "/");
-}
diff --git a/test/javascript/tests-cluster/with-quorum/attachments_overridden_quorum.js b/test/javascript/tests-cluster/with-quorum/attachments_overridden_quorum.js
deleted file mode 100644
index cbeb985..0000000
--- a/test/javascript/tests-cluster/with-quorum/attachments_overridden_quorum.js
+++ /dev/null
@@ -1,42 +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.
-
-//Test attachments operations with an overridden quorum parameter
-couchTests.skip = true;
-couchTests.attachments_overriden_quorum= function(debug) {
- return console.log('done in test/elixir/test/cluster_with_quorum_test.exs');
- var db_name = get_random_db_name();
- var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"},{"w":3});
- db.createDb();
- if (debug) debugger;
-
- var doc = db.save({_id:"dummy"});
- T(doc.ok);
-
- var xhr = CouchDB.request("PUT", "/" + db_name + "/dummy/foo.txt?rev=" + doc.rev, {
- body:"This is no base64 encoded text",
- headers:{"Content-Type": "text/plain;charset=utf-8"}
- });
- //TODO: Define correct behaviour
- //T(xhr.status == 202,"Should return 202");
- var rev = JSON.parse(xhr.responseText).rev;
-
- xhr = CouchDB.request("PUT", "/" + db_name + "/dummy/foo.txt?rev=" + rev, {
- body:"This is no base64 encoded text-2",
- headers:{"Content-Type": "text/plain;charset=utf-8"}
- });
- console.log("TODO: Clarify correct behaviour. Is not considering overridden quorum. 202->"+xhr.status);
- //TODO: Define correct behaviour
- //T(xhr.status == 202,"Should return 202");
-
- db.deleteDb();
-}
diff --git a/test/javascript/tests-cluster/with-quorum/db_creation.js b/test/javascript/tests-cluster/with-quorum/db_creation.js
deleted file mode 100644
index c8a416d..0000000
--- a/test/javascript/tests-cluster/with-quorum/db_creation.js
+++ /dev/null
@@ -1,28 +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.
-
-// Do DB creation under cluster with quorum conditions.
-couchTests.db_creation = function(debug) {
- return console.log('done in test/elixir/test/cluster_with_quorum_test.exs');
-
- if (debug) debugger;
-
- var db_name = get_random_db_name()
- var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"});
-
- // DB Creation should return 201 - Created
- xhr = CouchDB.request("PUT", "/" + db_name + "/");
- T(xhr.status == 201);
-
- // cleanup
- db.deleteDb();
-};
diff --git a/test/javascript/tests-cluster/with-quorum/db_creation_overridden_quorum.js b/test/javascript/tests-cluster/with-quorum/db_creation_overridden_quorum.js
deleted file mode 100644
index af27f95..0000000
--- a/test/javascript/tests-cluster/with-quorum/db_creation_overridden_quorum.js
+++ /dev/null
@@ -1,30 +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.
-
-// Do DB creation under cluster with quorum conditions but overriding write quorum.
-couchTests.skip = true;
-couchTests.db_creation_overridden_quorum = function(debug) {
- return console.log('done in test/elixir/test/cluster_with_quorum_test.exs');
-
- if (debug) debugger;
-
- var db_name = get_random_db_name()
- var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"},{"w":3});
-
- // DB Creation should return 202 - Accepted
- xhr = CouchDB.request("PUT", "/" + db_name + "/");
- console.log("TODO: Clarify correct behaviour. Is not considering overridden quorum. 202->"+xhr.status)
- //T(xhr.status == 202,"Should return 202");
-
- // cleanup
- db.deleteDb();
-};
diff --git a/test/javascript/tests-cluster/with-quorum/db_deletion.js b/test/javascript/tests-cluster/with-quorum/db_deletion.js
deleted file mode 100644
index 70e7034..0000000
--- a/test/javascript/tests-cluster/with-quorum/db_deletion.js
+++ /dev/null
@@ -1,31 +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.
-
-// Do DB deletion under cluster with quorum conditions.
-couchTests.db_deletion = function(debug) {
- return console.log('done in test/elixir/test/cluster_with_quorum_test.exs');
-
- if (debug) debugger;
-
- var db_name = get_random_db_name()
- var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"});
-
- db.createDb();
-
- // DB Deletion should return 202 - Acceted as the custer is not complete
- xhr = CouchDB.request("DELETE", "/" + db_name + "/");
- T(xhr.status == 202);
-
-// DB Deletion should return 404 - Not found
- xhr = CouchDB.request("DELETE", "/not-existing-db/");
- T(xhr.status == 404);
-};
diff --git a/test/javascript/tests-cluster/with-quorum/db_deletion_overridden_quorum.js b/test/javascript/tests-cluster/with-quorum/db_deletion_overridden_quorum.js
deleted file mode 100644
index 8e9c65e..0000000
--- a/test/javascript/tests-cluster/with-quorum/db_deletion_overridden_quorum.js
+++ /dev/null
@@ -1,24 +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.
-
-// Do DB deletion in a cluster with quorum conditions.
-couchTests.db_deletion_overridden_quorum = function(debug) {
- return console.log('done in test/elixir/test/cluster_with_quorum_test.exs');
-
- if (debug) debugger;
-
- var db_name = get_random_db_name()
- var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"},{"w":3});
- db.createDb();
- db.deleteDb();
- T(db.last_req.status="202","Should return 202");
-};
diff --git a/test/javascript/tests-cluster/with-quorum/doc_bulk.js b/test/javascript/tests-cluster/with-quorum/doc_bulk.js
deleted file mode 100644
index 1cb8574..0000000
--- a/test/javascript/tests-cluster/with-quorum/doc_bulk.js
+++ /dev/null
@@ -1,26 +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.
-
-couchTests.doc_bulk = function(debug) {
- return console.log('done in test/elixir/test/cluster_with_quorum_test.exs');
- var db_name = get_random_db_name();
- var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"});
- db.createDb();
- if (debug) debugger;
-
- var docs = makeDocs(5);
- // Create the docs
- var results = db.bulkSave(docs);
- T(db.last_req.status="201","Should return 201")
-
- db.deleteDb();
-}
diff --git a/test/javascript/tests-cluster/with-quorum/doc_bulk_overridden_quorum.js b/test/javascript/tests-cluster/with-quorum/doc_bulk_overridden_quorum.js
deleted file mode 100644
index 2a3be06..0000000
--- a/test/javascript/tests-cluster/with-quorum/doc_bulk_overridden_quorum.js
+++ /dev/null
@@ -1,26 +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.
-
-couchTests.doc_bulk_overridden_quorum = function(debug) {
- return console.log('done in test/elixir/test/cluster_with_quorum_test.exs');
- var db_name = get_random_db_name();
- var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"},{"w":3});
- db.createDb();
- if (debug) debugger;
-
- var docs = makeDocs(5);
- // Create the docs
- var results = db.bulkSave(docs);
- T(db.last_req.status="202","Should return 202")
-
- db.deleteDb();
-}
diff --git a/test/javascript/tests-cluster/with-quorum/doc_copy.js b/test/javascript/tests-cluster/with-quorum/doc_copy.js
deleted file mode 100644
index e79d38c..0000000
--- a/test/javascript/tests-cluster/with-quorum/doc_copy.js
+++ /dev/null
@@ -1,28 +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.
-
-couchTests.doc_copy = function(debug) {
- return console.log('done in test/elixir/test/cluster_with_quorum_test.exs');
- var db_name = get_random_db_name();
- var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"});
- db.createDb();
- if (debug) debugger;
-
- db.save({_id:"dummy"});
-
- var xhr = CouchDB.request("COPY", "/" + db_name + "/dummy", {
- headers: {"Destination":"dummy2"}
- });
- T(xhr.status=="201","Should return 201 ");
-
- db.deleteDb();
-}
diff --git a/test/javascript/tests-cluster/with-quorum/doc_copy_overridden_quorum.js b/test/javascript/tests-cluster/with-quorum/doc_copy_overridden_quorum.js
deleted file mode 100644
index a816817..0000000
--- a/test/javascript/tests-cluster/with-quorum/doc_copy_overridden_quorum.js
+++ /dev/null
@@ -1,32 +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.
-
-couchTests.skip = true;
-couchTests.doc_copy_overriden_quorum = function(debug) {
- return console.log('done in test/elixir/test/cluster_with_quorum_test.exs');
- var db_name = get_random_db_name();
- var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"},{"w":3});
- db.createDb();
- if (debug) debugger;
-
- db.save({_id:"dummy"});
-
- var xhr = CouchDB.request("COPY", "/" + db_name + "/dummy", {
- headers: {"Destination":"dummy2"}
- });
- //TODO: Define correct behaviour
- //T(xhr.status=="202","Should return 202");
- console.log("TODO: Clarify correct behaviour. Is not considering overridden quorum. 202->"+xhr.status);
-
- db.deleteDb();
-
-}
diff --git a/test/javascript/tests-cluster/with-quorum/doc_crud.js b/test/javascript/tests-cluster/with-quorum/doc_crud.js
deleted file mode 100644
index ab90e60..0000000
--- a/test/javascript/tests-cluster/with-quorum/doc_crud.js
+++ /dev/null
@@ -1,32 +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.
-
-couchTests.doc_crud = function(debug) {
- return console.log('done in test/elixir/test/cluster_with_quorum_test.exs');
- var db_name = get_random_db_name();
- var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"});
- db.createDb();
- if (debug) debugger;
-
- db.save({_id:"0",a:1});
- T(db.last_req.status=="201");
-
- var doc = db.open("0");
- db.save(doc);
- T(db.last_req.status=="201");
-
- doc = db.open("0");
- db.deleteDoc(doc);
- T(db.last_req.status="200");
- db.deleteDb();
-
-}
diff --git a/test/javascript/tests-cluster/with-quorum/doc_crud_overridden_quorum.js b/test/javascript/tests-cluster/with-quorum/doc_crud_overridden_quorum.js
deleted file mode 100644
index a351378..0000000
--- a/test/javascript/tests-cluster/with-quorum/doc_crud_overridden_quorum.js
+++ /dev/null
@@ -1,32 +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.
-
-couchTests.doc_crud_overridden_quorum = function(debug) {
- return console.log('done in test/elixir/test/cluster_with_quorum_test.exs');
- var db_name = get_random_db_name();
- var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"},{"w":3});
- db.createDb();
- if (debug) debugger;
-
- db.save({_id:"0",a:1});
- T(db.last_req.status=="202","Should return 202 status");
-
- var doc = db.open("0");
- db.save(doc);
- T(db.last_req.status=="202","Should return 202 status");
-
- doc = db.open("0");
- db.deleteDoc(doc);
- T(db.last_req.status="202","Should return 202 status");
-
- db.deleteDb();
-}
diff --git a/test/javascript/tests-cluster/without-quorum/attachments.js b/test/javascript/tests-cluster/without-quorum/attachments.js
deleted file mode 100644
index 349cc88..0000000
--- a/test/javascript/tests-cluster/without-quorum/attachments.js
+++ /dev/null
@@ -1,40 +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.
-
-couchTests.attachments= function(debug) {
- return console.log('done in test/elixir/test/cluster_without_quorum_test.exs');
- var db_name = get_random_db_name();
- var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"});
- db.createDb();
- if (debug) debugger;
-
- var doc = db.save({_id:"dummy"});
- T(doc.ok);
- var xhr = CouchDB.request("PUT", "/" + db_name + "/dummy/foo.txt?rev=" + doc.rev, {
- body:"This is no base64 encoded text",
- headers:{"Content-Type": "text/plain;charset=utf-8"}
- });
- T(xhr.status == 202,"Should return 202 Accepted");
- var rev = JSON.parse(xhr.responseText).rev;
-
- xhr = CouchDB.request("PUT", "/" + db_name + "/dummy/foo.txt?rev=" + rev, {
- body:"This is no base64 encoded text-2",
- headers:{"Content-Type": "text/plain;charset=utf-8"}
- });
- T(xhr.status == 202,"Should return 202 Accepted");
- rev = JSON.parse(xhr.responseText).rev;
-
- //db.deleteDb();
- // cleanup
- // TODO DB deletions fails if the quorum is not met.
- xhr = CouchDB.request("DELETE", "/" + db_name + "/");
-}
diff --git a/test/javascript/tests-cluster/without-quorum/attachments_delete.js b/test/javascript/tests-cluster/without-quorum/attachments_delete.js
deleted file mode 100644
index 8b8a2db..0000000
--- a/test/javascript/tests-cluster/without-quorum/attachments_delete.js
+++ /dev/null
@@ -1,39 +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.
-
-couchTests.skip = true;
-couchTests.attachments_delete= function(debug) {
- return console.log('done in test/elixir/test/cluster_without_quorum_test.exs');
- var db_name = get_random_db_name();
- var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"});
- db.createDb();
- if (debug) debugger;
-
- var doc = db.save({_id:"dummy"});
- T(doc.ok);
- var xhr = CouchDB.request("PUT", "/" + db_name + "/dummy/foo.txt?rev=" + doc.rev, {
- body:"This is no base64 encoded text",
- headers:{"Content-Type": "text/plain;charset=utf-8"}
- });
- T(xhr.status == 202,"Should return 202 Accepted");
- var rev = JSON.parse(xhr.responseText).rev;
-
- xhr = CouchDB.request("DELETE", "/" + db_name + "/dummy/foo.txt?rev=" + rev);
- console.log("TODO: Clarify correct behaviour. Is not considering quorum. 202->"+xhr.status);
- //TODO: Define correct behaviour
- //T(xhr.status == 202,"Should return 202 Accepted but returns "+xhr.status);
-
- //db.deleteDb();
- // cleanup
- // TODO DB deletions fails if the quorum is not met.
- xhr = CouchDB.request("DELETE", "/" + db_name + "/");
-}
diff --git a/test/javascript/tests-cluster/without-quorum/attachments_delete_overridden_quorum.js b/test/javascript/tests-cluster/without-quorum/attachments_delete_overridden_quorum.js
deleted file mode 100644
index 48247e0..0000000
--- a/test/javascript/tests-cluster/without-quorum/attachments_delete_overridden_quorum.js
+++ /dev/null
@@ -1,38 +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.
-
-couchTests.skip = true;
-couchTests.attachments_delete_overridden_quorum= function(debug) {
- return console.log('done in test/elixir/test/cluster_without_quorum_test.exs');
- var db_name = get_random_db_name();
- var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"},{"w":1});
- db.createDb();
- if (debug) debugger;
-
- var doc = db.save({_id:"dummy"});
- T(doc.ok);
- var xhr = CouchDB.request("PUT", "/" + db_name + "/dummy/foo.txt?rev=" + doc.rev, {
- body:"This is no base64 encoded text",
- headers:{"Content-Type": "text/plain;charset=utf-8"}
- });
- var rev = JSON.parse(xhr.responseText).rev;
-
- xhr = CouchDB.request("DELETE", "/" + db_name + "/dummy/foo.txt?rev=" + rev);
- console.log("TODO: Clarify correct behaviour. Is not considering quorum. 202->"+xhr.status);
- //TODO: Define correct behaviour
- //T(xhr.status == 200,"Should return 200 but returns "+xhr.status);
-
- //db.deleteDb();
- // cleanup
- // TODO DB deletions fails if the quorum is not met.
- xhr = CouchDB.request("DELETE", "/" + db_name + "/");
-}
diff --git a/test/javascript/tests-cluster/without-quorum/attachments_overridden_quorum.js b/test/javascript/tests-cluster/without-quorum/attachments_overridden_quorum.js
deleted file mode 100644
index 2b8e75f..0000000
--- a/test/javascript/tests-cluster/without-quorum/attachments_overridden_quorum.js
+++ /dev/null
@@ -1,43 +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.
-
-//Test attachments operations with an overridden quorum parameter
-couchTests.attachments_overriden_quorum= function(debug) {
- return console.log('done in test/elixir/test/cluster_without_quorum_test.exs');
- var db_name = get_random_db_name();
- var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"},{"w":1});
- db.createDb();
- if (debug) debugger;
-
- var doc = db.save({_id:"dummy"});
- T(doc.ok);
-
- var xhr = CouchDB.request("PUT", "/" + db_name + "/dummy/foo.txt?rev=" + doc.rev, {
- body:"This is no base64 encoded text",
- headers:{"Content-Type": "text/plain;charset=utf-8"}
- });
- //TODO: Define correct behaviour
- //T(xhr.status == 201,"Should return 201");
- var rev = JSON.parse(xhr.responseText).rev;
-
- xhr = CouchDB.request("PUT", "/" + db_name + "/dummy/foo.txt?rev=" + rev, {
- body:"This is no base64 encoded text-2",
- headers:{"Content-Type": "text/plain;charset=utf-8"}
- });
- //TODO: Define correct behaviour
- //T(xhr.status == 201,"Should return 201");
-
- //db.deleteDb();
- // cleanup
- // TODO DB deletions fails if the quorum is not met.
- xhr = CouchDB.request("DELETE", "/" + db_name + "/");
-}
diff --git a/test/javascript/tests-cluster/without-quorum/db_creation.js b/test/javascript/tests-cluster/without-quorum/db_creation.js
deleted file mode 100644
index dd9b294..0000000
--- a/test/javascript/tests-cluster/without-quorum/db_creation.js
+++ /dev/null
@@ -1,28 +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.
-
-// Do DB creation under cluster without quorum conditions.
-couchTests.db_creation = function(debug) {
- return console.log('done in test/elixir/test/cluster_without_quorum_test.exs');
-
- if (debug) debugger;
-
- var db_name = get_random_db_name()
- var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"});
-
- // DB Creation should return 202- Accepted
- xhr = CouchDB.request("PUT", "/" + db_name + "/");
- T(xhr.status == 202);
-
- // cleanup
- db.deleteDb();
-};
diff --git a/test/javascript/tests-cluster/without-quorum/db_creation_overridden_quorum.js b/test/javascript/tests-cluster/without-quorum/db_creation_overridden_quorum.js
deleted file mode 100644
index 8ed9b44..0000000
--- a/test/javascript/tests-cluster/without-quorum/db_creation_overridden_quorum.js
+++ /dev/null
@@ -1,32 +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.
-
-// Do DB creation under cluster with quorum conditions but overriding write quorum.
-couchTests.skip = true;
-couchTests.db_creation_overridden_quorum = function(debug) {
- return console.log('done in test/elixir/test/cluster_without_quorum_test.exs');
-
- if (debug) debugger;
-
- var db_name = get_random_db_name()
- var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"},{"w":1});
-
- // DB Creation should return 201 - Created
- xhr = CouchDB.request("PUT", "/" + db_name + "/");
- console.log("TODO: Clarify correct behaviour. Is not considering overridden quorum. 201->"+xhr.status)
- //T(xhr.status == 201,"Should return 201");
-
- //db.deleteDb();
- // cleanup
- // TODO DB deletions fails if the quorum is not met.
- xhr = CouchDB.request("DELETE", "/" + db_name + "/");
-};
diff --git a/test/javascript/tests-cluster/without-quorum/db_deletion.js b/test/javascript/tests-cluster/without-quorum/db_deletion.js
deleted file mode 100644
index f156b0e..0000000
--- a/test/javascript/tests-cluster/without-quorum/db_deletion.js
+++ /dev/null
@@ -1,31 +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.
-
-// Do DB creation under cluster with quorum conditions.
-couchTests.db_deletion = function(debug) {
- return console.log('done in test/elixir/test/cluster_without_quorum_test.exs');
-
- if (debug) debugger;
-
- var db_name = get_random_db_name()
- var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"});
-
- db.createDb();
-
- // DB Deletion should return 202 - Acepted
- xhr = CouchDB.request("DELETE", "/" + db_name + "/");
- T(xhr.status == 202);
-
- // DB Deletion should return 404 - Not found
- xhr = CouchDB.request("DELETE", "/not-existing-db/");
- T(xhr.status == 404);
-};
diff --git a/test/javascript/tests-cluster/without-quorum/db_deletion_overridden_quorum.js b/test/javascript/tests-cluster/without-quorum/db_deletion_overridden_quorum.js
deleted file mode 100644
index 86dea83..0000000
--- a/test/javascript/tests-cluster/without-quorum/db_deletion_overridden_quorum.js
+++ /dev/null
@@ -1,26 +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.
-
-// Do DB deletion in a cluster with quorum conditions.
-couchTests.db_deletion_overridden_quorum = function(debug) {
- return console.log('done in test/elixir/test/cluster_without_quorum_test.exs');
-
- if (debug) debugger;
-
- var db_name = get_random_db_name()
- var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"},{"w":1});
- db.createDb();
-
- // DB deletions does not consider overriden quorum param.
- xhr = CouchDB.request("DELETE", "/" + db_name + "/");
- T(db.last_req.status="202","Should return 202");
-};
diff --git a/test/javascript/tests-cluster/without-quorum/doc_bulk.js b/test/javascript/tests-cluster/without-quorum/doc_bulk.js
deleted file mode 100644
index 37f67ec..0000000
--- a/test/javascript/tests-cluster/without-quorum/doc_bulk.js
+++ /dev/null
@@ -1,29 +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.
-
-couchTests.doc_bulk = function(debug) {
- return console.log('done in test/elixir/test/cluster_without_quorum_test.exs');
- var db_name = get_random_db_name();
- var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"});
- db.createDb();
- if (debug) debugger;
-
- var docs = makeDocs(5);
- // Create the docs
- var results = db.bulkSave(docs);
- T(db.last_req.status="202","Should return 202")
-
- //db.deleteDb();
- // cleanup
- // TODO DB deletions fails if the quorum is not met.
- xhr = CouchDB.request("DELETE", "/" + db_name + "/");
-}
diff --git a/test/javascript/tests-cluster/without-quorum/doc_bulk_overridden_quorum.js b/test/javascript/tests-cluster/without-quorum/doc_bulk_overridden_quorum.js
deleted file mode 100644
index 0f2f364..0000000
--- a/test/javascript/tests-cluster/without-quorum/doc_bulk_overridden_quorum.js
+++ /dev/null
@@ -1,29 +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.
-
-couchTests.doc_bulk_overridden_quorum = function(debug) {
- return console.log('done in test/elixir/test/cluster_without_quorum_test.exs');
- var db_name = get_random_db_name();
- var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"},{"w":1});
- db.createDb();
- if (debug) debugger;
-
- var docs = makeDocs(5);
- // Create the docs
- var results = db.bulkSave(docs);
- T(db.last_req.status="201","Should return 201")
-
- //db.deleteDb();
- // cleanup
- // TODO DB deletions fails if the quorum is not met.
- xhr = CouchDB.request("DELETE", "/" + db_name + "/");
-}
diff --git a/test/javascript/tests-cluster/without-quorum/doc_copy.js b/test/javascript/tests-cluster/without-quorum/doc_copy.js
deleted file mode 100644
index 6e7ae45..0000000
--- a/test/javascript/tests-cluster/without-quorum/doc_copy.js
+++ /dev/null
@@ -1,31 +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.
-
-couchTests.doc_copy = function(debug) {
- return console.log('done in test/elixir/test/cluster_without_quorum_test.exs');
- var db_name = get_random_db_name();
- var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"});
- db.createDb();
- if (debug) debugger;
-
- db.save({_id:"dummy"});
-
- var xhr = CouchDB.request("COPY", "/" + db_name + "/dummy", {
- headers: {"Destination":"dummy2"}
- });
- T(xhr.status=="202","Should return 202 ");
-
- //db.deleteDb();
- // cleanup
- // TODO DB deletions fails if the quorum is not met.
- xhr = CouchDB.request("DELETE", "/" + db_name + "/");
-}
diff --git a/test/javascript/tests-cluster/without-quorum/doc_copy_overridden_quorum.js b/test/javascript/tests-cluster/without-quorum/doc_copy_overridden_quorum.js
deleted file mode 100644
index 301240e..0000000
--- a/test/javascript/tests-cluster/without-quorum/doc_copy_overridden_quorum.js
+++ /dev/null
@@ -1,35 +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.
-
-couchTests.skip = true;
-couchTests.doc_copy_overriden_quorum = function(debug) {
- return console.log('done in test/elixir/test/cluster_without_quorum_test.exs');
- var db_name = get_random_db_name();
- var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"},{"w":1});
- db.createDb();
- if (debug) debugger;
-
- db.save({_id:"dummy"});
-
- var xhr = CouchDB.request("COPY", "/" + db_name + "/dummy", {
- headers: {"Destination":"dummy2"}
- });
- console.log("TODO: Clarify correct behaviour. Is not considering overridden quorum. 201->"+xhr.status);
- //TODO Defie correct behaviour
- //T(xhr.status=="201","Should return 201");
-
- //db.deleteDb();
- // cleanup
- // TODO DB deletions fails if the quorum is not met.
- xhr = CouchDB.request("DELETE", "/" + db_name + "/");
-
-}
diff --git a/test/javascript/tests-cluster/without-quorum/doc_crud.js b/test/javascript/tests-cluster/without-quorum/doc_crud.js
deleted file mode 100644
index 0a009d5..0000000
--- a/test/javascript/tests-cluster/without-quorum/doc_crud.js
+++ /dev/null
@@ -1,36 +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.
-
-couchTests.doc_crud = function(debug) {
- return console.log('done in test/elixir/test/cluster_without_quorum_test.exs');
- var db_name = get_random_db_name();
- var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"});
- db.createDb();
- if (debug) debugger;
-
- db.save({_id:"0",a:1});
- T(db.last_req.status=="202","Should return 202 status");
-
- var doc = db.open("0");
- db.save(doc);
- T(db.last_req.status=="202","Should return 202 status");
-
- doc = db.open("0");
- db.deleteDoc(doc);
- T(db.last_req.status="202","Should return 202 status");
-
- //db.deleteDb();
- // cleanup
- // TODO DB deletions fails if the quorum is not met.
- xhr = CouchDB.request("DELETE", "/" + db_name + "/");
-
-}
diff --git a/test/javascript/tests-cluster/without-quorum/doc_crud_overridden_quorum.js b/test/javascript/tests-cluster/without-quorum/doc_crud_overridden_quorum.js
deleted file mode 100644
index 9eb83bd..0000000
--- a/test/javascript/tests-cluster/without-quorum/doc_crud_overridden_quorum.js
+++ /dev/null
@@ -1,35 +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.
-
-couchTests.doc_crud_overridden_quorum = function(debug) {
- return console.log('done in test/elixir/test/cluster_without_quorum_test.exs');
- var db_name = get_random_db_name();
- var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"},{"w":1});
- db.createDb();
- if (debug) debugger;
-
- db.save({_id:"0",a:1});
- T(db.last_req.status=="201","Should return 201 status");
-
- var doc = db.open("0");
- db.save(doc);
- T(db.last_req.status=="201","Should return 201 status");
-
- doc = db.open("0");
- db.deleteDoc(doc);
- T(db.last_req.status="200","Should return 200 status");
-
- //db.deleteDb();
- // cleanup
- // TODO DB deletions fails if the quorum is not met.
- xhr = CouchDB.request("DELETE", "/" + db_name + "/");
-}
diff --git a/test/javascript/tests/all_docs.js b/test/javascript/tests/all_docs.js
deleted file mode 100644
index 0eb382f..0000000
--- a/test/javascript/tests/all_docs.js
+++ /dev/null
@@ -1,167 +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.
-
-couchTests.elixir = true;
-couchTests.all_docs = function(debug) {
- return console.log('done in test/elixir/test/all_docs_test.exs');
- var db_name = get_random_db_name();
- var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"}, {w: 3});
- db.createDb();
- if (debug) debugger;
-
- // Create some more documents.
- // Notice the use of the ok member on the return result.
-
- var doc1 = db.save({_id:"0",a:1,b:1});
- var doc2 = db.save({_id:"3",a:4,b:16});
- var doc3 = db.save({_id:"1",a:2,b:4});
- var doc4 = db.save({_id:"2",a:3,b:9});
-
- T(doc1.ok);
- T(doc2.ok);
- T(doc3.ok);
- T(doc4.ok);
-
- var revs = [];
- revs.push(doc1.rev);
- revs.push(doc2.rev);
- revs.push(doc3.rev);
- revs.push(doc4.rev);
-
- // Check the all docs
- var results = db.allDocs();
- var rows = results.rows;
-
- T(results.total_rows == results.rows.length);
-
- for(var i=0; i < rows.length; i++) {
- T(rows[i].id >= "0" && rows[i].id <= "4");
- }
-
- // Check _all_docs with descending=true
- var desc = db.allDocs({descending:true});
- T(desc.total_rows == desc.rows.length);
-
- // Check _all_docs offset
- var all = db.allDocs({startkey:"2"});
- T(all.offset == 2);
-
- // Confirm that queries may assume raw collation.
- var raw = db.allDocs({ startkey: "org.couchdb.user:",
- endkey : "org.couchdb.user;"
- });
- TEquals(0, raw.rows.length);
-
-
- // check that all docs show up in the changes feed
- // the order can vary
- var changes = db.changes();
- changes.results.forEach(function(row, idx) {
- var rev = row.changes[0].rev;
- TEquals(true, revs.indexOf(rev) !== -1, "doc " + i + " should be in changes");
- });
-
- // check that deletions also show up right
- var doc1 = db.open("1");
- var deleted = db.deleteDoc(doc1);
- T(deleted.ok);
- changes = db.changes();
- T(changes.results.length == 4);
- var deleted_doc = changes.results.filter(function(row) {
- return row.deleted == true;
- })[0];
- TEquals("1", deleted_doc.id, "deletes");
-
- // (remember old seq)
- var orig_doc = changes.results.filter(function(row) {
- return row.id == "3"
- })[0];
- // do an update
- var doc3 = db.open("3");
- doc3.updated = "totally";
- doc3 = db.save(doc3);
- changes = db.changes();
-
- // the update should make doc id 3 have another seq num (not nec. higher or the last though)
- T(changes.results.length == 4);
- var updated_doc = changes.results.filter(function(row) {
- return row.id == "3"
- })[0];
- T(orig_doc.seq != updated_doc.seq, "seq num should be different");
-
- // ok now lets see what happens with include docs
- changes = db.changes({include_docs: true});
- T(changes.results.length == 4);
-
- var updated_doc = changes.results.filter(function(row) {
- return row.id == doc3.id
- })[0];
- T(updated_doc.doc.updated == "totally");
-
- var deleted_doc = changes.results.filter(function(row) {
- return row.deleted == true;
- })[0];
- TEquals(true, deleted_doc.doc._deleted, "deletes");
-
- rows = db.allDocs({include_docs: true}, ["1"]).rows;
- TEquals(1, rows.length);
- TEquals("1", rows[0].key);
- TEquals("1", rows[0].id);
- TEquals(true, rows[0].value.deleted);
- TEquals(null, rows[0].doc);
-
- // add conflicts
- var conflictDoc1 = {
- _id: "3", _rev: "2-aa01552213fafa022e6167113ed01087", value: "X"
- };
- var conflictDoc2 = {
- _id: "3", _rev: "2-ff01552213fafa022e6167113ed01087", value: "Z"
- };
- T(db.save(conflictDoc1, {new_edits: false}));
- T(db.save(conflictDoc2, {new_edits: false}));
-
- var winRev = db.open("3");
-
- changes = db.changes({include_docs: true, conflicts: true, style: "all_docs"});
-
- var doc3 = changes.results.filter(function(row) {
- return row.id == "3";
- })[0];
-
- TEquals("3", doc3.id);
- TEquals(3, doc3.changes.length);
- TEquals(winRev._rev, doc3.changes[0].rev);
- TEquals("3", doc3.doc._id);
- TEquals(winRev._rev, doc3.doc._rev);
- TEquals(true, doc3.doc._conflicts instanceof Array);
- TEquals(2, doc3.doc._conflicts.length);
-
- rows = db.allDocs({include_docs: true, conflicts: true}).rows;
- TEquals(3, rows.length);
- TEquals("3", rows[2].key);
- TEquals("3", rows[2].id);
- TEquals(winRev._rev, rows[2].value.rev);
- TEquals(winRev._rev, rows[2].doc._rev);
- TEquals("3", rows[2].doc._id);
- TEquals(true, rows[2].doc._conflicts instanceof Array);
- TEquals(2, rows[2].doc._conflicts.length);
-
- // test the all docs collates sanely
- db.save({_id: "Z", foo: "Z"});
- db.save({_id: "a", foo: "a"});
-
- var rows = db.allDocs({startkey: "Z", endkey: "Z"}).rows;
- T(rows.length == 1);
-
- // cleanup
- db.deleteDb();
-};
diff --git a/test/javascript/tests/attachment_names.js b/test/javascript/tests/attachment_names.js
deleted file mode 100644
index 16a23ac..0000000
--- a/test/javascript/tests/attachment_names.js
+++ /dev/null
@@ -1,99 +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.
-
-couchTests.elixir = true;
-couchTests.attachment_names = function(debug) {
- return console.log('done in test/elixir/test/attachment_names_test.exs');
- var db_name = get_random_db_name();
- var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"}, {w: 3});
- db.createDb();
- if (debug) debugger;
-
- var goodDoc = {
- _id: "good_doc",
- _attachments: {
- "Колян.txt": {
- content_type:"application/octet-stream",
- data: "VGhpcyBpcyBhIGJhc2U2NCBlbmNvZGVkIHRleHQ="
- }
- }
- };
-
- var save_response = db.save(goodDoc);
- T(save_response.ok);
-
- var xhr = CouchDB.request("GET", "/" + db_name + "/good_doc/Колян.txt");
- T(xhr.responseText == "This is a base64 encoded text");
- T(xhr.getResponseHeader("Content-Type") == "application/octet-stream");
- TEquals("\"aEI7pOYCRBLTRQvvqYrrJQ==\"", xhr.getResponseHeader("Etag"));
-
- var binAttDoc = {
- _id: "bin_doc",
- _attachments:{
- "footxt": {
- content_type:"text/plain",
- data: "VGhpcyBpcyBhIGJhc2U2NCBlbmNvZGVkIHRleHQ="
- }
- }
- };
-
- // inline attachments
- resp = db.save(binAttDoc);
- TEquals(true, resp.ok, "attachment_name: inline attachment");
-
-
- // standalone docs
- var bin_data = "JHAPDO*AU£PN ){(3u[d 93DQ9¡€])} ææøo'∂ƒæ≤çæππ•¥∫¶®#†π¶®¥π€ª®˙π8np";
-
-
- var xhr = (CouchDB.request("PUT", "/" + db_name + "/bin_doc3/attachmenttxt", {
- headers:{"Content-Type":"text/plain;charset=utf-8"},
- body:bin_data
- }));
-
- var resp = JSON.parse(xhr.responseText);
- TEquals(201, xhr.status, "attachment_name: standalone API");
- TEquals(true, resp.ok, "attachment_name: standalone API");
-
- // bulk docs
- var docs = { docs: [binAttDoc] };
- var xhr = CouchDB.request("POST", "/" + db_name + "/_bulk_docs", {
- body: JSON.stringify(docs)
- });
-
- TEquals(201, xhr.status, "attachment_name: bulk docs");
-
-
- // leading underscores
- var binAttDoc = {
- _id: "bin_doc2",
- _attachments:{
- "_foo.txt": {
- content_type:"text/plain",
- data: "VGhpcyBpcyBhIGJhc2U2NCBlbmNvZGVkIHRleHQ="
- }
- }
- };
-
- try {
- db.save(binAttDoc);
- TEquals(1, 2, "Attachment name with leading underscore saved. Should never show!");
- } catch (e) {
- TEquals("bad_request", e.error, "attachment_name: leading underscore");
- TEquals("Attachment name '_foo.txt' starts with prohibited character '_'", e.reason, "attachment_name: leading underscore");
- }
-
- // todo: form uploads, waiting for cmlenz' test case for form uploads
- // cleanup
- db.deleteDb();
-
-};
diff --git a/test/javascript/tests/attachment_paths.js b/test/javascript/tests/attachment_paths.js
deleted file mode 100644
index b8c6a79..0000000
--- a/test/javascript/tests/attachment_paths.js
+++ /dev/null
@@ -1,156 +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.
-
-couchTests.elixir = true;
-couchTests.attachment_paths = function(debug) {
- return console.log('done in test/elixir/test/attachment_paths_test.exs');
- if (debug) debugger;
- var r_db_name = get_random_db_name()
- var dbNames = [r_db_name, r_db_name + "/with_slashes"];
- for (var i=0; i < dbNames.length; i++) {
- var db = new CouchDB(dbNames[i]);
- var dbName = encodeURIComponent(dbNames[i]);
- db.createDb();
-
- // first just save a regular doc with an attachment that has a slash in the url.
- // (also gonna run an encoding check case)
- var binAttDoc = {
- _id: "bin_doc",
- _attachments:{
- "foo/bar.txt": {
- content_type:"text/plain",
- data: "VGhpcyBpcyBhIGJhc2U2NCBlbmNvZGVkIHRleHQ="
- },
- "foo%2Fbaz.txt": {
- content_type:"text/plain",
- data: "V2UgbGlrZSBwZXJjZW50IHR3byBGLg=="
- }
- }
- };
-
- T(db.save(binAttDoc).ok);
-
- var xhr = CouchDB.request("GET", "/"+dbName+"/bin_doc/foo/bar.txt");
- T(xhr.responseText == "This is a base64 encoded text");
- T(xhr.getResponseHeader("Content-Type") == "text/plain");
-
- // lets try it with an escaped attachment id...
- // weird that it's at two urls
- var xhr = CouchDB.request("GET", "/"+dbName+"/bin_doc/foo%2Fbar.txt");
- T(xhr.status == 200);
- // xhr.responseText == "This is a base64 encoded text"
-
- var xhr = CouchDB.request("GET", "/"+dbName+"/bin_doc/foo/baz.txt");
- T(xhr.status == 404);
-
- var xhr = CouchDB.request("GET", "/"+dbName+"/bin_doc/foo%252Fbaz.txt");
- T(xhr.status == 200);
- T(xhr.responseText == "We like percent two F.");
-
- // require a _rev to PUT
- var xhr = CouchDB.request("PUT", "/"+dbName+"/bin_doc/foo/attachment.txt", {
- headers:{"Content-Type":"text/plain;charset=utf-8"},
- body:"Just some text"
- });
- T(xhr.status == 409);
-
- var xhr = CouchDB.request("PUT", "/"+dbName+"/bin_doc/foo/bar2.txt?rev=" + binAttDoc._rev, {
- body:"This is no base64 encoded text",
- headers:{"Content-Type": "text/plain;charset=utf-8"}
- });
- T(xhr.status == 201);
- var rev = JSON.parse(xhr.responseText).rev;
-
- binAttDoc = db.open("bin_doc");
-
- T(binAttDoc._attachments["foo/bar.txt"] !== undefined);
- T(binAttDoc._attachments["foo%2Fbaz.txt"] !== undefined);
- T(binAttDoc._attachments["foo/bar2.txt"] !== undefined);
- TEquals("text/plain;charset=utf-8", // thank you Safari
- binAttDoc._attachments["foo/bar2.txt"].content_type.toLowerCase(),
- "correct content-type"
- );
- T(binAttDoc._attachments["foo/bar2.txt"].length == 30);
-
- //// now repeat the while thing with a design doc
-
- // first just save a regular doc with an attachment that has a slash in the url.
- // (also gonna run an encoding check case)
- var binAttDoc = {
- _id: "_design/bin_doc",
- _attachments:{
- "foo/bar.txt": {
- content_type:"text/plain",
- data: "VGhpcyBpcyBhIGJhc2U2NCBlbmNvZGVkIHRleHQ="
- },
- "foo%2Fbaz.txt": {
- content_type:"text/plain",
- data: "V2UgbGlrZSBwZXJjZW50IHR3byBGLg=="
- }
- }
- };
-
- T(db.save(binAttDoc).ok);
-
- var xhr = CouchDB.request("GET", "/"+dbName+"/_design%2Fbin_doc/foo/bar.txt");
- T(xhr.responseText == "This is a base64 encoded text");
- T(xhr.getResponseHeader("Content-Type") == "text/plain");
-
- // lets try it with an escaped attachment id...
- // weird that it's at two urls
- var xhr = CouchDB.request("GET", "/"+dbName+"/_design%2Fbin_doc/foo%2Fbar.txt");
- T(xhr.responseText == "This is a base64 encoded text");
- T(xhr.status == 200);
-
- // err, 3 urls
- var xhr = CouchDB.request("GET", "/"+dbName+"/_design/bin_doc/foo%2Fbar.txt");
- T(xhr.responseText == "This is a base64 encoded text");
- T(xhr.status == 200);
-
- // I mean um, 4 urls
- var xhr = CouchDB.request("GET", "/"+dbName+"/_design/bin_doc/foo/bar.txt");
- T(xhr.responseText == "This is a base64 encoded text");
- T(xhr.status == 200);
-
- var xhr = CouchDB.request("GET", "/"+dbName+"/_design%2Fbin_doc/foo/baz.txt");
- T(xhr.status == 404);
-
- var xhr = CouchDB.request("GET", "/"+dbName+"/_design%2Fbin_doc/foo%252Fbaz.txt");
- T(xhr.status == 200);
- T(xhr.responseText == "We like percent two F.");
-
- // require a _rev to PUT
- var xhr = CouchDB.request("PUT", "/"+dbName+"/_design%2Fbin_doc/foo/attachment.txt", {
- headers:{"Content-Type":"text/plain;charset=utf-8"},
- body:"Just some text"
- });
- T(xhr.status == 409);
-
- var xhr = CouchDB.request("PUT", "/"+dbName+"/_design%2Fbin_doc/foo/bar2.txt?rev=" + binAttDoc._rev, {
- body:"This is no base64 encoded text",
- headers:{"Content-Type": "text/plain;charset=utf-8"}
- });
- T(xhr.status == 201);
- var rev = JSON.parse(xhr.responseText).rev;
-
- binAttDoc = db.open("_design/bin_doc");
-
- T(binAttDoc._attachments["foo/bar.txt"] !== undefined);
- T(binAttDoc._attachments["foo/bar2.txt"] !== undefined);
- TEquals("text/plain;charset=utf-8", // thank you Safari
- binAttDoc._attachments["foo/bar2.txt"].content_type.toLowerCase(),
- "correct content-type"
- );
- T(binAttDoc._attachments["foo/bar2.txt"].length == 30);
- db.deleteDb();
- }
-};
diff --git a/test/javascript/tests/attachment_ranges.js b/test/javascript/tests/attachment_ranges.js
deleted file mode 100644
index 564885c..0000000
--- a/test/javascript/tests/attachment_ranges.js
+++ /dev/null
@@ -1,164 +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.
-
-function cacheBust() {
- return "?anti-cache=" + String(Math.round(Math.random() * 1000000));
-};
-
-couchTests.elixir = true;
-couchTests.attachment_ranges = function(debug) {
- return console.log('done in test/elixir/test/attachment_ranges_test.exs');
- var db_name = get_random_db_name();
- var db = new CouchDB(db_name, {
- "X-Couch-Full-Commit": "false"
- });
- db.createDb();
-
- if (debug) debugger;
-
- if((typeof window != "undefined") && window.navigator.userAgent.match(/Chrome/)) {
- // Chrome is broken.
- return;
- }
-
- var binAttDoc = {
- _id: "bin_doc",
- _attachments: {
- "foo.txt": {
- content_type: "application/octet-stream",
- data: "VGhpcyBpcyBhIGJhc2U2NCBlbmNvZGVkIHRleHQ="
- }
- }
- };
-
- var save_response = db.save(binAttDoc);
- T(save_response.ok);
-
- // Fetching the whole entity is a 206.
- var xhr = CouchDB.request("GET", "/" + db_name + "/bin_doc/foo.txt" + cacheBust(), {
- headers: {
- "Range": "bytes=0-28"
- }
- });
- TEquals(206, xhr.status, "fetch 0-28");
- TEquals("This is a base64 encoded text", xhr.responseText);
- TEquals("bytes 0-28/29", xhr.getResponseHeader("Content-Range"));
- TEquals("29", xhr.getResponseHeader("Content-Length"));
-
- // Fetch the whole entity without an end offset is a 200.
- var xhr = CouchDB.request("GET", "/" + db_name + "/bin_doc/foo.txt" + cacheBust(), {
- headers: {
- "Range": "bytes=0-"
- }
- });
- TEquals(200, xhr.status, "fetch 0-");
- TEquals("This is a base64 encoded text", xhr.responseText);
- TEquals(null, xhr.getResponseHeader("Content-Range"));
- TEquals("29", xhr.getResponseHeader("Content-Length"));
-
- // Even if you ask multiple times.
- var xhr = CouchDB.request("GET", "/" + db_name + "/bin_doc/foo.txt" + cacheBust(), {
- headers: {
- "Range": "bytes=0-,0-,0-"
- }
- });
- TEquals(200, xhr.status, "multiple 0-'s");
-
- // Badly formed range header is a 200.
- var xhr = CouchDB.request("GET", "/" + db_name + "/bin_doc/foo.txt" + cacheBust(), {
- headers: {
- "Range": "bytes:0-"
- }
- });
- TEquals(200, xhr.status, "fetch with bad range header");
-
- // Fetch the end of an entity without an end offset is a 206.
- var xhr = CouchDB.request("GET", "/" + db_name + "/bin_doc/foo.txt" + cacheBust(), {
- headers: {
- "Range": "bytes=2-"
- }
- });
- TEquals(206, xhr.status, "fetch 2-");
- TEquals("is is a base64 encoded text", xhr.responseText);
- TEquals("bytes 2-28/29", xhr.getResponseHeader("Content-Range"));
- TEquals("27", xhr.getResponseHeader("Content-Length"));
-
- // Fetch past the end of the entity is a 206
- var xhr = CouchDB.request("GET", "/" + db_name + "/bin_doc/foo.txt" + cacheBust(), {
- headers: {
- "Range": "bytes=0-29"
- }
- });
- TEquals(206, xhr.status, "fetch 0-29");
- TEquals("bytes 0-28/29", xhr.getResponseHeader("Content-Range"));
- TEquals("29", xhr.getResponseHeader("Content-Length"));
-
- // Fetch first part of entity is a 206
- var xhr = CouchDB.request("GET", "/" + db_name + "/bin_doc/foo.txt" + cacheBust(), {
- headers: {
- "Range": "bytes=0-3"
- }
- });
- TEquals(206, xhr.status, "fetch 0-3");
- TEquals("This", xhr.responseText);
- TEquals("4", xhr.getResponseHeader("Content-Length"));
- TEquals("bytes 0-3/29", xhr.getResponseHeader("Content-Range"));
-
- // Fetch middle of entity is also a 206
- var xhr = CouchDB.request("GET", "/" + db_name + "/bin_doc/foo.txt" + cacheBust(), {
- headers: {
- "Range": "bytes=10-15"
- }
- });
- TEquals(206, xhr.status, "fetch 10-15");
- TEquals("base64", xhr.responseText);
- TEquals("6", xhr.getResponseHeader("Content-Length"));
- TEquals("bytes 10-15/29", xhr.getResponseHeader("Content-Range"));
-
- // Fetch end of entity is also a 206
- var xhr = CouchDB.request("GET", "/" + db_name + "/bin_doc/foo.txt" + cacheBust(), {
- headers: {
- "Range": "bytes=-3"
- }
- });
- TEquals(206, xhr.status, "fetch -3");
- TEquals("ext", xhr.responseText);
- TEquals("3", xhr.getResponseHeader("Content-Length"));
- TEquals("bytes 26-28/29", xhr.getResponseHeader("Content-Range"));
-
- // backward range is 416
- var xhr = CouchDB.request("GET", "/" + db_name + "/bin_doc/foo.txt" + cacheBust(), {
- headers: {
- "Range": "bytes=5-3"
- }
- });
- TEquals(416, xhr.status, "fetch 5-3");
-
- // range completely outside of entity is 416
- var xhr = CouchDB.request("GET", "/" + db_name + "/bin_doc/foo.txt" + cacheBust(), {
- headers: {
- "Range": "bytes=300-310"
- }
- });
- TEquals(416, xhr.status, "fetch 300-310");
-
- // We ignore a Range header with too many ranges
- var xhr = CouchDB.request("GET", "/" + db_name + "/bin_doc/foo.txt" + cacheBust(), {
- headers: {
- "Range": "bytes=0-1,0-1,0-1,0-1,0-1,0-1,0-1,0-1,0-1,0-1"
- }
- });
- TEquals(200, xhr.status, "too many ranges");
- // cleanup
- db.deleteDb();
-
-};
diff --git a/test/javascript/tests/attachment_views.js b/test/javascript/tests/attachment_views.js
deleted file mode 100644
index c6c4b18..0000000
--- a/test/javascript/tests/attachment_views.js
+++ /dev/null
@@ -1,145 +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.
-
-couchTests.elixir = true;
-couchTests.attachment_views= function(debug) {
- return console.log('done in test/elixir/test/attachment_views_test.exs');
-
- var db_name = get_random_db_name()
- var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"});
- db.createDb();
- if (debug) debugger;
-
- // count attachments in a view
-
- var attachmentData = "VGhpcyBpcyBhIGJhc2U2NCBlbmNvZGVkIHRleHQ=";
-
- db.bulkSave(makeDocs(0, 10));
-
- db.bulkSave(makeDocs(10, 20, {
- _attachments:{
- "foo.txt": {
- content_type:"text/plain",
- data: attachmentData
- }
- }
- }));
-
- db.bulkSave(makeDocs(20, 30, {
- _attachments:{
- "foo.txt": {
- content_type:"text/plain",
- data: attachmentData
- },
- "bar.txt": {
- content_type:"text/plain",
- data: attachmentData
- }
- }
- }));
-
- db.bulkSave(makeDocs(30, 40, {
- _attachments:{
- "foo.txt": {
- content_type:"text/plain",
- data: attachmentData
- },
- "bar.txt": {
- content_type:"text/plain",
- data: attachmentData
- },
- "baz.txt": {
- content_type:"text/plain",
- data: attachmentData
- }
- }
- }));
-
- var mapFunction = function(doc) {
- var count = 0;
-
- for(var idx in doc._attachments) {
- count = count + 1;
- }
-
- emit(parseInt(doc._id), count);
- };
-
- var reduceFunction = function(key, values) {
- return sum(values);
- };
-
- var result = db.query(mapFunction, reduceFunction);
-
- T(result.rows.length == 1);
- T(result.rows[0].value == 60);
-
- var result = db.query(mapFunction, reduceFunction, {
- startkey:10,
- endkey:19
- });
-
- T(result.rows.length == 1);
- T(result.rows[0].value == 10);
-
- var result = db.query(mapFunction, reduceFunction, {
- startkey:20,
- endkey:29
- });
-
- T(result.rows.length == 1);
- T(result.rows[0].value == 20);
-
- var result = db.query(mapFunction, null, {
- startkey: 30,
- endkey: 39,
- include_docs: true
- });
-
- T(result.rows.length == 10);
- T(result.rows[0].value == 3);
- T(result.rows[0].doc._attachments['baz.txt'].stub === true);
- T(result.rows[0].doc._attachments['baz.txt'].data === undefined);
- T(result.rows[0].doc._attachments['baz.txt'].encoding === undefined);
- T(result.rows[0].doc._attachments['baz.txt'].encoded_length === undefined);
-
- var result = db.query(mapFunction, null, {
- startkey: 30,
- endkey: 39,
- include_docs: true,
- attachments: true
- });
-
- T(result.rows.length == 10);
- T(result.rows[0].value == 3);
- T(result.rows[0].doc._attachments['baz.txt'].data === attachmentData);
- T(result.rows[0].doc._attachments['baz.txt'].stub === undefined);
- T(result.rows[0].doc._attachments['baz.txt'].encoding === undefined);
- T(result.rows[0].doc._attachments['baz.txt'].encoded_length === undefined);
-
- var result = db.query(mapFunction, null, {
- startkey: 30,
- endkey: 39,
- include_docs: true,
- att_encoding_info: true
- });
-
- T(result.rows.length == 10);
- T(result.rows[0].value == 3);
- T(result.rows[0].doc._attachments['baz.txt'].data === undefined);
- T(result.rows[0].doc._attachments['baz.txt'].stub === true);
- T(result.rows[0].doc._attachments['baz.txt'].encoding === "gzip");
- T(result.rows[0].doc._attachments['baz.txt'].encoded_length === 47);
-
- // cleanup
- db.deleteDb();
-};
diff --git a/test/javascript/tests/attachments.js b/test/javascript/tests/attachments.js
deleted file mode 100644
index 61fe8b9..0000000
--- a/test/javascript/tests/attachments.js
+++ /dev/null
@@ -1,358 +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.
-
-couchTests.elixir = true;
-couchTests.attachments= function(debug) {
- return console.log('done in test/elixir/test/attachment_test.exs');
- var db_name = get_random_db_name();
- var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"});
- db.createDb();
- if (debug) debugger;
-
-
- // MD5 Digests of compressible attachments and therefore Etags
- // will vary depending on platform gzip implementation.
- // These MIME types are defined in [attachments] compressible_types
- var binAttDoc = {
- _id: "bin_doc",
- _attachments:{
- "foo.txt": {
- content_type:"application/octet-stream",
- data: "VGhpcyBpcyBhIGJhc2U2NCBlbmNvZGVkIHRleHQ="
- }
- }
- };
-
- var save_response = db.save(binAttDoc);
- T(save_response.ok);
-
- var badAttDoc = {
- _id: "bad_doc",
- _attachments: {
- "foo.txt": {
- content_type: "text/plain",
- data: "notBase64Encoded="
- }
- }
- };
-
- try {
- db.save(badAttDoc);
- T(false && "Shouldn't get here!");
- } catch (e) {
- TEquals("bad_request", e.error);
- TEquals("Invalid attachment data for foo.txt", e.message);
- }
-
- var xhr = CouchDB.request("GET", "/" + db_name + "/bin_doc/foo.txt");
- T(xhr.responseText == "This is a base64 encoded text");
- T(xhr.getResponseHeader("Content-Type") == "application/octet-stream");
- TEquals("\"aEI7pOYCRBLTRQvvqYrrJQ==\"", xhr.getResponseHeader("Etag"));
-
- // empty attachment
- var binAttDoc2 = {
- _id: "bin_doc2",
- _attachments:{
- "foo.txt": {
- content_type:"text/plain",
- data: ""
- }
- }
- }
-
- T(db.save(binAttDoc2).ok);
-
- var xhr = CouchDB.request("GET", "/" + db_name + "/bin_doc2/foo.txt");
- T(xhr.responseText.length == 0);
- T(xhr.getResponseHeader("Content-Type") == "text/plain");
-
- // test RESTful doc API
-
- var xhr = CouchDB.request("PUT", "/" + db_name + "/bin_doc2/foo2.txt?rev=" + binAttDoc2._rev, {
- body:"This is no base64 encoded text",
- headers:{"Content-Type": "text/plain;charset=utf-8"}
- });
- T(xhr.status == 201);
- TEquals("/bin_doc2/foo2.txt",
- xhr.getResponseHeader("Location").substr(-18),
- "should return Location header to newly created or updated attachment");
-
- var rev = JSON.parse(xhr.responseText).rev;
-
- binAttDoc2 = db.open("bin_doc2");
-
- T(binAttDoc2._attachments["foo.txt"] !== undefined);
- T(binAttDoc2._attachments["foo2.txt"] !== undefined);
- TEqualsIgnoreCase("text/plain;charset=utf-8", binAttDoc2._attachments["foo2.txt"].content_type);
- T(binAttDoc2._attachments["foo2.txt"].length == 30);
-
- var xhr = CouchDB.request("GET", "/" + db_name + "/bin_doc2/foo2.txt");
- T(xhr.responseText == "This is no base64 encoded text");
- TEqualsIgnoreCase("text/plain;charset=utf-8", xhr.getResponseHeader("Content-Type"));
-
- // test without rev, should fail
- var xhr = CouchDB.request("DELETE", "/" + db_name + "/bin_doc2/foo2.txt");
- T(xhr.status == 409);
-
- // test with rev, should not fail
- var xhr = CouchDB.request("DELETE", "/" + db_name + "/bin_doc2/foo2.txt?rev=" + rev);
- T(xhr.status == 200);
- TEquals(null, xhr.getResponseHeader("Location"),
- "should not return Location header on DELETE request");
-
- // test binary data
- var bin_data = "JHAPDO*AU£PN ){(3u[d 93DQ9¡€])} ææøo'∂ƒæ≤çæππ•¥∫¶®#†π¶®¥π€ª®˙π8np";
- var xhr = CouchDB.request("PUT", "/" + db_name + "/bin_doc3/attachment.txt", {
- headers:{"Content-Type":"text/plain;charset=utf-8"},
- body:bin_data
- });
- T(xhr.status == 201);
- var rev = JSON.parse(xhr.responseText).rev;
-// TODO: revisit Etags (missing on doc write)
-// TEquals('"' + rev + '"', xhr.getResponseHeader("Etag"));
-
- var xhr = CouchDB.request("GET", "/" + db_name + "/bin_doc3/attachment.txt");
- T(xhr.responseText == bin_data);
- TEqualsIgnoreCase("text/plain;charset=utf-8", xhr.getResponseHeader("Content-Type"));
-
- // without rev
- var xhr = CouchDB.request("PUT", "/" + db_name + "/bin_doc3/attachment.txt", {
- headers:{"Content-Type":"text/plain;charset=utf-8"},
- body:bin_data
- });
- T(xhr.status == 409);
-
- // with nonexistent rev
- var xhr = CouchDB.request("PUT", "/" + db_name + "/bin_doc3/attachment.txt" + "?rev=1-adae8575ecea588919bd08eb020c708e", {
- headers:{"Content-Type":"text/plain;charset=utf-8"},
- body:bin_data
- });
- T(xhr.status == 409);
-
- // with current rev
- var xhr = CouchDB.request("PUT", "/" + db_name + "/bin_doc3/attachment.txt?rev=" + rev, {
- headers:{"Content-Type":"text/plain;charset=utf-8"},
- body:bin_data
- });
- T(xhr.status == 201);
- var rev = JSON.parse(xhr.responseText).rev;
-// TODO: revisit Etags (missing on doc write)
-// TEquals('"' + rev + '"', xhr.getResponseHeader("Etag"));
-
- var xhr = CouchDB.request("GET", "/" + db_name + "/bin_doc3/attachment.txt");
- T(xhr.responseText == bin_data);
- TEqualsIgnoreCase("text/plain;charset=utf-8", xhr.getResponseHeader("Content-Type"));
-
- var xhr = CouchDB.request("GET", "/" + db_name + "/bin_doc3/attachment.txt?rev=" + rev);
- T(xhr.responseText == bin_data);
- TEqualsIgnoreCase("text/plain;charset=utf-8", xhr.getResponseHeader("Content-Type"));
-
- var xhr = CouchDB.request("DELETE", "/" + db_name + "/bin_doc3/attachment.txt?rev=" + rev);
- T(xhr.status == 200);
-
- var xhr = CouchDB.request("GET", "/" + db_name + "/bin_doc3/attachment.txt");
- T(xhr.status == 404);
-
- // deleted attachment is still accessible with revision
- var xhr = CouchDB.request("GET", "/" + db_name + "/bin_doc3/attachment.txt?rev=" + rev);
- T(xhr.status == 200);
- T(xhr.responseText == bin_data);
- TEqualsIgnoreCase("text/plain;charset=utf-8", xhr.getResponseHeader("Content-Type"));
-
- // empty attachments
- var xhr = CouchDB.request("PUT", "/" + db_name + "/bin_doc4/attachment.txt", {
- headers:{"Content-Type":"text/plain;charset=utf-8"},
- body:""
- });
- T(xhr.status == 201);
- var rev = JSON.parse(xhr.responseText).rev;
-
- var xhr = CouchDB.request("GET", "/" + db_name + "/bin_doc4/attachment.txt");
- T(xhr.status == 200);
- T(xhr.responseText.length == 0);
-
- // overwrite previsously empty attachment
- var xhr = CouchDB.request("PUT", "/" + db_name + "/bin_doc4/attachment.txt?rev=" + rev, {
- headers:{"Content-Type":"text/plain;charset=utf-8"},
- body:"This is a string"
- });
- T(xhr.status == 201);
-
- var xhr = CouchDB.request("GET", "/" + db_name + "/bin_doc4/attachment.txt");
- T(xhr.status == 200);
- T(xhr.responseText == "This is a string");
-
- // Attachment sparseness COUCHDB-220
-
- var docs = [];
- for (var i = 0; i < 5; i++) {
- var doc = {
- _id: (i).toString(),
- _attachments:{
- "foo.txt": {
- content_type:"text/plain",
- data: "VGhpcyBpcyBhIGJhc2U2NCBlbmNvZGVkIHRleHQ="
- }
- }
- };
- docs.push(doc);
- }
-
- var saved = db.bulkSave(docs);
- // now delete the docs, and while we are looping over them, remove the
- // '_rev' field so we can re-create after deletion.
- var to_up = [];
- for (i=0;i<saved.length;i++) {
- to_up.push({'_id': saved[i]['id'], '_rev': saved[i]['rev'], '_deleted': true});
- delete docs[i]._rev;
- }
- // delete them.
- var saved2 = db.bulkSave(to_up);
- // re-create them
- var saved3 = db.bulkSave(docs);
-
- var before = db.info().sizes.file;
-
- // Compact it.
- /*T(db.compact().ok);
- T(db.last_req.status == 202);
- // compaction isn't instantaneous, loop until done
- while (db.info().compact_running) {};
-
- var after = db.info().sizes.file;
-
- // Compaction should reduce the database slightly, but not
- // orders of magnitude (unless attachments introduce sparseness)
- T(after > before * 0.1, "before: " + before + " after: " + after);
-*/
-
- // test large attachments - COUCHDB-366
- var lorem = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. '
- for (var i=0; i<10; i++) {
- lorem = lorem + lorem;
- }
- var xhr = CouchDB.request("PUT", "/" + db_name + "/bin_doc5/lorem.txt", {
- headers:{"Content-Type":"text/plain;charset=utf-8"},
- body:lorem
- });
- T(xhr.status == 201);
- var rev = JSON.parse(xhr.responseText).rev;
-
- var xhr = CouchDB.request("GET", "/" + db_name + "/bin_doc5/lorem.txt");
- T(xhr.responseText == lorem);
- TEqualsIgnoreCase("text/plain;charset=utf-8", xhr.getResponseHeader("Content-Type"));
-
- // test large inline attachment too
- var lorem_b64 = 'TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4g'
- for (var i=0; i<10; i++) {
- lorem_b64 = lorem_b64 + lorem_b64;
- }
- var doc = db.open("bin_doc5", {attachments:true});
- TEquals(lorem_b64, doc._attachments["lorem.txt"].data, 'binary attachment data should match');
-
- // test etags for attachments.
- var xhr = CouchDB.request("GET", "/" + db_name + "/bin_doc5/lorem.txt");
- T(xhr.status == 200);
- var etag = xhr.getResponseHeader("etag");
- xhr = CouchDB.request("GET", "/" + db_name + "/bin_doc5/lorem.txt", {
- headers: {"if-none-match": etag}
- });
- T(xhr.status == 304);
-
- // test COUCHDB-497 - empty attachments
- var xhr = CouchDB.request("PUT", "/" + db_name + "/bin_doc5/empty.txt?rev="+rev, {
- headers:{"Content-Type":"text/plain;charset=utf-8", "Content-Length": "0"},
- body:""
- });
- TEquals(201, xhr.status, "should send 201 Accepted");
- var rev = JSON.parse(xhr.responseText).rev;
- var xhr = CouchDB.request("PUT", "/" + db_name + "/bin_doc5/empty.txt?rev="+rev, {
- headers:{"Content-Type":"text/plain;charset=utf-8"}
- });
- TEquals(201, xhr.status, "should send 201 Accepted");
-
- // implicit doc creation allows creating docs with a reserved id. COUCHDB-565
- var xhr = CouchDB.request("PUT", "/" + db_name + "/_nonexistant/attachment.txt", {
- headers: {"Content-Type":"text/plain;charset=utf-8"},
- body: "THIS IS AN ATTACHMENT. BOOYA!"
- });
- TEquals(400, xhr.status, "should return error code 400 Bad Request");
-
- // test COUCHDB-809 - stubs should only require the 'stub' field
- var bin_doc6 = {
- _id: "bin_doc6",
- _attachments:{
- "foo.txt": {
- content_type:"text/plain",
- data: "VGhpcyBpcyBhIGJhc2U2NCBlbmNvZGVkIHRleHQ="
- }
- }
- };
- T(db.save(bin_doc6).ok);
- // stub out the attachment
- bin_doc6._attachments["foo.txt"] = { stub: true };
- T(db.save(bin_doc6).ok == true);
-
- // wrong rev pos specified
-
- // stub out the attachment with the wrong revpos
- bin_doc6._attachments["foo.txt"] = { stub: true, revpos: 10};
- try {
- T(db.save(bin_doc6).ok == true);
- T(false && "Shouldn't get here!");
- } catch (e) {
- T(e.error == "missing_stub");
- }
-
- // test MD5 header
- var bin_data = "foo bar"
- var xhr = CouchDB.request("PUT", "/" + db_name + "/bin_doc7/attachment.txt", {
- headers:{"Content-Type":"application/octet-stream",
- "Content-MD5":"MntvB0NYESObxH4VRDUycw=="},
- body:bin_data
- });
- TEquals(201, xhr.status);
-
- var xhr = CouchDB.request("GET", "/" + db_name + "/bin_doc7/attachment.txt");
- TEquals('MntvB0NYESObxH4VRDUycw==', xhr.getResponseHeader("Content-MD5"));
-
- // test attachment via multipart/form-data
- var bin_doc8 = {
- _id: "bin_doc8"
- };
- T(db.save(bin_doc8).ok);
- var doc = db.open("bin_doc8");
- var body = "------TF\r\n" +
- "Content-Disposition: form-data; name=\"_rev\"\r\n\r\n" +
- doc._rev + "\r\n" +
- "------TF\r\n" +
- "Content-Disposition: form-data; name=\"_attachments\"; filename=\"file.txt\"\r\n" +
- "Content-Type: text/plain\r\n\r\n" +
- "contents of file.txt\r\n\r\n" +
- "------TF--"
- xhr = CouchDB.request("POST", "/" + db_name + "/bin_doc8", {
- headers: {
- "Content-Type": "multipart/form-data; boundary=----TF",
- "Content-Length": body.length
- },
- body: body
- });
- TEquals(201, xhr.status);
- TEquals(true, JSON.parse(xhr.responseText).ok);
- var doc = db.open("bin_doc8");
- T(doc._attachments);
- T(doc._attachments['file.txt']);
-
- // cleanup
- db.deleteDb();
-
-};
diff --git a/test/javascript/tests/attachments_multipart.js b/test/javascript/tests/attachments_multipart.js
deleted file mode 100644
index 793c8c9..0000000
--- a/test/javascript/tests/attachments_multipart.js
+++ /dev/null
@@ -1,426 +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.
-
-couchTests.elixir = true;
-couchTests.attachments_multipart= function(debug) {
- return console.log('done in test/elixir/test/attachment_multipart_test.exs');
- var db_name = get_random_db_name()
- var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"});
- db.createDb();
- if (debug) debugger;
-
- // mime multipart
-
- var xhr = CouchDB.request("PUT", "/" + db_name + "/multipart", {
- headers: {"Content-Type": "multipart/related;boundary=\"abc123\""},
- body:
- "--abc123\r\n" +
- "content-type: application/json\r\n" +
- "\r\n" +
- JSON.stringify({
- "body":"This is a body.",
- "_attachments":{
- "foo.txt": {
- "follows":true,
- "content_type":"application/test",
- "length":21
- },
- "bar.txt": {
- "follows":true,
- "content_type":"application/test",
- "length":20
- },
- "baz.txt": {
- "follows":true,
- "content_type":"text/plain",
- "length":19
- }
- }
- }) +
- "\r\n--abc123\r\n" +
- "\r\n" +
- "this is 21 chars long" +
- "\r\n--abc123\r\n" +
- "\r\n" +
- "this is 20 chars lon" +
- "\r\n--abc123\r\n" +
- "\r\n" +
- "this is 19 chars lo" +
- "\r\n--abc123--epilogue"
- });
-
- var result = JSON.parse(xhr.responseText);
-
- T(result.ok);
-
-
-
- TEquals(201, xhr.status, "should send 201 Accepted");
-
- xhr = CouchDB.request("GET", "/" + db_name + "/multipart/foo.txt");
-
- T(xhr.responseText == "this is 21 chars long");
-
- xhr = CouchDB.request("GET", "/" + db_name + "/multipart/bar.txt");
-
- T(xhr.responseText == "this is 20 chars lon");
-
- xhr = CouchDB.request("GET", "/" + db_name + "/multipart/baz.txt");
-
- T(xhr.responseText == "this is 19 chars lo");
-
- // now edit an attachment
-
- var doc = db.open("multipart", {att_encoding_info: true});
- var firstrev = doc._rev;
-
- T(doc._attachments["foo.txt"].stub == true);
- T(doc._attachments["bar.txt"].stub == true);
- T(doc._attachments["baz.txt"].stub == true);
- TEquals("undefined", typeof doc._attachments["foo.txt"].encoding);
- TEquals("undefined", typeof doc._attachments["bar.txt"].encoding);
- TEquals("gzip", doc._attachments["baz.txt"].encoding);
-
- //lets change attachment bar
- delete doc._attachments["bar.txt"].stub; // remove stub member (or could set to false)
- delete doc._attachments["bar.txt"].digest; // remove the digest (it's for the gzip form)
- doc._attachments["bar.txt"].length = 18;
- doc._attachments["bar.txt"].follows = true;
- //lets delete attachment baz:
- delete doc._attachments["baz.txt"];
-
- var xhr = CouchDB.request("PUT", "/" + db_name + "/multipart", {
- headers: {"Content-Type": "multipart/related;boundary=\"abc123\""},
- body:
- "--abc123\r\n" +
- "content-type: application/json\r\n" +
- "\r\n" +
- JSON.stringify(doc) +
- "\r\n--abc123\r\n" +
- "\r\n" +
- "this is 18 chars l" +
- "\r\n--abc123--"
- });
- TEquals(201, xhr.status);
-
- xhr = CouchDB.request("GET", "/" + db_name + "/multipart/bar.txt");
-
- T(xhr.responseText == "this is 18 chars l");
-
- xhr = CouchDB.request("GET", "/" + db_name + "/multipart/baz.txt");
- T(xhr.status == 404);
-
- // now test receiving multipart docs
-
- function getBoundary(xhr) {
- var ctype = CouchDB.xhrheader(xhr, "Content-Type");
- var ctypeArgs = ctype.split("; ").slice(1);
- var boundary = null;
- for(var i=0; i<ctypeArgs.length; i++) {
- if (ctypeArgs[i].indexOf("boundary=") == 0) {
- boundary = ctypeArgs[i].split("=")[1];
- if (boundary.charAt(0) == '"') {
- // stringified boundary, parse as json
- // (will maybe not if there are escape quotes)
- boundary = JSON.parse(boundary);
- }
- }
- }
- return boundary;
- }
-
- function parseMultipart(xhr) {
- var boundary = getBoundary(xhr);
- var mimetext = CouchDB.xhrbody(xhr);
- // strip off leading boundary
- var leading = "--" + boundary + "\r\n";
- var last = "\r\n--" + boundary + "--";
-
- // strip off leading and trailing boundary
- var leadingIdx = mimetext.indexOf(leading) + leading.length;
- var trailingIdx = mimetext.indexOf(last);
- mimetext = mimetext.slice(leadingIdx, trailingIdx);
-
- // now split the sections
- var sections = mimetext.split(new RegExp("\\r\\n--" + boundary));
-
- // spilt out the headers for each section
- for(var i=0; i < sections.length; i++) {
- var section = sections[i];
- var headerEndIdx = section.indexOf("\r\n\r\n");
- var headersraw = section.slice(0, headerEndIdx).split(/\r\n/);
- var body = section.slice(headerEndIdx + 4);
- var headers = {};
- for(var j=0; j<headersraw.length; j++) {
- var tmp = headersraw[j].split(": ");
- headers[tmp[0]] = tmp[1];
- }
- sections[i] = {"headers":headers, "body":body};
- }
-
- return sections;
- }
-
-
- xhr = CouchDB.request("GET", "/" + db_name + "/multipart?attachments=true",
- {headers:{"accept": "multipart/related,*/*;"}});
-
- T(xhr.status == 200);
-
- // parse out the multipart
- var sections = parseMultipart(xhr);
- TEquals("790", xhr.getResponseHeader("Content-Length"),
- "Content-Length should be correct");
- T(sections.length == 3);
- // The first section is the json doc. Check it's content-type.
- // Each part carries their own meta data.
- TEquals("application/json", sections[0].headers['Content-Type'],
- "Content-Type should be application/json for section[0]");
- TEquals("application/test", sections[1].headers['Content-Type'],
- "Content-Type should be application/test for section[1]");
- TEquals("application/test", sections[2].headers['Content-Type'],
- "Content-Type should be application/test for section[2]");
-
- TEquals("21", sections[1].headers['Content-Length'],
- "Content-Length should be 21 section[1]");
- TEquals("18", sections[2].headers['Content-Length'],
- "Content-Length should be 18 section[2]");
-
- TEquals('attachment; filename="foo.txt"', sections[1].headers['Content-Disposition'],
- "Content-Disposition should be foo.txt section[1]");
- TEquals('attachment; filename="bar.txt"', sections[2].headers['Content-Disposition'],
- "Content-Disposition should be bar.txt section[2]");
-
- var doc = JSON.parse(sections[0].body);
-
- T(doc._attachments['foo.txt'].follows == true);
- T(doc._attachments['bar.txt'].follows == true);
-
- T(sections[1].body == "this is 21 chars long");
- TEquals("this is 18 chars l", sections[2].body, "should be 18 chars long");
-
- // now get attachments incrementally (only the attachments changes since
- // a certain rev).
-
- xhr = CouchDB.request("GET", "/" + db_name + "/multipart?atts_since=[\"" + firstrev + "\"]",
- {headers:{"accept": "multipart/related, */*"}});
-
- T(xhr.status == 200);
-
- var sections = parseMultipart(xhr);
-
- T(sections.length == 2);
-
- var doc = JSON.parse(sections[0].body);
-
- T(doc._attachments['foo.txt'].stub == true);
- T(doc._attachments['bar.txt'].follows == true);
-
- TEquals("this is 18 chars l", sections[1].body, "should be 18 chars long 2");
-
- // try the atts_since parameter together with the open_revs parameter
- xhr = CouchDB.request(
- "GET",
- "/" + db_name + "/multipart?open_revs=[" +
- '"' + doc._rev + '"]&atts_since=["' + firstrev + '"]',
- {headers: {"accept": "multipart/mixed"}}
- );
-
- T(xhr.status === 200);
-
- sections = parseMultipart(xhr);
- // 1 section, with a multipart/related Content-Type
- T(sections.length === 1);
- T(sections[0].headers['Content-Type'].indexOf('multipart/related;') === 0);
-
- var innerSections = parseMultipart(sections[0]);
- // 2 inner sections: a document body section plus an attachment data section
-// TODO: why does atts_since not work?
-// T(innerSections.length === 2);
- T(innerSections.length === 3);
- T(innerSections[0].headers['Content-Type'] === 'application/json');
-
- doc = JSON.parse(innerSections[0].body);
-
-// TODO: why does atts_since not work?
-// T(doc._attachments['foo.txt'].stub === true);
- T(doc._attachments['foo.txt'].follows === true);
- T(doc._attachments['bar.txt'].follows === true);
-
-// TODO: why does atts_since not work?
- T(innerSections[1].body === "this is 21 chars long");
- T(innerSections[2].body === "this is 18 chars l");
-
- // try it with a rev that doesn't exist (should get all attachments)
-
- xhr = CouchDB.request("GET", "/" + db_name + "/multipart?atts_since=[\"1-2897589\"]",
- {headers:{"accept": "multipart/related,*/*;"}});
-
- T(xhr.status == 200);
-
- var sections = parseMultipart(xhr);
-
- T(sections.length == 3);
-
- var doc = JSON.parse(sections[0].body);
-
- T(doc._attachments['foo.txt'].follows == true);
- T(doc._attachments['bar.txt'].follows == true);
-
- T(sections[1].body == "this is 21 chars long");
- TEquals("this is 18 chars l", sections[2].body, "should be 18 chars long 3");
- // try it with a rev that doesn't exist, and one that does
-
- xhr = CouchDB.request("GET", "/" + db_name + "/multipart?atts_since=[\"1-2897589\",\"" + firstrev + "\"]",
- {headers:{"accept": "multipart/related,*/*;"}});
-
- T(xhr.status == 200);
-
- var sections = parseMultipart(xhr);
-
- T(sections.length == 2);
-
- var doc = JSON.parse(sections[0].body);
-
- T(doc._attachments['foo.txt'].stub == true);
- T(doc._attachments['bar.txt'].follows == true);
-
- TEquals("this is 18 chars l", sections[1].body, "should be 18 chars long 4");
-
- // check that with the document multipart/mixed API it's possible to receive
- // attachments in compressed form (if they're stored in compressed form)
-
- var server_config = [
- {
- section: "attachments",
- key: "compression_level",
- value: "8"
- },
- {
- section: "attachments",
- key: "compressible_types",
- value: "text/plain"
- }
- ];
-
- function testMultipartAttCompression() {
- var doc = { _id: "foobar" };
- var lorem =
- CouchDB.request("GET", "/_utils/script/test/lorem.txt").responseText;
- var helloData = "hello world";
-
- TEquals(true, db.save(doc).ok);
-
- var firstRev = doc._rev;
- var xhr = CouchDB.request(
- "PUT",
- "/" + db.name + "/" + doc._id + "/data.bin?rev=" + firstRev,
- {
- body: helloData,
- headers: {"Content-Type": "application/binary"}
- }
- );
- TEquals(201, xhr.status);
-
- var secondRev = db.open(doc._id)._rev;
- xhr = CouchDB.request(
- "PUT",
- "/" + db.name + "/" + doc._id + "/lorem.txt?rev=" + secondRev,
- {
- body: lorem,
- headers: {"Content-Type": "text/plain"}
- }
- );
- TEquals(201, xhr.status);
-
- var thirdRev = db.open(doc._id)._rev;
-
- xhr = CouchDB.request(
- "GET",
- '/' + db.name + '/' + doc._id + '?open_revs=["' + thirdRev + '"]',
- {
- headers: {
- "Accept": "multipart/mixed",
- "X-CouchDB-Send-Encoded-Atts": "true"
- }
- }
- );
- TEquals(200, xhr.status);
-
- var sections = parseMultipart(xhr);
- // 1 section, with a multipart/related Content-Type
- TEquals(1, sections.length);
- TEquals(0,
- sections[0].headers['Content-Type'].indexOf('multipart/related;'));
-
- var innerSections = parseMultipart(sections[0]);
- // 3 inner sections: a document body section plus 2 attachment data sections
- TEquals(3, innerSections.length);
- TEquals('application/json', innerSections[0].headers['Content-Type']);
-
- doc = JSON.parse(innerSections[0].body);
-
- TEquals(true, doc._attachments['lorem.txt'].follows);
- TEquals("gzip", doc._attachments['lorem.txt'].encoding);
- TEquals(true, doc._attachments['data.bin'].follows);
- T(doc._attachments['data.bin'] !== "gzip");
-
- if (innerSections[1].body === helloData) {
- T(innerSections[2].body !== lorem);
- } else if (innerSections[2].body === helloData) {
- T(innerSections[1].body !== lorem);
- } else {
- T(false, "Could not found data.bin attachment data");
- }
-
- // now test that it works together with the atts_since parameter
-
- xhr = CouchDB.request(
- "GET",
- '/' + db.name + '/' + doc._id + '?open_revs=["' + thirdRev + '"]' +
- '&atts_since=["' + secondRev + '"]',
- {
- headers: {
- "Accept": "multipart/mixed",
- "X-CouchDB-Send-Encoded-Atts": "true"
- }
- }
- );
- TEquals(200, xhr.status);
-
- sections = parseMultipart(xhr);
- // 1 section, with a multipart/related Content-Type
- TEquals(1, sections.length);
- TEquals(0,
- sections[0].headers['Content-Type'].indexOf('multipart/related;'));
-
- innerSections = parseMultipart(sections[0]);
- // 2 inner sections: a document body section plus 1 attachment data section
-// TODO: why does atts_since not work?
-// TEquals(2, innerSections.length);
- TEquals('application/json', innerSections[0].headers['Content-Type']);
-
- doc = JSON.parse(innerSections[0].body);
-
- TEquals(true, doc._attachments['lorem.txt'].follows);
- TEquals("gzip", doc._attachments['lorem.txt'].encoding);
-// TODO: why does atts_since not work?
-// TEquals("undefined", typeof doc._attachments['data.bin'].follows);
-// TEquals(true, doc._attachments['data.bin'].stub);
- T(innerSections[1].body !== lorem);
- }
-
- run_on_modified_server(server_config, testMultipartAttCompression);
-
-// // cleanup
- db.deleteDb();
-};
diff --git a/test/javascript/tests/auth_cache.js b/test/javascript/tests/auth_cache.js
deleted file mode 100644
index 73fec35..0000000
--- a/test/javascript/tests/auth_cache.js
+++ /dev/null
@@ -1,274 +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.
-
-couchTests.elixir = true;
-couchTests.auth_cache = function(debug) {
- if (debug) debugger;
-
- // Simple secret key generator
- function generateSecret(length) {
- var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" +
- "0123456789+/";
- var secret = '';
- for (var i = 0; i < length; i++) {
- secret += tab.charAt(Math.floor(Math.random() * 64));
- }
- return secret;
- }
-
- var db_name = get_random_db_name();
- var authDb = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"}, {w: 3});
- authDb.createDb();
- var server_config = [
- {
- section: "chttpd_auth",
- key: "authentication_db",
- value: authDb.name
- },
- {
- section: "chttpd_auth",
- key: "auth_cache_size",
- value: "3"
- },
- {
- section: "httpd",
- key: "authentication_handlers",
- value: "{couch_httpd_auth, default_authentication_handler}"
- },
- {
- section: "chttpd_auth",
- key: "secret",
- value: generateSecret(64)
- }
- ];
-
-
- function hits() {
- var hits = CouchDB.requestStats(["couchdb", "auth_cache_hits"], true);
- return hits.value || 0;
- }
-
-
- function misses() {
- var misses = CouchDB.requestStats(["couchdb", "auth_cache_misses"], true);
- return misses.value || 0;
- }
-
-
- function testFun() {
- var hits_before,
- misses_before,
- hits_after,
- misses_after;
-
- var fdmanana = CouchDB.prepareUserDoc({
- name: "fdmanana",
- roles: ["dev"]
- }, "qwerty");
-
- T(authDb.save(fdmanana).ok);
-
- var chris = CouchDB.prepareUserDoc({
- name: "chris",
- roles: ["dev", "mafia", "white_costume"]
- }, "the_god_father");
-
- T(authDb.save(chris).ok);
-
- var joe = CouchDB.prepareUserDoc({
- name: "joe",
- roles: ["erlnager"]
- }, "functional");
-
- T(authDb.save(joe).ok);
-
- var johndoe = CouchDB.prepareUserDoc({
- name: "johndoe",
- roles: ["user"]
- }, "123456");
-
- T(authDb.save(johndoe).ok);
-
- hits_before = hits();
- misses_before = misses();
-
- T(CouchDB.login("fdmanana", "qwerty").ok);
- T(CouchDB.logout().ok);
-
- hits_after = hits();
- misses_after = misses();
-
- T(misses_after === (misses_before + 1));
- // XXX BUGGED T(hits_after === hits_before);
-
- hits_before = hits_after;
- misses_before = misses_after;
-
- T(CouchDB.login("fdmanana", "qwerty").ok);
- T(CouchDB.logout().ok);
-
- hits_after = hits();
- misses_after = misses();
-
- T(misses_after === misses_before);
- // XXX BUGGED T(hits_after === (hits_before + 1));
-
- hits_before = hits_after;
- misses_before = misses_after;
-
- T(CouchDB.login("chris", "the_god_father").ok);
- T(CouchDB.logout().ok);
-
- hits_after = hits();
- misses_after = misses();
-
- T(misses_after === (misses_before + 1));
- // XXX BUGGED T(hits_after === hits_before);
-
- hits_before = hits_after;
- misses_before = misses_after;
-
- T(CouchDB.login("joe", "functional").ok);
- T(CouchDB.logout().ok);
-
- hits_after = hits();
- misses_after = misses();
-
- T(misses_after === (misses_before + 1));
- // XXX BUGGED T(hits_after === hits_before);
-
- hits_before = hits_after;
- misses_before = misses_after;
-
- T(CouchDB.login("johndoe", "123456").ok);
- T(CouchDB.logout().ok);
-
- hits_after = hits();
- misses_after = misses();
-
- T(misses_after === (misses_before + 1));
- // XXX BUGGED T(hits_after === hits_before);
-
- hits_before = hits_after;
- misses_before = misses_after;
-
- T(CouchDB.login("joe", "functional").ok);
- T(CouchDB.logout().ok);
-
- hits_after = hits();
- misses_after = misses();
-
- // it's an MRU cache, joe was removed from cache to add johndoe
- // XXX BUGGED T(misses_after === (misses_before + 1));
- // XXX BUGGED T(hits_after === hits_before);
-
- hits_before = hits_after;
- misses_before = misses_after;
-
- T(CouchDB.login("fdmanana", "qwerty").ok);
- T(CouchDB.logout().ok);
-
- hits_after = hits();
- misses_after = misses();
-
- T(misses_after === misses_before);
- // XXX BUGGED T(hits_after === (hits_before + 1));
-
- hits_before = hits_after;
- misses_before = misses_after;
-
- fdmanana.password = "foobar";
- T(authDb.save(fdmanana).ok);
-
- // cache was refreshed
-/* // XXX BUGGED
- T(CouchDB.login("fdmanana", "qwerty").error === "unauthorized");
- T(CouchDB.login("fdmanana", "foobar").ok);
- T(CouchDB.logout().ok);
-*/
-
- hits_after = hits();
- misses_after = misses();
-
- T(misses_after === misses_before);
- // XXX BUGGED T(hits_after === (hits_before + 2));
-
- hits_before = hits_after;
- misses_before = misses_after;
-
- // and yet another update
- fdmanana.password = "javascript";
- T(authDb.save(fdmanana).ok);
-
- // cache was refreshed
-/* // XXX BUGGED
- T(CouchDB.login("fdmanana", "foobar").error === "unauthorized");
- T(CouchDB.login("fdmanana", "javascript").ok);
- T(CouchDB.logout().ok);
-*/
-
- hits_after = hits();
- misses_after = misses();
-
- T(misses_after === misses_before);
- // XXX BUGGED T(hits_after === (hits_before + 2));
-
- T(authDb.deleteDoc(fdmanana).ok);
-
- hits_before = hits_after;
- misses_before = misses_after;
-
- T(CouchDB.login("fdmanana", "javascript").error === "unauthorized");
-
- hits_after = hits();
- misses_after = misses();
-
- T(misses_after === misses_before);
- T(hits_after === (hits_before + 1));
-
- // login, compact authentication DB, login again and verify that
- // there was a cache hit
- hits_before = hits_after;
- misses_before = misses_after;
-
- T(CouchDB.login("johndoe", "123456").ok);
- T(CouchDB.logout().ok);
-
- hits_after = hits();
- misses_after = misses();
-
- // XXX BUGGED T(misses_after === (misses_before + 1));
- // XXX BUGGED T(hits_after === hits_before);
-
- T(authDb.compact().ok);
-
- while (authDb.info().compact_running);
-
- hits_before = hits_after;
- misses_before = misses_after;
-
- T(CouchDB.login("johndoe", "123456").ok);
- T(CouchDB.logout().ok);
-
- hits_after = hits();
- misses_after = misses();
-
- // XXX BUGGED T(misses_after === misses_before);
- // XXX BUGGED T(hits_after === (hits_before + 1));
- }
-
-
- run_on_modified_server(server_config, testFun);
-
- // cleanup
- authDb.deleteDb();
-}
diff --git a/test/javascript/tests/basics.js b/test/javascript/tests/basics.js
deleted file mode 100644
index 51abb40..0000000
--- a/test/javascript/tests/basics.js
+++ /dev/null
@@ -1,302 +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.
-
-// Do some basic tests.
-couchTests.elixir = true;
-couchTests.basics = function(debug) {
- return console.log('done in test/elixir/test/basics_test.exs');
- if (debug) debugger;
-
- var result = JSON.parse(CouchDB.request("GET", "/").responseText);
- T(result.couchdb == "Welcome");
-
- var db_name = get_random_db_name()
- var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"});
-
- //TODO bug COUCHDB-100: DELETE on non-existent DB returns 500 instead of 404
- //TODO db.deleteDb();
-
- db.createDb();
-
- // PUT on existing DB should return 412 instead of 500
- xhr = CouchDB.request("PUT", "/" + db_name + "/");
- T(xhr.status == 412);
-
- // creating a new DB should return Location header
- // and it should work for dbs with slashes (COUCHDB-411)
- var db_name2 = get_random_db_name();
- var dbnames = [db_name2, db_name2 + "%2Fwith_slashes"];
- dbnames.forEach(function(dbname) {
- xhr = CouchDB.request("DELETE", "/" + dbname);
- xhr = CouchDB.request("PUT", "/" + dbname);
- TEquals(dbname,
- xhr.getResponseHeader("Location").substr(-dbname.length),
- "should return Location header to newly created document");
- TEquals(CouchDB.protocol,
- xhr.getResponseHeader("Location").substr(0, CouchDB.protocol.length),
- "should return absolute Location header to newly created document");
- CouchDB.request("DELETE", "/" + dbname);
- });
-
- // Get the database info, check the db_name
- TEquals(db.info().db_name, db_name, "get correct database name");
- T(CouchDB.allDbs().indexOf("" + db_name + "") != -1);
-
- // Get the database info, check the doc_count
- T(db.info().doc_count == 0);
-
- // create a document and save it to the database
- var doc = {_id:"0",a:1,b:1};
- var result = db.save(doc);
-
- T(result.ok==true); // return object has an ok member with a value true
- T(result.id); // the _id of the document is set.
- T(result.rev); // the revision id of the document is set.
-
- // Verify the input doc is now set with the doc id and rev
- // (for caller convenience).
- T(doc._id == result.id && doc._rev == result.rev);
-
- var id = result.id; // save off the id for later
-
- // make sure the revs_info status is good
- var doc = db.open(id, {revs_info:true});
- T(doc._revs_info[0].status == "available");
-
- // make sure you can do a seq=true option
- var doc = db.open(id, {local_seq:true});
- T(doc._local_seq == 1);
-
-
- // Create some more documents.
- // Notice the use of the ok member on the return result.
- T(db.save({_id:"1",a:2,b:4}).ok);
- T(db.save({_id:"2",a:3,b:9}).ok);
- T(db.save({_id:"3",a:4,b:16}).ok);
-
- // with n=3 and w=r=2, it SHOULD be reliable in clusters - execute often 2 see...
-
- // Check the database doc count
- T(db.info().doc_count == 4);
-
- // COUCHDB-954
- var oldRev = db.save({_id:"COUCHDB-954", a:1}).rev;
- var newRev = db.save({_id:"COUCHDB-954", _rev:oldRev}).rev;
-
- // test behavior of open_revs with explicit revision list
- var result = db.open("COUCHDB-954", {open_revs:[oldRev,newRev]});
- T(result.length == 2, "should get two revisions back");
- T(result[0].ok);
- T(result[1].ok);
-
- // latest=true suppresses non-leaf revisions
-// TODO: does no more work on cluster - function_clause error fabric_doc_open_revs:handle_message/3
-// var result = db.open("COUCHDB-954", {open_revs:[oldRev,newRev], latest:true});
-// T(result.length == 1, "should only get the child revision with latest=true");
-// T(result[0].ok._rev == newRev, "should get the child and not the parent");
-
- // latest=true returns a child when you ask for a parent
- var result = db.open("COUCHDB-954", {open_revs:[oldRev], latest:true});
- T(result[0].ok._rev == newRev, "should get child when we requested parent");
-
- // clean up after ourselves
- db.save({_id:"COUCHDB-954", _rev:newRev, _deleted:true});
-
- // Test a simple map functions
-
- // create a map function that selects all documents whose "a" member
- // has a value of 4, and then returns the document's b value.
- var mapFunction = function(doc){
- if (doc.a==4)
- emit(null, doc.b);
- };
-
- var results = db.query(mapFunction);
-
- // verify only one document found and the result value (doc.b).
- T(results.total_rows == 1 && results.rows[0].value == 16);
-
- // reopen document we saved earlier
- var existingDoc = db.open(id);
-
- T(existingDoc.a==1);
-
- //modify and save
- existingDoc.a=4;
- db.save(existingDoc);
-
- // redo the map query
- results = db.query(mapFunction);
-
- // the modified document should now be in the results.
- T(results.total_rows == 2);
-
- // write 2 more documents
- T(db.save({a:3,b:9}).ok);
- T(db.save({a:4,b:16}).ok);
-
- results = db.query(mapFunction);
-
- // 1 more document should now be in the result.
- T(results.total_rows == 3);
- TEquals(6, db.info().doc_count, 'number of docs in db');
-
- var reduceFunction = function(keys, values){
- return sum(values);
- };
-
- results = db.query(mapFunction, reduceFunction);
-
- T(results.rows[0].value == 33);
-
- // delete a document
- T(db.deleteDoc(existingDoc).ok);
-
- // make sure we can't open the doc
- T(db.open(existingDoc._id) == null);
-
- results = db.query(mapFunction);
-
- // 1 less document should now be in the results.
- T(results.total_rows == 2);
- T(db.info().doc_count == (5));
-
- // make sure we can still open the old rev of the deleted doc
- T(db.open(existingDoc._id, {rev: existingDoc._rev}) != null);
- // make sure restart works
-// TODO: investigate why it won't work
-// T(db.ensureFullCommit().ok);
-// restartServer();
-
- // make sure we can still open
- T(db.open(existingDoc._id, {rev: existingDoc._rev}) != null);
-
- // test that the POST response has a Location header
- var xhr = CouchDB.request("POST", "/" + db_name + "", {
- body: JSON.stringify({"foo":"bar"}),
- headers: {"Content-Type": "application/json"}
- });
- var resp = JSON.parse(xhr.responseText);
- T(resp.ok);
- var loc = xhr.getResponseHeader("Location");
- T(loc, "should have a Location header");
- var locs = loc.split('/');
- T(locs[locs.length-1] == resp.id);
- T(locs[locs.length-2] == "" + db_name + "");
-
- // test that that POST's with an _id aren't overriden with a UUID.
- var xhr = CouchDB.request("POST", "/" + db_name + "", {
- headers: {"Content-Type": "application/json"},
- body: JSON.stringify({"_id": "oppossum", "yar": "matey"})
- });
- var resp = JSON.parse(xhr.responseText);
- T(resp.ok);
- T(resp.id == "oppossum");
- var doc = db.open("oppossum");
- T(doc.yar == "matey");
-
- // document put's should return a Location header
- var xhr = CouchDB.request("PUT", "/" + db_name + "/newdoc", {
- body: JSON.stringify({"a":1})
- });
- TEquals("/" + db_name + "/newdoc",
- xhr.getResponseHeader("Location").substr(-(db_name.length + 1 + 7)),
- "should return Location header to newly created document");
- TEquals(CouchDB.protocol,
- xhr.getResponseHeader("Location").substr(0, CouchDB.protocol.length),
- "should return absolute Location header to newly created document");
-
- // deleting a non-existent doc should be 404
- xhr = CouchDB.request("DELETE", "/" + db_name + "/doc-does-not-exist");
- T(xhr.status == 404);
-
- // Check for invalid document members
- var bad_docs = [
- ["goldfish", {"_zing": 4}],
- ["zebrafish", {"_zoom": "hello"}],
- ["mudfish", {"zane": "goldfish", "_fan": "something smells delicious"}],
- ["tastyfish", {"_bing": {"wha?": "soda can"}}]
- ];
- var test_doc = function(info) {
- var data = JSON.stringify(info[1]);
- xhr = CouchDB.request("PUT", "/" + db_name + "/" + info[0], {body: data});
- T(xhr.status == 400);
- result = JSON.parse(xhr.responseText);
- T(result.error == "doc_validation");
-
- xhr = CouchDB.request("POST", "/" + db_name + "/", {
- headers: {"Content-Type": "application/json"},
- body: data
- });
- T(xhr.status == 400);
- result = JSON.parse(xhr.responseText);
- T(result.error == "doc_validation");
- };
- bad_docs.forEach(test_doc);
-
- // Check some common error responses.
- // PUT body not an object
- xhr = CouchDB.request("PUT", "/" + db_name + "/bar", {body: "[]"});
- T(xhr.status == 400);
- result = JSON.parse(xhr.responseText);
- T(result.error == "bad_request");
- T(result.reason == "Document must be a JSON object");
-
- // Body of a _bulk_docs is not an object
- xhr = CouchDB.request("POST", "/" + db_name + "/_bulk_docs", {body: "[]"});
- T(xhr.status == 400);
- result = JSON.parse(xhr.responseText);
- T(result.error == "bad_request");
- T(result.reason == "Request body must be a JSON object");
-
- // Body of an _all_docs multi-get is not a {"key": [...]} structure.
- xhr = CouchDB.request("POST", "/" + db_name + "/_all_docs", {body: "[]"});
- T(xhr.status == 400);
- result = JSON.parse(xhr.responseText);
- T(result.error == "bad_request");
- T(result.reason == "Request body must be a JSON object");
- var data = "{\"keys\": 1}";
- xhr = CouchDB.request("POST", "/" + db_name + "/_all_docs", {body:data});
- T(xhr.status == 400);
- result = JSON.parse(xhr.responseText);
- T(result.error == "bad_request");
- T(result.reason == "`keys` body member must be an array.");
-
- // oops, the doc id got lost in code nirwana
- xhr = CouchDB.request("DELETE", "/" + db_name + "/?rev=foobarbaz");
- TEquals(400, xhr.status, "should return a bad request");
- result = JSON.parse(xhr.responseText);
- TEquals("bad_request", result.error);
- TEquals("You tried to DELETE a database with a ?=rev parameter. Did you mean to DELETE a document instead?", result.reason);
-
- // On restart, a request for creating a database that already exists can
- // not override the existing database file
- // TODO
- // db = new CouchDB(db_name);
- // xhr = CouchDB.request("PUT", "/" + db.name);
- // TEquals(201, xhr.status);
- //
- // TEquals(true, db.save({"_id": "doc1"}).ok);
- // TEquals(true, db.ensureFullCommit().ok);
- //
- // TEquals(1, db.info().doc_count);
- //
- // restartServer();
- //
- // xhr = CouchDB.request("PUT", "/" + db.name);
- // TEquals(412, xhr.status);
- //
- // TEquals(1, db.info().doc_count);
-
- // cleanup
- db.deleteDb();
-};
diff --git a/test/javascript/tests/batch_save.js b/test/javascript/tests/batch_save.js
deleted file mode 100644
index bbfb2ed..0000000
--- a/test/javascript/tests/batch_save.js
+++ /dev/null
@@ -1,52 +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.
-
-couchTests.elixir = true;
-couchTests.batch_save = function(debug) {
- return console.log('done in test/elixir/test/batch_save_test.exs');
- var db_name = get_random_db_name()
- var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"});
- db.createDb();
- if (debug) debugger;
-
- var i
- for(i=0; i < 100; i++) {
- T(db.save({_id:i.toString(),a:i,b:i}, {batch : "ok"}).ok);
-
- // test that response is 202 Accepted
- T(db.last_req.status == 202);
- }
-
- for(i=0; i < 100; i++) {
- // attempt to save the same document a bunch of times
- T(db.save({_id:"foo",a:i,b:i}, {batch : "ok"}).ok);
-
- // test that response is 202 Accepted
- T(db.last_req.status == 202);
- }
-
- while(db.allDocs().total_rows != 101){};
-
- // repeat the tests for POST
- for(i=0; i < 100; i++) {
- var resp = db.request("POST", db.uri + "?batch=ok", {
- headers: {"Content-Type": "application/json"},
- body: JSON.stringify({a:1})
- });
- T(JSON.parse(resp.responseText).ok);
- }
-
- while(db.allDocs().total_rows != 201){};
-
- // cleanup
- db.deleteDb();
-};
diff --git a/test/javascript/tests/bulk_docs.js b/test/javascript/tests/bulk_docs.js
deleted file mode 100644
index 767a543..0000000
--- a/test/javascript/tests/bulk_docs.js
+++ /dev/null
@@ -1,153 +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.
-
-couchTests.elixir = true;
-couchTests.bulk_docs = function(debug) {
- return console.log('done in test/elixir/test/basics_test.exs');
- var db_name = get_random_db_name();
- var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"});
- db.createDb();
- if (debug) debugger;
-
- var docs = makeDocs(5);
-
- // Create the docs
- var results = db.bulkSave(docs);
-
- T(results.length == 5);
- for (var i = 0; i < 5; i++) {
- T(results[i].id == docs[i]._id);
- T(results[i].rev);
- // Update the doc
- docs[i].string = docs[i].string + ".00";
- }
-
- // Save the docs
- results = db.bulkSave(docs);
- T(results.length == 5);
- for (i = 0; i < 5; i++) {
- T(results[i].id == i.toString());
-
- // set the delete flag to delete the docs in the next step
- docs[i]._deleted = true;
- }
-
- // now test a bulk update with a conflict
- // open and save
- var doc = db.open("0");
- db.save(doc);
-
- // Now bulk delete the docs
- results = db.bulkSave(docs);
-
- // doc "0" should be a conflict
- T(results.length == 5);
- T(results[0].id == "0");
- T(results[0].error == "conflict");
- T(typeof results[0].rev === "undefined"); // no rev member when a conflict
-
- // but the rest are not
- for (i = 1; i < 5; i++) {
- T(results[i].id == i.toString());
- T(results[i].rev);
- T(db.open(docs[i]._id) == null);
- }
-
- // now force a conflict to to save
-
- // save doc 0, this will cause a conflict when we save docs[0]
- var doc = db.open("0");
- docs[0] = db.open("0");
- db.save(doc);
-
- docs[0].shooby = "dooby";
-
- // Now save the bulk docs, When we use all_or_nothing, we don't get conflict
- // checking, all docs are saved regardless of conflict status, or none are
- // saved.
-// TODO: all_or_nothing is not yet supported on clusters
-// results = db.bulkSave(docs,{all_or_nothing:true});
-// T(results.error === undefined);
-//
-// var doc = db.open("0", {conflicts:true});
-// var docConflict = db.open("0", {rev:doc._conflicts[0]});
-//
-// T(doc.shooby == "dooby" || docConflict.shooby == "dooby");
-
- // verify creating a document with no id returns a new id
- var req = CouchDB.request("POST", "/" + db_name + "/_bulk_docs", {
- body: JSON.stringify({"docs": [{"foo":"bar"}]})
- });
- results = JSON.parse(req.responseText);
-
- T(results[0].id != "");
- T(results[0].rev != "");
-
-
- // Regression test for failure on update/delete
- var newdoc = {"_id": "foobar", "body": "baz"};
- T(db.save(newdoc).ok);
- var update = {"_id": newdoc._id, "_rev": newdoc._rev, "body": "blam"};
- var torem = {"_id": newdoc._id, "_rev": newdoc._rev, "_deleted": true};
- results = db.bulkSave([update, torem]);
- T(results[0].error == "conflict" || results[1].error == "conflict");
-
-
- // verify that sending a request with no docs causes error thrown
- var req = CouchDB.request("POST", "/" + db_name + "/_bulk_docs", {
- body: JSON.stringify({"doc": [{"foo":"bar"}]})
- });
-
- T(req.status == 400 );
- result = JSON.parse(req.responseText);
- T(result.error == "bad_request");
- T(result.reason == "POST body must include `docs` parameter.");
-
- // verify that sending a request with invalid `docs` causes error
- var req = CouchDB.request("POST", "/" + db_name + "/_bulk_docs", {
- body: JSON.stringify({"docs": "foo"})
- });
-
- T(req.status == 400);
- result = JSON.parse(req.responseText);
- T(result.error == "bad_request");
- T(result.reason == "`docs` parameter must be an array.");
-
- // verify that sending a request with invalid `new_edits` causes error
- var req = CouchDB.request("POST", "/" + db_name + "/_bulk_docs", {
- body: JSON.stringify({"docs": [], "new_edits": 0})
- });
-
- T(req.status == 400);
- result = JSON.parse(req.responseText);
- T(result.error == "bad_request");
- T(result.reason == "`new_edits` parameter must be a boolean.");
-
- // jira-911
- db.deleteDb();
- // avoid Heisenbugs w/ files remaining - create a new name
- db_name = get_random_db_name();
- db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"});
- db.createDb();
- docs = [];
- docs.push({"_id":"0", "a" : 0});
- docs.push({"_id":"1", "a" : 1});
- docs.push({"_id":"1", "a" : 2});
- docs.push({"_id":"3", "a" : 3});
- results = db.bulkSave(docs);
- T(results[1].id == "1");
- T(results[1].error == undefined);
- T(results[2].error == "conflict");
-
- // cleanup
- db.deleteDb();
-};
diff --git a/test/javascript/tests/changes.js b/test/javascript/tests/changes.js
deleted file mode 100644
index 338c157..0000000
--- a/test/javascript/tests/changes.js
+++ /dev/null
@@ -1,812 +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.
-couchTests.elixir = true;
-
-function jsonp(obj) {
- T(jsonp_flag == 0);
- T(obj.results.length == 1 && obj.last_seq == 1, "jsonp");
- jsonp_flag = 1;
-}
-
-couchTests.changes = function(debug) {
- return console.log('done in test/elixir/test/changes_test.exs and changes_async_test.exs');
-
- var db;
- if (debug) debugger;
-
- // poor man's browser detection
- var is_safari = false;
- if (typeof (navigator) == "undefined") {
- is_safari = true; // For CouchHTTP based runners
- } else if (navigator.userAgent.match(/AppleWebKit/)) {
- is_safari = true;
- }
-
- testChanges("live");
- testChanges("continuous");
- function testChanges(feed) {
- var db_name = get_random_db_name();
- // (write-quorums help keep a consistent feed)
- db = new CouchDB(db_name, {"X-Couch-Full-Commit":"true"}, {"w": 3});
- db.createDb();
-
- var req = CouchDB.request("GET", "/" + db_name + "/_changes");
- var resp = JSON.parse(req.responseText);
-
- TEquals(0, resp.results.length, "db must be empty")
- TEquals("0", resp.last_seq.substr(0, 1), "seq must start with 0")
- var docFoo = {_id:"foo", bar:1};
- T(db.save(docFoo).ok);
- T(db.ensureFullCommit().ok);
- T(db.open(docFoo._id)._id == docFoo._id);
-
- retry_part(function(){ // avoid Heisenbugs
- req = CouchDB.request("GET", "/" + db_name + "/_changes");
- var resp = JSON.parse(req.responseText);
- TEquals("1", resp.last_seq.substr(0, 1), "seq must start with 1");
- T(resp.results.length == 1, "one doc db");
- T(resp.results[0].changes[0].rev == docFoo._rev);
- });
-
- // test with callback
-// TODO: either allow jsonp in the default global config or implement a config chg mechanism analogouts 2 sebastianrothbucher:clustertest - or leave out
-// run_on_modified_server(
-// [{section: "httpd",
-// key: "allow_jsonp",
-// value: "true"}],
-// function() {
-// var xhr = CouchDB.request("GET", "/" + db_name + "/_changes?callback=jsonp");
-// T(xhr.status == 200);
-// jsonp_flag = 0;
-// eval(xhr.responseText);
-// T(jsonp_flag == 1);
-// });
-
- // increase timeout to 100 to have enough time 2 assemble (seems like too little timeouts kill
- req = CouchDB.request("GET", "/" + db_name + "/_changes?feed=" + feed + "&timeout=100");
- var lines = req.responseText.split("\n");
- T(JSON.parse(lines[0]).changes[0].rev == docFoo._rev);
- // the sequence is not fully ordered and a complex structure now
- T(JSON.parse(lines[1]).last_seq[0] == 1);
-
- var xhr;
-
- try {
- xhr = CouchDB.newXhr();
- } catch (err) {
- }
-
- // these will NEVER run as we're always in navigator == undefined
- if (!is_safari && xhr) {
- // Only test the continuous stuff if we have a real XHR object
- // with real async support.
-
- // WebKit (last checked on nightly #47686) does fail on processing
- // the async-request properly while javascript is executed.
-
- xhr.open("GET", CouchDB.proxyUrl("/" + db_name + "/_changes?feed=" + feed + "&timeout=500"), true);
- xhr.send("");
-
- var docBar = {_id:"bar", bar:1};
- db.save(docBar);
-
- var lines, change1, change2;
- waitForSuccess(function() {
- lines = xhr.responseText.split("\n");
- change1 = JSON.parse(lines[0]);
- change2 = JSON.parse(lines[1]);
- if (change2.seq != 2) {
- throw "bad seq, try again";
- }
- return true;
- }, "bar-only");
-
- T(change1.seq == 1);
- T(change1.id == "foo");
-
- T(change2.seq == 2);
- T(change2.id == "bar");
- T(change2.changes[0].rev == docBar._rev);
-
-
- var docBaz = {_id:"baz", baz:1};
- db.save(docBaz);
-
- var change3;
- waitForSuccess(function() {
- lines = xhr.responseText.split("\n");
- change3 = JSON.parse(lines[2]);
- if (change3.seq != 3) {
- throw "bad seq, try again";
- }
- return true;
- });
-
- T(change3.seq == 3);
- T(change3.id == "baz");
- T(change3.changes[0].rev == docBaz._rev);
-
-
- xhr = CouchDB.newXhr();
-
- //verify the heartbeat newlines are sent
- xhr.open("GET", CouchDB.proxyUrl("/" + db_name + "/_changes?feed=" + feed + "&heartbeat=10&timeout=500"), true);
- xhr.send("");
-
- var str;
- waitForSuccess(function() {
- str = xhr.responseText;
- if (str.charAt(str.length - 1) != "\n" || str.charAt(str.length - 2) != "\n") {
- throw("keep waiting");
- }
- return true;
- }, "heartbeat");
-
- T(str.charAt(str.length - 1) == "\n");
- T(str.charAt(str.length - 2) == "\n");
-
- // otherwise we'll continue to receive heartbeats forever
- xhr.abort();
- }
- db.deleteDb();
- }
-
- // these will NEVER run as we're always in navigator == undefined
- if (!is_safari && xhr) {
- // test Server Sent Event (eventsource)
- if (!!window.EventSource) {
- var source = new EventSource(
- "/" + db_name + "/_changes?feed=eventsource");
- var results = [];
- var sourceListener = function(e) {
- var data = JSON.parse(e.data);
- results.push(data);
- };
-
- source.addEventListener('message', sourceListener , false);
-
- waitForSuccess(function() {
- if (results.length != 3) {
- throw "bad seq, try again";
- }
- return true;
- });
-
- source.removeEventListener('message', sourceListener, false);
-
- T(results[0].seq == 1);
- T(results[0].id == "foo");
-
- T(results[1].seq == 2);
- T(results[1].id == "bar");
- T(results[1].changes[0].rev == docBar._rev);
- }
-
- // test that we receive EventSource heartbeat events
- if (!!window.EventSource) {
- var source = new EventSource(
- "/" + db_name + "/_changes?feed=eventsource&heartbeat=10");
-
- var count_heartbeats = 0;
- source.addEventListener('heartbeat', function () { count_heartbeats = count_heartbeats + 1; } , false);
-
- waitForSuccess(function() {
- if (count_heartbeats < 3) {
- throw "keep waiting";
- }
- return true;
- }, "eventsource-heartbeat");
-
- T(count_heartbeats >= 3);
- source.close();
- }
-
- // test longpolling
- xhr = CouchDB.newXhr();
-
- xhr.open("GET", CouchDB.proxyUrl("/" + db_name + "/_changes?feed=longpoll"), true);
- xhr.send("");
-
- waitForSuccess(function() {
- lines = xhr.responseText.split("\n");
- if (lines[5] != '"last_seq":3}') {
- throw("still waiting");
- }
- return true;
- }, "last_seq");
-
- xhr = CouchDB.newXhr();
-
- xhr.open("GET", CouchDB.proxyUrl("/" + db_name + "/_changes?feed=longpoll&since=3"), true);
- xhr.send("");
-
- var docBarz = {_id:"barz", bar:1};
- db.save(docBarz);
-
- var parse_changes_line = function(line) {
- if (line.charAt(line.length-1) == ",") {
- var linetrimmed = line.substring(0, line.length-1);
- } else {
- var linetrimmed = line;
- }
- return JSON.parse(linetrimmed);
- };
-
- waitForSuccess(function() {
- lines = xhr.responseText.split("\n");
- if (lines[3] != '"last_seq":4}') {
- throw("still waiting");
- }
- return true;
- }, "change_lines");
-
- var change = parse_changes_line(lines[1]);
- T(change.seq == 4);
- T(change.id == "barz");
- T(change.changes[0].rev == docBarz._rev);
- T(lines[3]=='"last_seq":4}');
-
-
- // test since=now
- xhr = CouchDB.newXhr();
-
- xhr.open("GET", "/" + db_name + "/_changes?feed=longpoll&since=now", true);
- xhr.send("");
-
- var docBarz = {_id:"barzzzz", bar:1};
- db.save(docBarz);
-
- var parse_changes_line = function(line) {
- if (line.charAt(line.length-1) == ",") {
- var linetrimmed = line.substring(0, line.length-1);
- } else {
- var linetrimmed = line;
- }
- return JSON.parse(linetrimmed);
- };
-
- waitForSuccess(function() {
- lines = xhr.responseText.split("\n");
- if (lines[3] != '"last_seq":5}') {
- throw("still waiting");
- }
- return true;
- }, "change_lines");
-
- var change = parse_changes_line(lines[1]);
- T(change.seq == 5);
- T(change.id == "barzzzz");
- T(change.changes[0].rev == docBarz._rev);
- T(lines[3]=='"last_seq":5}');
- }
-
- db.deleteDb();
- // test on a new DB
- var db_name = get_random_db_name();
- db = new CouchDB(db_name, {"X-Couch-Full-Commit":"true"}, {"w": 3});
- db.createDb();
-
- // test the filtered changes
- var ddoc = {
- _id : "_design/changes_filter",
- "filters" : {
- "bop" : "function(doc, req) { return (doc.bop);}",
- "dynamic" : stringFun(function(doc, req) {
- var field = req.query.field;
- return doc[field];
- }),
- "userCtx" : stringFun(function(doc, req) {
- return doc.user && (doc.user == req.userCtx.name);
- }),
- "conflicted" : "function(doc, req) { return (doc._conflicts);}"
- },
- options : {
- local_seq : true
- },
- views : {
- local_seq : {
- map : "function(doc) {emit(doc._local_seq, null)}"
- },
- blah: {
- map : 'function(doc) {' +
- ' if (doc._id == "blah") {' +
- ' emit(null, null);' +
- ' }' +
- '}'
- }
- }
- };
-
- db.save(ddoc);
-
- var req = CouchDB.request("GET", "/" + db_name + "/_changes?filter=changes_filter/bop");
- var resp = JSON.parse(req.responseText);
- T(resp.results.length == 0);
-
- var docres1 = db.save({"bop" : "foom"});
- T(docres1.ok);
- var docres2 = db.save({"bop" : false});
- T(docres2.ok);
-
- var req = CouchDB.request("GET", "/" + db_name + "/_changes?filter=changes_filter/bop");
- var resp = JSON.parse(req.responseText);
- var seqold = resp.results[0].seq;
- T(resp.results.length == 1, "filtered/bop");
- T(resp.results[0].changes[0].rev == docres1.rev, "filtered/bop rev");
- // save and reload (substitute for all those parts that never run)
- var chgdoc1 = db.open(docres1.id);
- chgdoc1.newattr = "s/th new";
- docres1 = db.save(chgdoc1);
- T(docres1.ok);
- req = CouchDB.request("GET", "/" + db_name + "/_changes?filter=changes_filter/bop");
- resp = JSON.parse(req.responseText);
- var seqchg = resp.results[0].seq;
- T(resp.results.length == 1, "filtered/bop new");
- T(resp.results[0].changes[0].rev == docres1.rev, "filtered/bop rev new");
- T(seqold != seqchg, "filtered/bop new seq number");
-
- req = CouchDB.request("GET", "/" + db_name + "/_changes?filter=changes_filter/dynamic&field=woox");
- resp = JSON.parse(req.responseText);
- T(resp.results.length == 0);
-
- req = CouchDB.request("GET", "/" + db_name + "/_changes?filter=changes_filter/dynamic&field=bop");
- resp = JSON.parse(req.responseText);
- T(resp.results.length == 1, "changes_filter/dynamic&field=bop");
- T(resp.results[0].changes[0].rev == docres1.rev, "filtered/dynamic&field=bop rev");
-
- // these will NEVER run as we're always in navigator == undefined
- if (!is_safari && xhr) { // full test requires parallel connections
- // filter with longpoll
- // longpoll filters full history when run without a since seq
- xhr = CouchDB.newXhr();
- xhr.open("GET", CouchDB.proxyUrl("/" + db_name + "/_changes?feed=longpoll&filter=changes_filter/bop"), false);
- xhr.send("");
- var resp = JSON.parse(xhr.responseText);
- T(resp.last_seq == 8);
- // longpoll waits until a matching change before returning
- xhr = CouchDB.newXhr();
- xhr.open("GET", CouchDB.proxyUrl("/" + db_name + "/_changes?feed=longpoll&since=7&filter=changes_filter/bop"), true);
- xhr.send("");
- db.save({"_id":"falsy", "bop" : ""}); // empty string is falsy
- db.save({"_id":"bingo","bop" : "bingo"});
-
- waitForSuccess(function() {
- resp = JSON.parse(xhr.responseText);
- return true;
- }, "longpoll-since");
-
- T(resp.last_seq == 10);
- T(resp.results && resp.results.length > 0 && resp.results[0]["id"] == "bingo", "filter the correct update");
- xhr.abort();
-
- var timeout = 500;
- var last_seq = 11;
- while (true) {
-
- // filter with continuous
- xhr = CouchDB.newXhr();
- xhr.open("GET", CouchDB.proxyUrl("/" + db_name + "/_changes?feed=continuous&filter=changes_filter/bop&timeout="+timeout), true);
- xhr.send("");
-
- db.save({"_id":"rusty", "bop" : "plankton"});
- T(xhr.readyState != 4, "test client too slow");
- var rusty = db.open("rusty", {cache_bust : new Date()});
- T(rusty._id == "rusty");
-
- waitForSuccess(function() { // throws an error after 5 seconds
- if (xhr.readyState != 4) {
- throw("still waiting");
- }
- return true;
- }, "continuous-rusty");
- lines = xhr.responseText.split("\n");
- var good = false;
- try {
- JSON.parse(lines[3]);
- good = true;
- } catch(e) {
- }
- if (good) {
- T(JSON.parse(lines[1]).id == "bingo", lines[1]);
- T(JSON.parse(lines[2]).id == "rusty", lines[2]);
- T(JSON.parse(lines[3]).last_seq == last_seq, lines[3]);
- break;
- } else {
- xhr.abort();
- db.deleteDoc(rusty);
- timeout = timeout * 2;
- last_seq = last_seq + 2;
- }
- }
- }
- // error conditions
-
- // non-existing design doc
- var req = CouchDB.request("GET",
- "/" + db_name + "/_changes?filter=nothingtosee/bop");
- TEquals(404, req.status, "should return 404 for non existant design doc");
-
- // non-existing filter
- var req = CouchDB.request("GET",
- "/" + db_name + "/_changes?filter=changes_filter/movealong");
- TEquals(404, req.status, "should return 404 for non existant filter fun");
-
- // both
- var req = CouchDB.request("GET",
- "/" + db_name + "/_changes?filter=nothingtosee/movealong");
- TEquals(404, req.status,
- "should return 404 for non existant design doc and filter fun");
-
- // changes get all_docs style with deleted docs
- var doc = {a:1};
- db.save(doc);
- db.deleteDoc(doc);
- var req = CouchDB.request("GET",
- "/" + db_name + "/_changes?filter=changes_filter/bop&style=all_docs");
- var resp = JSON.parse(req.responseText);
- var expect = (!is_safari && xhr) ? 3: 1;
- TEquals(expect, resp.results.length, "should return matching rows");
-
- // test filter on view function (map)
- //
- T(db.save({"_id":"blah", "bop" : "plankton"}).ok);
- var req = CouchDB.request("GET", "/" + db_name + "/_changes?filter=_view&view=changes_filter/blah");
- var resp = JSON.parse(req.responseText);
- T(resp.results.length === 1);
- T(resp.results[0].id === "blah");
-
-
- // test for userCtx
-// TODO: either make part of global config, or allow 4 config changes - or leave out
-/*
- run_on_modified_server(
- [{section: "httpd",
- key: "authentication_handlers",
- value: "{couch_httpd_auth, special_test_authentication_handler}"},
- {section:"httpd",
- key: "WWW-Authenticate",
- value: "X-Couch-Test-Auth"}],
-
- function() {
- var authOpts = {"headers":{"WWW-Authenticate": "X-Couch-Test-Auth Chris Anderson:mp3"}};
-
- var req = CouchDB.request("GET", "/_session", authOpts);
- var resp = JSON.parse(req.responseText);
-
- T(db.save({"user" : "Noah Slater"}).ok);
- var req = CouchDB.request("GET", "/" + db_name + "/_changes?filter=changes_filter/userCtx", authOpts);
- var resp = JSON.parse(req.responseText);
- T(resp.results.length == 0);
-
- var docResp = db.save({"user" : "Chris Anderson"});
- T(docResp.ok);
- T(db.ensureFullCommit().ok);
- req = CouchDB.request("GET", "/" + db_name + "/_changes?filter=changes_filter/userCtx", authOpts);
- resp = JSON.parse(req.responseText);
- T(resp.results.length == 1, "userCtx");
- T(resp.results[0].id == docResp.id);
- }
- );
-*/
-
- req = CouchDB.request("GET", "/" + db_name + "/_changes?limit=1");
- resp = JSON.parse(req.responseText);
- TEquals(1, resp.results.length);
-
- //filter includes _conflicts
-// TODO: all_or_nothing not yet in place
-// var id = db.save({'food' : 'pizza'}).id;
-// db.bulkSave([{_id: id, 'food' : 'pasta'}], {all_or_nothing:true});
-//
-// req = CouchDB.request("GET", "/" + db_name + "/_changes?filter=changes_filter/conflicted");
-// resp = JSON.parse(req.responseText);
-// T(resp.results.length == 1, "filter=changes_filter/conflicted");
-
- // test with erlang filter function
-// TODO: either make part of global config, or allow 4 config changes - or leave out
-/*
- run_on_modified_server([{
- section: "native_query_servers",
- key: "erlang",
- value: "{couch_native_process, start_link, []}"
- }], function() {
- var erl_ddoc = {
- _id: "_design/erlang",
- language: "erlang",
- filters: {
- foo:
- 'fun({Doc}, Req) -> ' +
- ' case couch_util:get_value(<<"value">>, Doc) of' +
- ' undefined -> false;' +
- ' Value -> (Value rem 2) =:= 0;' +
- ' _ -> false' +
- ' end ' +
- 'end.'
- }
- };
-
- db.deleteDb();
- db.createDb();
- T(db.save(erl_ddoc).ok);
-
- var req = CouchDB.request("GET", "/" + db_name + "/_changes?filter=erlang/foo");
- var resp = JSON.parse(req.responseText);
- T(resp.results.length === 0);
-
- T(db.save({_id: "doc1", value : 1}).ok);
- T(db.save({_id: "doc2", value : 2}).ok);
- T(db.save({_id: "doc3", value : 3}).ok);
- T(db.save({_id: "doc4", value : 4}).ok);
-
- var req = CouchDB.request("GET", "/" + db_name + "/_changes?filter=erlang/foo");
- var resp = JSON.parse(req.responseText);
- T(resp.results.length === 2);
- T(resp.results[0].id === "doc2");
- T(resp.results[1].id === "doc4");
-
- // test filtering on docids
- //
-
- var options = {
- headers: {"Content-Type": "application/json"},
- body: JSON.stringify({"doc_ids": ["something", "anotherthing", "andmore"]})
- };
-
- var req = CouchDB.request("POST", "/" + db_name + "/_changes?filter=_doc_ids", options);
- var resp = JSON.parse(req.responseText);
- T(resp.results.length === 0);
-
- T(db.save({"_id":"something", "bop" : "plankton"}).ok);
- var req = CouchDB.request("POST", "/" + db_name + "/_changes?filter=_doc_ids", options);
- var resp = JSON.parse(req.responseText);
- T(resp.results.length === 1);
- T(resp.results[0].id === "something");
-
- T(db.save({"_id":"anotherthing", "bop" : "plankton"}).ok);
- var req = CouchDB.request("POST", "/" + db_name + "/_changes?filter=_doc_ids", options);
- var resp = JSON.parse(req.responseText);
- T(resp.results.length === 2);
- T(resp.results[0].id === "something");
- T(resp.results[1].id === "anotherthing");
-
- var docids = JSON.stringify(["something", "anotherthing", "andmore"]),
- req = CouchDB.request("GET", "/" + db_name + "/_changes?filter=_doc_ids&doc_ids="+docids, options);
- var resp = JSON.parse(req.responseText);
- T(resp.results.length === 2);
- T(resp.results[0].id === "something");
- T(resp.results[1].id === "anotherthing");
-
- var req = CouchDB.request("GET", "/" + db_name + "/_changes?filter=_design");
- var resp = JSON.parse(req.responseText);
- T(resp.results.length === 1);
- T(resp.results[0].id === "_design/erlang");
-
-
- if (!is_safari && xhr) {
- // filter docids with continuous
- xhr = CouchDB.newXhr();
- xhr.open("POST", CouchDB.proxyUrl("/" + db_name + "/_changes?feed=continuous&timeout=500&since=7&filter=_doc_ids"), true);
- xhr.setRequestHeader("Content-Type", "application/json");
-
- xhr.send(options.body);
-
- T(db.save({"_id":"andmore", "bop" : "plankton"}).ok);
-
- waitForSuccess(function() {
- if (xhr.readyState != 4) {
- throw("still waiting");
- }
- return true;
- }, "andmore-only");
-
- var line = JSON.parse(xhr.responseText.split("\n")[0]);
- T(line.seq == 8);
- T(line.id == "andmore");
- }
- });
-*/
-
- db.deleteDb();
- // COUCHDB-1037 - empty result for ?limit=1&filter=foo/bar in some cases
- // test w/ new temp DB
- db_name = get_random_db_name();
- db = new CouchDB(db_name, {"X-Couch-Full-Commit":"true"}, {"w": 3});
- T(db.createDb());
-
- ddoc = {
- _id: "_design/testdocs",
- filters: {
- testdocsonly: (function(doc, req) {
- return (typeof doc.integer === "number");
- }).toString()
- }
- };
- T(db.save(ddoc));
-
- ddoc = {
- _id: "_design/foobar",
- foo: "bar"
- };
- T(db.save(ddoc));
-
- db.bulkSave(makeDocs(0, 5));
-
-// for n>1 you can't be sure all docs are there immediately - so either stick w/ -n 1 or implement check-wait-check or use the quorum (for now, the latter seems 2 suffice)
-
- req = CouchDB.request("GET", "/" + db.name + "/_changes");
- resp = JSON.parse(req.responseText);
- // you can't know wether 7 is the last seq as you don't know how many collapse into one number
- //TEquals(7, resp.last_seq);
- TEquals(7, resp.results.length);
-
- req = CouchDB.request(
- "GET", "/"+ db.name + "/_changes?limit=1&filter=testdocs/testdocsonly");
- resp = JSON.parse(req.responseText);
- // (seq as before)
- //TEquals(3, resp.last_seq);
- TEquals(1, resp.results.length);
- // also, we can't guarantee ordering
- T(resp.results[0].id.match("[0-5]"));
-
- req = CouchDB.request(
... 12695 lines suppressed ...