summaryrefslogtreecommitdiff
path: root/test/javascript/test.js
blob: 7f8a07877e1f26023e86ba98f30586b5c297e9fc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
// 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.

// couch.js, with modifications

// 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.

// some monkeypatches
var JSON = {
  parse : function(string) {
    return eval('('+string+')');
  },
  stringify : function(obj) {
    return toJSON(obj||null);
  }
};

RegExp.escape = function(text) {
  if (!arguments.callee.sRE) {
    var specials = [
      '/', '.', '*', '+', '?', '|',
      '(', ')', '[', ']', '{', '}', '\\'
    ];
    arguments.callee.sRE = new RegExp(
      '(\\' + specials.join('|\\') + ')', 'g'
    );
  }
  return text.replace(arguments.callee.sRE, '\\$1');
}

// This is a JS wrapper for the curl function made available in couch_js.c,
// it should be used in other JavaScripts that would like to make HTTP calls.

var HTTP = (function() {
  function parseCurl(string) {
    var parts = string.split(/\r\n\r\n/);
    var body = parts.pop();
    var header = parts.pop();
    var headers = header.split(/\n/);

    var status = /HTTP\/1.\d (\d*)/.exec(header)[1];
    return {
      responseText: body,
      status: parseInt(status),
      getResponseHeader: function(key) {
        var keymatcher = new RegExp(RegExp.escape(key), "i");
        for (var i in headers) {
          var h = headers[i];
          if (keymatcher.test(h)) {
            var value = h.substr(key.length+2);
            return value.replace(/^\s+|\s+$/g,"");
          }
        }
        return "";
      }
    }
  };
  return {
    GET : function(url, body, headers) {
      var st, urx = url, hx = (headers || null);
      st = gethttp(urx, hx);
      return parseCurl(st);
    },
    HEAD : function(url, body, headers) {
      var st, urx = url, hx = (headers || null);
      st = headhttp(urx, hx);
      return parseCurl(st);
    },
    DELETE : function(url, body, headers) {
      var st, urx = url, hx = (headers || null);
      st = delhttp(urx, hx);
      return parseCurl(st);
    },
    MOVE : function(url, body, headers) {
      var st, urx = url, hx = (headers || null);
      st = movehttp(urx, hx);
      return parseCurl(st);
    },
    COPY : function(url, body, headers) {
      var st, urx = url, hx = (headers || null);
      st = copyhttp(urx, hx);
      return parseCurl(st);
    },
    POST : function(url, body, headers) {
      var st, urx = url, bx = (body || ""), hx = (headers || {});
      hx['Content-Type'] = hx['Content-Type'] || "application/json";
      st = posthttp(urx, bx, hx);
      return parseCurl(st);
    },
    PUT : function(url, body, headers) {
      var st, urx = url, bx = (body || ""), hx = (headers || {});
      hx['Content-Type'] = hx['Content-Type'] || "application/json";
      st = puthttp(urx, bx, hx);
      return parseCurl(st);
    }
  };
})();

// Monkeypatches to CouchDB client for use of curl.

CouchDB.host = (typeof window == 'undefined' || !window) ? "127.0.0.1:5984" : window;

CouchDB.request = function(method, uri, options) {
  var full_uri = "http://" + CouchDB.host + uri;
  options = options || {};
  var response = HTTP[method](full_uri, options.body, options.headers);
  return response;
}


function toJSON(val) {
  if (typeof(val) == "undefined") {
    throw {error:"bad_value", reason:"Cannot encode 'undefined' value as JSON"};
  }
  var subs = {'\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f',
              '\r': '\\r', '"' : '\\"', '\\': '\\\\'};
  if (typeof(val) == "xml") { // E4X support
    val = val.toXMLString();
  }
  return {
    "Array": function(v) {
      var buf = [];
      for (var i = 0; i < v.length; i++) {
        buf.push(toJSON(v[i]));
      }
      return "[" + buf.join(",") + "]";
    },
    "Boolean": function(v) {
      return v.toString();
    },
    "Date": function(v) {
      var f = function(n) { return n < 10 ? '0' + n : n }
      return '"' + v.getUTCFullYear()   + '-' +
                 f(v.getUTCMonth() + 1) + '-' +
                 f(v.getUTCDate())      + 'T' +
                 f(v.getUTCHours())     + ':' +
                 f(v.getUTCMinutes())   + ':' +
                 f(v.getUTCSeconds())   + 'Z"';
    },
    "Number": function(v) {
      return isFinite(v) ? v.toString() : "null";
    },
    "Object": function(v) {
      if (v === null) return "null";
      var buf = [];
      for (var k in v) {
        if (!v.hasOwnProperty(k) || typeof(k) !== "string" || v[k] === undefined) {
          continue;
        }
        buf.push(toJSON(k, val) + ": " + toJSON(v[k]));
      }
      return "{" + buf.join(",") + "}";
    },
    "String": function(v) {
      if (/["\\\x00-\x1f]/.test(v)) {
        v = v.replace(/([\x00-\x1f\\"])/g, function(a, b) {
          var c = subs[b];
          if (c) return c;
          c = b.charCodeAt();
          return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
        });
      }
      return '"' + v + '"';
    }
  }[val != null ? val.constructor.name : "Object"](val);
}



// *************** Test Framework Console Adapter ****************** //

var p = print;
var numFailures = 0;

function runAllTestsConsole() {
  var numTests = 0;
  var debug = false;
  for (var t in couchTests) {
    p(t);
    if (t == "utf8") {
      p("We skip the utf8 test because it fails due to problems in couch_js.c");
      p("Run the in-browser tests to verify utf8.\n");
    } else {
      numTests += 1;
      var testFun = couchTests[t];
      runTestConsole(testFun, debug);
    }
  }
  p("Results: "+numFailures.toString() + " failures in "+numTests+" tests.")
};

function runTestConsole(testFun, debug) {
  var start = new Date().getTime();
  try {
    if (!debug) testFun = patchTest(testFun) || testFun;
    testFun();
    p("PASS");
  } catch(e) {
    p("ERROR");
    p("Exception raised: "+e.toString());
    p("Backtrace: "+e.stack);
  }
  var duration = new Date().getTime() - start;
  p(duration+"ms\n");
};


// 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) {
  if (!arg1) {
    p("Assertion failed: "+(arg2 != null ? arg2 : arg1).toString());
    numFailures += 1
  }
}

p("Running CouchDB Test Suite\n");
p("Host: "+CouchDB.host);

try {
  p("Version: "+CouchDB.getVersion()+"\n");
  runAllTestsConsole();
  // runTestConsole(tests.attachments);
} catch (e) {
  p(e.toString());
}

p("\nFinished");